use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use serde::{Deserialize, Serialize};
use crate::cli::ReviewVerdict;
use crate::combine::{CombineCheck, CombineRecord, CombineState, CombinedRun};
use crate::serve::Surface;
static TMP_COUNTER: AtomicU64 = AtomicU64::new(1);
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Readiness {
Ready,
Waiting { reasons: Vec<String> },
}
pub trait Publisher: Send + Sync {
fn push_branch(&self, root: &Path, branch: &str) -> Result<(), String>;
fn open_pull_request(
&self,
root: &Path,
branch: &str,
title: &str,
body: &str,
) -> Result<String, String>;
}
pub struct RealPublisher;
impl Publisher for RealPublisher {
fn push_branch(&self, root: &Path, branch: &str) -> Result<(), String> {
crate::publish::push_branch(root, branch)
}
fn open_pull_request(
&self,
root: &Path,
branch: &str,
title: &str,
body: &str,
) -> Result<String, String> {
crate::publish::open_pull_request(root, branch, title, body)
}
}
#[derive(Default)]
struct RequestsInner {
running: HashSet<String>,
publishing: HashSet<String>,
}
pub struct PublishGuard {
state: Arc<RequestsState>,
request: String,
}
impl Drop for PublishGuard {
fn drop(&mut self) {
let mut inner = self.state.lock_inner();
inner.publishing.remove(&self.request);
}
}
pub struct RequestsState {
inner: Mutex<RequestsInner>,
cv: Condvar,
}
impl Default for RequestsState {
fn default() -> Self {
Self::new()
}
}
impl RequestsState {
pub fn new() -> Self {
Self {
inner: Mutex::new(RequestsInner::default()),
cv: Condvar::new(),
}
}
fn lock_inner(&self) -> MutexGuard<'_, RequestsInner> {
self.inner.lock().unwrap_or_else(|e| e.into_inner())
}
pub fn is_combining(&self, request: &str) -> bool {
self.lock_inner().running.contains(request)
}
pub fn try_begin_publish(self: &Arc<Self>, request: &str) -> Option<PublishGuard> {
let mut inner = self.lock_inner();
if !inner.publishing.insert(request.to_string()) {
return None;
}
Some(PublishGuard {
state: Arc::clone(self),
request: request.to_string(),
})
}
pub fn wait_for_idle(&self, request: &str) {
let mut inner = self.lock_inner();
while inner.running.contains(request) {
inner = self.cv.wait(inner).unwrap_or_else(|e| e.into_inner());
}
}
pub fn wait_all_idle(&self) {
let mut inner = self.lock_inner();
while !inner.running.is_empty() {
inner = self.cv.wait(inner).unwrap_or_else(|e| e.into_inner());
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct CommitSummary {
pub sha: String,
pub subject: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PublishedRecord {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pushed_commit: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pull_request_url: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AttemptResult {
Combined,
Conflict,
CheckFailed,
Error,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AttemptRecord {
pub runs: Vec<CombinedRun>,
pub result: AttemptResult,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
pub reported: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct RequestStatus {
pub request: String,
pub runs: Vec<String>,
pub left_out: Vec<String>,
pub state: String,
pub waiting_reasons: Vec<String>,
pub branch: Option<String>,
pub base: Option<String>,
pub commits: Vec<CommitSummary>,
#[serde(skip_serializing_if = "Option::is_none")]
pub check: Option<CombineCheck>,
pub conflicting_run: Option<String>,
pub conflicting_files: Vec<String>,
pub failing_step: Option<String>,
pub output_tail: Option<String>,
pub error: Option<String>,
pub suggested_title: Option<String>,
pub suggested_body: Option<String>,
pub pushed: bool,
pub pull_request_url: Option<String>,
pub started_by: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RequestActionError {
BadRequest(String),
NotOwned(String),
Conflict(String),
Internal(String),
}
struct StartRunInfo {
id: String,
request: Option<String>,
surface: Option<String>,
started_by: Option<String>,
base: Option<String>,
started_at: u64,
is_research: bool,
}
fn is_research_start(wt_dir: &Path, id: &str, val: &serde_json::Value) -> bool {
val.get("research")
.and_then(|v| v.as_bool())
.unwrap_or(false)
|| val
.get("tags")
.and_then(|v| v.as_array())
.is_some_and(|arr| arr.iter().any(|t| t.as_str() == Some("research")))
|| wt_dir.join(format!("{id}.report.md")).exists()
}
fn parse_start_file(wt_dir: &Path, path: &Path) -> Result<StartRunInfo, String> {
let content = std::fs::read_to_string(path)
.map_err(|e| format!("failed to read {}: {e}", path.display()))?;
let val: serde_json::Value = serde_json::from_str(&content)
.map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
let file_id = path
.file_name()
.and_then(|n| n.to_str())
.and_then(|n| n.strip_suffix(".start.json"))
.filter(|s| !s.is_empty())
.ok_or_else(|| format!("invalid start file name: {}", path.display()))?;
if let Some(id_val) = val.get("id") {
let field_id = id_val.as_str().ok_or_else(|| {
format!(
"start file {} has non-string id {id_val}, expected {file_id}",
path.display()
)
})?;
if field_id != file_id {
return Err(format!(
"start file {} has id {field_id} which differs from file name id {file_id}",
path.display()
));
}
}
let request = match val.get("request") {
None | Some(serde_json::Value::Null) => None,
Some(serde_json::Value::String(s)) => Some(s.clone()),
Some(_) => {
return Err(format!(
"start file {} has non-string request field",
path.display()
));
}
};
let surface = match val.get("surface") {
None | Some(serde_json::Value::Null) => None,
Some(serde_json::Value::String(s)) => Some(s.clone()),
Some(_) => {
return Err(format!(
"start file {} has non-string surface field",
path.display()
));
}
};
let started_by = match val.get("started_by") {
None | Some(serde_json::Value::Null) => None,
Some(serde_json::Value::String(s)) if !s.is_empty() => Some(s.clone()),
Some(_) => {
return Err(format!(
"{}: started_by must be a surface name",
path.display()
));
}
};
let base = match val.get("base") {
None | Some(serde_json::Value::Null) => None,
Some(serde_json::Value::String(s)) => Some(s.clone()),
Some(_) => {
return Err(format!(
"start file {} has non-string base field",
path.display()
));
}
};
let is_research = is_research_start(wt_dir, file_id, &val);
let started_at = match val.get("started_at") {
Some(v) => v
.as_u64()
.ok_or_else(|| format!("start file {} has non-numeric started_at", path.display()))?,
None => 0,
};
Ok(StartRunInfo {
id: file_id.to_string(),
request,
surface,
started_by,
base,
started_at,
is_research,
})
}
fn list_start_files(wt_dir: &Path) -> Result<Vec<PathBuf>, String> {
let read_dir = match std::fs::read_dir(wt_dir) {
Ok(rd) => rd,
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(format!("failed to read {}: {e}", wt_dir.display())),
};
let mut entries = Vec::new();
for entry in read_dir {
let entry =
entry.map_err(|e| format!("failed to read entry in {}: {e}", wt_dir.display()))?;
let path = entry.path();
if path
.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.ends_with(".start.json"))
{
entries.push(path);
}
}
entries.sort();
Ok(entries)
}
enum RequestOwnership {
Owned,
OtherSurface,
Unowned,
NotFound,
}
enum RequestOwnershipError {
Mixed(String),
IoOrParse(String),
}
fn check_request_ownership(
surface: &Surface,
request: &str,
) -> Result<RequestOwnership, RequestOwnershipError> {
let wt_dir = surface.root.join(".wt");
let entries = list_start_files(&wt_dir).map_err(RequestOwnershipError::IoOrParse)?;
let mut owners: HashSet<Option<String>> = HashSet::new();
let mut started_bys: HashSet<Option<String>> = HashSet::new();
for path in entries {
let info = parse_start_file(&wt_dir, &path).map_err(RequestOwnershipError::IoOrParse)?;
if info.request.as_deref() == Some(request) {
owners.insert(info.surface);
started_bys.insert(info.started_by);
}
}
if owners.is_empty() {
return Ok(RequestOwnership::NotFound);
}
if owners.len() > 1 {
return Err(RequestOwnershipError::Mixed(format!(
"request {request} has runs from more than one surface"
)));
}
if started_bys.len() > 1 {
return Err(RequestOwnershipError::Mixed(format!(
"request {request} has runs started by different surfaces"
)));
}
match owners.into_iter().next().flatten() {
Some(owner) if owner == surface.surface_id => Ok(RequestOwnership::Owned),
Some(_) => Ok(RequestOwnership::OtherSurface),
None => Ok(RequestOwnership::Unowned),
}
}
pub fn owned_run_ids_in(records_dir: &Path, surface_id: &str) -> Result<HashSet<String>, String> {
let entries = list_start_files(records_dir)?;
let mut ids = HashSet::new();
for path in entries {
let info = parse_start_file(records_dir, &path)?;
if info.surface.as_deref() == Some(surface_id) {
ids.insert(info.id);
}
}
Ok(ids)
}
pub fn owned_run_ids(surface: &Surface) -> Result<HashSet<String>, String> {
let wt_dir = surface.root.join(".wt");
owned_run_ids_in(&wt_dir, &surface.surface_id)
}
pub fn request_owner_check(surface: &Surface, request: &str) -> Result<(), RequestActionError> {
crate::dispatch::validate_request_id(request).map_err(RequestActionError::BadRequest)?;
match check_request_ownership(surface, request) {
Ok(RequestOwnership::Owned) => Ok(()),
Ok(RequestOwnership::OtherSurface) => Err(RequestActionError::NotOwned(format!(
"request {request} belongs to another surface"
))),
Ok(RequestOwnership::Unowned) => Err(RequestActionError::NotOwned(format!(
"request {request} was not started by a surface"
))),
Ok(RequestOwnership::NotFound) => Err(RequestActionError::Conflict(format!(
"request {request} has not been combined"
))),
Err(RequestOwnershipError::Mixed(msg)) => Err(RequestActionError::BadRequest(msg)),
Err(RequestOwnershipError::IoOrParse(msg)) => Err(RequestActionError::Internal(msg)),
}
}
pub(crate) fn run_owner_check_in(
records_dir: &Path,
surface_id: &str,
run_id: &str,
) -> Result<(), RequestActionError> {
let path = records_dir.join(format!("{run_id}.start.json"));
if !path.exists() {
return Err(RequestActionError::NotOwned(format!(
"run {run_id} was not started by a surface"
)));
}
let info = parse_start_file(records_dir, &path).map_err(RequestActionError::Internal)?;
match info.surface.as_deref() {
Some(owner) if owner == surface_id => Ok(()),
Some(_) => Err(RequestActionError::NotOwned(format!(
"run {run_id} belongs to another surface"
))),
None => Err(RequestActionError::NotOwned(format!(
"run {run_id} was not started by a surface"
))),
}
}
pub(crate) fn run_owner_check(surface: &Surface, run_id: &str) -> Result<(), RequestActionError> {
let wt_dir = surface.root.join(".wt");
run_owner_check_in(&wt_dir, &surface.surface_id, run_id)
}
pub fn run_request_id(root: &Path, run_id: &str) -> Result<Option<String>, String> {
let wt_dir = root.join(".wt");
let path = wt_dir.join(format!("{run_id}.start.json"));
if !path.exists() {
return Ok(None);
}
let info = parse_start_file(&wt_dir, &path)?;
if info.is_research {
return Ok(None);
}
Ok(info.request)
}
pub fn request_readiness(root: &Path, request: &str) -> Result<Readiness, String> {
crate::dispatch::validate_request_id(request)?;
let wt_dir = root.join(".wt");
let entries = list_start_files(&wt_dir)?;
let mut matched_runs = Vec::new();
for path in entries {
let info = parse_start_file(&wt_dir, &path)?;
if info.is_research {
continue;
}
if info.request.as_deref() == Some(request) {
matched_runs.push(info);
}
}
if matched_runs.is_empty() {
return Ok(Readiness::Waiting {
reasons: vec!["no runs for request".to_string()],
});
}
matched_runs.sort_by(|a, b| {
a.started_at
.cmp(&b.started_at)
.then_with(|| a.id.cmp(&b.id))
});
let mut active_runs = Vec::new();
let mut left_out_ids: BTreeSet<String> = BTreeSet::new();
for run in matched_runs {
let verdict = crate::queue_actions::read_verdict(root, &run.id)?;
if crate::combine::is_left_out_verdict(verdict) {
left_out_ids.insert(run.id);
} else {
active_runs.push((run, verdict));
}
}
if active_runs.is_empty() {
return Ok(Readiness::Waiting {
reasons: vec!["every run was redone".to_string()],
});
}
let left_out_refs: BTreeSet<&str> = left_out_ids.iter().map(String::as_str).collect();
for (run, _) in &active_runs {
crate::combine::check_not_based_on_left_out(
root,
&run.id,
run.base.as_deref(),
&left_out_refs,
)?;
}
let mut reasons = Vec::new();
for (run, verdict) in active_runs {
let id = &run.id;
let summary_path = wt_dir.join(format!("{id}.json"));
let outcome = match std::fs::read_to_string(&summary_path) {
Ok(raw) => {
let val: serde_json::Value = serde_json::from_str(&raw)
.map_err(|e| format!("failed to parse {}: {e}", summary_path.display()))?;
let outcome = val
.get("outcome")
.and_then(|v| v.as_str())
.ok_or_else(|| {
format!(
"summary file {} is missing string outcome",
summary_path.display()
)
})?
.to_string();
if outcome != "verified" {
reasons.push(format!("{id}: {outcome}"));
}
Some(outcome)
}
Err(e) if e.kind() == ErrorKind::NotFound => {
reasons.push(format!("{id}: unfinished"));
None
}
Err(e) => {
return Err(format!("failed to read {}: {e}", summary_path.display()));
}
};
let checks_path = wt_dir.join(format!("{id}.checks.json"));
let (checks_recorded, flags) = crate::replay::read_checks(&checks_path)
.map_err(|e| format!("{}: {e}", checks_path.display()))?;
if crate::queue_actions::read_hold(root, id)?.is_some() {
reasons.push(format!("{id}: on hold"));
}
if let Some(ref outcome_str) = outcome {
if outcome_str == "verified" {
if !checks_recorded {
reasons.push(format!("{id}: no checks file"));
} else {
let card =
crate::replay::card_for_run(false, outcome_str, checks_recorded, &flags);
let cleared_by_verdict = matches!(
verdict,
Some(ReviewVerdict::Accepted | ReviewVerdict::Fixed)
);
if card != "clean" && !cleared_by_verdict {
reasons.push(format!("{id}: flagged ({})", flags.join("; ")));
}
}
}
}
}
if reasons.is_empty() {
Ok(Readiness::Ready)
} else {
Ok(Readiness::Waiting { reasons })
}
}
fn combine_record_path(root: &Path, request: &str) -> PathBuf {
root.join(".wt")
.join("combined")
.join(format!("{request}.json"))
}
fn attempt_record_path(root: &Path, request: &str) -> PathBuf {
root.join(".wt")
.join("combined")
.join(format!("{request}.attempt.json"))
}
fn published_record_path(root: &Path, request: &str) -> PathBuf {
root.join(".wt")
.join("combined")
.join(format!("{request}.published.json"))
}
fn write_json_atomic<T: Serialize>(path: &Path, value: &T, label: &str) -> Result<(), String> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
}
let mut json = serde_json::to_string_pretty(value)
.map_err(|e| format!("failed to serialize {label}: {e}"))?;
json.push('\n');
let mut tmp_name = path.as_os_str().to_os_string();
let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
tmp_name.push(format!(".tmp.{}.{seq}", std::process::id()));
let tmp_path = PathBuf::from(tmp_name);
std::fs::write(&tmp_path, json)
.map_err(|e| format!("failed to write {}: {e}", tmp_path.display()))?;
std::fs::rename(&tmp_path, path).map_err(|e| {
let _ = std::fs::remove_file(&tmp_path);
format!(
"failed to rename {} to {}: {e}",
tmp_path.display(),
path.display()
)
})
}
pub fn load_combine_record(root: &Path, request: &str) -> Result<Option<CombineRecord>, String> {
let path = combine_record_path(root, request);
let raw = match std::fs::read_to_string(&path) {
Ok(s) => s,
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
};
let record: CombineRecord = serde_json::from_str(&raw)
.map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
Ok(Some(record))
}
pub fn load_attempt_record(root: &Path, request: &str) -> Result<Option<AttemptRecord>, String> {
let path = attempt_record_path(root, request);
let raw = match std::fs::read_to_string(&path) {
Ok(s) => s,
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
};
let record: AttemptRecord = serde_json::from_str(&raw)
.map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
if record.result == AttemptResult::Error
&& record.error.as_deref().is_none_or(|s| s.trim().is_empty())
{
return Err(format!(
"invalid attempt file {}: result error is missing error text",
path.display()
));
}
Ok(Some(record))
}
pub fn write_attempt_record(
root: &Path,
request: &str,
record: &AttemptRecord,
) -> Result<(), String> {
let path = attempt_record_path(root, request);
write_json_atomic(&path, record, "attempt record")
}
pub fn load_published_record(root: &Path, request: &str) -> Result<PublishedRecord, String> {
let path = published_record_path(root, request);
let raw = match std::fs::read_to_string(&path) {
Ok(s) => s,
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(PublishedRecord::default()),
Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
};
serde_json::from_str(&raw).map_err(|e| format!("failed to parse {}: {e}", path.display()))
}
pub fn write_published_record(
root: &Path,
request: &str,
record: &PublishedRecord,
) -> Result<(), String> {
let path = published_record_path(root, request);
write_json_atomic(&path, record, "published record")
}
fn git_stdout(root: &Path, args: &[&str]) -> Result<String, String> {
let out = Command::new("git")
.args(args)
.current_dir(root)
.output()
.map_err(|e| format!("failed to run git {}: {e}", args.join(" ")))?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
return Err(format!("git {} failed: {stderr}", args.join(" ")));
}
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}
fn git_rev_parse(root: &Path, rev: &str) -> Result<String, String> {
git_stdout(root, &["rev-parse", "--verify", rev])
}
fn git_commit_subject(root: &Path, sha: &str) -> Result<String, String> {
git_stdout(root, &["show", "-s", "--format=%s", sha])
.map_err(|e| format!("failed to read subject for commit {sha}: {e}"))
}
fn run_branch(wt_dir: &Path, run_id: &str) -> Result<String, String> {
let summary_path = wt_dir.join(format!("{run_id}.json"));
let raw = std::fs::read_to_string(&summary_path)
.map_err(|e| format!("failed to read {}: {e}", summary_path.display()))?;
let val: serde_json::Value = serde_json::from_str(&raw)
.map_err(|e| format!("failed to parse {}: {e}", summary_path.display()))?;
let branch_hint = match val.get("branch") {
None | Some(serde_json::Value::Null) => None,
Some(serde_json::Value::String(s)) => Some(s.clone()),
Some(_) => {
return Err(format!(
"summary file {} has non-string branch",
summary_path.display()
));
}
};
Ok(branch_hint.unwrap_or_else(|| format!("wip/{run_id}")))
}
fn git_branch_exists(root: &Path, run_id: &str, branch: &str) -> Result<bool, String> {
let ref_name = format!("refs/heads/{branch}");
let out = Command::new("git")
.args(["show-ref", "--verify", "--quiet", &ref_name])
.current_dir(root)
.output()
.map_err(|e| {
format!("run {run_id}: failed to check branch {branch} with git show-ref: {e}")
})?;
match out.status.code() {
Some(0) => Ok(true),
Some(1) => Ok(false),
code => {
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
let status_desc = match code {
Some(c) => format!("exit code {c}"),
None => "terminated by signal".to_string(),
};
if stderr.is_empty() {
Err(format!(
"run {run_id}: git show-ref failed for branch {branch} ({status_desc})"
))
} else {
Err(format!(
"run {run_id}: git show-ref failed for branch {branch} ({status_desc}): {stderr}"
))
}
}
}
}
fn resolve_current_run_tips(root: &Path, request: &str) -> Result<Vec<CombinedRun>, String> {
let wt_dir = root.join(".wt");
let entries = list_start_files(&wt_dir)?;
let mut tips = BTreeMap::new();
for path in entries {
let info = parse_start_file(&wt_dir, &path)?;
if info.is_research || info.request.as_deref() != Some(request) {
continue;
}
if crate::combine::is_run_left_out(root, &info.id)? {
continue;
}
let branch = run_branch(&wt_dir, &info.id)?;
let rev = format!("refs/heads/{branch}^{{commit}}");
let sha = git_rev_parse(root, &rev).map_err(|e| {
format!(
"run {}: branch {branch} does not resolve to a commit: {e}",
info.id
)
})?;
tips.insert(info.id, sha);
}
Ok(tips
.into_iter()
.map(|(id, tip)| CombinedRun { id, tip })
.collect())
}
fn sorted_runs(mut runs: Vec<CombinedRun>) -> Vec<CombinedRun> {
runs.sort_by(|a, b| a.id.cmp(&b.id));
runs
}
fn record_runs_match_tips(record: &CombineRecord, current_runs: &[CombinedRun]) -> bool {
if record.runs.len() != current_runs.len() {
return false;
}
sorted_runs(record.runs.clone()) == current_runs
}
enum CombinedRunBranchState {
Gone,
AtRecordedTip,
Changed,
}
fn check_recorded_run_branch(
root: &Path,
wt_dir: &Path,
run: &CombinedRun,
) -> Result<CombinedRunBranchState, String> {
let branch = run_branch(wt_dir, &run.id)?;
if !git_branch_exists(root, &run.id, &branch)? {
return Ok(CombinedRunBranchState::Gone);
}
let rev = format!("refs/heads/{branch}^{{commit}}");
let sha = git_rev_parse(root, &rev).map_err(|e| {
format!(
"run {}: branch {branch} does not resolve to a commit: {e}",
run.id
)
})?;
if sha == run.tip {
Ok(CombinedRunBranchState::AtRecordedTip)
} else {
Ok(CombinedRunBranchState::Changed)
}
}
fn active_request_run_ids(root: &Path, request: &str) -> Result<Vec<String>, String> {
let wt_dir = root.join(".wt");
let entries = list_start_files(&wt_dir)?;
let mut run_ids = Vec::new();
for path in entries {
let info = parse_start_file(&wt_dir, &path)?;
if info.is_research || info.request.as_deref() != Some(request) {
continue;
}
if crate::combine::is_run_left_out(root, &info.id)? {
continue;
}
run_ids.push(info.id);
}
Ok(run_ids)
}
fn request_is_done(root: &Path, request: &str, rec: &CombineRecord) -> Result<bool, String> {
if rec.state != CombineState::Combined {
return Ok(false);
}
let active_runs = active_request_run_ids(root, request)?;
if active_runs.is_empty() {
return Ok(false);
}
let recorded_by_id: HashMap<&str, &CombinedRun> =
rec.runs.iter().map(|run| (run.id.as_str(), run)).collect();
let wt_dir = root.join(".wt");
let mut any_branch_gone = false;
for run_id in &active_runs {
let Some(&recorded_run) = recorded_by_id.get(run_id.as_str()) else {
return Ok(false);
};
match check_recorded_run_branch(root, &wt_dir, recorded_run)? {
CombinedRunBranchState::Gone => any_branch_gone = true,
CombinedRunBranchState::AtRecordedTip => {}
CombinedRunBranchState::Changed => return Ok(false),
}
}
Ok(any_branch_gone)
}
fn check_record_combined_for_request(
root: &Path,
request: &str,
run_ids: &[&str],
) -> Result<BTreeSet<String>, String> {
let Some(rec) = load_combine_record(root, request)? else {
return Ok(BTreeSet::new());
};
if rec.state != CombineState::Combined {
return Ok(BTreeSet::new());
}
let wt_dir = root.join(".wt");
let mut combined = BTreeSet::new();
for run in &rec.runs {
if !run_ids.contains(&run.id.as_str()) {
continue;
}
match check_recorded_run_branch(root, &wt_dir, run)? {
CombinedRunBranchState::Gone | CombinedRunBranchState::AtRecordedTip => {
combined.insert(run.id.clone());
}
CombinedRunBranchState::Changed => {}
}
}
Ok(combined)
}
pub fn combined_run_ids(
root: &Path,
runs: &[(&str, Option<&str>)],
) -> Result<BTreeSet<String>, String> {
let mut by_request: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
for &(run_id, request) in runs {
if let Some(req) = request {
by_request.entry(req).or_default().push(run_id);
}
}
let mut combined = BTreeSet::new();
for (request, run_ids) in by_request {
combined.extend(check_record_combined_for_request(root, request, &run_ids)?);
}
Ok(combined)
}
fn combine_record_tip(record: &CombineRecord) -> &str {
record.commits.last().unwrap_or(&record.base).as_str()
}
fn is_record_pushed(published: &PublishedRecord, record: &CombineRecord) -> bool {
published.pushed_commit.as_deref() == Some(combine_record_tip(record))
}
fn branch_matches_record(root: &Path, record: &CombineRecord) -> bool {
let expected = combine_record_tip(record);
let rev = format!("refs/heads/{}^{{commit}}", record.branch);
git_rev_parse(root, &rev).is_ok_and(|actual| actual == expected)
}
fn format_record_failure(record: &CombineRecord, record_path: &Path) -> Result<String, String> {
match record.state {
CombineState::Conflict => {
let run = record
.conflicting_run
.as_deref()
.filter(|r| !r.is_empty())
.ok_or_else(|| {
format!(
"combine record {} has state conflict with missing conflicting_run",
record_path.display()
)
})?;
if record.conflicting_files.is_empty() {
return Err(format!(
"combine record {} has state conflict with empty conflicting_files",
record_path.display()
));
}
let files = record.conflicting_files.join(", ");
Ok(format!(
"Combine failed for request {} (state: conflict).\nConflicting run: {run}\nConflicting files: {files}",
record.request
))
}
CombineState::CheckFailed => {
let step = record
.failing_step
.as_deref()
.filter(|s| !s.is_empty())
.ok_or_else(|| {
format!(
"combine record {} has state check_failed with missing failing_step",
record_path.display()
)
})?;
let tail = record
.output_tail
.as_deref()
.filter(|t| !t.is_empty())
.ok_or_else(|| {
format!(
"combine record {} has state check_failed with missing or empty output_tail",
record_path.display()
)
})?;
Ok(format!(
"Combine failed for request {} (state: check_failed).\nFailing step: {step}\nOutput tail:\n{tail}",
record.request
))
}
CombineState::Combined => Err(format!(
"combine record {} has state combined: not a failure record",
record_path.display()
)),
}
}
pub fn format_combined_message(rec: &CombineRecord) -> String {
let short_hashes = rec
.commits
.iter()
.map(|c| c.chars().take(8).collect::<String>())
.collect::<Vec<_>>()
.join(", ");
format!(
"Request {} is combined on branch {} ({} commit(s): {}).\nIts check passed. Tell the user what changed, and ask to publish it if they want a pull request.",
rec.request,
rec.branch,
rec.commits.len(),
short_hashes
)
}
fn format_error_failure(request: &str, err_text: &str) -> String {
format!("Combine failed for request {request} (state: error).\nError: {err_text}")
}
struct RunningGuard {
state: Arc<RequestsState>,
request: String,
}
impl Drop for RunningGuard {
fn drop(&mut self) {
let mut inner = self.state.lock_inner();
inner.running.remove(&self.request);
self.state.cv.notify_all();
}
}
fn retry_attempt_message(
root: &Path,
request: &str,
attempt: &AttemptRecord,
) -> Result<String, String> {
let path = attempt_record_path(root, request);
match attempt.result {
AttemptResult::Conflict | AttemptResult::CheckFailed => {
let expected_state = match attempt.result {
AttemptResult::Conflict => CombineState::Conflict,
AttemptResult::CheckFailed => CombineState::CheckFailed,
AttemptResult::Combined | AttemptResult::Error => unreachable!(),
};
match load_combine_record(root, request)? {
Some(rec) if rec.state == expected_state => {
format_record_failure(&rec, &combine_record_path(root, request))
}
_ => Err(format!(
"attempt file {} has result {:?} without a matching combine record",
path.display(),
attempt.result
)),
}
}
AttemptResult::Error => {
let err_text = attempt.error.as_deref().ok_or_else(|| {
format!(
"attempt file {} has result error without error text",
path.display()
)
})?;
Ok(format_error_failure(request, err_text))
}
AttemptResult::Combined => match load_combine_record(root, request)? {
Some(rec) if rec.state == CombineState::Combined => Ok(format_combined_message(&rec)),
_ => Err(format!(
"attempt file {} has result {:?} without a matching combine record",
path.display(),
attempt.result
)),
},
}
}
fn record_and_report_failure(
root: &Path,
session: &crate::session::Session,
request: &str,
runs: Vec<CombinedRun>,
result: AttemptResult,
error: Option<String>,
msg: &str,
) {
let mut attempt = AttemptRecord {
runs,
result,
error,
reported: false,
};
if let Err(e) = write_attempt_record(root, request, &attempt) {
session.record_error(&format!(
"failed to write attempt record for {request}: {e}"
));
}
match session.queue_for_request(request, msg) {
Ok(_) => {
attempt.reported = true;
if let Err(e) = write_attempt_record(root, request, &attempt) {
session.record_error(&format!(
"failed to write attempt record for {request}: {e}"
));
}
}
Err(e) => {
session.record_error(&format!(
"failed to queue combine failure for {request}: {e}"
));
}
}
}
fn conversation_busy(surface: &Surface) -> bool {
let info = surface.session.info();
info.busy || info.queued > 0
}
fn ready_waiting_reason(conversation_busy: bool) -> String {
if conversation_busy {
"the conversation model is still working".to_string()
} else {
"waiting to combine".to_string()
}
}
pub fn maybe_combine(surface: &Surface, request: &str) -> Result<bool, String> {
crate::dispatch::validate_request_id(request)?;
match check_request_ownership(surface, request) {
Ok(RequestOwnership::Owned) => {}
Ok(
RequestOwnership::OtherSurface | RequestOwnership::Unowned | RequestOwnership::NotFound,
) => return Ok(false),
Err(RequestOwnershipError::Mixed(msg) | RequestOwnershipError::IoOrParse(msg)) => {
return Err(msg);
}
}
if conversation_busy(surface) {
return Ok(false);
}
match request_readiness(&surface.root, request)? {
Readiness::Waiting { .. } => return Ok(false),
Readiness::Ready => {}
}
if let Some(rec) = load_combine_record(&surface.root, request)? {
if request_is_done(&surface.root, request, &rec)? {
return Ok(false);
}
}
let current_runs = resolve_current_run_tips(&surface.root, request)?;
{
let mut inner = surface.requests.lock_inner();
if inner.running.contains(request) {
return Ok(false);
}
if let Some(mut attempt) = load_attempt_record(&surface.root, request)? {
if attempt.runs == current_runs {
if !attempt.reported {
match retry_attempt_message(&surface.root, request, &attempt) {
Ok(msg) => match surface.session.queue_for_request(request, &msg) {
Ok(_) => {
attempt.reported = true;
write_attempt_record(&surface.root, request, &attempt)?;
}
Err(e) => {
surface.session.record_error(&format!(
"failed to queue combine result for {request}: {e}"
));
}
},
Err(e) => {
let msg = format_error_failure(request, &e);
record_and_report_failure(
&surface.root,
&surface.session,
request,
attempt.runs,
AttemptResult::Error,
Some(e),
&msg,
);
}
}
}
return Ok(false);
}
}
inner.running.insert(request.to_string());
}
let root = surface.root.clone();
let session = surface.session.clone();
let requests_state = Arc::clone(&surface.requests);
let request_owned = request.to_string();
std::thread::spawn(move || {
let _guard = RunningGuard {
state: Arc::clone(&requests_state),
request: request_owned.clone(),
};
let mut out = Vec::new();
let mut err = Vec::new();
let code = crate::combine::combine_in(&root, &request_owned, &mut out, &mut err);
match code {
0 => {
let rec_path = combine_record_path(&root, &request_owned);
let (runs, rec) = match load_combine_record(&root, &request_owned) {
Ok(Some(rec)) => (sorted_runs(rec.runs.clone()), Some(rec)),
Ok(None) => {
session.record_error(&format!(
"combine record {} is missing after combine for {request_owned}",
rec_path.display()
));
(current_runs, None)
}
Err(e) => {
session.record_error(&format!(
"failed to read combine record after combine for {request_owned}: {e}"
));
(current_runs, None)
}
};
let mut attempt = AttemptRecord {
runs,
result: AttemptResult::Combined,
error: None,
reported: false,
};
if let Err(e) = write_attempt_record(&root, &request_owned, &attempt) {
session.record_error(&format!(
"failed to write attempt record for {request_owned}: {e}"
));
}
if let Some(rec) = rec {
let msg = format_combined_message(&rec);
match session.queue_for_request(&request_owned, &msg) {
Ok(_) => {
attempt.reported = true;
if let Err(e) = write_attempt_record(&root, &request_owned, &attempt) {
session.record_error(&format!(
"failed to write attempt record for {request_owned}: {e}"
));
}
}
Err(e) => {
session.record_error(&format!(
"failed to queue combine result for {request_owned}: {e}"
));
}
}
}
}
1 => match load_combine_record(&root, &request_owned) {
Ok(Some(rec))
if matches!(
rec.state,
CombineState::Conflict | CombineState::CheckFailed
) =>
{
let result = match rec.state {
CombineState::Conflict => AttemptResult::Conflict,
CombineState::CheckFailed => AttemptResult::CheckFailed,
CombineState::Combined => unreachable!(),
};
let runs = sorted_runs(rec.runs.clone());
let rec_path = combine_record_path(&root, &request_owned);
match format_record_failure(&rec, &rec_path) {
Ok(msg) => {
record_and_report_failure(
&root,
&session,
&request_owned,
runs,
result,
None,
&msg,
);
}
Err(e) => {
let msg = format_error_failure(&request_owned, &e);
record_and_report_failure(
&root,
&session,
&request_owned,
runs,
AttemptResult::Error,
Some(e),
&msg,
);
}
}
}
Ok(_) => {
let err_text = String::from_utf8_lossy(&err).trim().to_string();
let err_text = if err_text.is_empty() {
format!("combine exited with code 1 without a conflict/check_failed record for {request_owned}")
} else {
err_text
};
let msg = format_error_failure(&request_owned, &err_text);
record_and_report_failure(
&root,
&session,
&request_owned,
current_runs,
AttemptResult::Error,
Some(err_text),
&msg,
);
}
Err(e) => {
let msg = format_error_failure(&request_owned, &e);
record_and_report_failure(
&root,
&session,
&request_owned,
current_runs,
AttemptResult::Error,
Some(e),
&msg,
);
}
},
other => {
let err_text = String::from_utf8_lossy(&err).trim().to_string();
let err_text = if err_text.is_empty() {
format!("combine exited with status {other}")
} else {
err_text
};
let msg = format_error_failure(&request_owned, &err_text);
record_and_report_failure(
&root,
&session,
&request_owned,
current_runs,
AttemptResult::Error,
Some(err_text),
&msg,
);
}
}
});
Ok(true)
}
fn resolve_commit_summaries(root: &Path, shas: &[String]) -> Result<Vec<CommitSummary>, String> {
let mut commits = Vec::with_capacity(shas.len());
for sha in shas {
let subject = git_commit_subject(root, sha)?;
commits.push(CommitSummary {
sha: sha.clone(),
subject,
});
}
Ok(commits)
}
fn suggested_pr_fields(commits: &[CommitSummary]) -> (Option<String>, Option<String>) {
if commits.is_empty() {
return (None, None);
}
let title = commits[0].subject.clone();
let body = commits
.iter()
.map(|c| c.subject.as_str())
.collect::<Vec<_>>()
.join("\n");
(Some(title), Some(body))
}
struct RequestGroup {
request: String,
max_started_at: u64,
runs: Vec<(u64, String)>,
owners: HashSet<Option<String>>,
started_bys: HashSet<Option<String>>,
}
pub fn list_requests(surface: &Surface) -> Result<Vec<RequestStatus>, String> {
let wt_dir = surface.root.join(".wt");
let entries = list_start_files(&wt_dir)?;
let mut groups: BTreeMap<String, RequestGroup> = BTreeMap::new();
for path in entries {
let info = parse_start_file(&wt_dir, &path)?;
let Some(req_id) = info.request else {
continue;
};
let entry = groups
.entry(req_id.clone())
.or_insert_with(|| RequestGroup {
request: req_id,
max_started_at: 0,
runs: Vec::new(),
owners: HashSet::new(),
started_bys: HashSet::new(),
});
entry.owners.insert(info.surface);
entry.started_bys.insert(info.started_by);
if info.is_research {
continue;
}
if info.started_at > entry.max_started_at {
entry.max_started_at = info.started_at;
}
entry.runs.push((info.started_at, info.id));
}
let mut ordered: Vec<RequestGroup> = Vec::new();
for group in groups.into_values() {
if group.owners.len() > 1 {
return Err(format!(
"request {} has runs from more than one surface",
group.request
));
}
if group.started_bys.len() > 1 {
return Err(format!(
"request {} has runs started by different surfaces",
group.request
));
}
if group.runs.is_empty() {
continue;
}
let owner = group.owners.iter().next().and_then(|o| o.as_deref());
if owner != Some(surface.surface_id.as_str()) {
continue;
}
ordered.push(group);
}
ordered.sort_by(|a, b| {
b.max_started_at
.cmp(&a.max_started_at)
.then_with(|| b.request.cmp(&a.request))
});
let busy = conversation_busy(surface);
let mut result = Vec::with_capacity(ordered.len());
for mut group in ordered {
group
.runs
.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
let run_ids: Vec<String> = group.runs.into_iter().map(|(_, id)| id).collect();
let started_by = group.started_bys.into_iter().next().flatten();
result.push(build_request_status(
surface,
group.request,
run_ids,
started_by,
busy,
));
}
Ok(result)
}
fn build_request_status(
surface: &Surface,
request: String,
runs: Vec<String>,
started_by: Option<String>,
conversation_busy: bool,
) -> RequestStatus {
let is_combining = surface.requests.is_combining(&request);
let record_res = load_combine_record(&surface.root, &request);
let published_res = load_published_record(&surface.root, &request);
let attempt_res = load_attempt_record(&surface.root, &request);
let left_out_res: Result<Vec<String>, String> = runs
.iter()
.filter_map(
|id| match crate::combine::is_run_left_out(&surface.root, id) {
Ok(true) => Some(Ok(id.clone())),
Ok(false) => None,
Err(e) => Some(Err(e)),
},
)
.collect();
let left_out = left_out_res.as_ref().ok().cloned().unwrap_or_default();
let (pushed, pull_request_url) = match (&published_res, &record_res) {
(Ok(p), Ok(Some(rec))) => (
rec.state == CombineState::Combined && is_record_pushed(p, rec),
p.pull_request_url.clone(),
),
(Ok(p), _) => (false, p.pull_request_url.clone()),
(Err(_), _) => (false, None),
};
let mut status = RequestStatus {
request: request.clone(),
runs,
left_out,
state: String::new(),
waiting_reasons: Vec::new(),
branch: None,
base: None,
commits: Vec::new(),
check: None,
conflicting_run: None,
conflicting_files: Vec::new(),
failing_step: None,
output_tail: None,
error: None,
suggested_title: None,
suggested_body: None,
pushed,
pull_request_url,
started_by,
};
if is_combining {
status.state = "combining".to_string();
if let Ok(Some(rec)) = record_res {
populate_record_metadata(&surface.root, &rec, &mut status);
}
return status;
}
if let Err(e) = left_out_res {
status.state = "error".to_string();
status.error = Some(e);
return status;
}
if let Err(e) = published_res {
status.state = "error".to_string();
status.error = Some(e);
return status;
}
let attempt = match attempt_res {
Ok(a) => a,
Err(e) => {
status.state = "error".to_string();
status.error = Some(e);
return status;
}
};
let record = match record_res {
Ok(r) => r,
Err(e) => {
status.state = "error".to_string();
status.error = Some(e);
return status;
}
};
match request_readiness(&surface.root, &request) {
Err(e) => {
status.state = "error".to_string();
status.error = Some(e);
status
}
Ok(Readiness::Waiting { reasons }) => {
status.state = "waiting".to_string();
status.waiting_reasons = reasons;
if let Some(ref rec) = record {
populate_record_metadata(&surface.root, rec, &mut status);
}
status
}
Ok(Readiness::Ready) => {
if let Some(ref rec) = record {
match request_is_done(&surface.root, &request, rec) {
Ok(true) => {
status.state = "done".to_string();
populate_record_metadata(&surface.root, rec, &mut status);
return status;
}
Ok(false) => {}
Err(e) => {
status.state = "error".to_string();
status.error = Some(e);
return status;
}
}
}
let current_runs = match resolve_current_run_tips(&surface.root, &request) {
Ok(t) => t,
Err(e) => {
status.state = "error".to_string();
status.error = Some(e);
return status;
}
};
if let Some(ref att) = attempt {
if att.runs == current_runs && att.result == AttemptResult::Error {
status.state = "error".to_string();
status.error = att.error.clone();
return status;
}
}
let Some(rec) = record else {
status.state = "waiting".to_string();
status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
return status;
};
if !record_runs_match_tips(&rec, ¤t_runs) {
status.state = "waiting".to_string();
status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
populate_record_metadata(&surface.root, &rec, &mut status);
return status;
}
let commits = match resolve_commit_summaries(&surface.root, &rec.commits) {
Ok(c) => c,
Err(e) => {
status.state = "error".to_string();
status.error = Some(e);
return status;
}
};
status.branch = Some(rec.branch.clone());
status.base = Some(rec.base.clone());
status.commits = commits;
status.check = Some(rec.check);
status.conflicting_run = rec.conflicting_run.clone();
status.conflicting_files = rec.conflicting_files.clone();
status.failing_step = rec.failing_step.clone();
status.output_tail = rec.output_tail.clone();
match rec.state {
CombineState::Combined => {
if branch_matches_record(&surface.root, &rec) {
status.state = "combined".to_string();
let (title, body) = suggested_pr_fields(&status.commits);
status.suggested_title = title;
status.suggested_body = body;
} else {
status.state = "waiting".to_string();
status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
}
}
CombineState::Conflict => {
status.state = "conflict".to_string();
}
CombineState::CheckFailed => {
status.state = "check_failed".to_string();
}
}
status
}
}
}
fn populate_record_metadata(root: &Path, rec: &CombineRecord, status: &mut RequestStatus) {
status.branch = Some(rec.branch.clone());
status.base = Some(rec.base.clone());
if let Ok(commits) = resolve_commit_summaries(root, &rec.commits) {
status.commits = commits;
}
status.check = Some(rec.check);
status.conflicting_run = rec.conflicting_run.clone();
status.conflicting_files = rec.conflicting_files.clone();
status.failing_step = rec.failing_step.clone();
status.output_tail = rec.output_tail.clone();
}
pub fn push_request(surface: &Surface, request: &str) -> Result<(), RequestActionError> {
request_owner_check(surface, request)?;
if surface.requests.is_combining(request) {
return Err(RequestActionError::Conflict(format!(
"request {request} is currently combining"
)));
}
let record = load_combine_record(&surface.root, request)
.map_err(RequestActionError::Internal)?
.ok_or_else(|| {
RequestActionError::Conflict(format!("request {request} has not been combined"))
})?;
if record.state != CombineState::Combined {
return Err(RequestActionError::Conflict(format!(
"request {request} is not combined (state: {:?})",
record.state
)));
}
if request_is_done(&surface.root, request, &record).map_err(RequestActionError::Internal)? {
return Err(RequestActionError::Conflict(format!(
"request {request} is done: its branches were already merged and removed"
)));
}
let mut published =
load_published_record(&surface.root, request).map_err(RequestActionError::Internal)?;
match surface.publisher.push_branch(&surface.root, &record.branch) {
Ok(()) => {
let rev = format!("refs/heads/{}^{{commit}}", record.branch);
let branch_commit =
git_rev_parse(&surface.root, &rev).map_err(RequestActionError::Internal)?;
published.pushed_commit = Some(branch_commit);
write_published_record(&surface.root, request, &published)
.map_err(RequestActionError::Internal)?;
if let Err(e) = surface.session.record_decision(
request,
"push",
Some(&format!("pushed {}", record.branch)),
None,
) {
surface.session.record_error(&format!(
"failed to record push decision for {request}: {e}"
));
}
Ok(())
}
Err(e) => {
surface.session.record_error(&format!(
"push failed for {request} ({}): {e}",
record.branch
));
Err(RequestActionError::Internal(e))
}
}
}
pub fn open_request_pull_request(
surface: &Surface,
request: &str,
title: &str,
body: &str,
) -> Result<String, RequestActionError> {
request_owner_check(surface, request)?;
let trimmed_title = title.trim();
if trimmed_title.is_empty() {
return Err(RequestActionError::BadRequest(
"field title must not be empty".to_string(),
));
}
if surface.requests.is_combining(request) {
return Err(RequestActionError::Conflict(format!(
"request {request} is currently combining"
)));
}
let record = load_combine_record(&surface.root, request)
.map_err(RequestActionError::Internal)?
.ok_or_else(|| {
RequestActionError::Conflict(format!("request {request} has not been combined"))
})?;
if record.state != CombineState::Combined {
return Err(RequestActionError::Conflict(format!(
"request {request} is not combined (state: {:?})",
record.state
)));
}
if request_is_done(&surface.root, request, &record).map_err(RequestActionError::Internal)? {
return Err(RequestActionError::Conflict(format!(
"request {request} is done: its branches were already merged and removed"
)));
}
let mut published =
load_published_record(&surface.root, request).map_err(RequestActionError::Internal)?;
if !is_record_pushed(&published, &record) {
return Err(RequestActionError::Conflict(format!(
"branch {} must be pushed before opening a pull request",
record.branch
)));
}
match surface
.publisher
.open_pull_request(&surface.root, &record.branch, trimmed_title, body)
{
Ok(url) => {
published.pull_request_url = Some(url.clone());
write_published_record(&surface.root, request, &published)
.map_err(RequestActionError::Internal)?;
if let Err(e) =
surface
.session
.record_decision(request, "pull_request", Some(&url), None)
{
surface.session.record_error(&format!(
"failed to record pull_request decision for {request}: {e}"
));
}
Ok(url)
}
Err(e) => {
surface.session.record_error(&format!(
"pull request failed for {request} ({}): {e}",
record.branch
));
Err(RequestActionError::Internal(e))
}
}
}
fn request_action_error_message(err: RequestActionError) -> String {
match err {
RequestActionError::BadRequest(msg)
| RequestActionError::NotOwned(msg)
| RequestActionError::Conflict(msg)
| RequestActionError::Internal(msg) => msg,
}
}
pub fn verify_auto_publish_branch(
root: &Path,
request: &str,
branch: &str,
) -> Result<String, String> {
let record = load_combine_record(root, request)?
.ok_or_else(|| format!("combine record for request {request} is missing"))?;
let expected = combine_record_tip(&record).to_string();
crate::publish::verify_branch_commit(root, branch, &expected)?;
Ok(expected)
}
pub fn publish_request_with_approval(
surface: &Surface,
approver: &dyn blyte_agent::approval::Approver,
request: &str,
title: &str,
body: &str,
) -> Result<String, String> {
if let Some(started_by) = blyte_agent::tools::blyte_started_by() {
return Err(format!(
"cannot publish during a turn started by another surface ({started_by})"
));
}
let trimmed_title = title.trim();
if trimmed_title.is_empty() {
return Err("publish title must not be blank".to_string());
}
if title.chars().count() > blyte_agent::tools::PUBLISH_TITLE_MAX_CHARS {
return Err(format!(
"publish title must be at most {} characters",
blyte_agent::tools::PUBLISH_TITLE_MAX_CHARS
));
}
if body.len() > blyte_agent::tools::PUBLISH_BODY_MAX_BYTES {
return Err(format!(
"publish body must be at most {} bytes",
blyte_agent::tools::PUBLISH_BODY_MAX_BYTES
));
}
crate::dispatch::validate_request_id(request)?;
match check_request_ownership(surface, request) {
Ok(RequestOwnership::Owned) => {}
Ok(RequestOwnership::OtherSurface) => {
return Err(format!("request {request} belongs to another surface"));
}
Ok(RequestOwnership::Unowned) => {
return Err(format!("request {request} was not started by this surface"));
}
Ok(RequestOwnership::NotFound) => {
return Err(format!("unknown request {request}"));
}
Err(RequestOwnershipError::Mixed(msg)) | Err(RequestOwnershipError::IoOrParse(msg)) => {
return Err(msg);
}
}
if surface.requests.is_combining(request) {
return Err(format!("request {request} is still combining"));
}
let statuses = list_requests(surface)?;
let status = statuses
.into_iter()
.find(|s| s.request == request)
.ok_or_else(|| format!("unknown request {request}"))?;
if status.state != "combined" {
return Err(format!(
"request {request} is not ready to publish (state: {})",
status.state
));
}
if status.pushed {
if let Some(url) = status.pull_request_url {
return Err(format!(
"request {request} already has an open pull request ({url})"
));
}
}
let publish_approval = crate::config::load_with_fallback(&surface.root)?
.map(|(cfg, _)| cfg.surface.publish)
.unwrap_or_default();
let branch = status
.branch
.ok_or_else(|| format!("request {request} has no combined branch"))?;
let (_publish_guard, commit) = match publish_approval {
crate::config::PublishApproval::Ask => {
if surface.session.has_pending_publish(request) {
return Err(format!(
"a publish approval for request {request} is already waiting"
));
}
let publish_guard = surface.requests.try_begin_publish(request).ok_or_else(|| {
format!("a publish approval for request {request} is already waiting")
})?;
if surface.session.has_pending_publish(request) {
return Err(format!(
"a publish approval for request {request} is already waiting"
));
}
let remote_url = crate::publish::origin_remote_url(&surface.root)?;
let base = crate::publish::default_branch(&surface.root)?;
let commit = crate::publish::branch_commit(&surface.root, &branch)?;
let commits = crate::publish::branch_commit_subjects(&surface.root, &branch, &base)?;
let details = blyte_agent::approval::PublishDetails {
request: request.to_string(),
remote_url,
branch: branch.clone(),
base,
commit: commit.clone(),
commits,
title: trimmed_title.to_string(),
body: body.to_string(),
};
match approver.ask_publish(&details) {
blyte_agent::approval::Approval::Approved => {}
blyte_agent::approval::Approval::Denied => {
return Err("the user declined".to_string());
}
blyte_agent::approval::Approval::Unavailable => {
return Err("publish approval is not available here".to_string());
}
}
crate::publish::verify_branch_commit(&surface.root, &branch, &commit)?;
(Some(publish_guard), commit)
}
crate::config::PublishApproval::Auto => {
let commit = verify_auto_publish_branch(&surface.root, request, &branch)?;
(None, commit)
}
};
let published = load_published_record(&surface.root, request)?;
let already_pushed = published.pushed_commit.as_deref() == Some(commit.as_str());
if !already_pushed {
push_request(surface, request).map_err(request_action_error_message)?;
}
match open_request_pull_request(surface, request, trimmed_title, body) {
Ok(url) => {
let mut notice = format!("Published {request}: branch {branch}, {url}");
if publish_approval == crate::config::PublishApproval::Auto {
notice.push_str(" (not asked: [surface] publish = \"auto\")");
}
if let Err(e) = surface
.session
.record_decision(request, "publish", Some(¬ice), None)
{
surface.session.record_error(&format!(
"failed to record publish notice for {request}: {e}"
));
}
Ok(url)
}
Err(err) => {
let detail = request_action_error_message(err);
if already_pushed {
Err(format!(
"branch {branch} was already pushed at {commit}, but opening the pull request failed: {detail}"
))
} else {
Err(format!(
"push succeeded for {branch} ({commit}), but opening the pull request failed: {detail}"
))
}
}
}
}
pub struct SurfacePublishTool {
surface: Arc<Surface>,
approver: Arc<dyn blyte_agent::approval::Approver>,
}
impl SurfacePublishTool {
pub fn new(surface: Arc<Surface>) -> Self {
let approver: Arc<dyn blyte_agent::approval::Approver> = surface.session.approver();
Self { surface, approver }
}
}
impl blyte_agent::tools::PublishTool for SurfacePublishTool {
fn publish(&self, request: &str, title: &str, body: &str) -> Result<String, String> {
publish_request_with_approval(&self.surface, self.approver.as_ref(), request, title, body)
}
}