diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 02e5f8851..937a175b0 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -3511,6 +3511,17 @@ "null" ] }, + "draft_hold": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunDraftHold", + "description": "Set when the run finished and its pull request is still a draft: why,\nand what to do about each reason. A held run is also `needs_input`,\nwith `waiting_on` naming the pull request. Null once the pull request\nis ready or closed." + } + ] + }, "duration_s": { "description": "How long the run took, in seconds.", "examples": [ @@ -4137,6 +4148,82 @@ ], "type": "object" }, + "RunDraftHold": { + "description": "Why a finished run's pull request is still a draft, with what to do\nabout each reason. A finished run never leaves its pull request a draft\nwithout one of these.", + "properties": { + "kind": { + "description": "`held` (a person must deal with a reason; the run is `needs_input`),\n`waiting` (CoderHelm waits for something that settles by itself and\nchecks again), or `failed` (CoderHelm decided it was ready but GitHub\nrefused every try to mark it).", + "examples": [ + "held" + ], + "type": "string" + }, + "pr_number": { + "description": "The pull request.", + "examples": [ + 318 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "reasons": { + "description": "Each reason, with what to do about it.", + "items": { + "$ref": "#/components/schemas/RunDraftHoldReason" + }, + "type": "array" + }, + "since": { + "description": "When it was first held for these reasons (RFC 3339).", + "examples": [ + "2026-11-06T22:17:25Z" + ], + "type": [ + "string", + "null" + ] + }, + "summary": { + "description": "The run page's line, ready to show.", + "examples": [ + "Finished, but pull request #318 stays a draft: Security items are open under Open items. Fix them on this branch (CoderHelm checks again on the next push), or delete each security line once a person has checked it." + ], + "type": "string" + } + }, + "required": [ + "kind", + "summary", + "reasons", + "pr_number" + ], + "type": "object" + }, + "RunDraftHoldReason": { + "description": "One reason a pull request stays a draft.", + "properties": { + "todo": { + "description": "What to do about it.", + "examples": [ + "Fix them on this branch (CoderHelm checks again on the next push), or delete each security line once a person has checked it." + ], + "type": "string" + }, + "what": { + "description": "What holds it.", + "examples": [ + "Security items are open under Open items" + ], + "type": "string" + } + }, + "required": [ + "what", + "todo" + ], + "type": "object" + }, "RunNote": { "description": "A note the run wrote while it worked.", "properties": { diff --git a/docs/incidents.md b/docs/incidents.md index 4ad7bb968..09b62064a 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -48,6 +48,7 @@ pipeline still calls it there. | p. `p_finished_work_loop` | A small ticket finished its 11 tasks, then spent 2.5 hours and $41.96 with no pull request: each 15-minute step re-ran the checks before the pull request from nothing and started fresh fix rounds. | The draft pull request opens before the proof check, the rules and the review, which then can't block it. A check runs once on a head and keeps its rounds across steps. A run with no real progress (tasks, the pull request, CI green, fewer findings) ends one way: a draft with Open items, waiting on a person. | | q. `q_run_ceiling` | The same bug had been fixed in one loop at a time. | A run has an absolute ceiling on passes, continuations, worked time and spend that only a person's Retry renews, held at the worker's one entry point, at every model call, and by the stuck-run sweep, each without the others. | | r. `r_github_limit` | A fix round hit GitHub's hourly limit. 29 writes and the diff came back "403 rate limit exceeded", and the run ended "the coder wrote no file ... That is CoderHelm's miss". | GitHub refusing for a while (its rate limit, a 5xx, no answer) never ends a run and is never blamed on the coder. The model is told the run pauses, the pass ends, and the run goes on as itself at GitHub's reset, with its page saying when. The wait adds no step and no pass. Writes GitHub rejected for a real reason are reported with that reason. A review waits for the reset without spending its retries. | +| s. `s_silent_draft` | A new-feature run finished with CI green and CoderHelm's review approving, and its pull request stayed a draft. Four of CoderHelm's own sandbox checks had failed on the head, the mark-ready step returned without a word, and the run page said completed. The same day, mark-ready messages that hit GitHub's rate limit were dropped and five more pull requests stayed drafts. | One decision settles every pull request a finished run leaves, on every path. With CI green and the review approving, CoderHelm's own sandbox failures and checklist items never hold the draft: the pull request is marked ready with them under Open items. A hold that remains names each reason and what to do at the top of the description, at warn in the log, and on the run, which is `needs_input` while a person must act. A mark-ready GitHub refuses is tried again after its reset, a bounded number of times, and the last refusal is recorded on the run. A sweep decides again for finished runs left a draft with no recorded reason, respecting a person's draft and a closed pull request. | ## Adding a case diff --git a/services/common/src/draft_hold.rs b/services/common/src/draft_hold.rs new file mode 100644 index 000000000..fbd0d283d --- /dev/null +++ b/services/common/src/draft_hold.rs @@ -0,0 +1,305 @@ +//! Why a finished run's pull request is still a draft, on the run record. +//! +//! A run once finished with CI green and CoderHelm's review approving, and +//! its pull request stayed a draft: CoderHelm's own sandbox checks had +//! failed on that head, the mark-ready step returned without a word, and the +//! run page said "completed". Nobody was told why the pull request wasn't +//! ready. Other mark-ready messages failed on GitHub's rate limit and were +//! dropped, with the same silent result. +//! +//! The rules: +//! +//! - every time CoderHelm decides a finished run's pull request stays a +//! draft, the reasons go on the run as a [`DraftHold`] (`draft_hold`), +//! each with what a person can do about it; +//! - a hold a person must act on ([`Kind::Held`], [`Kind::Failed`]) also +//! sets the run to `needs_input`, with a [`crate::run_wait::WaitingOn`] +//! that names the pull request and the reasons, so the run never reads +//! as plain "completed" while its pull request is held; +//! - a wait CoderHelm settles by itself ([`Kind::Waiting`]) leaves the +//! status alone and says what it waits for; +//! - once the pull request is ready (or closed), the hold is removed and +//! `draft_settled` says how it ended, so the sweep stops looking at it. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use serde::{Deserialize, Serialize}; + +/// Run attribute holding the [`DraftHold`] JSON. +pub const FIELD: &str = "draft_hold"; +/// Run attribute set once the run's pull request left draft or was closed +/// (`ready`, `closed`): nothing holds it any more. +pub const FIELD_SETTLED: &str = "draft_settled"; + +const MAX_WHAT: usize = 600; +const MAX_TODO: usize = 400; +const MAX_REASONS: usize = 8; + +/// What kind of hold it is. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + /// Something a person must decide or fix keeps it a draft. + #[default] + Held, + /// CoderHelm waits for something that settles by itself (a repeat run, + /// checks still running) and checks again on its own. + Waiting, + /// CoderHelm decided it was ready but couldn't mark it: GitHub kept + /// refusing through every retry. + Failed, +} + +/// One reason, with what a person can do about it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Reason { + /// What holds it, in plain words. + pub what: String, + /// What to do about it, in plain words. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub todo: String, +} + +fn one_line(s: &str, max: usize) -> String { + let s = s.split_whitespace().collect::>().join(" "); + crate::truncate_str(&s, max).to_string() +} + +impl Reason { + pub fn new(what: impl AsRef, todo: impl AsRef) -> Self { + Reason { + what: one_line(what.as_ref(), MAX_WHAT), + todo: one_line(todo.as_ref(), MAX_TODO), + } + } + + /// `what. todo`, one sentence each. + pub fn line(&self) -> String { + let what = self.what.trim().trim_end_matches('.'); + if self.todo.is_empty() { + format!("{what}.") + } else { + format!("{what}. {}", self.todo.trim()) + } + } +} + +/// Why a finished run's pull request is still a draft. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct DraftHold { + pub kind: Kind, + /// Never empty: a hold always names its reason. + pub reasons: Vec, + #[serde(default)] + pub pr_number: u64, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub pr_url: String, + /// When the pull request was first held for these reasons (RFC 3339). + #[serde(default)] + pub since: String, + /// When CoderHelm last decided (RFC 3339): the sweep decides again once + /// this is old. + #[serde(default)] + pub checked_at: String, +} + +impl DraftHold { + /// A hold, or `None` when there is no reason: a hold is never for + /// nothing. + pub fn new(kind: Kind, reasons: Vec, pr_number: u64, pr_url: &str) -> Option { + let mut reasons: Vec = reasons + .into_iter() + .filter(|r| !r.what.trim().is_empty()) + .collect(); + reasons.dedup(); + reasons.truncate(MAX_REASONS); + if reasons.is_empty() { + return None; + } + let now = chrono::Utc::now().to_rfc3339(); + Some(DraftHold { + kind, + reasons, + pr_number, + pr_url: pr_url.trim().to_string(), + since: now.clone(), + checked_at: now, + }) + } + + /// Keeps the earlier `since` when the reasons are the same ones. + pub fn continuing(mut self, before: Option<&DraftHold>) -> Self { + if let Some(b) = before { + if b.kind == self.kind && b.reasons == self.reasons && !b.since.is_empty() { + self.since = b.since.clone(); + } + } + self + } + + /// Whether a person must act (the run waits on them). + pub fn needs_person(&self) -> bool { + matches!(self.kind, Kind::Held | Kind::Failed) + } + + fn pr_words(&self) -> String { + if self.pr_number > 0 { + format!("pull request #{}", self.pr_number) + } else { + "the pull request".to_string() + } + } + + /// What the run page says, in one line: "Finished, but the PR stays a + /// draft: . ". + pub fn summary(&self) -> String { + let reasons = self + .reasons + .iter() + .map(Reason::line) + .collect::>() + .join(" "); + match self.kind { + Kind::Held => format!("Finished, but {} stays a draft: {reasons}", self.pr_words()), + Kind::Waiting => format!( + "Finished; {} stays a draft for now: {reasons} CoderHelm checks again by itself \ + and marks it ready when that is done.", + self.pr_words() + ), + Kind::Failed => format!( + "Finished, and {} should be ready, but CoderHelm couldn't mark it: {reasons}", + self.pr_words() + ), + } + } + + /// What a held run waits for from a person. + pub fn waiting_on(&self) -> crate::run_wait::WaitingOn { + let detail = self + .reasons + .iter() + .map(Reason::line) + .collect::>() + .join("\n"); + let action = if self.pr_number > 0 { + format!( + "Deal with what keeps pull request #{} a draft", + self.pr_number + ) + } else { + "Deal with what keeps the pull request a draft".to_string() + }; + crate::run_wait::WaitingOn::action(&action, &detail, &self.pr_url).unwrap_or_else(|| { + crate::run_wait::WaitingOn::fixed( + "Deal with what keeps the pull request a draft", + &detail, + &self.pr_url, + ) + }) + } + + pub fn to_attr(&self) -> AttributeValue { + AttributeValue::S(serde_json::to_string(self).unwrap_or_default()) + } + + /// Read back from a run record. `None` when absent, unreadable or + /// without a reason. + pub fn of_item(item: &HashMap) -> Option { + let h: DraftHold = item + .get(FIELD) + .and_then(|v| v.as_s().ok()) + .and_then(|s| serde_json::from_str(s).ok())?; + (!h.reasons.is_empty()).then_some(h) + } + + /// Whether the last decision is older than `secs` at `now`. + pub fn stale(&self, secs: i64, now: chrono::DateTime) -> bool { + chrono::DateTime::parse_from_rfc3339(&self.checked_at) + .map(|t| (now - t.with_timezone(&chrono::Utc)).num_seconds() >= secs) + .unwrap_or(true) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_hold_always_names_its_reason() { + assert_eq!(DraftHold::new(Kind::Held, vec![], 5, ""), None); + assert_eq!( + DraftHold::new(Kind::Held, vec![Reason::new(" ", "x")], 5, ""), + None + ); + let h = DraftHold::new( + Kind::Held, + vec![Reason::new( + "Security items are open in the description", + "Fix them on this branch, or delete each line once it is checked.", + )], + 583, + "https://github.com/acme/api/pull/583", + ) + .unwrap(); + assert_eq!( + h.summary(), + "Finished, but pull request #583 stays a draft: Security items are open in the \ + description. Fix them on this branch, or delete each line once it is checked." + ); + assert!(h.needs_person()); + let w = h.waiting_on(); + assert_eq!(w.action, "Deal with what keeps pull request #583 a draft"); + assert!(w.detail.contains("Security items")); + assert_eq!(w.url, "https://github.com/acme/api/pull/583"); + } + + #[test] + fn a_wait_says_coderhelm_goes_on_by_itself() { + let h = DraftHold::new( + Kind::Waiting, + vec![Reason::new( + "The repeat run of the affected test hasn't passed yet", + "", + )], + 9, + "", + ) + .unwrap(); + assert!(!h.needs_person()); + assert!(h.summary().contains("CoderHelm checks again by itself")); + } + + #[test] + fn it_round_trips_and_keeps_its_start_while_the_reasons_stay() { + let r = vec![Reason::new("a", "b")]; + let mut first = DraftHold::new(Kind::Held, r.clone(), 1, "").unwrap(); + first.since = "2026-11-06T22:17:00Z".into(); + let item: HashMap = + [(FIELD.to_string(), first.to_attr())].into_iter().collect(); + assert_eq!(DraftHold::of_item(&item), Some(first.clone())); + let again = DraftHold::new(Kind::Held, r, 1, "") + .unwrap() + .continuing(Some(&first)); + assert_eq!(again.since, "2026-11-06T22:17:00Z"); + let other = DraftHold::new(Kind::Held, vec![Reason::new("c", "")], 1, "") + .unwrap() + .continuing(Some(&first)); + assert_ne!(other.since, "2026-11-06T22:17:00Z"); + } + + #[test] + fn a_decision_goes_stale() { + let mut h = DraftHold::new(Kind::Held, vec![Reason::new("a", "")], 1, "").unwrap(); + h.checked_at = "2026-11-06T22:00:00Z".into(); + let t = |s: &str| { + chrono::DateTime::parse_from_rfc3339(s) + .unwrap() + .with_timezone(&chrono::Utc) + }; + assert!(!h.stale(3600, t("2026-11-06T22:59:00Z"))); + assert!(h.stale(3600, t("2026-11-06T23:00:00Z"))); + h.checked_at = String::new(); + assert!(h.stale(3600, t("2026-11-06T23:00:00Z"))); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 06ec0a378..266d68144 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -52,6 +52,8 @@ pub mod alert_notify; /// channel, sealed webhook URLs. pub mod notify; +/// Why a finished run's pull request is still a draft, on the run record. +pub mod draft_hold; /// Read-only lookups against a team's own systems (their API today). Shared so /// the dashboard's test path and the reviewer's tool path enforce the same rules. pub mod e2e; diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 82f476d41..2038c279b 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -864,6 +864,28 @@ pub struct MarkReadyMessage { pub repo_owner: String, pub repo_name: String, pub pr_number: u64, + /// The run whose pull request this is, when the sender knows it (else + /// the worker looks it up by the pull request). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub run_id: String, + /// Tries so far that GitHub refused for a while (its rate limit, a 5xx, + /// an unreadable timeline). A refused try is sent again after a delay, + /// up to `common::github_wait::MAX_WAITS`; the last refusal is recorded + /// on the run. + #[serde(default, skip_serializing_if = "is_zero_u32")] + pub attempt: u32, + /// Not before this time (epoch seconds): a wait longer than one SQS + /// delay is sent on in hops until then. + #[serde(default, skip_serializing_if = "is_zero_u64")] + pub not_before: u64, + /// Squash the branch before marking it ready, under the first commit's + /// message when true (the in-run path). Unset: no squash. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub squash_keep_first: Option, +} + +fn is_zero_u64(n: &u64) -> bool { + *n == 0 } /// A force push to `branch` (from `before` to `after`). diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 0fdf05322..4e8e00842 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -929,6 +929,68 @@ pub struct RunWaitingOn { pub since: Option, } +/// Why a finished run's pull request is still a draft, with what to do +/// about each reason. A finished run never leaves its pull request a draft +/// without one of these. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct RunDraftHold { + /// `held` (a person must deal with a reason; the run is `needs_input`), + /// `waiting` (CoderHelm waits for something that settles by itself and + /// checks again), or `failed` (CoderHelm decided it was ready but GitHub + /// refused every try to mark it). + #[schema(example = "held")] + pub kind: String, + /// The run page's line, ready to show. + #[schema( + example = "Finished, but pull request #318 stays a draft: Security items are open under Open items. Fix them on this branch (CoderHelm checks again on the next push), or delete each security line once a person has checked it." + )] + pub summary: String, + /// Each reason, with what to do about it. + pub reasons: Vec, + /// The pull request. + #[schema(example = 318)] + pub pr_number: u64, + /// When it was first held for these reasons (RFC 3339). + #[schema(example = "2026-11-06T22:17:25Z")] + pub since: Option, +} + +/// One reason a pull request stays a draft. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct RunDraftHoldReason { + /// What holds it. + #[schema(example = "Security items are open under Open items")] + pub what: String, + /// What to do about it. + #[schema( + example = "Fix them on this branch (CoderHelm checks again on the next push), or delete each security line once a person has checked it." + )] + pub todo: String, +} + +fn draft_hold_of(item: &run_search::Item) -> Option { + let h = common::draft_hold::DraftHold::of_item(item)?; + Some(RunDraftHold { + kind: match h.kind { + common::draft_hold::Kind::Held => "held", + common::draft_hold::Kind::Waiting => "waiting", + common::draft_hold::Kind::Failed => "failed", + } + .to_string(), + summary: h.summary(), + reasons: h + .reasons + .iter() + .map(|r| RunDraftHoldReason { + what: r.what.clone(), + todo: r.todo.clone(), + }) + .collect(), + pr_number: h.pr_number, + since: Some(h.since).filter(|s| !s.is_empty()), + }) +} + fn waiting_on_of(item: &run_search::Item) -> Option { let w = common::run_wait::WaitingOn::of_item(item)?; Some(RunWaitingOn { @@ -1181,6 +1243,12 @@ pub struct Run { /// request). A run never waits on a person for nothing. #[schema(example = json!(null))] pub waiting_on: Option, + /// Set when the run finished and its pull request is still a draft: why, + /// and what to do about each reason. A held run is also `needs_input`, + /// with `waiting_on` naming the pull request. Null once the pull request + /// is ready or closed. + #[schema(example = json!(null))] + pub draft_hold: Option, } /// The public values a run's code generator was missing, as the API shows them. @@ -1721,6 +1789,7 @@ fn run_of( } else { None }, + draft_hold: draft_hold_of(item), } } diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 6c8863b44..ff38d55c2 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -3091,6 +3091,7 @@ async fn handle_workflow_run( repo_owner: repo_owner.to_string(), repo_name: repo_name.to_string(), pr_number, + ..Default::default() }); let _ = send_to_queue(state, &state.config.ticket_queue_url, &message).await; } diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 9dd3f8449..85dd2a068 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -415,10 +415,10 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) } } models::WorkerMessage::MarkReady(msg) => { - info!(team_id = %msg.team_id, pr_number = msg.pr_number, "Marking PR ready"); - if let Err(e) = mark_pr_ready(&state, msg).await { - error!("Mark PR ready failed: {e}"); - } + info!(team_id = %msg.team_id, pr_number = msg.pr_number, attempt = msg.attempt, "Deciding whether the PR leaves draft"); + // One decision for every mark-ready path; a refusal from GitHub + // is sent again, and every hold is recorded (`passes::ready`). + passes::ready::on_message(&state, msg).await; } models::WorkerMessage::PlanExecute(msg) => { info!(team_id = %msg.team_id, plan_id = %msg.plan_id, "Executing plan"); @@ -511,6 +511,15 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) ), Err(e) => error!("Stuck-review sweep failed: {e:?}"), } + // Finished runs whose pull request is still a draft with no + // recorded reason: decided again, so none stays silently held. + let drafts = passes::ready::sweep(&state).await; + info!( + looked_at = drafts.looked_at, + decided = drafts.decided, + prs = ?drafts.settled, + "Draft sweep done" + ); } models::WorkerMessage::ReviewReminder => { info!("Running review-reminder sweep"); @@ -746,85 +755,3 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) models::WorkerMessage::UsageRecord(_) => {} } } - -async fn mark_pr_ready( - state: &WorkerState, - msg: models::MarkReadyMessage, -) -> Result<(), Box> { - let github = clients::github::GitHubClient::new( - &state.secrets.github_app_id, - &state.secrets.github_private_key, - msg.installation_id, - &state.http, - )?; - // Fetch the PR to get its GraphQL node_id (REST PATCH {"draft":false} doesn't work) - let pr = github - .get_pull_request(&msg.repo_owner, &msg.repo_name, msg.pr_number) - .await?; - if pr["state"].as_str() != Some("open") || pr["draft"].as_bool() != Some(true) { - info!( - pr_number = msg.pr_number, - "PR is closed or not a draft — nothing to mark ready" - ); - return Ok(()); - } - // CoderHelm's own review still lists findings it hasn't fixed: the PR - // stays a draft until its fix rounds clear them (`own_review`). - if let Some(why) = pr["body"].as_str().and_then(passes::stack::hold) { - info!(pr_number = msg.pr_number, why = %why, "PR stays a draft"); - return Ok(()); - } - if let Some(why) = pr["body"].as_str().and_then(passes::own_review::hold) { - info!(pr_number = msg.pr_number, why = %why, "PR stays a draft"); - return Ok(()); - } - // A person put this PR back into draft: a CI pass must not undo that. A - // timeline that can't be read leaves the draft alone (fail closed). - let timeline = github - .list_issue_timeline(&msg.repo_owner, &msg.repo_name, msg.pr_number) - .await?; - if let Some(who) = clients::github::human_converted_to_draft(&timeline) { - info!(pr_number = msg.pr_number, converted_by = %who, "PR was put back into draft by a person — not marking ready"); - return Ok(()); - } - // A failing-test fix stays a draft until the checks that test it are - // green on its head and a repeat run passed (this message also brings - // the check back while it waits). - if let passes::test_fix::Hold::Wait(_) = passes::test_fix::ready_gate( - state, - &github, - &msg.team_id, - &msg.repo_owner, - &msg.repo_name, - msg.pr_number, - ) - .await - { - return Ok(()); - } - // A new feature stays a draft until its verification checklist passes. - if passes::feature::ready_hold( - state, - &github, - &msg.team_id, - &msg.repo_owner, - &msg.repo_name, - msg.pr_number, - ) - .await - .is_some() - { - return Ok(()); - } - let node_id = pr - .get("node_id") - .and_then(|v| v.as_str()) - .ok_or("PR missing node_id")?; - github.mark_pr_ready(node_id).await?; - info!( - pr_number = msg.pr_number, - repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), - "PR marked ready for review" - ); - Ok(()) -} diff --git a/services/worker/src/passes/completeness.rs b/services/worker/src/passes/completeness.rs index 6c21c6b2a..2b0130f0c 100644 --- a/services/worker/src/passes/completeness.rs +++ b/services/worker/src/passes/completeness.rs @@ -132,10 +132,14 @@ pub enum Section { /// everything: a reader never ships over an objection without seeing it /// (see [`objections_section`]). Objections, + /// Why the pull request is still a draft, and what to do about it, at + /// the very top (see `ready::status_section`): a finished run never + /// leaves its pull request a draft without saying why here. + DraftStatus, } impl Section { - const ALL: [Section; 9] = [ + const ALL: [Section; 10] = [ Section::Links, Section::Mirrors, Section::MergeOrder, @@ -145,6 +149,7 @@ impl Section { Section::Unfinished, Section::OpenFindings, Section::Objections, + Section::DraftStatus, ]; /// Its start and end markers. @@ -168,6 +173,7 @@ impl Section { Section::Unfinished => (super::proof::UNFINISHED_START, super::proof::UNFINISHED_END), Section::OpenFindings => (super::own_review::START, super::own_review::END), Section::Objections => (OBJECTIONS_START, OBJECTIONS_END), + Section::DraftStatus => (super::ready::STATUS_START, super::ready::STATUS_END), } } } @@ -204,6 +210,7 @@ pub struct Owned { pub unfinished: String, pub open_findings: String, pub objections: String, + pub draft_status: String, } impl Owned { @@ -218,6 +225,7 @@ impl Owned { Section::Unfinished => &mut self.unfinished, Section::OpenFindings => &mut self.open_findings, Section::Objections => &mut self.objections, + Section::DraftStatus => &mut self.draft_status, } } @@ -398,6 +406,16 @@ pub fn assemble(rest: &str, owned: &Owned) -> String { format!("{objections}\n\n{body}") }; } + // Why it is still a draft goes first of all: the reader sees it before + // anything else. + let draft_status = owned.draft_status.trim(); + if !draft_status.is_empty() { + body = if body.is_empty() { + draft_status.to_string() + } else { + format!("{draft_status}\n\n{body}") + }; + } format!("{body}{footer}") } @@ -1182,6 +1200,7 @@ mod tests { unfinished: String::new(), open_findings: String::new(), objections: String::new(), + draft_status: String::new(), links: String::new(), mirrors: mirrors_section(&[Mirror { path: "envs/prod/users.tf".into(), diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index ddf8821b3..f8335a3b1 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -1494,7 +1494,15 @@ async fn follow_fix( let _ = gh .create_issue_comment(&msg.repo_owner, &msg.repo_name, pr, &format!("The fix held: `{}` passed {total} of {total} repeat runs. Ready for review.", r.title)) .await; - super::resume::mark_e2e_pr_ready(gh, &msg.repo_owner, &msg.repo_name, pr).await; + super::resume::mark_e2e_pr_ready( + state, + gh, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + pr, + ) + .await; } } else { r.fix_status = Some("failed".into()); @@ -2102,7 +2110,15 @@ async fn follow_generated( rec.phase = Some("proven".into()); if let Some(pr) = pr { let _ = gh.create_issue_comment(&msg.repo_owner, &msg.repo_name, pr, &format!("The new test passed {GENERATED_RUNS} of {GENERATED_RUNS} repeat runs. Ready for review.")).await; - super::resume::mark_e2e_pr_ready(gh, &msg.repo_owner, &msg.repo_name, pr).await; + super::resume::mark_e2e_pr_ready( + state, + gh, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + pr, + ) + .await; } } } @@ -2122,7 +2138,15 @@ async fn follow_generated( rec.phase = Some("proven".into()); if let Some(pr) = pr { let _ = gh.create_issue_comment(&msg.repo_owner, &msg.repo_name, pr, &format!("The new test passed {GENERATED_RUNS} of {GENERATED_RUNS} repeat runs, and it fails on the code from before the bug fix, so it would have caught the bug. Ready for review.")).await; - super::resume::mark_e2e_pr_ready(gh, &msg.repo_owner, &msg.repo_name, pr).await; + super::resume::mark_e2e_pr_ready( + state, + gh, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + pr, + ) + .await; } } else { rec.phase = Some("failed".into()); diff --git a/services/worker/src/passes/feature/mod.rs b/services/worker/src/passes/feature/mod.rs index 759a1d1d2..0dd0358fa 100644 --- a/services/worker/src/passes/feature/mod.rs +++ b/services/worker/src/passes/feature/mod.rs @@ -861,9 +861,10 @@ pub(crate) async fn load_connection( } } -/// What the rules left failing, as Open items. The checklist already keeps -/// the pull request a draft until it passes (`ready_hold`), so these only say -/// what is open. +/// What the rules left failing, as Open items. They keep the pull request a +/// draft only until the repository's CI is green and CoderHelm's review +/// approved (`ready::decide`); then it is marked ready with them still +/// listed, for a person to look at. pub fn open_findings(f: &PrFacts) -> Vec { checklist::failing(&f.checklist) .into_iter() @@ -876,7 +877,8 @@ pub fn open_findings(f: &PrFacts) -> Vec { .map(|detail| super::proof::Finding { point: "rule_failing".to_string(), detail, - settle: "Fix it on this branch; the pull request stays a draft until the rules pass." + settle: "Fix it on this branch, or judge it fine: once CI is green and the review \ + approved, the pull request is marked ready with this still listed." .to_string(), ..Default::default() }) @@ -1327,9 +1329,36 @@ pub async fn register_pr( } } -/// Why a feature pull request stays a draft, read from its head now: the -/// checklist's diff items fail, or the sandbox checks failed on this same -/// head. `None` when it may leave draft (or isn't a feature pull request). +/// What CoderHelm's own checks of a feature pull request still find on its +/// head: sandbox checks that failed on this same head, and checklist items +/// that fail. Every checklist item here is about tests (their count, specs, +/// test maps, responsive checks), none a correctness, security or data-loss +/// finding, so `ready::decide` weighs them against the repository's CI and +/// the review instead of letting them hold the draft alone. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FeatureHold { + pub sandbox_failed: Vec, + pub checklist_fails: Vec, +} + +impl FeatureHold { + /// Every item, one line each. + pub fn items(&self) -> Vec { + self.sandbox_failed + .iter() + .map(|l| format!("CoderHelm's sandbox check failed: {l}")) + .chain( + self.checklist_fails + .iter() + .map(|l| format!("Verification checklist: {l}")), + ) + .collect() + } +} + +/// What CoderHelm's own checks still find on a feature pull request's head +/// ([`FeatureHold`]). `None` when nothing (or it isn't a feature pull +/// request, or what it needs can't be read: a read failure never holds). pub async fn ready_hold( state: &WorkerState, github: &GitHubClient, @@ -1337,7 +1366,7 @@ pub async fn ready_hold( owner: &str, repo: &str, pr: u64, -) -> Option { +) -> Option { let full = format!("{owner}/{repo}"); let item = state .dynamo @@ -1353,13 +1382,24 @@ pub async fn ready_hold( let p = github.get_pull_request(owner, repo, pr).await.ok()?; let sha = p["head"]["sha"].as_str().unwrap_or("").to_string(); let base = p["base"]["ref"].as_str().unwrap_or("main").to_string(); - if sha == r.sha && !r.sandbox_failed.is_empty() { - return Some(r.sandbox_failed.join("; ")); - } - let files = github + let sandbox_failed = if sha == r.sha { + r.sandbox_failed.clone() + } else { + Vec::new() + }; + let held = |checklist_fails: Vec| { + let h = FeatureHold { + sandbox_failed: sandbox_failed.clone(), + checklist_fails, + }; + (!h.items().is_empty()).then_some(h) + }; + let Ok(files) = github .compare_files_with_patches(owner, repo, &base, &sha) .await - .ok()?; + else { + return held(Vec::new()); + }; let mut facts = r.facts.clone(); facts.cases_added = checklist::unit_cases_added(&files); facts.responsive_specs.clear(); @@ -1386,12 +1426,11 @@ pub async fn ready_hold( .map(|(m, s)| format!("{m}: {s}")) .collect(); let fails = checklist::failing(&checklist::static_items(&facts)); - if fails.is_empty() { - None - } else { - info!(pr, fails = ?fails, "Feature checklist fails; the PR stays a draft"); - Some(fails.join("; ")) + let h = held(fails); + if let Some(h) = &h { + info!(pr, sandbox_failed = ?h.sandbox_failed, checklist_fails = ?h.checklist_fails, "CoderHelm's own feature checks still find items on the head"); } + h } #[cfg(test)] diff --git a/services/worker/src/passes/incidents/i_finished_work_pr.rs b/services/worker/src/passes/incidents/i_finished_work_pr.rs index 9444e5404..35b702eca 100644 --- a/services/worker/src/passes/incidents/i_finished_work_pr.rs +++ b/services/worker/src/passes/incidents/i_finished_work_pr.rs @@ -123,7 +123,7 @@ fn planned_work_left_opens_a_draft_then_coderhelm_finishes_it() { assert!(gh.pr(21).draft); assert_eq!( draft_hold(&gh.pr(21).body, "Add the card block", false), - Some("planned work not done is listed in the description") + Some("Planned work is not done yet (listed under Not finished)".to_string()) ); assert!(gh .pr(21) diff --git a/services/worker/src/passes/incidents/k_own_review_findings.rs b/services/worker/src/passes/incidents/k_own_review_findings.rs index daf5d61b1..3c9fbe94c 100644 --- a/services/worker/src/passes/incidents/k_own_review_findings.rs +++ b/services/worker/src/passes/incidents/k_own_review_findings.rs @@ -93,15 +93,15 @@ fn the_own_review_requests_changes_and_lists_every_non_optional_finding() { ), 0, )); - // While they are listed the PR stays a draft: neither mark-ready path - // goes on. + // While they are listed the PR stays a draft: every mark-ready path + // goes through the one decision, which holds on them. assert!(draft_hold(&body, "Keep the text", true).is_some()); + let ready = include_str!("../ready.rs"); + let holds = fn_src(ready, "pub fn body_holds("); + assert!(holds.contains("own_review::hold(body)")); + assert!(fn_src(ready, "pub fn decide(").contains("body_holds(&f.body)")); let main = include_str!("../../main.rs"); - let mark = fn_src(main, "\nasync fn mark_pr_ready("); - let gate = mark - .find("own_review::hold") - .expect("mark_pr_ready checks own_review::hold"); - assert!(gate < mark.find("github.mark_pr_ready(").unwrap()); + assert!(main.contains("passes::ready::on_message(&state, msg)")); // The run gets them as a fix round, not a completion. let rr = RunReview { verdict: "APPROVE", diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index adb80bbe0..723815ca3 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -33,3 +33,4 @@ mod o_mention_resumes_held_work; mod p_finished_work_loop; mod q_run_ceiling; mod r_github_limit; +mod s_silent_draft; diff --git a/services/worker/src/passes/incidents/s_silent_draft.rs b/services/worker/src/passes/incidents/s_silent_draft.rs new file mode 100644 index 000000000..fa9d51a75 --- /dev/null +++ b/services/worker/src/passes/incidents/s_silent_draft.rs @@ -0,0 +1,260 @@ +//! s. A new-feature run checked its rules on the pull request: one checklist +//! item failing, then after a fix round none, but four of CoderHelm's own +//! sandbox checks failing on the new head. The repository's CI passed, the +//! review ran and approved, and the run logged "Review passed — completing +//! run", "Run completed" and "Run handed its PR over — review queued". No +//! "PR marked ready" and no "stays a draft" line was ever logged: the +//! mark-ready step had returned on the sandbox failures without a word. The +//! pull request stayed a draft, the run page said completed, and nobody was +//! told why. The same day, mark-ready messages that hit GitHub's rate limit +//! were logged as "Mark PR ready failed" and dropped, leaving five more pull +//! requests drafts. +//! +//! Guarantee: one decision (`ready::decide`) settles every pull request a +//! finished run leaves, on every path. With the repository's CI green and +//! CoderHelm's review approving, CoderHelm's own sandbox failures and +//! checklist items never hold the draft: the pull request is marked ready +//! with them under Open items. A hold that remains names each reason and +//! what to do, at the top of the description, at warn in the log, and on the +//! run, which is `needs_input` (never plain completed) while a person must +//! act. A mark-ready GitHub refuses is sent again after its reset, a bounded +//! number of times, and the last refusal is recorded on the run. A sweep +//! decides again for finished runs whose pull request is still a draft with +//! no recorded reason, so earlier casualties heal by themselves. + +use super::fixture::*; +use crate::models::{MarkReadyMessage, WorkerMessage}; +use crate::passes::feature::FeatureHold; +use crate::passes::ready::{self, Ci, Decision, Facts}; +use common::draft_hold::{DraftHold, Kind, Reason}; + +/// Nothing was said: the old failure is the absence of any line. +const OLD: &str = "Mark PR ready failed"; + +fn the_four_sandbox_failures() -> FeatureHold { + FeatureHold { + sandbox_failed: vec![ + "`pnpm test --filter api`: 3 failed".into(), + "`pnpm lint`: 2 errors".into(), + "`pnpm typecheck`: 1 error".into(), + "`pnpm test:e2e card`: 1 failed".into(), + ], + checklist_fails: vec![], + } +} + +fn the_pull_request_at_completion() -> Facts { + Facts { + draft: true, + title: "GH-41: Add the card block".into(), + body: "## Summary\nAdds the card block.\n\n## Verification\n- CI.".into(), + feature: Some(the_four_sandbox_failures()), + // The repository's CI on the head, CoderHelm's own review check left out. + ci: ready::ci_standing( + &[ + serde_json::json!({"name": "build", "status": "completed", "conclusion": "success", + "started_at": "2026-11-06T22:15:00Z", "app": {"slug": "github-actions"}}), + serde_json::json!({"name": "test", "status": "completed", "conclusion": "success", + "started_at": "2026-11-06T22:15:00Z", "app": {"slug": "github-actions"}}), + serde_json::json!({"name": common::review_check::CHECK_NAME, "status": "completed", + "conclusion": "success", "started_at": "2026-11-06T22:17:00Z", + "app": {"slug": "coderhelm"}}), + ], + &[], + ), + approved: true, + ..Default::default() + } +} + +#[test] +fn a_green_approved_pr_is_marked_ready_with_the_sandbox_failures_listed() { + let mut end = Ending { + status: "completed".into(), + pr: Some(21), + draft: true, + ..Default::default() + }; + let f = the_pull_request_at_completion(); + assert_eq!( + f.ci, + Ci { + green: true, + why: String::new() + } + ); + let d = ready::decide(&f); + let open = match &d { + Decision::Ready { open } => open.clone(), + other => panic!("held on CoderHelm's own sandbox: {other:?}"), + }; + assert_eq!(open.len(), 4); + end.draft = false; + let body = ready::body_for(&f.body, &d).expect("the description lists them"); + assert!(body.contains("## Open items")); + for o in &open { + assert!(body.contains(o.as_str()), "{o} in {body}"); + } + assert!(body.contains("this doesn't keep the draft: look at it before merging")); + assert!(!body.contains(ready::STATUS_START)); + end.said(body); + assert!(!end.draft); + assert_eq!(end.status, "completed"); + end.never_says(OLD); +} + +#[test] +fn a_hold_that_remains_is_named_everywhere_and_the_run_waits_on_a_person() { + let mut end = Ending { + status: "completed".into(), + pr: Some(21), + draft: true, + ..Default::default() + }; + // The same pull request with CI red: the sandbox failures hold, by name. + let f = Facts { + ci: Ci { + green: false, + why: "CI fails on this head: `test`".into(), + }, + ..the_pull_request_at_completion() + }; + let d = ready::decide(&f); + let Decision::Held { reasons } = &d else { + panic!("{d:?}") + }; + // The description says it at the top, with what to do. + let body = ready::body_for(&f.body, &d).unwrap(); + assert!(body.starts_with(ready::STATUS_START), "{body}"); + assert!(body.contains("**This pull request stays a draft.**")); + assert!(body.contains("`pnpm lint`: 2 errors")); + assert!(body.contains("mark it ready yourself")); + end.said(body); + // The run says it, and waits on a person instead of reading completed. + let hold = DraftHold::new( + Kind::Held, + reasons.clone(), + 21, + "https://github.com/acme/site/pull/21", + ) + .unwrap(); + assert!(hold.needs_person()); + let summary = hold.summary(); + assert!(summary.starts_with("Finished, but pull request #21 stays a draft: ")); + assert!(summary.contains("CI fails on this head: `test`")); + end.said(summary); + let wait = hold.waiting_on(); + assert_eq!(wait.action, "Deal with what keeps pull request #21 a draft"); + end.status = common::run_status::NEEDS_INPUT.into(); + end.said(wait.line()); + assert_eq!(end.status, "needs_input"); + assert!(end.draft); + end.never_says(OLD); +} + +#[test] +fn every_path_goes_through_the_one_decision_and_no_hold_returns_silently() { + // The run's own completion and the mark-ready message. + let resume = include_str!("../resume.rs"); + let mark = fn_src(resume, "pub(crate) async fn mark_pr_ready("); + assert!(mark.contains("super::ready::settle(&ctx)")); + assert!(!mark.contains("return;"), "no early silent return"); + assert!(fn_src(resume, "pub(crate) async fn ready_or_prove(").contains("ready::settle(&ctx)")); + assert!( + fn_src(resume, "pub(crate) async fn mark_e2e_pr_ready(").contains("ready::settle(&ctx)") + ); + let main = include_str!("../../main.rs"); + assert!(main.contains("passes::ready::on_message(&state, msg)")); + assert!(!main.contains("\nasync fn mark_pr_ready(")); + // Each outcome is said: a hold at warn, on the description and the run. + let src = include_str!("../ready.rs"); + let settle = fn_src(src, "pub async fn settle("); + let held = &settle[settle.find("Decision::Held { reasons } => {").unwrap()..]; + let held = &held[..held.find("Decision::Wait").unwrap()]; + assert!(held.contains("warn!(")); + assert!(held.contains("write_body(")); + assert!(held.contains("record_hold(")); + // A run that finishes after its hold was recorded is needs_input. + let end_run = fn_src(resume, "\nasync fn end_run("); + assert!(end_run.contains("ready::after_completion(state, &msg.team_id, run_id)")); + // The sweep runs with the stuck-review sweep. + assert!(main.contains("passes::ready::sweep(&state)")); +} + +#[test] +fn a_refused_mark_ready_is_tried_again_and_the_last_refusal_is_recorded() { + let mut end = Ending { + status: "completed".into(), + pr: Some(1387), + draft: true, + ..Default::default() + }; + // The message that was dropped, as the webhook sent it: it still parses. + let old = r#"{"type":"mark_ready","team_id":"TEAM#1","installation_id":41,"repo_owner":"acme","repo_name":"web","pr_number":1387}"#; + let WorkerMessage::MarkReady(m) = serde_json::from_str::(old).unwrap() else { + panic!() + }; + assert_eq!(m.attempt, 0); + // GitHub's limit: the next try waits for the reset, a bounded number of + // times. + let src = include_str!("../ready.rs"); + let retry = fn_src(src, "async fn retry_or_give_up("); + assert!(retry.contains("attempt <= common::github_wait::MAX_WAITS")); + assert!(retry.contains("not_before: common::github_wait::until(now, r.wait_secs)")); + assert!(retry.contains("Kind::Failed")); + let next = MarkReadyMessage { + attempt: m.attempt + 1, + ..m + }; + assert_eq!(next.attempt, 1); + // An unreadable timeline is a try again, never "leave the draft as is". + let gather = fn_src(src, "async fn gather("); + assert!(gather.contains("the pull request's timeline couldn't be read")); + assert!(!src.contains("leaving the draft as is")); + // After every try: recorded on the run like a hold, with what to do. + let failed = DraftHold::new( + Kind::Failed, + vec![Reason::new( + "GitHub didn't mark it ready (GitHub's rate limit) on each of 8 tries", + "Mark it ready for review on GitHub yourself; CoderHelm also tries again within the \ + hour.", + )], + 1387, + "", + ) + .unwrap(); + assert!(failed.needs_person()); + end.status = common::run_status::NEEDS_INPUT.into(); + end.said(failed.summary()); + assert!(end.says("couldn't mark it: GitHub didn't mark it ready (GitHub's rate limit)")); + end.never_says(OLD); +} + +#[test] +fn the_sweep_heals_a_finished_run_left_a_draft_with_no_reason() { + let now = chrono::Utc::now(); + let casualty = ready::Candidate { + team_id: "TEAM#1".into(), + run_id: "01RUNDRAFT".into(), + status: "completed".into(), + owner: OWNER.into(), + repo: REPO.into(), + pr: 21, + installation_id: 41, + hold: None, + }; + assert_eq!(ready::sweep_step(&casualty, now), ready::SweepStep::Decide); + // A person's draft and a closed pull request are respected by the + // decision it makes. + let theirs = Facts { + put_back_by: Some("dana".into()), + ..the_pull_request_at_completion() + }; + assert!(matches!(ready::decide(&theirs), Decision::Held { reasons } + if reasons[0].what == "`dana` put it back to draft")); + let closed = Facts { + closed: true, + ..the_pull_request_at_completion() + }; + assert_eq!(ready::decide(&closed), Decision::Closed); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 0ab8e6e38..99a3a7f54 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1088,6 +1088,8 @@ pub mod pr_outcomes; mod pr_risk; mod proof; pub mod quarantine; +/// Whether a finished run's pull request leaves draft, decided in one place. +pub mod ready; pub mod relay_retry; pub mod release_notes; pub mod release_plan; diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index a335a2b6a..333910da3 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -1583,6 +1583,7 @@ fn owned_sections(plan: &PlanResult, proof: &Proof<'_>, repo: &str) -> super::co review_fixes: String::new(), open_findings: String::new(), objections: String::new(), + draft_status: String::new(), // A small failing-test fix carries no open items or questions. open_items: if small_test_fix { String::new() diff --git a/services/worker/src/passes/proof.rs b/services/worker/src/passes/proof.rs index 5b4db93d5..e528f399e 100644 --- a/services/worker/src/passes/proof.rs +++ b/services/worker/src/passes/proof.rs @@ -1333,15 +1333,27 @@ pub fn holds_security_items(body: &str) -> bool { /// gone when `items` is empty), other Open items kept as they are. `None` /// when there is nothing to change. pub fn with_security_items(body: &str, items: &[Finding]) -> Option { + with_marked_items(body, SECURITY_MARK, items.iter().map(item_line).collect()) +} + +/// On an Open item a check left open when CoderHelm marked the pull request +/// ready anyway (`ready`): CoderHelm's own sandbox or checklist found it, CI +/// is green and the review approved, so it is for a person to look at, not a +/// reason to keep the draft. +pub const READY_OPEN_MARK: &str = ""; + +/// The description with the Open items that carry `mark` replaced by `new` +/// (each line already carrying the mark; none when empty), other Open items +/// kept as they are. `None` when there is nothing to change. +pub fn with_marked_items(body: &str, mark: &str, new: Vec) -> Option { let (mut owned, rest) = super::completeness::take_owned(body); - let new: Vec = items.iter().map(item_line).collect(); - if new.is_empty() && !owned.open_items.contains(SECURITY_MARK) { + if new.is_empty() && !owned.open_items.contains(mark) { return None; } let kept: Vec<&str> = owned .open_items .lines() - .filter(|l| !l.contains(SECURITY_MARK)) + .filter(|l| !l.contains(mark)) .collect(); let others: Vec<&str> = kept .iter() diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs new file mode 100644 index 000000000..823e8bf57 --- /dev/null +++ b/services/worker/src/passes/ready.rs @@ -0,0 +1,1714 @@ +//! Whether a finished run's pull request leaves draft, decided in one place. +//! +//! A run finished with CI green and CoderHelm's review approving. Its pull +//! request stayed a draft: CoderHelm's own sandbox checks had failed on that +//! head, the mark-ready step returned without a word, and the run page said +//! "completed". The same day, mark-ready messages that hit GitHub's rate +//! limit were logged once and dropped, and five more pull requests were +//! never marked ready. Two mark-ready paths each carried their own list of +//! holds, and every hold was silent. +//! +//! The rules: +//! +//! - [`decide`] is the one decision, and every way a pull request is marked +//! ready goes through [`settle`]: the run's own completion +//! (`resume::mark_pr_ready`), the mark-ready message (CI passed, a +//! failing-test fix's recheck), an end-to-end proof that held, and the +//! sweep. It answers [`Decision::Ready`], [`Decision::Held`] with named +//! reasons, or [`Decision::Wait`] with what it waits for. +//! - CoderHelm defaults to progress. Its own sandbox failures and +//! verification checklist items (all about tests, none a correctness, +//! security or data-loss finding) don't keep the draft once the +//! repository's CI is green on the head and CoderHelm's review approved +//! it: the pull request is marked ready with them listed under Open items. +//! What a person must decide keeps it a draft: security items, planned +//! work not done, a check the change didn't pass, CoderHelm's own open +//! review findings, a stacked change asking for a look, a person putting +//! it back to draft, a failing-test fix that loosens a test, and redirect +//! or link checks that fail now. +//! - A hold is never silent. It is logged at warn with the reasons, written +//! at the top of the description, and recorded on the run +//! (`common::draft_hold`). A hold a person must act on sets the run to +//! `needs_input` with what to do, so the run never reads as plain +//! "completed" while its pull request is held. +//! - Marking ready can't be lost. GitHub refusing for a while (its rate +//! limit, a 5xx, a timeline it can't serve) sends the decision again after +//! GitHub's reset, up to `common::github_wait::MAX_WAITS` tries; the last +//! refusal is recorded on the run like a hold. +//! - [`sweep`] finds finished runs whose pull request is still a draft with +//! no recorded reason, and decides again: it marks the pull request ready +//! or records why not. A person's draft and a closed pull request are +//! respected. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::draft_hold::{DraftHold, Kind, Reason}; +use common::run_status::EndedValues; +use common::run_wait::NeedsInput; +use tracing::{error, info, warn}; + +use super::feature::FeatureHold; +use super::test_fix::Hold as TestHold; +use super::{attr_n, attr_s}; +use crate::clients::github::GitHubClient; +use crate::models::{MarkReadyMessage, WorkerMessage}; +use crate::WorkerState; + +/// Around the description's draft status, at its very top. +pub const STATUS_START: &str = ""; +pub const STATUS_END: &str = ""; + +/// A held pull request is decided again this long after the last decision +/// (the sweep): a person may have dealt with it without a push. +pub const RECHECK_HELD_SECS: i64 = 3600; +/// The sweep looks at runs finished this recently. +pub const SWEEP_WINDOW_DAYS: i64 = 14; +/// Decisions one sweep makes at most; the rest wait for the next sweep. +pub const SWEEP_MAX_DECISIONS: usize = 40; +/// The longest delay one SQS message carries. +const MAX_DELAY_SECS: u64 = common::github_wait::MAX_HOP_SECS; +/// The first wait after a refusal that named no reset. +const BASE_RETRY_SECS: u64 = 60; + +// ── the decision ──────────────────────────────────────────────────────── + +/// Where the repository's own CI stands on the head (CoderHelm's own checks +/// left out). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Ci { + pub green: bool, + /// Why it isn't green, in plain words; empty when green. + pub why: String, +} + +/// An end-to-end fix or new test's repeat-run proof. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum E2e { + /// Not such a pull request, or proven. + #[default] + None, + /// Its repeat runs are going. + Running, + /// The fix loosened the test or its repeat runs failed. + Refused, +} + +/// What [`decide`] reads, gathered from GitHub and the records. +#[derive(Debug, Clone, Default)] +pub struct Facts { + pub closed: bool, + pub draft: bool, + pub body: String, + pub title: String, + /// An end-to-end fix or generated test whose repeat runs proved it. + pub proven: bool, + pub e2e: E2e, + /// A person put it back to draft (their login). + pub put_back_by: Option, + /// Redirect and link checks failing now. + pub links_blocking: Vec, + /// The failing-test fix's own ready check; `None` for any other pull + /// request. + pub test_fix: Option, + /// What CoderHelm's own feature checks still find on the head. + pub feature: Option, + pub ci: Ci, + /// CoderHelm's review verdict on the head is APPROVE. + pub approved: bool, +} + +/// What happens to the pull request. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Decision { + /// Mark it ready (or it is already). `open` goes under Open items: what + /// CoderHelm's own checks found that doesn't hold the draft. + Ready { open: Vec }, + /// It stays a draft until a person deals with each reason. + Held { reasons: Vec }, + /// It stays a draft while something settles by itself; CoderHelm + /// decides again on its own (`until` epoch seconds, when known). + Wait { why: String, until: Option }, + /// A person closed it: nothing to mark, and it is never reopened. + Closed, +} + +/// The reasons the description itself holds the draft for, each with what a +/// person can do. Every one of these is something a person must decide or +/// fix, so each stays a hold (see the module's rules). +pub fn body_holds(body: &str) -> Vec { + let mut out = Vec::new(); + // Security: never shipped over without a person. + if super::proof::holds_security_items(body) { + out.push(Reason::new( + "Security items are open under Open items", + "Fix them on this branch (CoderHelm checks again on the next push), or delete each \ + security line once a person has checked it.", + )); + } + // The change doesn't yet do what the ticket asked: correctness. + if super::proof::holds_unfinished(body) { + out.push(Reason::new( + "Planned work is not done yet (listed under Not finished)", + "CoderHelm keeps working it on this pull request; finish it on the branch, or remove \ + the section if the work isn't needed.", + )); + } + // A check that would once have stopped the pull request (carried-over + // commits, missing registrations, a migration that can't be released + // safely, redirects): a named, checked problem. + if super::proof::holds_blocked(body) { + out.push(Reason::new( + "A check the change didn't pass is listed under Open items", + "Fix it on this branch, or delete that line once a person has dealt with it.", + )); + } + // Correctness findings of CoderHelm's own review, not yet fixed. + if let Some(why) = super::own_review::hold(body) { + out.push(Reason::new( + why, + "CoderHelm fixes them in its review rounds; fix them on the branch, or remove a \ + finding from the list once a person has judged it.", + )); + } + // A stacked change asks a person to look first. + if let Some(why) = super::stack::hold(body) { + out.push(Reason::new( + why, + "Look at the change it builds on, then remove the hold line from its \"Builds on\" \ + section.", + )); + } + out +} + +/// The one decision. Pure, so every case is tested. +pub fn decide(f: &Facts) -> Decision { + if f.closed { + return Decision::Closed; + } + let open = match (&f.feature, f.ci.green && f.approved) { + (Some(h), true) => h.items(), + _ => Vec::new(), + }; + if !f.draft { + return Decision::Ready { open }; + } + // A person put it back to draft: their call, and nothing CoderHelm + // decides undoes it. + if let Some(who) = &f.put_back_by { + return Decision::Held { + reasons: vec![Reason::new( + format!("`{who}` put it back to draft"), + "It stays a draft until a person marks it ready; CoderHelm doesn't undo that.", + )], + }; + } + let mut reasons = body_holds(&f.body); + // Redirects and links the change adds that fail when checked now: a + // named, checked correctness problem a reader would hit. + if !f.links_blocking.is_empty() { + reasons.push(Reason::new( + format!( + "The redirect and link checks fail now: {}", + f.links_blocking.join("; ") + ), + "Fix them on this branch; the checks run again on the next push and when the pull \ + request is marked ready.", + )); + } + let mut wait: Option = None; + match &f.test_fix { + // A "fix" that loosens the test can hide the bug: a person decides. + Some(TestHold::Refused(why)) => reasons.push(Reason::new( + format!("This failing-test fix stays a draft: {why}"), + "Change the fix so the test isn't loosened, or mark it ready yourself if the change \ + is right.", + )), + Some(TestHold::GaveUp(why)) => reasons.push(Reason::new( + format!("This failing-test fix never cleared its ready check: {why}"), + "Run the affected test on the branch and mark it ready yourself, or push a fix.", + )), + Some(TestHold::Wait(why)) => wait = Some(format!("this failing-test fix waits: {why}")), + Some(TestHold::Go) | None => {} + } + match f.e2e { + E2e::Refused => reasons.push(Reason::new( + "The end-to-end fix was refused: it loosened the test, or its repeat runs failed \ + (the comment on the pull request says which)", + "Push a fix that makes the test pass without loosening it, or close the pull request.", + )), + E2e::Running => { + wait.get_or_insert_with(|| "its repeat runs are going".to_string()); + } + E2e::None => { + if !f.proven && super::resume::is_e2e_proof_pr(&f.title) { + wait.get_or_insert_with(|| { + "it is an end-to-end fix or new test, which leaves draft once its repeat \ + runs prove it" + .to_string() + }); + } + } + } + // CoderHelm's own sandbox and checklist findings weigh against the + // repository's CI and the review: with both green they are open items + // on a ready pull request, never a hold by themselves. + if let Some(h) = &f.feature { + if !(f.ci.green && f.approved) { + let mut not_yet = Vec::new(); + if !f.ci.green { + not_yet.push(if f.ci.why.is_empty() { + "the repository's CI isn't green on this head".to_string() + } else { + f.ci.why.clone() + }); + } + if !f.approved { + not_yet.push("CoderHelm's review hasn't approved this head".to_string()); + } + reasons.push(Reason::new( + format!( + "CoderHelm's own checks still find {} item(s) on this head ({}), and {}", + h.items().len(), + h.items().join("; "), + not_yet.join(", and ") + ), + "Fix them on this branch, or mark it ready yourself if they're fine. Once CI is \ + green and the review approves, CoderHelm marks it ready with them listed.", + )); + } + } + if !reasons.is_empty() { + return Decision::Held { reasons }; + } + if let Some(why) = wait { + return Decision::Wait { why, until: None }; + } + Decision::Ready { open } +} + +/// The description's draft status for a decision; empty when it is ready. +pub fn status_section(d: &Decision) -> String { + match d { + Decision::Held { reasons } => { + let items: Vec = reasons.iter().map(|r| format!("- {}", r.line())).collect(); + format!( + "{STATUS_START}\n**This pull request stays a draft.** CoderHelm finished its \ + work; a person needs to deal with:\n{}\n{STATUS_END}", + items.join("\n") + ) + } + Decision::Wait { why, .. } => format!( + "{STATUS_START}\n**This pull request stays a draft for now:** {}. CoderHelm checks \ + again by itself and marks it ready when that is done.\n{STATUS_END}", + why.trim().trim_end_matches('.') + ), + Decision::Ready { .. } | Decision::Closed => String::new(), + } +} + +/// The description once CoderHelm couldn't mark it ready after every try. +fn failed_section(why: &str) -> String { + format!( + "{STATUS_START}\n**This pull request should be ready, but CoderHelm couldn't mark it:** \ + {}. Mark it ready for review yourself; CoderHelm also tries again within the hour.\n\ + {STATUS_END}", + why.trim().trim_end_matches('.') + ) +} + +/// The Open items lines for what CoderHelm's checks found on a pull request +/// it marked ready anyway, leaving out what the section already says. +pub fn open_item_lines(body: &str, open: &[String]) -> Vec { + let (owned, _) = super::completeness::take_owned(body); + open.iter() + .filter(|o| { + let core = o + .trim_start_matches("CoderHelm's sandbox check failed: ") + .trim_start_matches("Verification checklist: "); + // Already listed (with its old mark, or by the rules at the PR). + !owned + .open_items + .lines() + .any(|l| !l.contains(super::proof::READY_OPEN_MARK) && l.contains(core)) + }) + .map(|o| { + format!( + "- {}. CI is green and the review approved, so this doesn't keep the draft: \ + look at it before merging. {}", + o.trim().trim_end_matches('.'), + super::proof::READY_OPEN_MARK + ) + }) + .collect() +} + +/// The description with its draft status (and, when ready, the open items) +/// set for a decision. `None` when nothing changes. +pub fn body_for(body: &str, d: &Decision) -> Option { + let mut out = super::completeness::with_section( + body, + super::completeness::Section::DraftStatus, + status_section(d), + ); + if let Decision::Ready { open } = d { + if let Some(b) = super::proof::with_marked_items( + &out, + super::proof::READY_OPEN_MARK, + open_item_lines(&out, open), + ) { + out = b; + } + } + (out != body).then_some(out) +} + +// ── settling one pull request ─────────────────────────────────────────── + +/// One pull request to decide. +pub struct Ctx<'a> { + pub state: &'a WorkerState, + pub github: &'a GitHubClient, + pub team_id: &'a str, + pub owner: &'a str, + pub repo: &'a str, + pub pr: u64, + /// The run whose pull request it is; looked up when empty. + pub run_id: String, + /// Squash before marking ready, under the first commit's message when + /// true (the run's own completion). `None`: no squash. + pub squash_keep_first: Option, + /// The end-to-end proof passed (its repeat runs held). + pub proven: bool, + pub e2e: E2e, + /// Tries GitHub refused so far. + pub attempt: u32, +} + +impl<'a> Ctx<'a> { + pub fn new( + state: &'a WorkerState, + github: &'a GitHubClient, + team_id: &'a str, + owner: &'a str, + repo: &'a str, + pr: u64, + ) -> Self { + Ctx { + state, + github, + team_id, + owner, + repo, + pr, + run_id: String::new(), + squash_keep_first: None, + proven: false, + e2e: E2e::None, + attempt: 0, + } + } +} + +/// GitHub didn't answer a read or the mark-ready the decision needs. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Refused { + /// What failed, in plain words. + pub what: String, + /// How long to wait before the next try. + pub wait_secs: u64, +} + +impl Refused { + fn of(what: &str, e: &(dyn std::error::Error + 'static), attempt: u32) -> Self { + let wait_secs = match crate::clients::github::outside_wait(e) { + Some((_, w)) => w, + None => backoff_secs(attempt), + }; + let reason = match crate::clients::github::outside_wait(e) { + Some((common::github_wait::Cause::RateLimit, _)) => "GitHub's rate limit", + Some((common::github_wait::Cause::Outage, _)) => "GitHub not answering", + None => "GitHub refused the request", + }; + Refused { + what: format!("{what} ({reason})"), + wait_secs, + } + } +} + +/// The wait before try `attempt + 1` when GitHub named no reset: one minute, +/// doubling, at most one SQS delay. +pub fn backoff_secs(attempt: u32) -> u64 { + BASE_RETRY_SECS + .saturating_mul(1u64 << attempt.min(10)) + .min(MAX_DELAY_SECS) +} + +/// What happened, for the caller's log and the tests. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + Ready, + Held, + Waiting, + Closed, + /// Sent again for later (GitHub refused for a while). + Retrying, + /// Every try was refused; recorded on the run. + GaveUp, +} + +/// Decides one pull request and does what the decision says: marks it +/// ready, or records why it stays a draft on the description, the run and +/// the log. Never silent, never lost. +pub async fn settle(ctx: &Ctx<'_>) -> Outcome { + if ctx.pr == 0 { + return Outcome::Closed; + } + let run_id = if ctx.run_id.is_empty() { + super::review_pr::lookup_run_by_pr(ctx.state, ctx.team_id, ctx.owner, ctx.repo, ctx.pr) + .await + .unwrap_or_default() + } else { + ctx.run_id.clone() + }; + let pr_url = format!( + "https://github.com/{}/{}/pull/{}", + ctx.owner, ctx.repo, ctx.pr + ); + let facts = match gather(ctx).await { + Ok(f) => f, + Err(r) => return retry_or_give_up(ctx, &run_id, &pr_url, r).await, + }; + let decision = decide(&facts); + match &decision { + Decision::Closed => { + info!(pr = ctx.pr, "PR is closed — not marking ready"); + record_settled(ctx.state, ctx.team_id, &run_id, "closed").await; + Outcome::Closed + } + Decision::Ready { open } => { + if facts.draft { + info!(pr = ctx.pr, open = ?open, "Marking PR ready"); + if let Err(r) = make_ready(ctx, &facts).await { + return retry_or_give_up(ctx, &run_id, &pr_url, r).await; + } + info!(pr = ctx.pr, open = open.len(), "PR marked ready"); + } else { + info!(pr = ctx.pr, "PR already not a draft"); + } + write_body(ctx, &facts.body, &decision).await; + record_settled(ctx.state, ctx.team_id, &run_id, "ready").await; + Outcome::Ready + } + Decision::Held { reasons } => { + let lines: Vec = reasons.iter().map(Reason::line).collect(); + warn!(pr = ctx.pr, run_id = %run_id, reasons = ?lines, "The PR stays a draft"); + write_body(ctx, &facts.body, &decision).await; + if let Some(h) = DraftHold::new(Kind::Held, reasons.clone(), ctx.pr, &pr_url) { + record_hold(ctx.state, ctx.team_id, &run_id, h).await; + } + Outcome::Held + } + Decision::Wait { why, .. } => { + info!(pr = ctx.pr, run_id = %run_id, why = %why, "The PR stays a draft for now"); + write_body(ctx, &facts.body, &decision).await; + if let Some(h) = + DraftHold::new(Kind::Waiting, vec![Reason::new(why, "")], ctx.pr, &pr_url) + { + record_hold(ctx.state, ctx.team_id, &run_id, h).await; + } + Outcome::Waiting + } + } +} + +/// Reads what [`decide`] needs. A closed or ready pull request is decided +/// from the pull request alone, so nothing with side effects runs for it +/// (the failing-test check starts workflow runs, the link check rewrites +/// the description). +async fn gather(ctx: &Ctx<'_>) -> Result { + let gh = ctx.github; + let read_pr = || async { + gh.get_pull_request(ctx.owner, ctx.repo, ctx.pr) + .await + .map_err(|e| Refused::of("the pull request couldn't be read", &*e, ctx.attempt)) + }; + let pr = read_pr().await?; + let mut f = Facts { + closed: pr["state"].as_str() == Some("closed"), + draft: pr["draft"].as_bool().unwrap_or(false), + proven: ctx.proven, + e2e: ctx.e2e, + ..Default::default() + }; + if f.closed || !f.draft { + f.body = pr["body"].as_str().unwrap_or("").to_string(); + f.title = pr["title"].as_str().unwrap_or("").to_string(); + return Ok(f); + } + // A person putting it back to draft is their call. A timeline that + // can't be read is tried again, never taken as "leave it". + let timeline = gh + .list_issue_timeline(ctx.owner, ctx.repo, ctx.pr) + .await + .map_err(|e| { + Refused::of( + "the pull request's timeline couldn't be read", + &*e, + ctx.attempt, + ) + })?; + f.put_back_by = crate::clients::github::human_converted_to_draft(&timeline); + if f.put_back_by.is_none() { + // Asking people to merge: the redirects and links are checked again + // and the description's table updated. + f.links_blocking = super::link_checks::refresh_pr( + ctx.state, + gh, + ctx.team_id, + ctx.owner, + ctx.repo, + ctx.pr, + "", + true, + ) + .await + .map(|r| r.blocking) + .unwrap_or_default(); + f.test_fix = match super::test_fix::ready_gate( + ctx.state, + gh, + ctx.team_id, + ctx.owner, + ctx.repo, + ctx.pr, + ) + .await + { + TestHold::Go => None, + h => Some(h), + }; + f.feature = + super::feature::ready_hold(ctx.state, gh, ctx.team_id, ctx.owner, ctx.repo, ctx.pr) + .await; + } + // The description as it is now (the link check may have rewritten it). + let pr = read_pr().await?; + f.closed = pr["state"].as_str() == Some("closed"); + f.draft = pr["draft"].as_bool().unwrap_or(f.draft); + f.body = pr["body"].as_str().unwrap_or("").to_string(); + f.title = pr["title"].as_str().unwrap_or("").to_string(); + if f.feature.is_some() { + let sha = pr["head"]["sha"].as_str().unwrap_or(""); + f.ci = ci_on(gh, ctx.owner, ctx.repo, sha).await.map_err(|e| { + Refused::of( + "the pull request's checks couldn't be read", + &*e, + ctx.attempt, + ) + })?; + f.approved = matches!( + common::merge_gate::bot_verdict_at_head( + &ctx.state.dynamo, + &ctx.state.config.settings_table_name, + ctx.team_id, + ctx.owner, + ctx.repo, + ctx.pr, + sha, + ) + .await, + Ok(Some(v)) if v == "APPROVE" + ); + } + Ok(f) +} + +/// Whether a check is CoderHelm's own (its review check, or any check its +/// app reports): never the repository's CI. +fn own_check(c: &serde_json::Value) -> bool { + let name = c["name"].as_str().or(c["context"].as_str()).unwrap_or(""); + name == common::review_check::CHECK_NAME + || super::is_own_login(name) + || super::is_own_login(c["app"]["slug"].as_str().unwrap_or("")) +} + +/// The repository's own CI on a head, from its check runs and statuses. +pub fn ci_standing(check_runs: &[serde_json::Value], statuses: &[serde_json::Value]) -> Ci { + let runs: Vec = check_runs + .iter() + .filter(|c| !own_check(c)) + .cloned() + .collect(); + let statuses: Vec = + statuses.iter().filter(|c| !own_check(c)).cloned().collect(); + let checks = common::e2e::check_gate::checks(&runs, &statuses); + if checks.is_empty() { + return Ci { + green: false, + why: "the repository reports no CI checks on this head".into(), + }; + } + let names = |v: Vec<&str>| { + v.iter() + .map(|n| format!("`{n}`")) + .collect::>() + .join(", ") + }; + let failed: Vec<&str> = checks + .iter() + .filter(|c| { + c.status == "completed" + && !matches!(c.conclusion.as_str(), "success" | "skipped" | "neutral") + }) + .map(|c| c.name.as_str()) + .collect(); + if !failed.is_empty() { + return Ci { + green: false, + why: format!("CI fails on this head: {}", names(failed)), + }; + } + let running: Vec<&str> = checks + .iter() + .filter(|c| c.status != "completed") + .map(|c| c.name.as_str()) + .collect(); + if !running.is_empty() { + return Ci { + green: false, + why: format!("CI is still running on this head: {}", names(running)), + }; + } + Ci { + green: true, + why: String::new(), + } +} + +async fn ci_on( + gh: &GitHubClient, + owner: &str, + repo: &str, + sha: &str, +) -> Result> { + let runs = gh.list_check_runs_for_ref(owner, repo, sha).await?; + let statuses = gh.get_commit_status(owner, repo, sha).await?; + Ok(ci_standing( + runs["check_runs"].as_array().map_or(&[][..], |a| a), + statuses["statuses"].as_array().map_or(&[][..], |a| a), + )) +} + +/// Marks the draft ready: the "Partial" title marker goes, the run's +/// history is squashed when asked (only while it is still CoderHelm's +/// draft), then GitHub's ready-for-review. +async fn make_ready(ctx: &Ctx<'_>, f: &Facts) -> Result<(), Refused> { + let gh = ctx.github; + let pr = gh + .get_pull_request(ctx.owner, ctx.repo, ctx.pr) + .await + .map_err(|e| Refused::of("the pull request couldn't be read", &*e, ctx.attempt))?; + // A PR reaching ready is no longer "partial". + if let Some(clean) = f.title.strip_prefix("⚠️ Partial: ") { + let _ = gh.update_pr_title(ctx.owner, ctx.repo, ctx.pr, clean).await; + } + // Final squash: the run's whole history (the implementation and every + // fix round) as one clean commit, best-effort. + if let (Some(keep_first), Some(head), Some(base)) = ( + ctx.squash_keep_first, + pr["head"]["ref"].as_str(), + pr["base"]["ref"].as_str(), + ) { + let title = if f.title.is_empty() { + "Apply changes" + } else { + f.title.as_str() + }; + let mut squash_msg = title + .strip_prefix("⚠️ Partial: ") + .unwrap_or(title) + .to_string(); + if keep_first { + if let Ok(commits) = gh.list_pr_commits(ctx.owner, ctx.repo, ctx.pr).await { + if let Some(m) = super::resume::first_own_commit_message(&commits) { + squash_msg = m; + } + } + } + // A commit message an agent wrote may carry a stand-in key (`ABC-0`); + // the PR title carries the real one. + let squash_msg = common::git_conventions::normalize_message( + &squash_msg, + common::git_conventions::subject_key(title).as_deref(), + ); + if let Err(e) = gh + .squash_branch(ctx.owner, ctx.repo, head, base, &squash_msg) + .await + { + warn!(pr = ctx.pr, error = %e, "Final squash before mark-ready failed — proceeding with full history"); + } + } + let Some(node_id) = pr["node_id"].as_str() else { + return Err(Refused { + what: "GitHub's answer for the pull request had no node id".into(), + wait_secs: backoff_secs(ctx.attempt), + }); + }; + gh.mark_pr_ready(node_id) + .await + .map(|_| ()) + .map_err(|e| Refused::of("GitHub didn't mark it ready", &*e, ctx.attempt)) +} + +async fn write_body(ctx: &Ctx<'_>, body: &str, d: &Decision) { + let Some(new) = body_for(body, d) else { + return; + }; + if let Err(e) = ctx + .github + .update_pr_body(ctx.owner, ctx.repo, ctx.pr, &new) + .await + { + warn!(pr = ctx.pr, error = %e, "Could not write the draft status to the description"); + } +} + +/// GitHub refused for a while: the decision is sent again after its reset, +/// or, once every try is taken (or it can't be sent), recorded on the run. +async fn retry_or_give_up(ctx: &Ctx<'_>, run_id: &str, pr_url: &str, r: Refused) -> Outcome { + let attempt = ctx.attempt + 1; + if attempt <= common::github_wait::MAX_WAITS { + let now = chrono::Utc::now().timestamp().max(0) as u64; + let msg = MarkReadyMessage { + team_id: ctx.team_id.to_string(), + installation_id: ctx.github.installation_id(), + repo_owner: ctx.owner.to_string(), + repo_name: ctx.repo.to_string(), + pr_number: ctx.pr, + run_id: run_id.to_string(), + attempt, + not_before: common::github_wait::until(now, r.wait_secs), + squash_keep_first: ctx.squash_keep_first, + }; + let delay = r.wait_secs.clamp(1, MAX_DELAY_SECS); + if send(ctx.state, &msg, delay).await { + warn!(pr = ctx.pr, attempt, wait_secs = r.wait_secs, what = %r.what, "Mark-ready refused by GitHub — trying again later"); + if let Some(h) = DraftHold::new( + Kind::Waiting, + vec![Reason::new( + format!( + "{}; CoderHelm tries again at {}", + r.what, + common::github_wait::clock(msg.not_before) + ), + "", + )], + ctx.pr, + pr_url, + ) { + record_hold(ctx.state, ctx.team_id, run_id, h).await; + } + return Outcome::Retrying; + } + } + error!(pr = ctx.pr, attempt = ctx.attempt, what = %r.what, "Could not mark the PR ready after every try"); + let what = format!("{} on each of {} tries", r.what, ctx.attempt.max(1)); + if let Ok(pr) = ctx + .github + .get_pull_request(ctx.owner, ctx.repo, ctx.pr) + .await + { + let body = pr["body"].as_str().unwrap_or(""); + let new = super::completeness::with_section( + body, + super::completeness::Section::DraftStatus, + failed_section(&what), + ); + if new != body { + let _ = ctx + .github + .update_pr_body(ctx.owner, ctx.repo, ctx.pr, &new) + .await; + } + } + if let Some(h) = DraftHold::new( + Kind::Failed, + vec![Reason::new( + what, + "Mark it ready for review on GitHub yourself; CoderHelm also tries again within the \ + hour.", + )], + ctx.pr, + pr_url, + ) { + record_hold(ctx.state, ctx.team_id, run_id, h).await; + } + Outcome::GaveUp +} + +async fn send(state: &WorkerState, msg: &MarkReadyMessage, delay: u64) -> bool { + let Ok(body) = serde_json::to_string(&WorkerMessage::MarkReady(MarkReadyMessage { + team_id: msg.team_id.clone(), + installation_id: msg.installation_id, + repo_owner: msg.repo_owner.clone(), + repo_name: msg.repo_name.clone(), + pr_number: msg.pr_number, + run_id: msg.run_id.clone(), + attempt: msg.attempt, + not_before: msg.not_before, + squash_keep_first: msg.squash_keep_first, + })) else { + return false; + }; + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .delay_seconds(delay as i32) + .send() + .await + { + Ok(_) => true, + Err(e) => { + warn!(pr = msg.pr_number, error = %e, "Could not queue the next mark-ready try"); + false + } + } +} + +/// The mark-ready message: CI passed on a finished run's branch, a +/// failing-test fix's recheck, or a try GitHub refused earlier. +pub async fn on_message(state: &WorkerState, msg: MarkReadyMessage) { + // A wait longer than one SQS delay goes on in hops until its time. + let now = chrono::Utc::now().timestamp().max(0) as u64; + if let Some(hop) = common::github_wait::hop(msg.not_before, now) { + let pr = msg.pr_number; + if !send(state, &msg, hop).await { + error!(pr, "Could not send the mark-ready wait on; deciding now"); + } else { + return; + } + } + let github = match GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + msg.installation_id, + &state.http, + ) { + Ok(g) => g, + Err(e) => { + error!(pr = msg.pr_number, error = %e, "No GitHub client for mark-ready"); + return; + } + }; + let mut ctx = Ctx::new( + state, + &github, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + ); + ctx.run_id = msg.run_id.clone(); + ctx.attempt = msg.attempt; + ctx.squash_keep_first = msg.squash_keep_first; + let outcome = settle(&ctx).await; + info!(pr = msg.pr_number, ?outcome, "Mark-ready decided"); +} + +// ── the run record ────────────────────────────────────────────────────── + +fn conditional_failed(e: &aws_sdk_dynamodb::error::SdkError) -> bool { + format!("{e:?}").contains("ConditionalCheckFailed") +} + +/// The run's status and hold, `None` when it can't be read. +async fn run_hold( + state: &WorkerState, + team_id: &str, + run_id: &str, +) -> Option<(String, Option)> { + let item = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("#s, draft_hold") + .expression_attribute_names("#s", "status") + .consistent_read(true) + .send() + .await + .ok()? + .item?; + let status = item + .get("status") + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default(); + Some((status, DraftHold::of_item(&item))) +} + +/// Records a hold on the run. A hold a person must act on sets a finished +/// run to `needs_input`, naming what to do; a run still working keeps its +/// status and gets the hold when it finishes (`after_completion`). +async fn record_hold(state: &WorkerState, team_id: &str, run_id: &str, hold: DraftHold) { + if run_id.is_empty() { + warn!(pr = hold.pr_number, summary = %hold.summary(), "No run found for the PR; the hold is in the description and the log only"); + return; + } + let before = run_hold(state, team_id, run_id).await; + let hold = hold.continuing(before.as_ref().and_then(|(_, h)| h.as_ref())); + let now = chrono::Utc::now().to_rfc3339(); + // `:held` is a condition value, never a status written here: the write + // goes through `NeedsInput::needs_input`. + let held = AttributeValue::S(common::run_status::NEEDS_INPUT.to_string()); + let (was, same) = match &before { + Some((status, prev)) => ( + status.clone(), + prev.as_ref() + .is_some_and(|p| p.kind == hold.kind && p.reasons == hold.reasons), + ), + None => (String::new(), false), + }; + let finished = matches!( + was.as_str(), + common::run_status::COMPLETED | common::run_status::SUCCESS + ); + let rewaiting = was == common::run_status::NEEDS_INPUT && !same; + if hold.needs_person() && (finished || rewaiting) { + // Handing the finished run to a person is a costly decision, so it + // goes through the stop judge's record. Nothing a model could weigh + // is left: `decide` already kept only what a person must act on. + let judged = super::stop_judge::cannot_proceed( + state, + team_id, + &super::stop_judge::run_subject(run_id), + super::stop_judge::Kind::Handoff, + "draft_hold", + &hold.summary(), + ) + .await; + if wait_on_person(state, team_id, run_id, &hold, &was, &judged).await { + return; + } + } else if hold.needs_person() { + // Still working (the run writes its status next and + // `after_completion` picks the hold up), or already waiting on + // these same reasons: the hold alone, below. + } else { + // A wait: a run a hold had set to needs_input is finished again. + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression( + "SET #s = :done, status_run_id = :sri, draft_hold = :h, updated_at = :t \ + REMOVE waiting_on, draft_settled", + ) + .condition_expression("#s = :held AND attribute_exists(draft_hold)") + .expression_attribute_names("#s", "status") + .expression_attribute_values(":done", attr_s(common::run_status::COMPLETED)) + .expression_attribute_values(":sri", attr_s(&format!("completed#{run_id}"))) + .expression_attribute_values(":h", hold.to_attr()) + .expression_attribute_values(":t", attr_s(&now)) + .expression_attribute_values(":held", held) + .send() + .await; + match res { + Ok(_) => return, + Err(e) if conditional_failed(&e) => {} + Err(e) => { + warn!(run_id, error = %e, "Could not record the draft wait on the run"); + return; + } + } + } + // Still working, or a status nothing here changes: the hold alone. + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET draft_hold = :h, updated_at = :t REMOVE draft_settled") + .condition_expression(format!( + "attribute_exists(run_id) AND {}", + common::run_status::not_ended("#s") + )) + .expression_attribute_names("#s", "status") + .ended_values() + .expression_attribute_values(":h", hold.to_attr()) + .expression_attribute_values(":t", attr_s(&now)) + .send() + .await; + if let Err(e) = res { + if !conditional_failed(&e) { + warn!(run_id, error = %e, "Could not record the draft hold on the run"); + } + } +} + +/// Sets a finished run to `needs_input` on its draft hold, naming what to +/// do. `false` when the run's status isn't one this changes. +async fn wait_on_person( + state: &WorkerState, + team_id: &str, + run_id: &str, + hold: &DraftHold, + was: &str, + _judged: &super::stop_judge::Judged, +) -> bool { + let now = chrono::Utc::now().to_rfc3339(); + // `:held` is a condition value, never a status written here: the write + // goes through `NeedsInput::needs_input`. + let held = AttributeValue::S(common::run_status::NEEDS_INPUT.to_string()); + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression( + "SET #s = :s, status_run_id = :sri, waiting_on = :wo, draft_hold = :h, updated_at = :t \ + REMOVE draft_settled", + ) + .condition_expression( + "#s IN (:done, :old_done) OR (#s = :held AND attribute_exists(draft_hold))", + ) + .expression_attribute_names("#s", "status") + .needs_input(run_id, &hold.waiting_on()) + .expression_attribute_values(":h", hold.to_attr()) + .expression_attribute_values(":t", attr_s(&now)) + .expression_attribute_values(":done", attr_s(common::run_status::COMPLETED)) + .expression_attribute_values(":old_done", attr_s(common::run_status::SUCCESS)) + .expression_attribute_values(":held", held) + .send() + .await; + match res { + Ok(_) => { + if was != common::run_status::NEEDS_INPUT { + super::webhooks::emit_run(state, team_id, run_id, common::run_status::NEEDS_INPUT) + .await; + } + true + } + Err(e) if conditional_failed(&e) => false, + Err(e) => { + warn!(run_id, error = %e, "Could not record the draft hold on the run"); + true + } + } +} + +/// The pull request left draft (`ready`) or was closed: the hold goes, and +/// a run a hold had set to needs_input is finished again. +async fn record_settled(state: &WorkerState, team_id: &str, run_id: &str, how: &str) { + if run_id.is_empty() { + return; + } + let now = chrono::Utc::now().to_rfc3339(); + let held = AttributeValue::S(common::run_status::NEEDS_INPUT.to_string()); + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression( + "SET #s = :done, status_run_id = :sri, draft_settled = :ds, updated_at = :t \ + REMOVE draft_hold, waiting_on", + ) + .condition_expression("#s = :held AND attribute_exists(draft_hold)") + .expression_attribute_names("#s", "status") + .expression_attribute_values(":done", attr_s(common::run_status::COMPLETED)) + .expression_attribute_values(":sri", attr_s(&format!("completed#{run_id}"))) + .expression_attribute_values(":ds", attr_s(how)) + .expression_attribute_values(":t", attr_s(&now)) + .expression_attribute_values(":held", held) + .send() + .await; + match res { + Ok(_) => return, + Err(e) if conditional_failed(&e) => {} + Err(e) => { + warn!(run_id, error = %e, "Could not record that the PR is settled"); + return; + } + } + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET draft_settled = :ds REMOVE draft_hold") + .condition_expression("attribute_exists(run_id)") + .expression_attribute_values(":ds", attr_s(how)) + .send() + .await; + if let Err(e) = res { + if !conditional_failed(&e) { + warn!(run_id, error = %e, "Could not record that the PR is settled"); + } + } +} + +/// A run just finished as `completed`: a hold recorded while it was still +/// working (the decision runs before the status is written) sets it to +/// `needs_input` now. +pub async fn after_completion(state: &WorkerState, team_id: &str, run_id: &str) { + let Some((status, Some(hold))) = run_hold(state, team_id, run_id).await else { + return; + }; + if status != common::run_status::COMPLETED || !hold.needs_person() { + return; + } + warn!(run_id, summary = %hold.summary(), "Run finished with its PR held as a draft"); + record_hold(state, team_id, run_id, hold).await; +} + +// ── the sweep ─────────────────────────────────────────────────────────── + +/// One finished run the sweep looks at. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Candidate { + pub team_id: String, + pub run_id: String, + pub status: String, + pub owner: String, + pub repo: String, + pub pr: u64, + pub installation_id: u64, + pub hold: Option, +} + +/// What the sweep does with a run. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SweepStep { + /// Decide again in full. + Decide, + /// Its hold is recent: only look whether the pull request left draft or + /// was closed (a person marked it ready, or closed it). + Peek, + /// Nothing to do (waiting on a person for something else). + Skip, +} + +/// Pure: what the sweep does with a candidate at `now`. +pub fn sweep_step(c: &Candidate, now: chrono::DateTime) -> SweepStep { + let finished = matches!( + c.status.as_str(), + common::run_status::COMPLETED | common::run_status::SUCCESS + ); + match ( + &c.hold, + finished, + c.status == common::run_status::NEEDS_INPUT, + ) { + // Finished with no recorded reason: the silent case. Decide. + (None, true, _) => SweepStep::Decide, + // Waiting on a person for something that isn't the draft. + (None, false, _) => SweepStep::Skip, + (Some(h), _, _) if h.stale(RECHECK_HELD_SECS, now) => SweepStep::Decide, + (Some(_), true, _) | (Some(_), _, true) => SweepStep::Peek, + (Some(_), false, false) => SweepStep::Skip, + } +} + +fn candidate_of(item: &HashMap) -> Option { + let s = |k: &str| item.get(k).and_then(|v| v.as_s().ok()).cloned(); + let n = |k: &str| { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse::().ok()) + .unwrap_or(0) + }; + let pr = n("pr_number"); + let (owner, repo) = s("pr_url") + .and_then(|u| common::pr_outcome::parse_pr_url(&u)) + .filter(|(_, _, num)| *num == pr) + .map(|(o, r, _)| (o, r)) + .or_else(|| { + let full = s("repo")?; + let (o, r) = full.split_once('/')?; + Some((o.to_string(), r.to_string())) + })?; + (pr > 0).then(|| Candidate { + team_id: s("team_id").unwrap_or_default(), + run_id: s("run_id").unwrap_or_default(), + status: s("status").unwrap_or_default(), + owner, + repo, + pr, + installation_id: n("installation_id"), + hold: DraftHold::of_item(item), + }) +} + +/// What one sweep did. +#[derive(Debug, Default)] +pub struct SweepReport { + pub looked_at: usize, + pub decided: usize, + /// `owner/repo#pr: outcome` for each one decided. + pub settled: Vec, +} + +/// Finished runs (in the last [`SWEEP_WINDOW_DAYS`]) whose pull request +/// isn't settled: each is decided again, so a pull request left a draft +/// with no recorded reason heals by itself. Runs with a recent hold are +/// only looked at, to notice a person marking the pull request ready. +pub async fn sweep(state: &WorkerState) -> SweepReport { + let mut report = SweepReport::default(); + let now = chrono::Utc::now(); + let cutoff = (now - chrono::Duration::days(SWEEP_WINDOW_DAYS)).to_rfc3339(); + let mut start: Option> = None; + let mut candidates = Vec::new(); + for _ in 0..200 { + let res = state + .dynamo + .scan() + .table_name(&state.config.runs_table_name) + .filter_expression( + "#s IN (:done, :old_done, :held) AND pr_number > :zero AND updated_at >= :cut \ + AND attribute_not_exists(draft_settled)", + ) + .projection_expression( + "team_id, run_id, #s, pr_number, pr_url, repo, installation_id, draft_hold", + ) + .expression_attribute_names("#s", "status") + .expression_attribute_values(":done", attr_s(common::run_status::COMPLETED)) + .expression_attribute_values(":old_done", attr_s(common::run_status::SUCCESS)) + .expression_attribute_values( + ":held", + AttributeValue::S(common::run_status::NEEDS_INPUT.to_string()), + ) + .expression_attribute_values(":zero", attr_n(0)) + .expression_attribute_values(":cut", attr_s(&cutoff)) + .set_exclusive_start_key(start.take()) + .send() + .await; + let page = match res { + Ok(p) => p, + Err(e) => { + warn!(error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "Draft sweep scan failed"); + break; + } + }; + candidates.extend(page.items().iter().filter_map(candidate_of)); + match page.last_evaluated_key { + Some(k) if !k.is_empty() => start = Some(k), + _ => break, + } + } + let mut clients: HashMap = HashMap::new(); + for c in candidates { + if report.decided >= SWEEP_MAX_DECISIONS { + break; + } + let step = sweep_step(&c, now); + if step == SweepStep::Skip || c.installation_id == 0 || c.team_id.is_empty() { + continue; + } + report.looked_at += 1; + if let std::collections::hash_map::Entry::Vacant(v) = clients.entry(c.installation_id) { + match GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + c.installation_id, + &state.http, + ) { + Ok(g) => { + v.insert(g); + } + Err(e) => { + warn!(installation = c.installation_id, error = %e, "Draft sweep: no GitHub client"); + continue; + } + } + } + let gh = &clients[&c.installation_id]; + if step == SweepStep::Peek { + match gh.get_pull_request(&c.owner, &c.repo, c.pr).await { + Ok(p) + if p["state"].as_str() == Some("open") + && p["draft"].as_bool() == Some(true) => + { + continue; + } + Ok(_) => {} + Err(_) => continue, + } + } + let mut ctx = Ctx::new(state, gh, &c.team_id, &c.owner, &c.repo, c.pr); + ctx.run_id = c.run_id.clone(); + let outcome = settle(&ctx).await; + report.decided += 1; + report + .settled + .push(format!("{}/{}#{}: {outcome:?}", c.owner, c.repo, c.pr)); + } + report +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn green_approved() -> Facts { + Facts { + draft: true, + ci: Ci { + green: true, + why: String::new(), + }, + approved: true, + ..Default::default() + } + } + + fn sandbox_fails() -> FeatureHold { + FeatureHold { + sandbox_failed: vec![ + "npm run test:unit: 2 failed".into(), + "npm run lint: 1 error".into(), + ], + checklist_fails: vec![], + } + } + + #[test] + fn sandbox_failures_dont_hold_a_pr_whose_ci_is_green_and_review_approved() { + let f = Facts { + feature: Some(sandbox_fails()), + ..green_approved() + }; + match decide(&f) { + Decision::Ready { open } => { + assert_eq!(open.len(), 2); + assert!(open[0].starts_with("CoderHelm's sandbox check failed: npm run test:unit")); + } + other => panic!("{other:?}"), + } + } + + #[test] + fn a_checklist_item_doesnt_hold_either() { + let f = Facts { + feature: Some(FeatureHold { + sandbox_failed: vec![], + checklist_fails: vec!["test map entry: not listed: e2e/map.json: a.spec.ts".into()], + }), + ..green_approved() + }; + assert!(matches!(decide(&f), Decision::Ready { open } if open.len() == 1)); + } + + #[test] + fn without_green_ci_or_an_approval_coderhelms_own_findings_hold_with_the_reason_named() { + let f = Facts { + feature: Some(sandbox_fails()), + ci: Ci { + green: false, + why: "CI fails on this head: `test`".into(), + }, + approved: true, + draft: true, + ..Default::default() + }; + match decide(&f) { + Decision::Held { reasons } => { + assert_eq!(reasons.len(), 1); + assert!(reasons[0].what.contains("npm run test:unit")); + assert!(reasons[0].what.contains("CI fails on this head: `test`")); + assert!(reasons[0].todo.contains("mark it ready yourself")); + } + other => panic!("{other:?}"), + } + let f = Facts { + feature: Some(sandbox_fails()), + approved: false, + ..green_approved() + }; + assert!(matches!(decide(&f), Decision::Held { reasons } + if reasons[0].what.contains("review hasn't approved"))); + } + + #[test] + fn what_a_person_must_decide_keeps_the_draft_even_with_green_ci_and_an_approval() { + let security = format!( + "## Summary\nx\n\n{}\n## Open items\n- The token check. {}\n{}", + crate::passes::proof::UNVERIFIED_START, + crate::passes::proof::SECURITY_MARK, + crate::passes::proof::UNVERIFIED_END + ); + let f = Facts { + body: security, + ..green_approved() + }; + assert!(matches!(decide(&f), Decision::Held { reasons } + if reasons[0].what.contains("Security items"))); + + let f = Facts { + put_back_by: Some("dana".into()), + ..green_approved() + }; + assert!(matches!(decide(&f), Decision::Held { reasons } + if reasons[0].what == "`dana` put it back to draft")); + + let f = Facts { + test_fix: Some(TestHold::Refused( + "it adds what the failing-test rules refuse: a wait".into(), + )), + ..green_approved() + }; + assert!(matches!(decide(&f), Decision::Held { .. })); + + let f = Facts { + links_blocking: vec!["/old redirects to a 404".into()], + ..green_approved() + }; + assert!(matches!(decide(&f), Decision::Held { reasons } + if reasons[0].what.contains("/old redirects to a 404"))); + + let f = Facts { + e2e: E2e::Refused, + ..green_approved() + }; + assert!(matches!(decide(&f), Decision::Held { .. })); + + let f = Facts { + test_fix: Some(TestHold::GaveUp("the repeat run never passed".into())), + ..green_approved() + }; + assert!(matches!(decide(&f), Decision::Held { reasons } + if reasons[0].todo.contains("mark it ready yourself"))); + } + + #[test] + fn what_settles_by_itself_is_a_wait() { + let f = Facts { + test_fix: Some(TestHold::Wait("the repeat run hasn't passed yet".into())), + ..green_approved() + }; + assert!(matches!(decide(&f), Decision::Wait { why, .. } if why.contains("repeat run"))); + let f = Facts { + e2e: E2e::Running, + ..green_approved() + }; + assert!(matches!(decide(&f), Decision::Wait { .. })); + let f = Facts { + title: format!("{}flaky login test", crate::passes::e2e::FIX_TICKET_PREFIX), + ..green_approved() + }; + assert!(matches!(decide(&f), Decision::Wait { .. })); + let f = Facts { proven: true, ..f }; + assert!(matches!(decide(&f), Decision::Ready { .. })); + } + + #[test] + fn a_closed_pr_is_left_alone_and_a_ready_one_stays_ready() { + let f = Facts { + closed: true, + put_back_by: Some("dana".into()), + ..green_approved() + }; + assert_eq!(decide(&f), Decision::Closed); + let f = Facts { + draft: false, + ..green_approved() + }; + assert_eq!(decide(&f), Decision::Ready { open: vec![] }); + } + + #[test] + fn every_hold_is_named_on_the_description_and_goes_once_ready() { + let held = Decision::Held { + reasons: vec![Reason::new( + "Security items are open under Open items", + "Fix them.", + )], + }; + let body = body_for("## Summary\nx", &held).unwrap(); + assert!(body.starts_with(STATUS_START), "{body}"); + assert!(body.contains("**This pull request stays a draft.**")); + assert!(body.contains("- Security items are open under Open items. Fix them.")); + // Written once. + assert_eq!(body_for(&body, &held), None); + // The status never reads as a hold marker of its own. + assert!(body_holds(&body).is_empty()); + let ready = Decision::Ready { + open: vec!["CoderHelm's sandbox check failed: npm test: 2 failed".into()], + }; + let after = body_for(&body, &ready).unwrap(); + assert!(!after.contains(STATUS_START)); + assert!(after.contains("## Open items")); + assert!(after.contains("npm test: 2 failed. CI is green and the review approved")); + assert!(after.contains(crate::passes::proof::READY_OPEN_MARK)); + // Again: the same open item, once. + assert_eq!(body_for(&after, &ready), None); + let wait = Decision::Wait { + why: "its repeat runs are going".into(), + until: None, + }; + assert!(body_for("x", &wait) + .unwrap() + .contains("stays a draft for now:** its repeat runs are going.")); + } + + #[test] + fn an_open_item_the_rules_already_listed_isnt_listed_twice() { + let body = format!( + "{}\n## Open items\n- npm test: 2 failed Fix it on this branch.\n{}", + crate::passes::proof::UNVERIFIED_START, + crate::passes::proof::UNVERIFIED_END + ); + let lines = open_item_lines( + &body, + &["CoderHelm's sandbox check failed: npm test: 2 failed".into()], + ); + assert!(lines.is_empty()); + } + + #[test] + fn ci_leaves_out_coderhelms_own_checks() { + let run = |name: &str, conclusion: &str, slug: &str| { + json!({"name": name, "status": "completed", "conclusion": conclusion, + "started_at": "2026-11-06T22:10:00Z", "app": {"slug": slug}}) + }; + let ci = ci_standing( + &[ + run("build", "success", "github-actions"), + run(common::review_check::CHECK_NAME, "failure", "coderhelm"), + ], + &[], + ); + assert!(ci.green, "{ci:?}"); + let ci = ci_standing(&[run("build", "failure", "github-actions")], &[]); + assert!(!ci.green && ci.why.contains("`build`")); + let ci = ci_standing( + &[run( + common::review_check::CHECK_NAME, + "success", + "coderhelm", + )], + &[], + ); + assert!(!ci.green && ci.why.contains("no CI checks")); + let pending = json!({"name": "e2e", "status": "in_progress", "conclusion": null}); + assert!(ci_standing(&[pending], &[]).why.contains("still running")); + } + + #[test] + fn refused_tries_wait_longer_each_time_up_to_one_delay() { + assert_eq!(backoff_secs(0), 60); + assert_eq!(backoff_secs(1), 120); + assert_eq!(backoff_secs(3), 480); + assert_eq!(backoff_secs(4), MAX_DELAY_SECS); + assert_eq!(backoff_secs(30), MAX_DELAY_SECS); + // A rate limit waits for GitHub's reset. + let e: Box = + "HTTP status client error (403 Forbidden) for url (https://api.github.com/graphql): \ + API rate limit exceeded" + .into(); + let r = Refused::of("GitHub didn't mark it ready", &*e, 0); + assert!(r.what.contains("GitHub's rate limit"), "{r:?}"); + assert_eq!(r.wait_secs, 60); + } + + #[test] + fn the_mark_ready_message_carries_its_tries_and_stays_compatible() { + let old = r#"{"type":"mark_ready","team_id":"T","installation_id":1,"repo_owner":"o","repo_name":"r","pr_number":5}"#; + match serde_json::from_str::(old).unwrap() { + WorkerMessage::MarkReady(m) => { + assert_eq!(m.attempt, 0); + assert_eq!(m.not_before, 0); + assert!(m.run_id.is_empty()); + assert_eq!(m.squash_keep_first, None); + } + other => panic!("{other:?}"), + } + let m = WorkerMessage::MarkReady(MarkReadyMessage { + team_id: "T".into(), + pr_number: 5, + run_id: "01R".into(), + attempt: 3, + not_before: 99, + squash_keep_first: Some(true), + ..Default::default() + }); + let back: WorkerMessage = + serde_json::from_str(&serde_json::to_string(&m).unwrap()).unwrap(); + match back { + WorkerMessage::MarkReady(b) => { + assert_eq!((b.attempt, b.not_before, b.run_id.as_str()), (3, 99, "01R")); + assert_eq!(b.squash_keep_first, Some(true)); + } + other => panic!("{other:?}"), + } + } + + #[test] + fn the_sweep_decides_silent_drafts_and_peeks_at_recent_holds() { + let now = chrono::Utc::now(); + let c = Candidate { + team_id: "T".into(), + run_id: "01R".into(), + status: "completed".into(), + owner: "o".into(), + repo: "r".into(), + pr: 583, + installation_id: 1, + hold: None, + }; + assert_eq!(sweep_step(&c, now), SweepStep::Decide); + let held = DraftHold::new(Kind::Held, vec![Reason::new("a", "")], 583, "").unwrap(); + let c2 = Candidate { + status: "needs_input".into(), + hold: Some(held.clone()), + ..c.clone() + }; + assert_eq!(sweep_step(&c2, now), SweepStep::Peek); + assert_eq!( + sweep_step(&c2, now + chrono::Duration::seconds(RECHECK_HELD_SECS + 1)), + SweepStep::Decide + ); + // Waiting on a person for something that isn't the draft. + let c3 = Candidate { + status: "needs_input".into(), + hold: None, + ..c.clone() + }; + assert_eq!(sweep_step(&c3, now), SweepStep::Skip); + } + + #[test] + fn a_candidate_is_read_from_its_pull_request_url() { + let item: HashMap = [ + ("team_id", attr_s("T")), + ("run_id", attr_s("01R")), + ("status", attr_s("completed")), + ("pr_number", attr_n(583)), + ("pr_url", attr_s("https://github.com/acme/api/pull/583")), + ("repo", attr_s("acme/web")), + ("installation_id", attr_n(9)), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), v)) + .collect(); + let c = candidate_of(&item).unwrap(); + assert_eq!( + (c.owner.as_str(), c.repo.as_str(), c.pr), + ("acme", "api", 583) + ); + assert_eq!(c.installation_id, 9); + } +} diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index e3b2f0f69..c85eb6407 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -4467,7 +4467,7 @@ async fn set_run_awaiting_ci( cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t, current_pass = :cp, \ status_run_id = :sri \ - REMOVE error_message, #err, #inc", + REMOVE error_message, #err, #inc, draft_hold", ) .condition_expression(common::run_status::not_ended("#s")) .expression_attribute_names("#s", "status") @@ -4507,6 +4507,10 @@ async fn set_run_awaiting_ci( } } +/// Marks a finished run's pull request ready, or records why it stays a +/// draft: one decision for every caller (`ready::settle`). The run's own +/// completion squashes its history first; with a team commit template, the +/// squash keeps the message the run's first commit was given from it. pub(crate) async fn mark_pr_ready( state: &WorkerState, team_id: &str, @@ -4515,46 +4519,19 @@ pub(crate) async fn mark_pr_ready( repo_name: &str, pr_number: u64, ) { - // Asking people to merge: the PR's redirects and links are checked - // again and the description's table updated; one that fails now keeps - // the PR a draft, with the reason in that table. - if let Some(r) = super::link_checks::refresh_pr( - state, github, team_id, repo_owner, repo_name, pr_number, "", true, - ) - .await - .filter(|r| !r.blocking.is_empty()) - { - warn!(pr_number, blocking = ?r.blocking, "Link and redirect checks fail now; the PR stays a draft"); - return; - } - // A failing-test fix stays a draft until the checks that test it are - // green on its head and a repeat run passed. - if let super::test_fix::Hold::Wait(_) = - super::test_fix::ready_gate(state, github, team_id, repo_owner, repo_name, pr_number).await - { - return; - } - // A new feature stays a draft until its verification checklist passes. - if super::feature::ready_hold(state, github, team_id, repo_owner, repo_name, pr_number) - .await - .is_some() - { - return; - } - // With a team commit template, the final squash keeps the message the - // run's first commit was given from it; otherwise the PR title, as always. let keep_first = super::load_git_conventions(state, team_id, "") .await .commit .is_some(); - mark_ready(github, repo_owner, repo_name, pr_number, false, keep_first).await + let mut ctx = super::ready::Ctx::new(state, github, team_id, repo_owner, repo_name, pr_number); + ctx.squash_keep_first = Some(keep_first); + super::ready::settle(&ctx).await; } -/// Marks an E2E fix or generated-test PR ready once its repeat runs proved it. -/// Those PRs are skipped by [`mark_pr_ready`]: green CI alone isn't enough. /// Marks a finished run's PR ready for review. A flaky-test fix PR starts its /// proof first, and stays a draft while the proof runs or after the fix was -/// refused; when no proof can run it is marked ready with a note saying so. +/// refused (each recorded, never silent); when no proof can run it is marked +/// ready with a note saying so. pub(crate) async fn ready_or_prove( state: &WorkerState, github: &GitHubClient, @@ -4564,27 +4541,33 @@ pub(crate) async fn ready_or_prove( pr_number: u64, ) { use super::e2e::Proof; + let mut ctx = super::ready::Ctx::new(state, github, team_id, repo_owner, repo_name, pr_number); match super::e2e::start_fix_proof(state, github, team_id, repo_owner, repo_name, pr_number) .await { - Proof::Ready => mark_e2e_pr_ready(github, repo_owner, repo_name, pr_number).await, - Proof::Running | Proof::Refused => info!( - pr_number, - "Flaky-test fix PR stays a draft while its proof runs or after it was refused" - ), + Proof::Ready => ctx.proven = true, + Proof::Running => ctx.e2e = super::ready::E2e::Running, + Proof::Refused => ctx.e2e = super::ready::E2e::Refused, Proof::NotAFix => { - mark_pr_ready(state, team_id, github, repo_owner, repo_name, pr_number).await + return mark_pr_ready(state, team_id, github, repo_owner, repo_name, pr_number).await } } + super::ready::settle(&ctx).await; } +/// Marks an E2E fix or generated-test PR ready once its repeat runs proved +/// it, through the same decision as every other PR (`ready::settle`). pub(crate) async fn mark_e2e_pr_ready( + state: &WorkerState, github: &GitHubClient, + team_id: &str, repo_owner: &str, repo_name: &str, pr_number: u64, ) { - mark_ready(github, repo_owner, repo_name, pr_number, true, false).await + let mut ctx = super::ready::Ctx::new(state, github, team_id, repo_owner, repo_name, pr_number); + ctx.proven = true; + super::ready::settle(&ctx).await; } /// Whether a PR title belongs to an E2E fix or generated test, which waits for @@ -4596,7 +4579,7 @@ pub(crate) fn is_e2e_proof_pr(title: &str) -> bool { /// The message of the PR's first commit CoderHelm made (the squash at PR /// open, written from the team's commit template). -fn first_own_commit_message(commits: &[serde_json::Value]) -> Option { +pub(crate) fn first_own_commit_message(commits: &[serde_json::Value]) -> Option { commits.iter().find_map(|c| { let own = [&c["committer"]["login"], &c["author"]["login"]] .iter() @@ -4607,170 +4590,16 @@ fn first_own_commit_message(commits: &[serde_json::Value]) -> Option { } /// Why an open pull request stays a draft, read from its description and -/// title; `None` when nothing holds it. Security items still open, planned -/// work not done ("Not finished"), and an end-to-end fix or generated test -/// whose repeat runs haven't proved it (`proven`) each hold it. -pub(crate) fn draft_hold(body: &str, title: &str, proven: bool) -> Option<&'static str> { - if super::proof::holds_security_items(body) { - return Some("security items are open in the description"); - } - if super::proof::holds_unfinished(body) { - return Some("planned work not done is listed in the description"); - } - if super::proof::holds_blocked(body) { - return Some("a check the change didn't pass is listed in the description"); - } - if super::own_review::hold(body).is_some() { - return Some("CoderHelm's own review findings are open in the description"); - } - if super::stack::hold(body).is_some() { - return Some("the stacked change asks for a look first"); - } - if !proven && is_e2e_proof_pr(title) { - return Some("an end-to-end proof PR waits for its repeat runs"); - } - None -} - -async fn mark_ready( - github: &GitHubClient, - repo_owner: &str, - repo_name: &str, - pr_number: u64, - proven: bool, - // The team has a commit template: squash under the first commit's - // message (CoderHelm wrote it from the template) instead of the title. - keep_first_message: bool, -) { - if pr_number == 0 { - return; - } - // Retry once on failure — transient GitHub API issues are common - for attempt in 1..=2 { - match github - .get_pull_request(repo_owner, repo_name, pr_number) - .await - { - Ok(pr) => { - // If the PR was closed (e.g. a human closed it), never - // reopen/mark it ready — respect the close. - if pr.get("state").and_then(|v| v.as_str()) == Some("closed") { - info!(pr_number, "PR is closed — not marking ready"); - return; - } - if let Some(why) = draft_hold( - pr.get("body").and_then(|v| v.as_str()).unwrap_or(""), - pr.get("title").and_then(|v| v.as_str()).unwrap_or(""), - proven, - ) { - info!(pr_number, why, "The PR stays a draft"); - return; - } - // A person put this PR back into draft: that is their call, and - // a later CI pass or run completion must not undo it. Only a - // draft CoderHelm opened (or marked ready itself) is its to mark - // ready. When the timeline can't be read, the draft is left alone - // this time (fail closed: a draft stays a draft). - if pr.get("draft").and_then(|v| v.as_bool()).unwrap_or(false) { - match github - .list_issue_timeline(repo_owner, repo_name, pr_number) - .await - { - Ok(timeline) => { - if let Some(who) = - crate::clients::github::human_converted_to_draft(&timeline) - { - info!(pr_number, converted_by = %who, "PR was put back into draft by a person — not marking ready"); - return; - } - } - Err(e) => { - warn!(pr_number, error = %e, "Could not read the PR timeline — leaving the draft as is"); - return; - } - } - } - // A PR reaching ready (CI + review passed) is no longer - // "partial" — drop the salvage marker from the title. - if let Some(title) = pr.get("title").and_then(|v| v.as_str()) { - if let Some(clean) = title.strip_prefix("⚠️ Partial: ") { - let _ = github - .update_pr_title(repo_owner, repo_name, pr_number, clean) - .await; - } - } - let is_draft = pr.get("draft").and_then(|v| v.as_bool()).unwrap_or(false); - if !is_draft { - info!(pr_number, "PR already not a draft — skipping mark_pr_ready"); - return; - } - // Final squash: collapse the run's whole history — the initial - // implementation AND every CI-fix cycle (including any - // restore/refix churn) — into ONE clean commit before the PR - // goes up for review. Runs once, here at completion: the loop is - // done (single writer), and only while still a draft, so a human - // who has taken the PR over isn't clobbered. Best-effort — a - // failure just leaves the noisier history. - if let (Some(head), Some(base)) = ( - pr.get("head") - .and_then(|h| h.get("ref")) - .and_then(|v| v.as_str()), - pr.get("base") - .and_then(|b| b.get("ref")) - .and_then(|v| v.as_str()), - ) { - let title = pr - .get("title") - .and_then(|v| v.as_str()) - .unwrap_or("Apply changes"); - let mut squash_msg = title - .strip_prefix("⚠️ Partial: ") - .unwrap_or(title) - .to_string(); - if keep_first_message { - if let Ok(commits) = github - .list_pr_commits(repo_owner, repo_name, pr_number) - .await - { - if let Some(m) = first_own_commit_message(&commits) { - squash_msg = m; - } - } - } - // A commit message an agent wrote may carry a stand-in - // key (`ABC-0`); the PR title carries the real one. - let squash_msg = common::git_conventions::normalize_message( - &squash_msg, - common::git_conventions::subject_key(title).as_deref(), - ); - if let Err(e) = github - .squash_branch(repo_owner, repo_name, head, base, &squash_msg) - .await - { - warn!(pr_number, error = %e, "Final squash before mark-ready failed — proceeding with full history"); - } - } - if let Some(node_id) = pr.get("node_id").and_then(|v| v.as_str()) { - match github.mark_pr_ready(node_id).await { - Ok(_) => { - info!(pr_number, "PR marked ready for review"); - return; - } - Err(e) => { - warn!(pr_number, attempt, error = %e, "Failed to mark PR ready"); - } - } - } else { - warn!(pr_number, attempt, "PR response missing node_id"); - } - } - Err(e) => warn!(pr_number, attempt, error = %e, "Failed to fetch PR for marking ready"), - } - if attempt < 2 { - tokio::time::sleep(std::time::Duration::from_secs(2)).await; - } +/// title (the first of `ready::body_holds`); `None` when nothing there holds +/// it. An end-to-end fix or generated test whose repeat runs haven't proved +/// it (`proven`) waits too. +#[cfg(test)] +pub(crate) fn draft_hold(body: &str, title: &str, proven: bool) -> Option { + if let Some(r) = super::ready::body_holds(body).into_iter().next() { + return Some(r.what); } - error!(pr_number, "Failed to mark PR ready after 2 attempts"); + (!proven && is_e2e_proof_pr(title)) + .then(|| "an end-to-end proof PR waits for its repeat runs".to_string()) } /// The own-review progress a run recorded. @@ -5105,6 +4934,11 @@ async fn end_run( // The team's counters already have these tokens: each model call is // counted as it happens (common::usage). info!(run_id, status, "Run completed"); + // The pull request's ready decision runs before this write: a hold it + // recorded makes the finished run `needs_input`, never plain completed. + if status == common::run_status::COMPLETED { + super::ready::after_completion(state, &msg.team_id, run_id).await; + } // CoderHelm's own pushes during the run weren't reviewed by the PR // reviewer (`review_scope::own_loop_holds_push`): a run that hands its // PR over asks for the review of its head now. A head the run's own ask diff --git a/services/worker/src/passes/test_fix.rs b/services/worker/src/passes/test_fix.rs index 8886747ca..37acd08cb 100644 --- a/services/worker/src/passes/test_fix.rs +++ b/services/worker/src/passes/test_fix.rs @@ -2384,8 +2384,17 @@ pub fn refusals(files: &[(String, String, String)], g: &GateRecord) -> Vec, ) -> Hold { if !refused.is_empty() { - return Hold::Wait(format!( + return Hold::Refused(format!( "it adds what the failing-test rules refuse: {}", refused.join("; ") )); @@ -2570,8 +2579,8 @@ pub async fn ready_gate( } } - let hold = decide(&refused, &standing, repeat_ok); - if let Hold::Wait(why) = &hold { + let mut hold = decide(&refused, &standing, repeat_ok); + if let Hold::Wait(why) | Hold::Refused(why) = hold.clone() { let no_repeat = repeat_ok.is_none() && g.ci_workflow.is_empty(); if g.noted != sha { g.noted = sha.clone(); @@ -2604,6 +2613,14 @@ pub async fn ready_gate( pr_number, ) .await; + } else { + // No recheck is left: the hold is final until a person acts, + // and `ready` records it on the run as one. + hold = Hold::GaveUp(format!( + "{why} (checked every {} minutes for about {} hours)", + RECHECK_SECS / 60, + MAX_POLLS * RECHECK_SECS as u32 / 3600 + )); } info!(pr_number, reason = %why, polls = g.polls, "Test fix stays a draft"); } @@ -2626,6 +2643,7 @@ async fn recheck_later( repo_owner: owner.to_string(), repo_name: repo.to_string(), pr_number: pr, + ..Default::default() }); let Ok(body) = serde_json::to_string(&msg) else { return; @@ -3129,7 +3147,7 @@ mod tests { what: "waitForTimeout".into(), }; assert!( - matches!(decide(&[finding.sentence()], &green, Some(true)), Hold::Wait(w) if w.contains("refuse")) + matches!(decide(&[finding.sentence()], &green, Some(true)), Hold::Refused(w) if w.contains("refuse")) ); }