diff --git a/docs/self-host/github-app.md b/docs/self-host/github-app.md index 661f6a3bf..7af4e5d6d 100644 --- a/docs/self-host/github-app.md +++ b/docs/self-host/github-app.md @@ -30,7 +30,7 @@ It uses GitHub's [manifest flow](https://docs.github.com/en/apps/sharing-github- | Contents | write | Read code; push the branch with its changes | | Pull requests | write | Open and update pull requests; post reviews | | Issues | write | Read assigned issues; post progress | -| Checks | write | Read CI results to fix failures; show the "CoderHelm review" check on a pull request's commit from the moment its review is scheduled (queued, saying when it starts) until it ends, linking to the review's session page | +| Checks | write | Read CI results to fix failures; show the "CoderHelm review" check on a pull request's commit from the moment CoderHelm accepts anything on it (a push, a reply, a re-review, an edited description), saying what it is doing, until it ends, linking to the session page; a reply that is only answered leaves the commit showing the standing verdict | | Actions | read | Read workflow runs and logs | | Commit statuses | read | CI that reports statuses instead of checks | | Workflows | write | Change workflow files when a task asks for it | diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 774b64299..0fbc5f103 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -13,6 +13,7 @@ pub mod model_ids; pub mod claim; /// A re-review started by an edit of a pull request's description: what /// counts as a change, and the keys that queue one review per edit burst. +pub mod prose; pub mod review_description; /// The code graph's per-repo switch and build status (gateway and worker). diff --git a/services/common/src/merge_gate.rs b/services/common/src/merge_gate.rs index 30676b404..17e042a0d 100644 --- a/services/common/src/merge_gate.rs +++ b/services/common/src/merge_gate.rs @@ -571,6 +571,31 @@ pub async fn bot_verdict_at_head( pr: u64, head_sha: &str, ) -> Result, BoxError> { + Ok( + bot_review_at_head(dynamo, table, team_id, owner, repo, pr, head_sha) + .await? + .map(|b| b.verdict), + ) +} + +/// CoderHelm's latest verdict for a head, and what holds it by name. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BotVerdict { + pub verdict: String, + /// Empty on a review older than named items, and on an approval. + pub holding: Vec, +} + +/// [`bot_verdict_at_head`] with what holds the verdict. +pub async fn bot_review_at_head( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + owner: &str, + repo: &str, + pr: u64, + head_sha: &str, +) -> Result, BoxError> { let prefix = format!("REVIEW#{owner}/{repo}#{pr:0>6}#"); let mut start: Option> = None; // Page through the newest records until one for this head is found; the @@ -594,7 +619,12 @@ pub async fn bot_verdict_at_head( continue; } if get("head_sha") == Some(head_sha) { - return Ok(Some(verdict.to_string())); + return Ok(Some(BotVerdict { + verdict: verdict.to_string(), + holding: get("holding") + .and_then(|h| serde_json::from_str(h).ok()) + .unwrap_or_default(), + })); } } match resp.last_evaluated_key() { diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 6c29517c0..4b84a7b27 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -762,6 +762,12 @@ pub struct ReviewMessage { /// goes on to the fix loop, which answers this person on the PR. #[serde(default)] pub requested_by: String, + /// The commit whose "CoderHelm review" check shows this job, when the job + /// itself resolves the head when it starts (`head_sha` empty): the gateway + /// queued the check there. A head that moves before the job starts gets + /// its own check. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub check_head: String, /// How many times this review already failed for a service error and /// was sent again (0 on the first run). #[serde(default)] diff --git a/services/common/src/prose.rs b/services/common/src/prose.rs new file mode 100644 index 000000000..eb96b0018 --- /dev/null +++ b/services/common/src/prose.rs @@ -0,0 +1,202 @@ +//! Text a person reads on a pull request is never cut mid-sentence: every cap +//! on posted text ends on a sentence boundary, and a sentence too long for a +//! cap is kept whole or dropped with a note, never split. + +/// Words whose full stop doesn't end a sentence. +const ABBREVIATIONS: &[&str] = &[ + "e.g", "i.e", "etc", "vs", "cf", "no", "approx", "mr", "ms", "dr", +]; + +/// The byte offsets just past each sentence end in `text`. A terminator ends +/// a sentence only when whitespace or the end of the text follows it, so the +/// dot in `src/lib.rs`, `v1.2.3` or `example.com` doesn't. +pub fn sentence_ends(text: &str) -> Vec { + let mut ends = Vec::new(); + let mut chars = text.char_indices().peekable(); + while let Some((i, c)) = chars.next() { + if !matches!(c, '.' | '!' | '?') { + continue; + } + // Closing marks stay with their sentence: `foo.rs.`, (done.), "yes." + let mut end = i + c.len_utf8(); + while let Some(&(j, n)) = chars.peek() { + if matches!( + n, + '.' | '!' | '?' | ')' | ']' | '"' | '\'' | '`' | '*' | '_' + ) { + end = j + n.len_utf8(); + chars.next(); + } else { + break; + } + } + let at_break = match chars.peek() { + None => true, + Some(&(_, n)) => n.is_whitespace(), + }; + if !at_break { + continue; + } + if c == '.' { + let word = text[..i] + .rsplit(|ch: char| ch.is_whitespace() || ch == '(') + .next() + .unwrap_or("") + .to_ascii_lowercase(); + if ABBREVIATIONS.contains(&word.as_str()) { + continue; + } + } + ends.push(end); + } + ends +} + +/// At most `max_sentences` whole sentences and about `max_bytes`. A first +/// sentence longer than `max_bytes` is kept whole: the cap never splits it. +/// Text with no sentence end is returned as it is. +pub fn first_sentences(text: &str, max_sentences: usize, max_bytes: usize) -> &str { + let ends = sentence_ends(text); + let mut cut = None; + for (n, &end) in ends.iter().enumerate() { + if n >= max_sentences || (end > max_bytes && cut.is_some()) { + break; + } + cut = Some(end); + } + match cut { + Some(end) => text[..end].trim_end(), + None => text.trim_end(), + } +} + +/// `text` within `max_bytes`, cut at the last sentence or paragraph end that +/// fits. `None` when it already fits. Empty when nothing whole fits. +fn cut_point(text: &str, max_bytes: usize) -> Option { + if text.len() <= max_bytes { + return None; + } + let sentence = sentence_ends(text) + .into_iter() + .take_while(|&e| e <= max_bytes) + .last(); + let paragraph = text + .match_indices("\n\n") + .map(|(i, _)| i) + .take_while(|&i| i <= max_bytes) + .last(); + Some(sentence.max(paragraph).unwrap_or(0)) +} + +/// `text` within `max_bytes` on a sentence or paragraph boundary, followed by +/// `note` (on its own paragraph) when anything was left out. +pub fn cap_on_sentence(text: &str, max_bytes: usize, note: &str) -> String { + if text.len() <= max_bytes { + return text.to_string(); + } + let end = cut_point(text, max_bytes.saturating_sub(note.len() + 2)).unwrap_or(0); + let kept = text[..end].trim_end(); + if kept.is_empty() { + note.to_string() + } else { + format!("{kept}\n\n{note}") + } +} + +/// A model's answer that stopped before it finished (its token limit) ends on +/// its last whole sentence. Only a last line of prose is judged: a list item, +/// a table row, a heading or a code block may end without a full stop. +pub fn end_on_sentence(text: &str) -> &str { + let t = text.trim_end(); + let last = t.lines().last().unwrap_or("").trim_start(); + let structured = last.starts_with(['-', '*', '|', '#', '>', '`']) + || last + .split('.') + .next() + .is_some_and(|n| !n.is_empty() && n.len() < 4 && n.bytes().all(|b| b.is_ascii_digit())); + if structured || t.ends_with("```") { + return t; + } + let ends = sentence_ends(t); + match ends.last() { + Some(&e) if e == t.len() => t, + Some(&e) => t[..e].trim_end(), + None => t, + } +} + +/// The first whole sentence of a model's free text on one line, for showing +/// it on its own; `None` when it holds no finished sentence. +pub fn one_whole_sentence(text: &str) -> Option { + let line = text.split_whitespace().collect::>().join(" "); + let end = *sentence_ends(&line).first()?; + Some(line[..end].trim().to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_dot_in_a_path_is_not_the_end_of_a_sentence() { + let s = "The job reads services/worker/src/main.rs and lambda/handler.py from the source \ + paths. It is fine."; + assert_eq!(sentence_ends(s).len(), 2); + assert_eq!(first_sentences(s, 1, 500), &s[..s.find(" It is").unwrap()]); + assert_eq!( + sentence_ends("Bumped to v1.2.3 on example.com now").len(), + 0 + ); + assert_eq!(sentence_ends("Use e.g. this one. Done.").len(), 2); + assert_eq!(sentence_ends("See `a.rs`. Then (done.) Next!").len(), 3); + } + + #[test] + fn a_long_first_sentence_is_kept_whole() { + let long = format!("{} end.", "word ".repeat(300)); + assert_eq!(first_sentences(&long, 4, 100), long); + let two = format!("Short one. {long}"); + assert_eq!(first_sentences(&two, 4, 100), "Short one."); + assert_eq!(first_sentences("no end here", 4, 5), "no end here"); + } + + #[test] + fn a_cap_ends_on_a_boundary_and_says_so() { + let text = "First sentence here. Second sentence here. Third sentence goes on and on."; + let out = cap_on_sentence(text, 40, "(more)"); + assert_eq!(out, "First sentence here.\n\n(more)"); + assert_eq!(cap_on_sentence("short.", 60, "(more)"), "short."); + let para = "para without an end\n\nmore without an end that is long enough to matter here"; + assert_eq!( + cap_on_sentence(para, 40, "(more)"), + "para without an end\n\n(more)" + ); + assert_eq!(cap_on_sentence(&"x".repeat(100), 20, "(more)"), "(more)"); + } + + #[test] + fn an_answer_cut_by_a_token_limit_ends_on_its_last_sentence() { + assert_eq!(end_on_sentence("All good. The source paths"), "All good."); + assert_eq!(end_on_sentence("All good.\n"), "All good."); + assert_eq!( + end_on_sentence("Items:\n- one\n- two"), + "Items:\n- one\n- two" + ); + assert_eq!( + end_on_sentence("Steps:\n1. one\n2. two"), + "Steps:\n1. one\n2. two" + ); + assert_eq!(end_on_sentence("```\ncode\n```"), "```\ncode\n```"); + assert_eq!(end_on_sentence("no sentence at all"), "no sentence at all"); + } + + #[test] + fn only_a_finished_sentence_is_shown_on_its_own() { + assert_eq!( + one_whole_sentence("The fact\nchanged. And more."), + Some("The fact changed.".to_string()) + ); + assert_eq!(one_whole_sentence("because it"), None); + assert_eq!(one_whole_sentence(" "), None); + } +} diff --git a/services/common/src/review_check.rs b/services/common/src/review_check.rs index 041666f23..b83e243bf 100644 --- a/services/common/src/review_check.rs +++ b/services/common/src/review_check.rs @@ -8,6 +8,15 @@ //! completes it however the job ends; a job that hands its review to a later //! one (a retry, a full review) hands the check over with it, queued again. //! +//! Every way CoderHelm accepts work on a PR shows here within seconds: a push, +//! a label, a reply, a re-review, an edited description. A job on a commit +//! whose check already finished opens a new run of the same name, which GitHub +//! shows in place of the finished one, so the commit keeps one check. A job +//! that ends without a new verdict (a reply that was only answered, a re-review +//! with nothing changed) completes its run with the conclusion and title of +//! the run before it ([`close_restoring`]), so the commit always shows the +//! verdict that stands. +//! //! Each check carries an `external_id` naming the job it waits for and when //! that job is due ([`external_id`]). A job finds its own check by that key, //! and a check still open long after its job was due is completed by the @@ -78,6 +87,83 @@ pub fn queued_title(head: &str, due: i64, now: i64) -> String { } } +/// Whether the gateway may show a job on the commit when it sends it. A reply +/// that didn't address CoderHelm may not be for it at all: only the worker can +/// tell, by reading whose thread or text it answers. It leaves the check alone +/// until then and opens it if the reply turns out to answer CoderHelm. +pub fn shows_when_sent(trigger: &str, mentioned: bool) -> bool { + match trigger { + "thread_reply" => mentioned, + "quote_reply" => false, + _ => true, + } +} + +/// What a job does, in the words of a check's title. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Work { + /// A person's comment to read and answer. + Reply, + /// A person asked for another look. + ReReview, + /// The description was edited to answer the review. + Description, + /// A push, a label, the PR opening or leaving draft, a run's own review. + Review, +} + +impl Work { + /// The work of a job from its trigger and whether it carries a comment. + pub fn of(trigger: &str, has_question: bool) -> Self { + if has_question { + return Work::Reply; + } + match trigger { + "reply" | "rerequest" => Work::ReReview, + crate::review_description::TRIGGER => Work::Description, + _ => Work::Review, + } + } +} + +/// Pure: the title of a check waiting for job `work`, due at `due`. +pub fn waiting_title(work: Work, head: &str, due: i64, now: i64) -> String { + let short = short(head); + match work { + Work::Reply => format!("Reading your reply on {short}"), + Work::ReReview => format!("Re-reviewing {short}"), + Work::Description => format!("Re-reviewing {short} with the edited description"), + Work::Review => queued_title(head, due, now), + } +} + +/// Pure: the title of a check whose job has started. +pub fn started_title(work: Work, head: &str) -> String { + let short = short(head); + match work { + Work::Reply => format!("Reading your reply on {short}"), + Work::ReReview => format!("Re-reviewing {short}"), + Work::Description => format!("Re-reviewing {short} with the edited description"), + Work::Review => format!("Reviewing {short}"), + } +} + +/// Pure: the summary of a check waiting for job `work`. +pub fn waiting_summary(work: Work, due: i64, now: i64, details_url: &str) -> String { + match work { + Work::Review => queued_summary(due, now, details_url), + Work::Reply => format!( + "CoderHelm got your reply and is reading it. The verdict on this commit stays as it \ + is unless something it rests on changed.\n\n[See the pull request's \ + reviews]({details_url}) on CoderHelm." + ), + Work::ReReview | Work::Description => format!( + "CoderHelm got the request and starts on it shortly.\n\n[See the pull request's \ + reviews]({details_url}) on CoderHelm." + ), + } +} + /// Pure: the summary of a check waiting for its review. pub fn queued_summary(due: i64, now: i64, details_url: &str) -> String { let wait = if due - now >= 30 { @@ -100,6 +186,8 @@ pub struct OpenCheck { pub key: Option, /// When that job was due, or when the check started. pub since: Option, + /// Waiting for its job (not yet taken over). + pub queued: bool, } impl OpenCheck { @@ -133,6 +221,7 @@ pub fn open_checks(list: &Value) -> Vec { id, key: parsed.map(|(_, k)| k.to_string()), since: parsed.map(|(d, _)| d).or(started), + queued: c["status"].as_str() == Some("queued"), }) }) .collect(); @@ -140,6 +229,41 @@ pub fn open_checks(list: &Value) -> Vec { out } +/// The finished result a commit's check shows: the newest completed CoderHelm +/// run that isn't `except`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Standing { + pub conclusion: &'static str, + pub title: String, + pub summary: String, +} + +/// A conclusion this code writes, or neutral. +fn known_conclusion(c: &str) -> &'static str { + match c { + "success" => "success", + "failure" => "failure", + "skipped" => "skipped", + _ => "neutral", + } +} + +/// Pure: [`Standing`] from a `check-runs` listing. +pub fn standing_in(list: &Value, except: u64) -> Option { + list["check_runs"] + .as_array()? + .iter() + .filter(|c| c["name"].as_str() == Some(CHECK_NAME)) + .filter(|c| c["status"].as_str() == Some("completed")) + .filter(|c| c["id"].as_u64() != Some(except)) + .max_by_key(|c| c["id"].as_u64().unwrap_or(0)) + .map(|c| Standing { + conclusion: known_conclusion(c["conclusion"].as_str().unwrap_or("")), + title: c["output"]["title"].as_str().unwrap_or("").to_string(), + summary: c["output"]["summary"].as_str().unwrap_or("").to_string(), + }) +} + /// The three check-run calls, so every path can be tested without GitHub. #[async_trait::async_trait] pub trait CheckCalls: Sync { @@ -201,10 +325,11 @@ impl CheckCalls for TokenCalls<'_> { } } -/// The listing of CoderHelm's checks on `head`. +/// The listing of CoderHelm's checks on `head`: every run, not only the newest +/// of the name, so a job can read what the commit showed before it. pub fn list_url(owner: &str, repo: &str, head: &str) -> String { format!( - "{API}/repos/{owner}/{repo}/commits/{head}/check-runs?check_name={}&per_page=100", + "{API}/repos/{owner}/{repo}/commits/{head}/check-runs?check_name={}&filter=all&per_page=100", urlencoding::encode(CHECK_NAME) ) } @@ -286,6 +411,21 @@ pub async fn queue( key: &str, due: i64, details_url: &str, +) -> Queued { + queue_work(api, t, Work::Review, key, due, details_url).await +} + +/// CoderHelm accepted `work` on `t.head` for job `key`, due at `due`: the +/// commit shows it right away. A commit already showing an open check keeps +/// it (the job running there speaks for the commit); a finished one is shown +/// over by this new run until the job ends. +pub async fn queue_work( + api: &C, + t: &Target<'_>, + work: Work, + key: &str, + due: i64, + details_url: &str, ) -> Queued { if t.head.is_empty() { return Queued::Nothing; @@ -304,8 +444,8 @@ pub async fn queue( "external_id": external_id(key, due), "details_url": details_url, "output": { - "title": crate::truncate_str(&queued_title(t.head, due, now), 250), - "summary": queued_summary(due, now, details_url), + "title": crate::truncate_str(&waiting_title(work, t.head, due, now), 250), + "summary": waiting_summary(work, due, now, details_url), }, }); let id = match api.create(t.owner, t.repo, &body).await { @@ -317,7 +457,7 @@ pub async fn queue( }; // A stale one left open on the same commit is given up on now. for c in open { - close(api, t, c.id, &stopped_close(details_url)).await; + close_restoring(api, t, c.id, &stopped_close(details_url)).await; } Queued::Created(id) } @@ -501,6 +641,32 @@ pub async fn close(api: &C, t: &Target<'_>, id: u64, c: } } +/// Complete check `id` for a job that ended without a new verdict: the commit +/// goes back to showing the run before it, the same conclusion and title, with +/// what this job did added to the summary. With no finished run before it, +/// `c` as it is. +pub async fn close_restoring(api: &C, t: &Target<'_>, id: u64, c: &Close) { + let standing = match api.list(t.owner, t.repo, t.head).await { + Ok(list) => standing_in(&list, id), + Err(e) => { + log_failure(t.installation, t.pr, "read the standing check", &e); + None + } + }; + match standing { + Some(s) => { + let restored = Close { + conclusion: s.conclusion, + title: s.title, + summary: format!("{}\n\n{}", s.summary.trim_end(), c.summary), + details_url: c.details_url.clone(), + }; + close(api, t, id, &restored).await; + } + None => close(api, t, id, c).await, + } +} + /// Complete the check waiting for job `key` on `t.head`, if there is one: /// for a job that ends before it takes its check over. pub async fn close_waiting( @@ -515,10 +681,15 @@ pub async fn close_waiting( let Some(open) = open_on_head(api, t).await else { return false; }; - let Some(mine) = open.iter().find(|o| o.key.as_deref() == Some(key)) else { + // Still waiting: a job already running under this key (a redelivered copy + // is what ends early) holds its check itself. + let Some(mine) = open + .iter() + .find(|o| o.queued && o.key.as_deref() == Some(key)) + else { return false; }; - close(api, t, mine.id, c).await; + close_restoring(api, t, mine.id, c).await; true } @@ -535,7 +706,7 @@ pub async fn close_stale( }; let mut n = 0; for c in open.iter().filter(|c| c.stale(now)) { - close(api, t, c.id, &stopped_close(details_url)).await; + close_restoring(api, t, c.id, &stopped_close(details_url)).await; n += 1; } n @@ -594,6 +765,17 @@ pub mod fake { pub fn count(&self) -> usize { self.runs.lock().unwrap().len() } + /// What GitHub shows for the commit: its newest run of the name. + pub fn shown(&self, head: &str) -> Value { + self.runs + .lock() + .unwrap() + .iter() + .filter(|r| r["head_sha"].as_str() == Some(head)) + .max_by_key(|r| r["id"].as_u64().unwrap_or(0)) + .cloned() + .unwrap_or(Value::Null) + } fn refused(&self, what: &str) -> Result<(), String> { self.calls.lock().unwrap().push(what.to_string()); if self.refuse { @@ -865,6 +1047,155 @@ mod tests { assert!(is_refusal("GitHub answered 403 Forbidden: x")); } + #[tokio::test] + async fn a_reply_answered_only_leaves_the_standing_verdict_showing() { + let gh = FakeChecks::default(); + let t = target(1); + let v = take_over_or_open(&gh, &t, "head#x", "Reading", "s") + .await + .unwrap(); + close( + &gh, + &t, + v, + &Close { + conclusion: "neutral", + title: "Changes requested: 2 findings".into(), + summary: "[Read the review](https://x/r) on the pull request.".into(), + details_url: None, + }, + ) + .await; + // The reply shows at once, in plain words, over the finished check. + let q = queue_work(&gh, &t, Work::Reply, "reply#9", now(), "https://app/pr").await; + let id = match q { + Queued::Created(id) => id, + other => panic!("{other:?}"), + }; + assert_eq!(gh.shown(HEAD)["status"], "queued"); + assert_eq!( + gh.shown(HEAD)["output"]["title"], + "Reading your reply on 9fceb02" + ); + // Then in progress with the session link. + let title = started_title(Work::Reply, HEAD); + assert_eq!( + start(&gh, &t, "reply#9", &title, "https://app/session?id=j").await, + Some(id) + ); + assert_eq!(gh.shown(HEAD)["status"], "in_progress"); + assert_eq!(gh.shown(HEAD)["details_url"], "https://app/session?id=j"); + // Answered, nothing changed: the commit shows the verdict again. + close_restoring( + &gh, + &t, + id, + &Close { + conclusion: "neutral", + title: "Answered".into(), + summary: "Answered on the pull request.".into(), + details_url: Some("https://app/session?id=j".into()), + }, + ) + .await; + let shown = gh.shown(HEAD); + assert_eq!(shown["conclusion"], "neutral"); + assert_eq!(shown["output"]["title"], "Changes requested: 2 findings"); + let summary = shown["output"]["summary"].as_str().unwrap(); + assert!(summary.contains("[Read the review](https://x/r)")); + assert!(summary.contains("Answered on the pull request.")); + assert_eq!(shown["details_url"], "https://app/session?id=j"); + // An approval stays a pass. + let gh = FakeChecks::default(); + let v = take_over_or_open(&gh, &t, "head#x", "Reading", "s") + .await + .unwrap(); + close( + &gh, + &t, + v, + &Close { + conclusion: "success", + title: "Approved, no findings".into(), + summary: "s".into(), + details_url: None, + }, + ) + .await; + let id = take_over_or_open(&gh, &t, "reply#1", "Reading", "s") + .await + .unwrap(); + close_restoring(&gh, &t, id, &stopped_close("u")).await; + assert_eq!(gh.shown(HEAD)["conclusion"], "success"); + assert_eq!(gh.shown(HEAD)["output"]["title"], "Approved, no findings"); + } + + #[tokio::test] + async fn a_stale_reply_check_goes_back_to_the_verdict_and_a_running_job_keeps_its_own() { + let gh = FakeChecks::default(); + let t = target(1); + let v = take_over_or_open(&gh, &t, "head#x", "Reading", "s") + .await + .unwrap(); + close( + &gh, + &t, + v, + &Close { + conclusion: "success", + title: "Approved, no findings".into(), + summary: "s".into(), + details_url: None, + }, + ) + .await; + queue_work( + &gh, + &t, + Work::ReReview, + "reply#2", + now() - STALE_AFTER_SECS - 60, + "u", + ) + .await; + assert_eq!(close_stale(&gh, &t, now(), "u").await, 1); + assert_eq!(gh.shown(HEAD)["output"]["title"], "Approved, no findings"); + assert_eq!(gh.shown(HEAD)["conclusion"], "success"); + // A redelivered copy of a job that is running doesn't end its check. + let gh = FakeChecks::default(); + queue_work(&gh, &t, Work::Reply, "reply#3", now(), "u").await; + start(&gh, &t, "reply#3", "R", "s").await; + assert!(!close_waiting(&gh, &t, "reply#3", &stopped_close("u")).await); + assert_eq!(gh.run(1)["status"], "in_progress"); + } + + #[test] + fn titles_say_what_is_happening_and_ignored_replies_show_nothing() { + let t0 = 1_793_896_153; + for (trigger, question, title) in [ + ("reply", true, "Reading your reply on 9fceb02"), + ("thread_reply", true, "Reading your reply on 9fceb02"), + ("reply", false, "Re-reviewing 9fceb02"), + ("rerequest", false, "Re-reviewing 9fceb02"), + ( + "description", + false, + "Re-reviewing 9fceb02 with the edited description", + ), + ("labeled", false, "Reviewing 9fceb02 shortly"), + ] { + assert_eq!( + waiting_title(Work::of(trigger, question), HEAD, t0, t0), + title + ); + } + assert!(shows_when_sent("reply", true)); + assert!(shows_when_sent("rerequest", false)); + assert!(shows_when_sent("thread_reply", true)); + assert!(!shows_when_sent("thread_reply", false)); + assert!(!shows_when_sent("quote_reply", false)); + } + #[test] fn a_standing_verdict_keeps_its_conclusion() { assert_eq!(standing_conclusion("APPROVE"), "success"); diff --git a/services/gateway/src/routes/description_review.rs b/services/gateway/src/routes/description_review.rs index 7f42faa1b..3314e8630 100644 --- a/services/gateway/src/routes/description_review.rs +++ b/services/gateway/src/routes/description_review.rs @@ -16,9 +16,9 @@ use serde_json::Value; use tracing::{info, warn}; use super::github_webhook::{ - check_run_budget, load_review_config, may_start_work, post_limit_comment, send_to_queue_after, + check_run_budget, load_review_config, may_start_work, post_limit_comment, send_review_job, }; -use crate::models::{ReviewMessage, WorkerMessage}; +use crate::models::ReviewMessage; use crate::AppState; /// A description edit that may answer the review. @@ -284,13 +284,7 @@ pub(crate) async fn handle( "Description edited to answer the review — re-review queued" ); let message = review_message(payload, team_id, installation_id, &cfg.label, &edit); - let sent = send_to_queue_after( - state, - &state.config.ticket_queue_url, - &WorkerMessage::Review(message), - desc::SETTLE_SECS, - ) - .await; + let sent = send_review_job(state, message, head_sha, desc::SETTLE_SECS).await; if sent.is_err() { // Not queued: the next edit (or GitHub's redelivery) may try again. common::claim::release(&state.dynamo, table, team_id, &settle_sk).await; diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index f7f4427e1..ebf995c85 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -1018,12 +1018,8 @@ async fn handle_review_comment( } } }; - send_to_queue( - state, - &state.config.ticket_queue_url, - &WorkerMessage::Review(message), - ) - .await + let head = pr["head"]["sha"].as_str().unwrap_or(""); + send_review_job(state, message, head, 0).await } /// True when the comment's author is a bot account, read from GitHub's @@ -1207,7 +1203,7 @@ async fn handle_quote_reply( owner, name, pr_number, comment_id, "Reviewer: quote reply → review job" ); - let message = WorkerMessage::Review(ReviewMessage { + let message = ReviewMessage { team_id: team_id.to_string(), installation_id, repo_owner: owner.to_string(), @@ -1220,8 +1216,8 @@ async fn handle_quote_reply( dedup_key: format!("quote#{comment_id}#{}", reply_fingerprint(body)), requested_by: commenter.to_string(), ..Default::default() - }); - send_to_queue(state, &state.config.ticket_queue_url, &message).await + }; + send_review_job(state, message, "", 0).await } async fn handle_issue_comment( @@ -1522,7 +1518,7 @@ async fn handle_issue_comment( ) .await; } - let message = WorkerMessage::Review(ReviewMessage { + let message = ReviewMessage { team_id: team_id.to_string(), installation_id, repo_owner: owner.to_string(), @@ -1537,8 +1533,8 @@ async fn handle_issue_comment( requested_by: commenter.to_string(), outstanding_work: outstanding.as_ref().map(|(_, w)| w.note()), ..Default::default() - }); - return send_to_queue(state, &state.config.ticket_queue_url, &message).await; + }; + return send_review_job(state, message, "", 0).await; } else { info!( owner, @@ -1797,7 +1793,7 @@ async fn handle_pull_request( // redelivery of the same event is the same job. let key = rerequest_key(delivery_id, payload); record_rereview(state, team_id, owner, name, pr_number, &key).await; - let message = WorkerMessage::Review(ReviewMessage { + let message = ReviewMessage { team_id: team_id.to_string(), installation_id, repo_owner: owner.to_string(), @@ -1811,8 +1807,11 @@ async fn handle_pull_request( reply_to_comment_id: None, requested_by: String::new(), ..Default::default() - }); - return send_to_queue(state, &state.config.ticket_queue_url, &message).await; + }; + let head = payload["pull_request"]["head"]["sha"] + .as_str() + .unwrap_or(""); + return send_review_job(state, message, head, 0).await; } if action == "labeled" @@ -2416,7 +2415,7 @@ async fn handle_pr_review( ) .await; } - let message = WorkerMessage::Review(ReviewMessage { + let message = ReviewMessage { team_id: team_id.to_string(), installation_id, repo_owner: owner.to_string(), @@ -2430,8 +2429,11 @@ async fn handle_pr_review( reply_to_comment_id: None, requested_by: reviewer.to_string(), ..Default::default() - }); - return send_to_queue(state, &state.config.ticket_queue_url, &message).await; + }; + let head = payload["pull_request"]["head"]["sha"] + .as_str() + .unwrap_or(""); + return send_review_job(state, message, head, 0).await; } } return Ok(StatusCode::OK); @@ -3896,24 +3898,7 @@ async fn handle_review_trigger( owner, name, pr_number, is_bot_pr, action, "Reviewer: trigger matched — enqueuing review job" ); - let dedup_key = format!("head#{head_sha}"); - let delay = review_delay_secs(action); - // The commit shows the review at once, queued, saying when it starts: - // GitHub shows checks per commit, and a push's review waits for the PR - // to go quiet. The worker takes this check over when the job starts. - let check = ReviewCheckSpot { - installation_id, - owner, - name, - pr_number, - head_sha: &head_sha, - key: &dedup_key, - }; - let calls = review_check_calls(state, installation_id).await; - if let Some(calls) = &calls { - check.queue(calls, i64::from(delay)).await; - } - let message = WorkerMessage::Review(ReviewMessage { + let message = ReviewMessage { team_id: team_id.to_string(), installation_id, repo_owner: owner.to_string(), @@ -3923,20 +3908,91 @@ async fn handle_review_trigger( label: cfg.label, question: None, trigger: action.to_string(), - dedup_key: dedup_key.clone(), + dedup_key: format!("head#{head_sha}"), reply_to_comment_id: None, requested_by: String::new(), ..Default::default() - }); - let sent = send_to_queue_after(state, &state.config.ticket_queue_url, &message, delay).await; + }; + send_review_job(state, message, &head_sha, review_delay_secs(action)).await +} + +/// The ONE way a review job leaves the gateway: the job is sent and the commit +/// shows it, together, so no trigger can start work the owner can't see. A +/// source test fails if anything else sends a review job. +/// +/// `head` is the commit the event names, when it names one; otherwise the PR's +/// head is read. The job's own `head_sha` is left as the trigger set it (empty +/// means the worker resolves the head when it starts). A reply that may not be +/// for CoderHelm shows nothing here: see `review_check::shows_when_sent`. +pub(crate) async fn send_review_job( + state: &AppState, + mut message: ReviewMessage, + head: &str, + delay_secs: i32, +) -> Result { + let mut shown: Option<(common::review_check::TokenCalls<'_>, String)> = None; + if common::review_check::shows_when_sent(&message.trigger, message.mentioned) { + if let Some(calls) = review_check_calls(state, message.installation_id).await { + let head = if head.is_empty() { + pr_head(state, &calls.token, &message).await + } else { + head.to_string() + }; + // Never holds the job up: the worker opens the check if this + // didn't get through. + let spot = ReviewCheckSpot::of(&message, &head); + let _ = tokio::time::timeout( + std::time::Duration::from_secs(REVIEW_CHECK_BUDGET_SECS), + spot.show(&calls, &message, i64::from(delay_secs)), + ) + .await; + shown = Some((calls, head)); + } + } + if let Some((_, head)) = &shown { + message.check_head = head.clone(); + } + let sent = send_to_queue_after( + state, + &state.config.ticket_queue_url, + &WorkerMessage::Review(message.clone()), + delay_secs, + ) + .await; if sent.is_err() { - if let Some(calls) = &calls { - check.not_queued(calls).await; + if let Some((calls, head)) = &shown { + ReviewCheckSpot::of(&message, head).not_queued(calls).await; } } sent } +/// How long showing a job's check may hold its webhook up. +const REVIEW_CHECK_BUDGET_SECS: u64 = 6; + +/// The head of the job's PR; empty when it can't be read (no check then, the +/// worker opens one when it has the head). +async fn pr_head(state: &AppState, token: &str, m: &ReviewMessage) -> String { + let url = format!( + "https://api.github.com/repos/{}/{}/pulls/{}", + m.repo_owner, m.repo_name, m.pr_number + ); + match super::merge_control::gh_get(state, token, &url).await { + Ok((code, body)) if code < 300 => body["head"]["sha"].as_str().unwrap_or("").to_string(), + Ok((code, _)) => { + warn!( + pr = m.pr_number, + code, "Could not read the PR's head for its check" + ); + String::new() + } + Err(e) => { + warn!(pr = m.pr_number, error = %e, "Could not read the PR's head for its check"); + String::new() + } + } +} + /// Where a scheduled review's queued check goes, and the job it waits for. struct ReviewCheckSpot<'a> { installation_id: u64, @@ -3947,7 +4003,39 @@ struct ReviewCheckSpot<'a> { key: &'a str, } -impl ReviewCheckSpot<'_> { +impl<'a> ReviewCheckSpot<'a> { + fn of(m: &'a ReviewMessage, head: &'a str) -> Self { + ReviewCheckSpot { + installation_id: m.installation_id, + owner: &m.repo_owner, + name: &m.repo_name, + pr_number: m.pr_number, + head_sha: head, + key: &m.dedup_key, + } + } + + /// Put job `m`, due in `delay_secs`, on the commit in plain words. A + /// refusal (no checks:write) is logged once and changes nothing. + async fn show( + &self, + calls: &C, + m: &ReviewMessage, + delay_secs: i64, + ) -> common::review_check::Queued { + let work = common::review_check::Work::of(&m.trigger, m.question.is_some()); + let due = chrono::Utc::now().timestamp() + delay_secs; + common::review_check::queue_work( + calls, + &self.target(), + work, + self.key, + due, + &self.details_url(), + ) + .await + } + fn target(&self) -> common::review_check::Target<'_> { common::review_check::Target { installation: self.installation_id, @@ -3967,17 +4055,6 @@ impl ReviewCheckSpot<'_> { ) } - /// Put the queued check on the commit, the review due in `delay_secs`. - /// A refusal (no checks:write) is logged once and changes nothing. - async fn queue( - &self, - calls: &C, - delay_secs: i64, - ) -> common::review_check::Queued { - let due = chrono::Utc::now().timestamp() + delay_secs; - common::review_check::queue(calls, &self.target(), self.key, due, &self.details_url()).await - } - /// The review job couldn't be sent: the check says so instead of waiting. async fn not_queued(&self, calls: &C) { let close = common::review_check::Close { @@ -4555,8 +4632,9 @@ mod review_delay_tests { use common::review_check::{fake::FakeChecks, Queued}; let gh = FakeChecks::default(); let s = spot(1); + let m = job("synchronize", s.key, None, false); let q = s - .queue(&gh, i64::from(review_delay_secs("synchronize"))) + .show(&gh, &m, i64::from(review_delay_secs("synchronize"))) .await; assert_eq!(q, Queued::Created(1)); let run = gh.run(1); @@ -4575,7 +4653,7 @@ mod review_delay_tests { common::review_check::parse_external_id(run["external_id"].as_str().unwrap()).unwrap(); assert_eq!(key, s.key); // A sibling event for the same commit adds no second check. - assert_eq!(s.queue(&gh, 0).await, Queued::Exists(1)); + assert_eq!(s.show(&gh, &m, 0).await, Queued::Exists(1)); assert_eq!(gh.count(), 1); // A job that couldn't be sent leaves no check waiting. s.not_queued(&gh).await; @@ -4587,11 +4665,172 @@ mod review_delay_tests { ); } + fn job( + trigger: &str, + key: &str, + question: Option<&str>, + mentioned: bool, + ) -> crate::models::ReviewMessage { + crate::models::ReviewMessage { + installation_id: 1, + repo_owner: "acme".into(), + repo_name: "web".into(), + pr_number: 7, + trigger: trigger.into(), + dedup_key: key.into(), + question: question.map(String::from), + mentioned, + ..Default::default() + } + } + + const HEAD: &str = "9fceb02d0ae598e95dc970b74767f19372d61af8"; + + /// Each trigger as the handlers build it, and what the commit shows as + /// soon as the job is sent. + #[tokio::test] + async fn every_trigger_shows_on_the_commit_with_a_plain_title() { + use common::review_check::fake::FakeChecks; + for (m, title) in [ + ( + job("thread_reply", "thread#1", Some("why?"), true), + "Reading your reply on 9fceb02", + ), + ( + job("reply", "reply#2", Some("why?"), true), + "Reading your reply on 9fceb02", + ), + (job("reply", "reply#3", None, true), "Re-reviewing 9fceb02"), + ( + job("reply", "review#4", None, false), + "Re-reviewing 9fceb02", + ), + ( + job("rerequest", "rereq#5", None, false), + "Re-reviewing 9fceb02", + ), + ( + job("rerequest", "dashboard#pr7#6", None, false), + "Re-reviewing 9fceb02", + ), + ( + job("rerequest", "rearm#h", None, false), + "Re-reviewing 9fceb02", + ), + ( + job("description", "desc#h#x", None, false), + "Re-reviewing 9fceb02 with the edited description", + ), + ( + job("labeled", "head#h", None, false), + "Reviewing 9fceb02 shortly", + ), + ] { + assert!(common::review_check::shows_when_sent( + &m.trigger, + m.mentioned + )); + let gh = FakeChecks::default(); + super::ReviewCheckSpot::of(&m, HEAD).show(&gh, &m, 0).await; + let run = gh.shown(HEAD); + assert_eq!(run["status"], "queued"); + assert_eq!(run["output"]["title"], title); + assert!(run["details_url"] + .as_str() + .unwrap() + .contains("/reviewer/pr?repo=acme/web&pr=7")); + let (_, key) = + common::review_check::parse_external_id(run["external_id"].as_str().unwrap()) + .unwrap(); + assert_eq!(key, m.dedup_key); + } + } + + /// A reply that may not be for CoderHelm isn't shown when it is sent: only + /// the worker can tell, and it leaves the check alone when it isn't. + #[test] + fn a_reply_that_may_not_be_for_coderhelm_shows_nothing_when_sent() { + assert!(!common::review_check::shows_when_sent( + "thread_reply", + false + )); + assert!(!common::review_check::shows_when_sent("quote_reply", false)); + } + + #[tokio::test] + async fn a_job_that_cannot_be_sent_gives_the_commit_its_verdict_back() { + use common::review_check::{close, fake::FakeChecks, take_over_or_open, Close}; + let gh = FakeChecks::default(); + let m = job("reply", "reply#2", Some("why?"), true); + let spot = super::ReviewCheckSpot::of(&m, HEAD); + let id = take_over_or_open(&gh, &spot.target(), "head#h", "Reading", "s") + .await + .unwrap(); + close( + &gh, + &spot.target(), + id, + &Close { + conclusion: "neutral", + title: "Changes requested: 1 finding".into(), + summary: "s".into(), + details_url: None, + }, + ) + .await; + spot.show(&gh, &m, 0).await; + spot.not_queued(&gh).await; + assert_eq!( + gh.shown(HEAD)["output"]["title"], + "Changes requested: 1 finding" + ); + } + + /// Whole-class guard: nothing in the gateway sends a review job except + /// `send_review_job`, so a new trigger can't forget the check. + #[test] + fn nothing_sends_a_review_job_around_the_helper() { + let mut offenders = Vec::new(); + let root = concat!(env!("CARGO_MANIFEST_DIR"), "/src"); + let mut stack = vec![std::path::PathBuf::from(root)]; + while let Some(dir) = stack.pop() { + for e in std::fs::read_dir(&dir).unwrap() { + let path = e.unwrap().path(); + if path.is_dir() { + stack.push(path); + continue; + } + if path.extension().and_then(|x| x.to_str()) != Some("rs") { + continue; + } + let src = std::fs::read_to_string(&path).unwrap(); + // The whole file: a module may have code after its tests. + let helper = src.find("pub(crate) async fn send_review_job"); + let needle = concat!("WorkerMessage::", "Review("); + for (at, _) in src.match_indices(needle) { + let in_helper = + helper.is_some_and(|h| at > h && src[h..at].find("\n}\n").is_none()); + // `send_to_queue_after` reads the message to show it as + // queued on the dashboard; it doesn't build one. + let reads = src[at..].starts_with(concat!("WorkerMessage::", "Review(r)")); + if !in_helper && !reads { + offenders.push(path.display().to_string()); + } + } + } + } + assert!( + offenders.is_empty(), + "review jobs sent around send_review_job: {offenders:?}" + ); + } + #[tokio::test] async fn an_install_without_checks_write_is_left_alone() { use common::review_check::{fake::FakeChecks, Queued}; let gh = FakeChecks::refusing(); - assert_eq!(spot(88_001).queue(&gh, 180).await, Queued::Nothing); + let m = job("synchronize", "head#x", None, false); + assert_eq!(spot(88_001).show(&gh, &m, 180).await, Queued::Nothing); spot(88_001).not_queued(&gh).await; assert!(gh.calls.lock().unwrap().iter().all(|c| c == "list")); assert_eq!(gh.count(), 0); diff --git a/services/gateway/src/routes/merge_control.rs b/services/gateway/src/routes/merge_control.rs index ccccd724e..f60fe79c7 100644 --- a/services/gateway/src/routes/merge_control.rs +++ b/services/gateway/src/routes/merge_control.rs @@ -283,7 +283,7 @@ pub(crate) async fn apply( .map_err(db_err)?; let next = merge_gate::rearm_next(verdict.as_deref(), cfg.enabled && !cfg.killed); if next == RearmNext::QueueReview { - let review = WorkerMessage::Review(ReviewMessage { + let review = ReviewMessage { team_id: team_id.to_string(), installation_id, repo_owner: owner.to_string(), @@ -301,13 +301,8 @@ pub(crate) async fn apply( String::new() }, ..Default::default() - }); - super::github_webhook::send_to_queue( - state, - &state.config.ticket_queue_url, - &review, - ) - .await?; + }; + super::github_webhook::send_review_job(state, review, &head, 0).await?; } // The gate checks every condition again on the current head. super::github_webhook::send_to_queue(state, &state.config.ticket_queue_url, &gate_msg) diff --git a/services/gateway/src/routes/reviewer.rs b/services/gateway/src/routes/reviewer.rs index fc3ec2c1f..a6d82c758 100644 --- a/services/gateway/src/routes/reviewer.rs +++ b/services/gateway/src/routes/reviewer.rs @@ -1896,7 +1896,7 @@ pub async fn re_review( let installation_id = super::api::get_team_installation_id(&state, &claims.team_id).await?; let window = chrono::Utc::now().timestamp() / RE_REVIEW_DEDUP_SECS; - let message = WorkerMessage::Review(ReviewMessage { + let message = ReviewMessage { team_id: claims.team_id.clone(), installation_id, repo_owner: owner.to_string(), @@ -1910,8 +1910,8 @@ pub async fn re_review( reply_to_comment_id: None, requested_by: String::new(), ..Default::default() - }); - super::github_webhook::send_to_queue(&state, &state.config.ticket_queue_url, &message).await?; + }; + super::github_webhook::send_review_job(&state, message, "", 0).await?; super::github_webhook::record_rereview( &state, &claims.team_id, diff --git a/services/worker/src/passes/await_merge.rs b/services/worker/src/passes/await_merge.rs index 5a92735bf..c7d551c3e 100644 --- a/services/worker/src/passes/await_merge.rs +++ b/services/worker/src/passes/await_merge.rs @@ -258,6 +258,8 @@ pub(crate) struct GateView { pub require_human: bool, /// CoderHelm's own latest verdict recorded for this head. pub bot_verdict: Option, + /// What holds that verdict, by name, as the review named it. + pub bot_holding: Vec, pub approvals: Approvals, /// Deploy labels the repo wants on a PR cleared to merge. pub want_labels: Vec, @@ -306,25 +308,28 @@ fn short(sha: &str) -> &str { pub(crate) fn decide_gate(v: &GateView) -> GateDecision { let bot_dismissed = v.approvals.bot_dismissed_at_head; let bot_approved = v.bot_verdict.as_deref() == Some("APPROVE") && !bot_dismissed; - let human_present = v.approvals.human_key(); + let human_present = v.approvals.human_key_at_head(); let mut lines: Vec<(Mark, String)> = Vec::new(); - lines.push(match (v.bot_verdict.as_deref(), bot_dismissed) { - (Some("APPROVE"), false) => (Mark::Done, "CoderHelm approved".to_string()), - (Some("APPROVE"), true) => ( + match (v.bot_verdict.as_deref(), bot_dismissed) { + (Some("APPROVE"), false) => lines.push((Mark::Done, "CoderHelm approved".to_string())), + (Some("APPROVE"), true) => lines.push(( Mark::Blocked, "CoderHelm's approval was dismissed. Comment `@coderhelm re-review` to review \ again" .to_string(), - ), - (Some(_), _) => (Mark::Blocked, "CoderHelm requested changes".to_string()), - (None, _) => (Mark::Waiting, "Waiting for CoderHelm's review".to_string()), - }); + )), + (Some(_), _) => lines.extend(holding_lines(&v.bot_holding)), + (None, _) => lines.push((Mark::Waiting, "Waiting for CoderHelm's review".to_string())), + } if v.require_human { lines.push(if human_present { ( Mark::Done, - format!("Approved by {}", mention_list(&v.approvals.approved_by)), + format!( + "Approved by {}", + mention_list(&v.approvals.approved_at_head) + ), ) } else if !v.approvals.blocking_by.is_empty() { ( @@ -334,6 +339,15 @@ pub(crate) fn decide_gate(v: &GateView) -> GateDecision { mention_list(&v.approvals.blocking_by) ), ) + } else if !v.approvals.approved_by.is_empty() { + ( + Mark::Waiting, + format!( + "Approved by {} on an earlier commit; waiting for a person's approval of \ + this one", + mention_list(&v.approvals.approved_by) + ), + ) } else { (Mark::Waiting, "Waiting for a person's approval".to_string()) }); @@ -436,6 +450,34 @@ pub(crate) fn decide_gate(v: &GateView) -> GateDecision { } } +/// Pure: the panel's lines for CoderHelm's block: what holds it, as the review +/// named it. A review older than named items points at the review. +fn holding_lines(holding: &[String]) -> Vec<(Mark, String)> { + const SHOW: usize = 5; + if holding.is_empty() { + return vec![( + Mark::Blocked, + "CoderHelm requested changes: its review of this commit says what holds the merge" + .to_string(), + )]; + } + let mut lines: Vec<(Mark, String)> = holding + .iter() + .take(SHOW) + .map(|h| (Mark::Blocked, format!("CoderHelm requested changes: {h}"))) + .collect(); + if holding.len() > SHOW { + lines.push(( + Mark::Blocked, + format!( + "CoderHelm requested changes: {} more in its review", + holding.len() - SHOW + ), + )); + } + lines +} + fn mention_list(logins: &[String]) -> String { logins .iter() @@ -820,8 +862,8 @@ async fn publish_status( async fn bot_verdict_at_head( state: &WorkerState, msg: &AwaitMergeMessage, -) -> Result, BoxError> { - common::merge_gate::bot_verdict_at_head( +) -> Result, BoxError> { + common::merge_gate::bot_review_at_head( &state.dynamo, &state.config.settings_table_name, &msg.team_id, @@ -1167,11 +1209,16 @@ async fn evaluate( } let approvals = fetch_approvals(github, owner, repo, msg.pr_number, &msg.head_sha).await?; - let bot_verdict = bot_verdict_at_head(state, msg).await?; + let bot = bot_verdict_at_head(state, msg).await?; + let (bot_verdict, bot_holding) = match bot { + Some(b) => (Some(b.verdict), b.holding), + None => (None, Vec::new()), + }; let mut view = GateView { draft: pr["draft"].as_bool().unwrap_or(false), require_human: cfg.require_human_approval || msg.self_authored, bot_verdict, + bot_holding, approvals, want_labels: cfg .deploy_label @@ -1564,6 +1611,44 @@ pub async fn arm( send(state, &msg, 0, SETTLE_DELAY_SECS).await } +/// A review of the head still requests changes: a gate that already shows its +/// panel on the PR reads it again, so the panel names what holds the merge now. +/// It can't merge on this verdict (see [`decide_gate`]). A PR without a panel, +/// or stopped by a person, is left alone. +#[allow(clippy::too_many_arguments)] +pub async fn refresh_panel( + state: &WorkerState, + team_id: &str, + installation_id: u64, + owner: &str, + repo: &str, + pr_number: u64, + head_sha: &str, + base_branch: &str, + self_authored: bool, +) { + let msg = AwaitMergeMessage { + team_id: team_id.to_string(), + installation_id, + repo_owner: owner.to_string(), + repo_name: repo.to_string(), + pr_number, + head_sha: head_sha.to_string(), + base_branch: base_branch.to_string(), + self_authored, + attempts: 0, + chain_id: String::new(), + error_retries: 0, + }; + match load_record(state, &msg).await { + Ok(r) if !r.status_body.is_empty() && r.stopped.is_none() => { + send(state, &msg, 0, 0).await; + } + Ok(_) => {} + Err(e) => warn!(pr = pr_number, error = %e, "Could not read the merge gate to refresh it"), + } +} + /// Enqueue an AwaitMerge tick with `attempts` and an SQS delay. async fn send(state: &WorkerState, msg: &AwaitMergeMessage, attempts: u32, delay: i32) -> bool { if state.config.ticket_queue_url.is_empty() { @@ -1754,8 +1839,10 @@ mod ci_tests { draft: false, require_human: true, bot_verdict: Some("APPROVE".into()), + bot_holding: vec![], approvals: Approvals { approved_by: vec!["alice".into()], + approved_at_head: vec!["alice".into()], ..Default::default() }, want_labels: vec![], @@ -1813,6 +1900,72 @@ mod ci_tests { .any(|(m, l)| *m == Mark::Blocked && l.contains("dismissed"))); } + /// Person approved, auto-merge armed, CoderHelm's block named on the panel; + /// the description is edited and the threads settle; the verdict clears. + /// What happens next, exactly: the approval re-arms the gate, which merges + /// only with a person's approval of this very commit and green CI. + #[test] + fn a_verdict_that_clears_merges_only_with_a_persons_approval_of_this_commit_and_green_ci() { + // Blocked, naming what holds it, not merged, CI not even read. + let mut v = view(); + v.bot_verdict = Some("REQUEST_CHANGES".into()); + v.bot_holding = vec!["`deploy.tf:3` State key is shared".into()]; + v.ci = Some(green()); + let d = decide_gate(&v); + assert_eq!(d.action, Action::WaitForPeople); + assert_eq!( + d.lines[0], + ( + Mark::Blocked, + "CoderHelm requested changes: `deploy.tf:3` State key is shared".to_string() + ) + ); + assert!(!d + .lines + .iter() + .any(|(_, l)| l == "CoderHelm requested changes")); + // The verdict clears: with the approval and green CI, the merge fires. + v.bot_verdict = Some("APPROVE".into()); + v.bot_holding = vec![]; + let d = decide_gate(&v); + assert_eq!(d.action, Action::Merge); + assert!(d.lines.iter().any(|(_, l)| l == "CoderHelm approved")); + // CI not green yet: it waits. + v.ci = None; + assert_eq!(decide_gate(&v).action, Action::ReadCi); + // The person's approval is of an earlier commit: it waits for a person. + let mut stale = view(); + stale.approvals.approved_at_head = vec![]; + stale.ci = Some(green()); + let d = decide_gate(&stale); + assert_eq!(d.action, Action::WaitForPeople); + assert!(d + .lines + .iter() + .any(|(m, l)| *m == Mark::Waiting && l.contains("on an earlier commit"))); + // A repo that turned off requiring a person merges on CoderHelm's + // approval and green CI alone; CoderHelm's own PRs never do (see + // `evaluate`: `require_human` is forced on for them). + let mut no_human = view(); + no_human.require_human = false; + no_human.approvals = Approvals::default(); + no_human.ci = Some(green()); + assert_eq!(decide_gate(&no_human).action, Action::Merge); + let src = include_str!("await_merge.rs"); + assert!(src.contains("require_human: cfg.require_human_approval || msg.self_authored")); + } + + #[test] + fn a_long_list_of_holds_points_at_the_review_and_an_old_record_does_too() { + let many: Vec = (1..=7).map(|i| format!("item {i}")).collect(); + let lines = holding_lines(&many); + assert_eq!(lines.len(), 6); + assert!(lines[5].1.contains("2 more in its review")); + assert!(holding_lines(&[])[0] + .1 + .contains("its review of this commit")); + } + #[test] fn coderhelm_s_request_for_changes_is_never_merged_on() { let mut v = view(); 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 717539199..765cdbdc1 100644 --- a/services/worker/src/passes/incidents/k_own_review_findings.rs +++ b/services/worker/src/passes/incidents/k_own_review_findings.rs @@ -56,7 +56,10 @@ fn the_own_review_requests_changes_and_lists_every_non_optional_finding() { let verdict = review_agent::decide_verdict(&findings, 0, &[], false); assert_eq!(verdict, "REQUEST_CHANGES"); assert_eq!( - review_severity::consistent_verdict("APPROVE", &findings), + crate::passes::review_verdict::Verdict::from_holding( + crate::passes::review_policy::named_holding(&findings, &[], &[], false, &[], &[]) + ) + .event(), "REQUEST_CHANGES" ); // On its own PR they are the run's to fix, listed at the top. @@ -70,12 +73,18 @@ fn the_own_review_requests_changes_and_lists_every_non_optional_finding() { assert!(body.starts_with(own_review::START)); end.said(body.clone()); end.said(review_agent::verdict_heading( - verdict, - &review_agent::HeadingCounts { - defects: 3, - own_open: 3, - ..Default::default() - }, + &crate::passes::review_verdict::Verdict::from_holding( + findings + .iter() + .map(|f| { + crate::passes::review_verdict::Holding::new( + crate::passes::review_verdict::HoldKind::Defect, + f.title.clone(), + ) + }) + .collect(), + ), + 0, )); // While they are listed the PR stays a draft: neither mark-ready path // goes on. @@ -103,8 +112,8 @@ fn the_review_posts_never_approve_with_a_blocker_and_arms_nothing_on_open_findin let src = include_str!("../review_pr.rs"); let run = fn_src(src, "\nasync fn run_once("); let consistent = run - .find("review_severity::consistent_verdict(") - .expect("run_once makes the verdict consistent with its findings"); + .find("review_policy::named_holding(") + .expect("run_once makes the verdict from what holds the merge"); let own = run .find("own_review::required(") .expect("run_once lists the own PR's open findings"); diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 8e3fca679..cddd4d366 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -864,6 +864,7 @@ pub mod review_actions; pub mod review_agent; #[cfg(test)] mod review_eval; +pub(crate) mod review_fingerprint; pub mod review_fix; pub mod review_labels; pub mod review_lessons; diff --git a/services/worker/src/passes/own_review.rs b/services/worker/src/passes/own_review.rs index 420661781..1617c9089 100644 --- a/services/worker/src/passes/own_review.rs +++ b/services/worker/src/passes/own_review.rs @@ -75,8 +75,8 @@ pub fn thread_line(path: &str, line: u64, body: &str) -> String { }) .find(|l| !l.is_empty()) .unwrap_or("Earlier finding"); + // Whole: a title is one line, and posted text is never cut mid-sentence. let title = title.split_whitespace().collect::>().join(" "); - let title = common::truncate_str(&title, 160); if line > 0 { format!("{title} (`{path}:{line}`)") } else { diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 14a821290..52e11fc1e 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -185,7 +185,9 @@ was checked and shows it. A matching filter or a passing test is not that; other `{}` or empty backticks. - When the change touches more than one environment, the Evidence list has one bullet per \ environment: what confirmed it, or exactly which environment couldn't be checked and what access \ -is missing."; +is missing. +- Deploy claims come only from what was read in the repo's CI workflows and module wiring, since \ +docs go stale. Name a manual deploy step only if a workflow or the wiring shows one is needed."; /// What the writer is told about the checks only a person can do: each one /// a numbered Verification step, and nowhere else. Empty when there are none. @@ -2121,6 +2123,10 @@ mod refresh_tests { assert!(rules.contains("real output (the real API response or page)")); assert!(rules.contains("A matching filter or a passing test is not that")); assert!(rules.contains("**Unproven** and the exact check a person should run")); + assert!(rules.contains("Deploy claims come only from what was read")); + assert!(rules.contains("CI workflows and module wiring")); + assert!(rules.contains("docs go stale")); + assert!(rules.contains("manual deploy step only if a workflow or the wiring shows")); } #[test] diff --git a/services/worker/src/passes/review_actions.rs b/services/worker/src/passes/review_actions.rs index be0a5dc25..46257ada9 100644 --- a/services/worker/src/passes/review_actions.rs +++ b/services/worker/src/passes/review_actions.rs @@ -227,6 +227,8 @@ pub struct ActionReport { pub struct Approvals { /// People whose latest verdict is APPROVED. pub approved_by: Vec, + /// Of those, the ones whose approval is of the head commit. + pub approved_at_head: Vec, /// Reviewers (people or other bots) whose latest verdict is /// CHANGES_REQUESTED. pub blocking_by: Vec, @@ -235,10 +237,12 @@ pub struct Approvals { } impl Approvals { - /// The person key of the two-key rule: someone approved and nobody's - /// standing request for changes outvotes it. - pub fn human_key(&self) -> bool { - !self.approved_by.is_empty() && self.blocking_by.is_empty() + /// The person key for merging on its own: a person approved this very + /// commit, and nobody's standing request for changes outvotes it. A merge + /// may reach production, so an approval of an earlier commit doesn't count + /// even where GitHub's own rules would keep it. + pub fn human_key_at_head(&self) -> bool { + !self.approved_at_head.is_empty() && self.blocking_by.is_empty() } } @@ -250,7 +254,8 @@ impl Approvals { /// clears one. CoderHelm's own reviews are never the person key, and a /// dismissal of its review of the head withdraws its key (fail closed). pub fn approval_state(reviews: &serde_json::Value, head_sha: &str) -> Approvals { - let mut latest: std::collections::BTreeMap = std::collections::BTreeMap::new(); + let mut latest: std::collections::BTreeMap = + std::collections::BTreeMap::new(); let mut bot_at_head: Option<&str> = None; for r in reviews.as_array().map(|a| a.as_slice()).unwrap_or(&[]) { let login = r["user"]["login"].as_str().unwrap_or(""); @@ -267,18 +272,27 @@ pub fn approval_state(reviews: &serde_json::Value, head_sha: &str) -> Approvals continue; } if matches!(state, "APPROVED" | "CHANGES_REQUESTED" | "DISMISSED") { - latest.insert(login.to_string(), state); + latest.insert( + login.to_string(), + (state, r["commit_id"].as_str().unwrap_or("")), + ); } } let with = |want: &str| -> Vec { latest .iter() - .filter(|(_, s)| **s == want) + .filter(|(_, (s, _))| *s == want) .map(|(l, _)| l.clone()) .collect() }; + let approved_at_head = latest + .iter() + .filter(|(_, (s, c))| *s == "APPROVED" && *c == head_sha) + .map(|(l, _)| l.clone()) + .collect(); Approvals { approved_by: with("APPROVED"), + approved_at_head, blocking_by: with("CHANGES_REQUESTED"), bot_dismissed_at_head: bot_at_head == Some("DISMISSED"), } @@ -848,7 +862,7 @@ mod tests { let a = approval_state(&reviews, "h1"); assert_eq!(a.approved_by, vec!["alice".to_string()]); assert_eq!(a.blocking_by, vec!["bob".to_string()]); - assert!(!a.human_key()); + assert!(!a.human_key_at_head()); } #[test] @@ -860,20 +874,20 @@ mod tests { ]); let a = approval_state(&reviews, "h2"); assert!(a.blocking_by.is_empty()); - assert!(a.human_key()); + assert!(a.human_key_at_head()); // A dismissed approval is no key either. let dismissed = serde_json::json!([ rv("alice", "APPROVED", "h1"), rv("alice", "DISMISSED", "h1"), ]); - assert!(!approval_state(&dismissed, "h1").human_key()); + assert!(!approval_state(&dismissed, "h1").human_key_at_head()); } #[test] fn coderhelm_s_review_is_never_the_person_key() { let reviews = serde_json::json!([rv("coderhelm[bot]", "APPROVED", "h1")]); let a = approval_state(&reviews, "h1"); - assert!(!a.human_key()); + assert!(!a.human_key_at_head()); assert!(!a.bot_dismissed_at_head); } diff --git a/services/worker/src/passes/review_agent.rs b/services/worker/src/passes/review_agent.rs index 5f58fec92..7dcf43e7c 100644 --- a/services/worker/src/passes/review_agent.rs +++ b/services/worker/src/passes/review_agent.rs @@ -835,78 +835,75 @@ pub fn decide_verdict( } } -/// What a review's heading says. The counts are of what holds the merge, -/// except `notes`: everything posted with an approval that doesn't. -#[derive(Debug, Clone, Copy, Default)] -pub struct HeadingCounts { - pub defects: usize, - /// On CoderHelm's own PR: findings it fixes itself before ready. - pub own_open: usize, - pub blocking_questions: usize, - pub blocking_facts: usize, - pub prior_open: usize, - pub verify_failed: bool, - pub notes: usize, -} - -fn plural(n: usize, one: &str, many: &str) -> String { - format!("{n} {}", if n == 1 { one } else { many }) -} - -/// The first line of a formal review: the verdict, and why in one sentence. -pub fn verdict_heading(verdict: &str, c: &HeadingCounts) -> String { - if verdict == "APPROVE" { - return if c.notes == 0 { +/// Pure: the review's first lines: the verdict and why, then each named thing +/// holding the merge. `notes` counts what is posted with an approval. +pub fn verdict_heading(verdict: &super::review_verdict::Verdict, notes: usize) -> String { + use super::review_verdict::HoldKind as K; + let plural = |n: usize, one: &str, many: &str| { + if n == 1 { + format!("1 {one}") + } else { + format!("{n} {many}") + } + }; + if verdict.holding().is_empty() { + return if notes == 0 { "✅ **Approved**: nothing in the change needs fixing.".to_string() } else { format!( "✅ **Approved with notes**: nothing blocks the merge; {} below {} for a look.", - plural(c.notes, "note", "notes"), - if c.notes == 1 { "is" } else { "are" } + plural(notes, "note", "notes"), + if notes == 1 { "is" } else { "are" } ) }; } + let count = |k: K| verdict.holding().iter().filter(|h| h.kind == k).count(); let mut why: Vec = Vec::new(); - if c.defects > 0 { - why.push(plural(c.defects, "defect to fix", "defects to fix")); - } - if c.defects == 0 && c.own_open > 0 { - why.push(plural( - c.own_open, + for (kind, one, many) in [ + (K::Defect, "defect to fix", "defects to fix"), + ( + K::OwnFinding, "finding CoderHelm fixes before this PR is ready", "findings CoderHelm fixes before this PR is ready", - )); - } - if c.blocking_questions > 0 { - why.push(plural( - c.blocking_questions, + ), + ( + K::Question, "question the change rests on", "questions the change rests on", - )); - } - if c.blocking_facts > 0 { - why.push(plural( - c.blocking_facts, + ), + ( + K::Fact, "unconfirmed fact the change relies on", "unconfirmed facts the change relies on", - )); - } - if c.prior_open > 0 { - why.push(plural( - c.prior_open, + ), + ( + K::EarlierThread, "earlier requested change still open", "earlier requested changes still open", - )); + ), + ( + K::KeptFromEarlier, + "item from my last review still holding", + "items from my last review still holding", + ), + ] { + if count(kind) > 0 { + why.push(plural(count(kind), one, many)); + } } - if c.verify_failed { + if count(K::Verification) > 0 { why.push("the verification run failed".to_string()); } - let reason = match why.len() { - 0 => "something holds the merge.".to_string(), - 1 => format!("{}.", why[0]), - n => format!("{} and {}.", why[..n - 1].join(", "), why[n - 1]), + let reason = match why.as_slice() { + [one] => one.clone(), + [rest @ .., last] => format!("{} and {last}", rest.join(", ")), + [] => plural(verdict.holding().len(), "item holds", "items hold"), }; - format!("❌ **Changes requested**: {reason}") + let mut out = format!("❌ **Changes requested**: {reason}.\n\n**Holding the merge:**"); + for h in verdict.holding() { + out.push_str(&format!("\n- {}", h.name)); + } + out } pub fn review_tools() -> Vec { @@ -1403,7 +1400,11 @@ pub fn fold_inline_into_body(body: &str, inline: &[InlineComment]) -> String { )); } // GitHub caps a review body at 65,536 characters. - common::truncate_str(&out, 60_000).to_string() + common::prose::cap_on_sentence( + &out, + 60_000, + "The rest of the findings didn't fit in this review; the session page lists them all.", + ) } /// Build a bounded diff string for the prompt (per-file patch, head+tail capped). @@ -3129,12 +3130,10 @@ mod evidence_tests { assert_eq!(facts.len(), 2, "{facts:?}"); let verdict = decide_verdict(&[], 0, &facts, false); assert_eq!(verdict, "APPROVE"); + assert_eq!(verdict, "APPROVE"); let heading = verdict_heading( - verdict, - &HeadingCounts { - notes: facts.iter().filter(|f| !f.blocks).count(), - ..Default::default() - }, + &crate::passes::review_verdict::Verdict::approve(), + facts.iter().filter(|f| !f.blocks).count(), ); assert!( heading.starts_with("✅ **Approved with notes**"), @@ -3231,52 +3230,60 @@ mod evidence_tests { } #[test] - fn the_heading_names_the_verdict_and_why_in_one_line() { - let approved = verdict_heading("APPROVE", &HeadingCounts::default()); + fn the_heading_names_the_verdict_and_what_holds_it() { + use crate::passes::review_verdict::{HoldKind as K, Holding, Verdict}; + let approved = verdict_heading(&Verdict::approve(), 0); assert_eq!( approved, "✅ **Approved**: nothing in the change needs fixing." ); - let notes = verdict_heading( - "APPROVE", - &HeadingCounts { - notes: 2, - ..Default::default() - }, - ); + let notes = verdict_heading(&Verdict::approve(), 2); assert_eq!( notes, "✅ **Approved with notes**: nothing blocks the merge; 2 notes below are for a look." ); let blocked = verdict_heading( - "REQUEST_CHANGES", - &HeadingCounts { - defects: 1, - blocking_facts: 2, - notes: 3, - ..Default::default() - }, + &Verdict::from_holding(vec![ + Holding::new(K::Defect, "`a.rs:3` Null deref"), + Holding::new(K::Fact, "The vendor returns cents"), + Holding::new(K::Fact, "The table has an index"), + ]), + 3, ); assert_eq!( blocked, - "❌ **Changes requested**: 1 defect to fix and 2 unconfirmed facts the change relies on." + "❌ **Changes requested**: 1 defect to fix and 2 unconfirmed facts the change relies on.\n\n\ + **Holding the merge:**\n- `a.rs:3` Null deref\n- The vendor returns cents\n- The table has an index" ); let prior = verdict_heading( - "REQUEST_CHANGES", - &HeadingCounts { - prior_open: 1, - blocking_questions: 1, - verify_failed: true, - ..Default::default() - }, + &Verdict::from_holding(vec![ + Holding::new(K::Question, "`a.rs:9` Is it idempotent?"), + Holding::new(K::EarlierThread, "Missing test (`b.rs:2`)"), + Holding::new(K::Verification, "The verification run failed"), + ]), + 0, ); - assert_eq!( - prior, + assert!(prior.starts_with( "❌ **Changes requested**: 1 question the change rests on, 1 earlier requested change still open and the verification run failed." - ); - for h in [approved, notes, blocked, prior] { - assert_eq!(h.lines().count(), 1); - assert!(!h.contains("Questions, nothing blocking")); - } + )); + } + + /// The zero case can't be written: nothing named is an approval, whatever + /// was proposed, on every route to the heading. + #[test] + fn changes_requested_with_nothing_named_cannot_be_written() { + use crate::passes::review_verdict::{may_post, HoldKind as K, Holding, Verdict}; + let nothing = Verdict::from_holding(vec![]); + assert_eq!(nothing.event(), "APPROVE"); + assert!(!may_post("REQUEST_CHANGES", ¬hing)); + assert!(may_post("APPROVE", ¬hing)); + assert!(may_post("COMMENT", ¬hing)); + // A blank name names nothing. + let blank = Verdict::from_holding(vec![Holding::new(K::Defect, " ")]); + assert_eq!(blank.event(), "APPROVE"); + assert!(!verdict_heading(&blank, 0).contains("Changes requested")); + let src = include_str!("review_agent.rs"); + let needle = concat!("something holds", " the merge"); + assert!(!src.contains(needle)); } } diff --git a/services/worker/src/passes/review_eval.rs b/services/worker/src/passes/review_eval.rs index bed83acdf..6124c66b5 100644 --- a/services/worker/src/passes/review_eval.rs +++ b/services/worker/src/passes/review_eval.rs @@ -324,6 +324,8 @@ impl Sim { head_sha: f.head.clone(), created_at: ts(f.at), body: "review".into(), + fingerprint: None, + holding: Vec::new(), }, ) }) @@ -340,6 +342,8 @@ impl Sim { "{} ({error}). Requesting a human look.", super::review_sweep::LEGACY_FAILED_PREFIX ), + fingerprint: None, + holding: Vec::new(), }, )); } @@ -370,6 +374,7 @@ impl Sim { thread_root_id: None, mentioned: false, requested_by: String::new(), + check_head: String::new(), attempt: 0, wait_secs: 0, reconcile_note: None, @@ -494,6 +499,7 @@ impl Sim { let mut view = GateView { draft: self.draft, require_human: cfg.require_human || self.self_authored, + bot_holding: vec![], bot_verdict: self.bot_verdicts.get(&self.head).cloned(), approvals: approval_state(&Value::Array(self.gh_reviews.clone()), &self.head), want_labels: vec![], @@ -736,6 +742,7 @@ impl Sim { let decision = decide( Input::Reply { change: conclusion.verdict_change, + more_than_words: true, }, &self.ctx(), ); diff --git a/services/worker/src/passes/review_fingerprint.rs b/services/worker/src/passes/review_fingerprint.rs new file mode 100644 index 000000000..f21da7884 --- /dev/null +++ b/services/worker/src/passes/review_fingerprint.rs @@ -0,0 +1,249 @@ +//! What "nothing changed since my last review" means: a stored fingerprint of +//! everything the verdict rests on, never the commit alone. +//! +//! A review stores it on its record. Before reviewing again the worker reads +//! the same things and compares them. Each part is hashed on its own, so the +//! comparison can say what changed; a part that couldn't be read counts as +//! changed, and a record without a fingerprint counts as changed, so anything +//! unknown is reviewed afresh. + +use common::review_description::body_hash; +use serde::{Deserialize, Serialize}; + +/// Everything a verdict rests on, as read for one review. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Fingerprint { + pub head: String, + /// The description's meaningful text (`review_description::normalized`). + pub description: String, + /// CoderHelm's own threads: which exist and which are resolved. + pub threads: Option, + /// CI on the head, the checks failing on the base, and the plan evidence. + pub results: Option, + /// What people wrote, a bare "re-review" aside. + pub people: Option, +} + +/// One thing that differs from the stored fingerprint. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Changed { + Commit, + Description, + Threads, + Results, + People, + /// The earlier review stored no fingerprint. + NoRecord, +} + +impl Changed { + fn words(self) -> &'static str { + match self { + Changed::Commit => "the commit", + Changed::Description => "the description", + Changed::Threads => "the review threads", + Changed::Results => "the CI or plan results", + Changed::People => "what people wrote", + Changed::NoRecord => "my earlier review has no record of what it read", + } + } +} + +/// Fixed words for what changed, for a posted line. +pub fn in_words(changed: &[Changed]) -> String { + let w: Vec<&str> = changed.iter().map(|c| c.words()).collect(); + match w.as_slice() { + [] => String::new(), + [one] => (*one).to_string(), + [rest @ .., last] => format!("{} and {last}", rest.join(", ")), + } +} + +fn differs(a: &Option, b: &Option) -> bool { + a.is_none() || b.is_none() || a != b +} + +/// What differs between the stored fingerprint and `now`. Empty only when +/// every part was read and is identical. +pub fn changes(stored: Option<&Fingerprint>, now: &Fingerprint) -> Vec { + let Some(s) = stored else { + return vec![Changed::NoRecord]; + }; + let mut out = Vec::new(); + if s.head != now.head { + out.push(Changed::Commit); + } + if s.description != now.description { + out.push(Changed::Description); + } + if differs(&s.threads, &now.threads) { + out.push(Changed::Threads); + } + if differs(&s.results, &now.results) { + out.push(Changed::Results); + } + if differs(&s.people, &now.people) { + out.push(Changed::People); + } + out +} + +/// A comment alone doesn't change what a verdict rests on: a reply's reading +/// may start a formal review only when something other than people's words +/// changed. A thread a person's words settled changes `Threads`. +pub fn more_than_words(changed: &[Changed]) -> bool { + changed.iter().any(|c| *c != Changed::People) +} + +/// The description part. +pub fn description_part(body: &str) -> String { + body_hash(body) +} + +/// The threads part, from (thread id, resolved). +pub fn threads_part>(threads: I) -> String { + let mut lines: Vec = threads + .into_iter() + .map(|(id, resolved)| format!("{id}={resolved}")) + .collect(); + lines.sort(); + body_hash(&lines.join("\n")) +} + +/// The results part: the head's check runs (name and result, CoderHelm's own +/// review check aside, which this job itself moves), the checks failing on the +/// base, and the plan evidence. +pub fn results_part(head_runs: &serde_json::Value, base_failing: &[String], plan: &str) -> String { + let mut lines: Vec = head_runs["check_runs"] + .as_array() + .map(|a| a.as_slice()) + .unwrap_or(&[]) + .iter() + .filter(|r| r["name"].as_str() != Some(common::review_check::CHECK_NAME)) + .map(|r| { + format!( + "{}={}", + r["name"].as_str().unwrap_or("?"), + r["conclusion"] + .as_str() + .unwrap_or_else(|| r["status"].as_str().unwrap_or("?")) + ) + }) + .collect(); + lines.sort(); + let mut base: Vec<&str> = base_failing.iter().map(String::as_str).collect(); + base.sort_unstable(); + body_hash(&format!( + "{}\nbase:{}\nplan:{plan}", + lines.join("\n"), + base.join(",") + )) +} + +/// The people part, from comments and review bodies (GitHub objects). What a +/// bot wrote and a bare "re-review" aren't new information. +pub fn people_part(items: &[serde_json::Value]) -> String { + let mut bodies: Vec = items + .iter() + .filter(|c| super::review_policy::is_person(&c["user"])) + .filter_map(|c| c["body"].as_str()) + .map(str::trim) + .filter(|b| !b.is_empty() && !super::review_policy::is_bare_command(b)) + .map(|b| b.to_string()) + .collect(); + bodies.sort(); + body_hash(&bodies.join("\n--\n")) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + pub(crate) fn fp() -> Fingerprint { + Fingerprint { + head: "h1".into(), + description: description_part("a description"), + threads: Some(threads_part([("t1".to_string(), false)])), + results: Some(results_part( + &json!({"check_runs": [{"name": "build", "conclusion": "success"}]}), + &[], + "", + )), + people: Some(people_part(&[])), + } + } + + #[test] + fn identical_means_every_part_was_read_and_is_the_same() { + assert!(changes(Some(&fp()), &fp()).is_empty()); + assert_eq!(changes(None, &fp()), vec![Changed::NoRecord]); + // A part that couldn't be read isn't the same. + let mut unread = fp(); + unread.results = None; + assert_eq!(changes(Some(&fp()), &unread), vec![Changed::Results]); + assert_eq!(changes(Some(&unread), &unread), vec![Changed::Results]); + } + + #[test] + fn each_thing_a_verdict_rests_on_changes_it() { + let mut new = fp(); + new.head = "h2".into(); + assert_eq!(changes(Some(&fp()), &new), vec![Changed::Commit]); + let mut new = fp(); + new.description = description_part("a description, confirmed in staging"); + assert_eq!(changes(Some(&fp()), &new), vec![Changed::Description]); + // Ticking a box or re-wrapping is not an edit. + new.description = description_part("a description"); + assert!(changes(Some(&fp()), &new).is_empty()); + let mut new = fp(); + new.threads = Some(threads_part([("t1".to_string(), true)])); + assert_eq!(changes(Some(&fp()), &new), vec![Changed::Threads]); + let mut new = fp(); + new.results = Some(results_part( + &json!({"check_runs": [{"name": "build", "conclusion": "failure"}]}), + &[], + "", + )); + assert_eq!(changes(Some(&fp()), &new), vec![Changed::Results]); + } + + #[test] + fn coderhelms_own_check_and_a_bare_ask_are_not_changes() { + let with_own = results_part( + &json!({"check_runs": [ + {"name": "build", "conclusion": "success"}, + {"name": common::review_check::CHECK_NAME, "status": "in_progress"} + ]}), + &[], + "", + ); + assert_eq!(Some(with_own), fp().results); + let person = json!({"login": "dev", "type": "User"}); + let bot = json!({"login": "coderhelm[bot]", "type": "Bot"}); + assert_eq!( + people_part(&[ + json!({"user": person, "body": "@coderhelm re-review please"}), + json!({"user": bot, "body": "Answered."}), + ]), + people_part(&[]) + ); + assert_ne!( + people_part(&[json!({"user": person, "body": "The deploy note is the blocker."})]), + people_part(&[]) + ); + } + + #[test] + fn a_comment_alone_is_only_words() { + assert!(!more_than_words(&[])); + assert!(!more_than_words(&[Changed::People])); + assert!(more_than_words(&[Changed::People, Changed::Threads])); + assert!(more_than_words(&[Changed::NoRecord])); + assert!(more_than_words(&[Changed::Description])); + assert_eq!( + in_words(&[Changed::Description, Changed::Threads, Changed::People]), + "the description, the review threads and what people wrote" + ); + } +} diff --git a/services/worker/src/passes/review_policy.rs b/services/worker/src/passes/review_policy.rs index 24aad346c..e7919e2e4 100644 --- a/services/worker/src/passes/review_policy.rs +++ b/services/worker/src/passes/review_policy.rs @@ -7,10 +7,12 @@ //! for a commit CoderHelm already reviewed returns the existing verdict //! ([`start`]); posting takes a conditional claim per (PR, head, trigger //! kind) so two jobs can't both post ([`verdict_claim_sk`]). -//! 2. Verdict stability: on an unchanged head the verdict never flips -//! between approve and request-changes without new information (a -//! person's comment, a reply the formal review must follow); a flip says -//! why ([`stabilize`]). +//! 2. Verdict stability: a repeat review on an identical fingerprint (see +//! `review_fingerprint`: everything the verdict rests on, never the commit +//! alone) doesn't flip on model noise, and a person's re-review ask there +//! gets the standing verdict without a model review ([`answers_from_standing`]). +//! When the fingerprint differs the verdict follows what holds the merge +//! now, and says what changed ([`stabilize`]). //! 3. Blocking policy: which findings hold the merge is //! [`super::review_severity`]'s decision (blocking by default). On top of //! it, follow-ups the PR already tracks, problems the PR didn't cause and @@ -21,7 +23,9 @@ //! on it is also a lesson for the reviewer ([`hold_late_blockers`]). use super::review_agent::{Evidence, Finding}; +use super::review_fingerprint::{in_words, Changed}; use super::review_sweep::ReviewRecord; +use super::review_verdict::{HoldKind, Holding}; use std::collections::{HashMap, HashSet}; /// Who asked for a review. @@ -126,24 +130,75 @@ pub enum Start { ReturnExisting { verdict: String, }, + /// The commit was reviewed, but its description has changed since (a + /// draft's edit is not reviewed until it is marked ready, say): reviewed + /// as a description edit. + DescriptionChanged, } /// Rule 1: an automatic trigger for an already-reviewed commit returns the -/// existing verdict. A person's ask runs (and must explain a change of -/// mind, see [`stabilize`]); a run's own review of its PR always runs, the -/// run needs its verdict. -pub fn start(trigger: &str, head: &str, records: &[ReviewRecord]) -> Start { +/// existing verdict, unless its description moved on since. A person's ask +/// goes on (and may be answered from the verdict, see +/// [`answers_from_standing`]); a run's own review of its PR always runs, the +/// run needs its verdict. An older record with no fingerprint keeps returning +/// its verdict here: a burst of events for one commit must not start paid +/// reviews, and a person's ask reviews it afresh. +pub fn start(trigger: &str, head: &str, description: &str, records: &[ReviewRecord]) -> Start { if trigger_kind(trigger) == TriggerKind::Explicit || trigger == super::review_pr::TRIGGER_RUN { return Start::Review; } match review_of_head(records, head) { - Some(r) => Start::ReturnExisting { - verdict: r.verdict.clone(), + Some(r) => match &r.fingerprint { + Some(f) if f.description != description => Start::DescriptionChanged, + _ => Start::ReturnExisting { + verdict: r.verdict.clone(), + }, }, None => Start::Review, } } +/// A person asked for another look and nothing the verdict rests on changed: +/// no model review, the standing verdict is the answer ([`standing_answer`]). +/// Only for a person's ask: the sweep, a run's own review, a description edit +/// and a reconciliation after a settled finding have their own reasons to run. +pub fn answers_from_standing(trigger: &str, changed: &[Changed], reviewed: bool) -> bool { + matches!(trigger, "reply" | "rerequest") && reviewed && changed.is_empty() +} + +/// The answer to a re-review ask with nothing changed. Fixed words from +/// structured facts; the threads stay as they are. +pub fn standing_answer(head: &str, verdict: &str, holding: &[String]) -> String { + let short = &head[..head.len().min(7)]; + let verdict = super::review_verdict::binary(verdict); + let mut s = format!( + "**Unchanged since my last review of `{short}`: {}.** The code, the description, the \ + review threads, the CI results and what people wrote are the same, so I didn't review \ + it again.", + human(verdict) + ); + if !holding.is_empty() { + s.push_str("\n\n**Still holding the merge:**"); + for h in holding { + s.push_str(&format!("\n- {h}")); + } + s.push_str("\n\nPush a fix, edit the description, or answer a finding in its thread."); + } + s +} + +/// The line after an answer whose reading disagrees with the verdict when +/// nothing the verdict rests on changed: a reading of a comment can't clear or +/// add a block, and the answer must not stand as if it had. +pub fn verdict_stands_note(head: &str, verdict: &str) -> String { + let short = &head[..head.len().min(7)]; + format!( + "My formal verdict on `{short}` stays: {}. A comment doesn't change it; a push, an edit \ + of the description, or an answer in a finding's thread does.", + human(super::review_verdict::binary(verdict)) + ) +} + /// Which review round this head is, and the head reviewed before it. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct Round { @@ -448,7 +503,7 @@ pub fn is_bare_command(text: &str) -> bool { words.len() <= 8 && words.iter().all(|w| FILLER.contains(&w.as_str())) } -fn is_person(user: &serde_json::Value) -> bool { +pub(crate) fn is_person(user: &serde_json::Value) -> bool { user["type"].as_str() != Some("Bot") && user["login"] .as_str() @@ -471,30 +526,94 @@ pub fn person_spoke_since(comments: &[serde_json::Value], since: &str) -> Option }) } +/// Everything holding the merge, by name, on every route: findings that hold +/// it, earlier threads still open (path, line, body), unconfirmed facts that +/// block, a failed verification, findings CoderHelm fixes on its own PR, and +/// items a held earlier verdict keeps. What `Verdict` is made from. +pub fn named_holding( + findings: &[Finding], + open_threads: &[(String, u64, String)], + unconfirmed: &[super::review_agent::UnconfirmedFact], + verify_failed: bool, + own_open: &[String], + kept: &[String], +) -> Vec { + let mut out: Vec = Vec::new(); + for f in findings.iter().filter(|f| f.holds_merge()) { + let kind = if f.evidence() == Evidence::Question { + HoldKind::Question + } else { + HoldKind::Defect + }; + let name = if f.line > 0 { + format!("`{}:{}` {}", f.file, f.line, f.title) + } else if f.file.is_empty() { + f.title.clone() + } else { + format!("`{}` {}", f.file, f.title) + }; + out.push(Holding::new(kind, name)); + } + for (path, line, body) in open_threads { + out.push(Holding::new( + HoldKind::EarlierThread, + super::own_review::thread_line(path, *line, body), + )); + } + for fact in unconfirmed.iter().filter(|f| f.blocks) { + out.push(Holding::new(HoldKind::Fact, fact.fact.clone())); + } + if verify_failed { + out.push(Holding::new( + HoldKind::Verification, + "The verification run failed", + )); + } + for line in own_open { + let listed = out.iter().any(|h| h.name == *line) + || findings + .iter() + .any(|f| f.holds_merge() && line.contains(&f.title)); + if !listed { + out.push(Holding::new(HoldKind::OwnFinding, line.clone())); + } + } + for name in kept { + if !out.iter().any(|h| h.name == *name) { + out.push(Holding::new(HoldKind::KeptFromEarlier, name.clone())); + } + } + out +} + /// The verdict after rule 2, and what the review says about it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Stable { pub verdict: &'static str, /// A line for the review body: why the verdict changed on this commit, - /// or why it didn't. + /// or why it didn't. Fixed words from structured facts; a model's reason + /// only ever as its own sentence in its own paragraph. pub note: Option, /// The verdict this one replaced on the same commit. pub flipped_from: Option, - /// The new verdict differed and was refused (no new information). + /// The new verdict differed and was refused (an identical fingerprint). pub held: bool, + /// What holds the merge from the earlier review when its block was held. + pub kept: Vec, } /// Rule 2. `previous` is CoderHelm's finished review of this same head, if -/// any. `explicit`: a person asked; a verdict that didn't change then says so -/// (a person's ask always gets a visible answer). `new_info` names what is new since it (a person's comment, a reply -/// the formal review must follow); without it the earlier verdict stands and -/// new blockers become notes. With it, the change is explained with -/// `change_of_mind` (the reviewer's own sentence) or `new_info`. +/// any; `changed` is what differs from its fingerprint (empty: identical). +/// `explicit`: a person asked, so a verdict that didn't change says so. +/// +/// Only an identical fingerprint holds an earlier verdict, and only a block +/// that still names what holds it can be held: nothing named left means no +/// block. With anything changed the verdict is what holds the merge now. pub fn stabilize( previous: Option<&ReviewRecord>, verdict: &'static str, findings: &mut [Finding], - new_info: Option<&str>, + changed: &[Changed], change_of_mind: &str, explicit: bool, ) -> Stable { @@ -503,6 +622,7 @@ pub fn stabilize( note: None, flipped_from: None, held: false, + kept: Vec::new(), }; let Some(prev) = previous else { return unchanged; @@ -513,34 +633,42 @@ pub fn stabilize( if !explicit { return unchanged; } - let because = match new_info { - Some(info) => format!("{} doesn't change it", info.trim()), - None => "the code is the same and nothing new came up since".to_string(), + let what = if changed.is_empty() { + "The code and description are the same.".to_string() + } else { + format!( + "Since then {} changed; the verdict didn't.", + in_words(changed) + ) }; return Stable { note: Some(format!( - "**Unchanged since my last review of `{short}`: {}**, because {because}.", + "**Unchanged since my last review of `{short}`: {}.** {what}", human(verdict) )), ..unchanged }; } - if let Some(info) = new_info { - let why = if change_of_mind.trim().is_empty() { - info.trim().to_string() - } else { - change_of_mind.trim().to_string() - }; - return Stable { - verdict, - note: Some(format!( - "**Changed my verdict on `{short}`** from {} to {}: {why}", + let flip = |what: String| Stable { + verdict, + note: Some(match common::prose::one_whole_sentence(change_of_mind) { + Some(reason) => format!( + "**Changed my verdict on `{short}`** from {} to {}. {what}\n\n{reason}", human(before), human(verdict) - )), - flipped_from: Some(before.to_string()), - held: false, - }; + ), + None => format!( + "**Changed my verdict on `{short}`** from {} to {}. {what}", + human(before), + human(verdict) + ), + }), + flipped_from: Some(before.to_string()), + held: false, + kept: Vec::new(), + }; + if !changed.is_empty() { + return flip(format!("What changed: {}.", in_words(changed))); } if before == "APPROVE" { for f in findings.iter_mut().filter(|f| f.holds_merge()) { @@ -549,21 +677,30 @@ pub fn stabilize( "Raised on a second look at a commit I already approved, with nothing new since: a note, not a block.", ); } + return Stable { + verdict: before, + note: Some(format!( + "Same commit as my last review (`{short}`) and nothing it rests on changed, so \ + my earlier verdict (approve) stands. Anything new below is a note." + )), + flipped_from: None, + held: true, + kept: Vec::new(), + }; + } + // A held block names what holds it, or it isn't a block. + if prev.holding.is_empty() { + return flip("Nothing named holds the merge.".to_string()); } Stable { verdict: before, note: Some(format!( - "Same commit as my last review (`{short}`) and nothing new since, so my earlier verdict \ - ({}) stands.{}", - human(before), - if before == "APPROVE" { - " Anything new below is a note." - } else { - " Reply with what changed, or push a fix." - } + "Same commit as my last review (`{short}`) and nothing it rests on changed, so my \ + earlier verdict (request changes) stands. Reply with what changed, or push a fix." )), flipped_from: None, held: true, + kept: prev.holding.clone(), } } @@ -577,6 +714,8 @@ fn human(verdict: &str) -> &'static str { #[cfg(test)] mod tests { + use super::super::review_fingerprint::{self as fp, Fingerprint}; + use super::super::review_verdict::Verdict; use super::*; fn rec(head: &str, verdict: &str, at: &str) -> ReviewRecord { @@ -586,6 +725,8 @@ mod tests { head_sha: head.into(), created_at: at.into(), body: "review".into(), + fingerprint: None, + holding: Vec::new(), } } @@ -606,23 +747,23 @@ mod tests { fn an_automatic_trigger_on_a_reviewed_head_returns_the_verdict() { let records = vec![rec("h1", "APPROVE", "2026-10-01T00:00:00Z")]; assert_eq!( - start("synchronize", "h1", &records), + start("synchronize", "h1", "", &records), Start::ReturnExisting { verdict: "APPROVE".into() } ); - assert_eq!(start("labeled", "h2", &records), Start::Review); + assert_eq!(start("labeled", "h2", "", &records), Start::Review); // A person asked, or a run needs the verdict: it runs. - assert_eq!(start("reply", "h1", &records), Start::Review); - assert_eq!(start("rerequest", "h1", &records), Start::Review); + assert_eq!(start("reply", "h1", "", &records), Start::Review); + assert_eq!(start("rerequest", "h1", "", &records), Start::Review); // A description edit that answers the review is a person's ask: the // same commit is reviewed again with the new description. - assert_eq!(start("description", "h1", &records), Start::Review); - assert_eq!(start("run", "h1", &records), Start::Review); + assert_eq!(start("description", "h1", "", &records), Start::Review); + assert_eq!(start("run", "h1", "", &records), Start::Review); // A review that didn't finish isn't a verdict. let mut failed = rec("h1", "REQUEST_CHANGES", "2026-10-01T00:00:00Z"); failed.body = format!("{} (x)", super::super::review_sweep::LEGACY_FAILED_PREFIX); - assert_eq!(start("synchronize", "h1", &[failed]), Start::Review); + assert_eq!(start("synchronize", "h1", "", &[failed]), Start::Review); } #[test] @@ -654,27 +795,28 @@ mod tests { } /// A person's re-review ask always gets a visible answer: an unchanged - /// verdict says it is unchanged, and why. + /// verdict says it is unchanged, from structured facts. #[test] fn an_explicit_ask_with_the_same_verdict_says_it_is_unchanged() { let prev = rec("h1aaaaaaa", "APPROVE", "2026-10-01T00:00:00Z"); - let s = stabilize(Some(&prev), "APPROVE", &mut [], None, "", true); + let s = stabilize(Some(&prev), "APPROVE", &mut [], &[], "", true); assert_eq!(s.verdict, "APPROVE"); - let note = s.note.unwrap(); - assert!(note.contains("Unchanged since my last review of `h1aaaaa`: approve")); - assert!(note.contains("because the code is the same")); + assert_eq!( + s.note.unwrap(), + "**Unchanged since my last review of `h1aaaaa`: approve.** The code and description are the same." + ); let s = stabilize( Some(&prev), "APPROVE", &mut [], - Some("what dev wrote since my last review"), + &[Changed::People], "", true, ); - assert!(s - .note - .unwrap() - .contains("what dev wrote since my last review doesn't change it")); + assert_eq!( + s.note.unwrap(), + "**Unchanged since my last review of `h1aaaaa`: approve.** Since then what people wrote changed; the verdict didn't." + ); } #[test] @@ -930,40 +1072,587 @@ mod tests { } #[test] - fn a_verdict_never_flips_on_an_unchanged_head_without_news() { + fn a_verdict_never_flips_on_an_identical_fingerprint() { let prev = rec("h1aaaaaaa", "APPROVE", "2026-10-01T00:00:00Z"); let mut fs = vec![defect("a.rs", 1, "high", "bug")]; - let s = stabilize(Some(&prev), "REQUEST_CHANGES", &mut fs, None, "", true); + let s = stabilize(Some(&prev), "REQUEST_CHANGES", &mut fs, &[], "", true); assert_eq!(s.verdict, "APPROVE"); - assert!(s.held && s.flipped_from.is_none()); - assert!(!fs[0].holds_merge()); - assert!(s.note.unwrap().contains("stands")); - - let prev_rc = rec("h1aaaaaaa", "REQUEST_CHANGES", "2026-10-01T00:00:00Z"); - let s = stabilize(Some(&prev_rc), "APPROVE", &mut [], None, "", false); + assert!(s.held); + assert!(!fs[0].holds_merge(), "the new blocker became a note"); + assert!(s.note.unwrap().contains("earlier verdict (approve) stands")); + // A block held this way still names what holds it. + let mut prev_rc = rec("h1aaaaaaa", "REQUEST_CHANGES", "2026-10-01T00:00:00Z"); + prev_rc.holding = vec!["`a.rs:3` Null deref".to_string()]; + let s = stabilize(Some(&prev_rc), "APPROVE", &mut [], &[], "noise.", false); assert_eq!(s.verdict, "REQUEST_CHANGES"); assert!(s.held); + assert_eq!(s.kept, prev_rc.holding); + assert!(!s.note.unwrap().contains("noise")); + } - // New information: the flip happens and says why. - let mut fs = vec![defect("a.rs", 1, "high", "bug")]; - let s = stabilize( + /// The live failure: a block with nothing named holding it can't be held. + #[test] + fn a_block_with_nothing_named_clears_even_on_an_identical_fingerprint() { + let prev = rec("a1b2c3daaa", "REQUEST_CHANGES", "2026-10-01T00:00:00Z"); + let s = stabilize(Some(&prev), "APPROVE", &mut [], &[], "", true); + assert_eq!(s.verdict, "APPROVE"); + assert!(s.note.unwrap().contains("Nothing named holds the merge")); + } + + #[test] + fn with_anything_changed_the_verdict_follows_what_holds_the_merge() { + let mut prev = rec("h1aaaaaaa", "REQUEST_CHANGES", "2026-10-01T00:00:00Z"); + prev.holding = vec!["x".to_string()]; + for changed in [ + vec![Changed::Description], + vec![Changed::Threads], + vec![Changed::Results], + vec![Changed::People], + vec![Changed::NoRecord], + ] { + let s = stabilize(Some(&prev), "APPROVE", &mut [], &changed, "", false); + assert_eq!(s.verdict, "APPROVE", "{changed:?}"); + assert_eq!(s.flipped_from.as_deref(), Some("REQUEST_CHANGES")); + } + // No earlier review of this commit: nothing to compare. + let s = stabilize(None, "REQUEST_CHANGES", &mut [], &[], "", true); + assert_eq!(s.note, None); + } + + /// Whatever a model writes, it is never inside a template sentence: a + /// finished sentence of it stands in its own paragraph, or it isn't shown. + #[test] + fn model_text_is_never_spliced_into_a_sentence() { + let mut prev = rec("h1aaaaaaa", "APPROVE", "2026-10-01T00:00:00Z"); + prev.holding = vec![]; + let model = "The reply concludes nothing blocks merge."; + for (verdict, explicit) in [("REQUEST_CHANGES", true), ("APPROVE", true)] { + let note = stabilize( + Some(&prev), + verdict, + &mut [], + &[Changed::People], + model, + explicit, + ) + .note + .unwrap(); + assert!(!note.contains("because"), "{note}"); + assert!(!note.contains("doesn't change it"), "{note}"); + if note.contains(model) { + assert!(note.ends_with(&format!("\n\n{model}")), "{note}"); + } + } + // An unfinished thought isn't shown at all. + let note = stabilize( Some(&prev), "REQUEST_CHANGES", - &mut fs, - Some("dev's reply"), - "dev confirmed the field is null for refunds, which this code dereferences", + &mut [], + &[Changed::People], + "because the reply", true, + ) + .note + .unwrap(); + assert!(!note.contains("because the reply"), "{note}"); + } + + /// The source shape behind the garbled note: no format string in the code + /// that writes posted review text puts a value in the middle of words when + /// that value is a model's free text. + #[test] + fn no_template_embeds_a_models_reason() { + let spliced = [ + "{because}", + "{} doesn't change it", + concat!("info.trim", "()"), + concat!(": {", "why}"), + ]; + for (name, src) in [ + ("review_policy.rs", include_str!("review_policy.rs")), + ("review_verdict.rs", include_str!("review_verdict.rs")), + ] { + let code = src.split("#[cfg(test)]").next().unwrap(); + for shape in spliced { + assert!(!code.contains(shape), "{name} still has {shape}"); + } + } + // The model's reason for a changed mind reaches posted text one way: + // as a whole sentence on its own. + let policy = include_str!("review_policy.rs") + .split("#[cfg(test)]") + .next() + .unwrap(); + assert!(policy.contains(concat!("one_whole_sentence(change", "_of_mind)"))); + // A reply's reason is prompt context for the review it starts, never + // what a posted note says changed: stabilize gets structured facts. + let pr = include_str!("review_pr.rs"); + assert!(pr.contains(concat!( + "&changed_since,\n &output.change", + "_of_mind" + ))); + assert!(!pr.contains(concat!("a reply on this PR changed", " the facts"))); + } + + /// run_once needs GitHub and the database to run, so its order is read + /// from its source: the answer comes before any review work, and the + /// posted verdict comes from what holds the merge. + #[test] + fn run_once_answers_before_reviewing_and_posts_only_the_named_verdict() { + let src = include_str!("review_pr.rs"); + let at = |needle: &str| src.find(needle).unwrap_or_else(|| panic!("{needle}")); + let answer = at(concat!("review_policy::answers_from", "_standing(")); + assert!(answer < at(concat!(".open_check(state, &github", ", &msg, &head_sha"))); + assert!(answer < at(concat!("review_lessons::settle_before", "_review("))); + assert!(at(concat!("live_job.follow", "_head(")) < answer); + let named = at(concat!("review_policy::named", "_holding(")); + assert!(named < at(concat!("&final", "_verdict,\n "))); + assert!(src.contains(concat!("let verdict = final", "_verdict.event();"))); + assert!(named < at(concat!("note_review", "_state(\n state"))); + } + + #[test] + fn a_reask_on_an_identical_fingerprint_is_answered_from_the_verdict() { + assert!(answers_from_standing("reply", &[], true)); + assert!(answers_from_standing("rerequest", &[], true)); + // Anything changed, or no review of this commit: reviewed. + assert!(!answers_from_standing("reply", &[Changed::People], true)); + assert!(!answers_from_standing( + "rerequest", + &[Changed::NoRecord], + true + )); + assert!(!answers_from_standing("reply", &[], false)); + // The routes with their own reason to run. + for t in ["description", "reconcile", "sweep", "run", "synchronize"] { + assert!(!answers_from_standing(t, &[], true), "{t}"); + } + let text = standing_answer( + "a1b2c3daaa", + "REQUEST_CHANGES", + &["`a.rs:3` Null deref".to_string()], ); - assert_eq!(s.verdict, "REQUEST_CHANGES"); - assert_eq!(s.flipped_from.as_deref(), Some("APPROVE")); - assert!(s.note.unwrap().contains("null for refunds")); - assert!(fs[0].holds_merge()); + assert!( + text.starts_with("**Unchanged since my last review of `a1b2c3d`: request changes.**") + ); + assert!(text.contains("- `a.rs:3` Null deref")); + assert!(!standing_answer("a1b2c3daaa", "APPROVE", &[]).contains("Still holding")); + } - // Same verdict on an automatic trigger, or no earlier review of this - // head: nothing to say. - let s = stabilize(Some(&prev), "APPROVE", &mut [], None, "", false); - assert_eq!(s.note, None); - let s = stabilize(None, "REQUEST_CHANGES", &mut [], None, "", true); - assert_eq!((s.verdict, s.held), ("REQUEST_CHANGES", false)); + #[test] + fn an_automatic_trigger_reviews_again_only_for_a_changed_description() { + let mut r = rec("h1", "REQUEST_CHANGES", "2026-10-01T00:00:00Z"); + r.fingerprint = Some(super::super::review_fingerprint::Fingerprint { + head: "h1".into(), + description: "d1".into(), + ..Default::default() + }); + let records = vec![r]; + assert_eq!( + start("ready_for_review", "h1", "d1", &records), + Start::ReturnExisting { + verdict: "REQUEST_CHANGES".into() + } + ); + assert_eq!( + start("ready_for_review", "h1", "d2", &records), + Start::DescriptionChanged + ); + } + + // ── Replays of what a person saw, through the same functions run_once uses ── + + /// A review record of `head`, its fingerprint as it was, naming `holding`. + fn stored(verdict: &str, holding: &[&str], fp: &Fingerprint) -> ReviewRecord { + let mut r = rec(&fp.head, verdict, "2026-11-04T00:00:00Z"); + r.fingerprint = Some(fp.clone()); + r.holding = holding.iter().map(|h| h.to_string()).collect(); + r + } + + fn state_of(open: bool) -> Fingerprint { + Fingerprint { + head: "a1b2c3d0000".into(), + description: fp::description_part("Applies with the deploy note below."), + threads: Some(fp::threads_part([ + ("T_1".to_string(), !open), + ("T_2".to_string(), !open), + ])), + results: Some(fp::results_part( + &serde_json::json!({"check_runs": [{"name": "plan", "conclusion": "success"}]}), + &[], + "", + )), + people: Some(fp::people_part(&[])), + } + } + + /// What run_once does from the model's verdict to the posted heading. + fn review( + prev: &ReviewRecord, + now: &Fingerprint, + findings: &mut [Finding], + open: &[(String, u64, String)], + ) -> (Verdict, Stable, String) { + let proposed = super::super::review_agent::decide_verdict(findings, open.len(), &[], false); + let changed = fp::changes(prev.fingerprint.as_ref(), now); + let stable = stabilize(Some(prev), proposed, findings, &changed, "", false); + let verdict = + Verdict::from_holding(named_holding(findings, open, &[], false, &[], &stable.kept)); + let heading = super::super::review_agent::verdict_heading(&verdict, 0); + (verdict, stable, heading) + } + + /// The live PR: description edited, both threads settled, no new findings, + /// same commit. It posted "something holds the merge" and stayed stuck. + #[test] + fn replay_description_edited_and_both_threads_settled_clears() { + let before = state_of(true); + let prev = stored( + "REQUEST_CHANGES", + &["`deploy.tf:3` State key is shared", "`deploy.tf:9` No lock"], + &before, + ); + let mut now = state_of(false); + now.description = fp::description_part("Applies on merge; the workflow shows no step."); + let (verdict, stable, heading) = review(&prev, &now, &mut [], &[]); + assert_eq!(verdict.event(), "APPROVE"); + assert_eq!(stable.flipped_from.as_deref(), Some("REQUEST_CHANGES")); + let note = stable.note.unwrap(); + assert!(note.contains("What changed: the description and the review threads.")); + assert!(heading.starts_with("✅ **Approved**")); + assert!(!heading.contains("Changes requested")); + // An APPROVE replaces the standing request for changes on GitHub, and + // it always posts when it clears a block. + let d = super::super::review_verdict::decide( + super::super::review_verdict::Input::Review { + verdict: verdict.event(), + has_news: false, + explicit: false, + already_answered: false, + }, + &super::super::review_verdict::Context { + standing: Some(super::super::review_verdict::StandingReview { + verdict: "REQUEST_CHANGES".into(), + failed: false, + head_sha: before.head.clone(), + }), + self_authored: false, + }, + ); + assert_eq!( + d, + super::super::review_verdict::Decision::Post { + event: "APPROVE", + dismiss_stale: false + } + ); + } + + #[test] + fn replay_a_settled_thread_with_another_holding_finding_still_blocks_and_names_it() { + let before = state_of(true); + let prev = stored("REQUEST_CHANGES", &["old"], &before); + let mut now = state_of(true); + now.threads = Some(fp::threads_part([ + ("T_1".to_string(), true), + ("T_2".to_string(), false), + ])); + let open = vec![( + "deploy.tf".to_string(), + 9, + "**No lock on the state** (bug)".to_string(), + )]; + let (verdict, _, heading) = review(&prev, &now, &mut [], &open); + assert_eq!(verdict.event(), "REQUEST_CHANGES"); + assert!(heading.contains("1 earlier requested change still open")); + assert!(heading.contains("No lock on the state"), "{heading}"); + assert!(heading.contains("deploy.tf:9"), "{heading}"); + } + + #[test] + fn replay_an_identical_fingerprint_keeps_a_real_block_named_against_model_noise() { + let state = state_of(true); + let prev = stored( + "REQUEST_CHANGES", + &["`deploy.tf:3` State key is shared"], + &state, + ); + // The model now finds nothing: noise. The block stands, named. + let (verdict, stable, heading) = review(&prev, &state, &mut [], &[]); + assert_eq!(verdict.event(), "REQUEST_CHANGES"); + assert!(stable.held); + assert!( + heading.contains("`deploy.tf:3` State key is shared"), + "{heading}" + ); + } + + /// An older record has no fingerprint: changed, reviewed afresh, and it + /// clears when nothing holds. + #[test] + fn replay_an_old_record_without_a_fingerprint_counts_as_changed() { + let mut prev = rec("a1b2c3d0000", "REQUEST_CHANGES", "2026-11-04T00:00:00Z"); + prev.fingerprint = None; + let now = state_of(false); + let changed = fp::changes(prev.fingerprint.as_ref(), &now); + assert_eq!(changed, vec![Changed::NoRecord]); + assert!(!answers_from_standing("reply", &changed, true)); + let (verdict, _, _) = review(&prev, &now, &mut [], &[]); + assert_eq!(verdict.event(), "APPROVE"); + } + + /// A re-review ask on an identical fingerprint: no model review, the same + /// verdict in the reply, the threads as they are. + #[test] + fn replay_a_rereview_ask_with_nothing_changed_stays_as_it_was() { + let state = state_of(true); + let prev = stored( + "REQUEST_CHANGES", + &["`deploy.tf:3` State key is shared"], + &state, + ); + let changed = fp::changes(prev.fingerprint.as_ref(), &state); + assert!(answers_from_standing("rerequest", &changed, true)); + let text = standing_answer(&prev.head_sha, &prev.verdict, &prev.holding); + assert!(text.contains("`a1b2c3d`: request changes")); + assert!(text.contains("`deploy.tf:3` State key is shared")); + // A bare ask is no new words either. + let mut with_ask = state.clone(); + with_ask.people = Some(fp::people_part(&[serde_json::json!({ + "user": {"login": "dev", "type": "User"}, + "body": "@coderhelm re-review", + })])); + assert!(fp::changes(prev.fingerprint.as_ref(), &with_ask).is_empty()); + } + + /// The reported comment: same head, same description, a person's comment + /// naming a blocker, a reading that says the opposite. One answer, no + /// formal review, nothing garbled, and the check keeps its verdict. + #[tokio::test] + async fn replay_a_comment_naming_a_blocker_gets_one_answer_and_the_verdict_stands() { + use super::super::review_agent::VerdictChange; + use super::super::review_verdict::{decide, Context, Decision, Input, StandingReview}; + use common::review_check as rc; + let state = state_of(true); + let prev = stored( + "REQUEST_CHANGES", + &["`deploy.tf:3` State key is shared"], + &state, + ); + let mut now = state.clone(); + now.people = Some(fp::people_part(&[serde_json::json!({ + "user": {"login": "dev", "type": "User"}, + "body": "The deploy note in the description is the blocker.", + })])); + let changed = fp::changes(prev.fingerprint.as_ref(), &now); + assert_eq!(changed, vec![Changed::People]); + let standing = StandingReview { + verdict: "REQUEST_CHANGES".into(), + failed: false, + head_sha: state.head.clone(), + }; + let ctx = Context { + standing: Some(standing.clone()), + self_authored: false, + }; + // The model read "nothing blocks": a reading can't clear a block. + let d = decide( + Input::Reply { + change: VerdictChange::Clear, + more_than_words: fp::more_than_words(&changed), + }, + &ctx, + ); + assert_eq!(d, Decision::Nothing); + assert!(super::super::review_verdict::reply_disagrees( + VerdictChange::Clear, + &standing + )); + let note = verdict_stands_note(&state.head, &standing.verdict); + assert_eq!( + note, + "My formal verdict on `a1b2c3d` stays: request changes. A comment doesn't change it; a push, an edit of the description, or an answer in a finding's thread does." + ); + // Same reading over an approval can't add a block either. + let approved = Context { + standing: Some(StandingReview { + verdict: "APPROVE".into(), + ..standing.clone() + }), + self_authored: false, + }; + assert_eq!( + decide( + Input::Reply { + change: VerdictChange::Block, + more_than_words: false + }, + &approved + ), + Decision::Nothing + ); + // The check: finished verdict, reply shown, back to the verdict. + let gh = rc::fake::FakeChecks::default(); + let t = rc::Target { + installation: 1, + owner: "o", + repo: "r", + pr: 7, + head: &state.head, + }; + let v = rc::take_over_or_open(&gh, &t, "head#x", "Reading", "u") + .await + .unwrap(); + rc::close( + &gh, + &t, + v, + &rc::Close { + conclusion: "neutral", + title: "Changes requested: 1 finding".into(), + summary: "s".into(), + details_url: None, + }, + ) + .await; + rc::queue_work(&gh, &t, rc::Work::Reply, "reply#9", 0, "u").await; + assert_eq!( + gh.shown(&state.head)["output"]["title"], + "Reading your reply on a1b2c3d" + ); + let id = rc::start(&gh, &t, "reply#9", "Reading your reply", "session") + .await + .unwrap(); + rc::close_restoring( + &gh, + &t, + id, + &rc::Close { + conclusion: "neutral", + title: "Answered".into(), + summary: "Answered.".into(), + details_url: Some("session".into()), + }, + ) + .await; + let shown = gh.shown(&state.head); + assert_eq!(shown["output"]["title"], "Changes requested: 1 finding"); + assert_eq!(shown["conclusion"], "neutral"); + assert_eq!(shown["details_url"], "session"); + } + + /// What still starts a review: a person's words that settle a thread change + /// the threads; an edited description; a new push. + #[test] + fn replay_the_cases_that_still_review() { + use super::super::review_agent::VerdictChange; + use super::super::review_verdict::{decide, Context, Decision, Input, StandingReview}; + let state = state_of(true); + let ctx = Context { + standing: Some(StandingReview { + verdict: "REQUEST_CHANGES".into(), + failed: false, + head_sha: state.head.clone(), + }), + self_authored: false, + }; + let starts = |now: &Fingerprint| { + decide( + Input::Reply { + change: VerdictChange::Clear, + more_than_words: fp::more_than_words(&fp::changes(Some(&state), now)), + }, + &ctx, + ) + }; + let mut thread = state.clone(); + thread.threads = Some(fp::threads_part([ + ("T_1".to_string(), true), + ("T_2".to_string(), false), + ])); + assert_eq!(starts(&thread), Decision::Review); + let mut edited = state.clone(); + edited.description = fp::description_part("A new description."); + assert_eq!(starts(&edited), Decision::Review); + let mut push = state.clone(); + push.head = "abc".into(); + assert_eq!(starts(&push), Decision::Review); + assert!(!answers_from_standing("description", &[], true)); + assert_eq!( + start("synchronize", "another-head", "d", &[]), + Start::Review + ); + // An error review on the PR isn't a verdict: a reply replaces it. + let failed = Context { + standing: Some(StandingReview { + verdict: "REQUEST_CHANGES".into(), + failed: true, + head_sha: state.head.clone(), + }), + self_authored: false, + }; + assert_eq!( + decide( + Input::Reply { + change: VerdictChange::None, + more_than_words: false + }, + &failed + ), + Decision::Review + ); + } + + /// Every route to a verdict: nothing named is an approval, anything named + /// is changes requested and the heading names it. + #[test] + fn every_route_through_the_chokepoint_names_what_holds_or_approves() { + use super::super::review_agent::{verdict_heading, UnconfirmedFact}; + let finding = [defect("a.rs", 3, "high", "bug")]; + let thread = [("b.rs".to_string(), 9, "**Open thing** (bug)".to_string())]; + let fact = [UnconfirmedFact { + fact: "The vendor returns cents".into(), + blocks: true, + why: String::new(), + }]; + let note_fact = [UnconfirmedFact { + fact: "Staging has no data".into(), + blocks: false, + why: String::new(), + }]; + let own = ["Own item (`c.rs:1`)".to_string()]; + let kept = ["Kept item".to_string()]; + for f in [&[][..], &finding[..]] { + for t in [&[][..], &thread[..]] { + for u in [&[][..], &fact[..], ¬e_fact[..]] { + for v in [false, true] { + for o in [&[][..], &own[..]] { + for k in [&[][..], &kept[..]] { + let holding = named_holding(f, t, u, v, o, k); + let verdict = Verdict::from_holding(holding.clone()); + let heading = verdict_heading(&verdict, 0); + if holding.is_empty() { + assert_eq!(verdict.event(), "APPROVE"); + assert!(heading.starts_with("✅")); + } else { + assert_eq!(verdict.event(), "REQUEST_CHANGES"); + for h in &holding { + assert!(heading.contains(&h.name), "{heading}"); + } + } + let empty = !f.is_empty() + || !t.is_empty() + || u.iter().any(|x| x.blocks) + || v + || !o.is_empty() + || !k.is_empty(); + assert_eq!(!holding.is_empty(), empty); + } + } + } + } + } + } } } diff --git a/services/worker/src/passes/review_policy_eval.rs b/services/worker/src/passes/review_policy_eval.rs index 2cd3c4e99..4155a52e8 100644 --- a/services/worker/src/passes/review_policy_eval.rs +++ b/services/worker/src/passes/review_policy_eval.rs @@ -186,7 +186,7 @@ impl Sim { fn begin(&mut self, step: &ReviewStep, group: usize) -> Option { let head = self.head.clone(); if let policy::Start::ReturnExisting { .. } = - policy::start(&step.trigger, &head, &self.records) + policy::start(&step.trigger, &head, "", &self.records) { self.skipped += 1; return None; @@ -283,22 +283,23 @@ impl Sim { let unconfirmed = review_agent::unconfirmed_external_facts("", &out.unconfirmed_facts); let verdict = review_agent::decide_verdict(&findings, holding, &unconfirmed, false); let same_head = policy::review_of_head(&job.records, &job.head).cloned(); - let new_info = same_head.as_ref().and_then(|prev| { - policy::person_spoke_since(&self.comments, &prev.created_at) - .map(|who| format!("what {who} wrote since my last review")) - }); + let changed: Vec = same_head + .as_ref() + .and_then(|prev| policy::person_spoke_since(&self.comments, &prev.created_at)) + .map(|_| vec![super::review_fingerprint::Changed::People]) + .unwrap_or_default(); let stable = policy::stabilize( same_head.as_ref(), verdict, &mut findings, - new_info.as_deref(), + &changed, &out.change_of_mind, policy::trigger_kind(&job.step.trigger) == policy::TriggerKind::Explicit, ); // Invariant (b). if let Some(prev) = &same_head { let before = super::review_verdict::binary(&prev.verdict); - if before != stable.verdict && new_info.is_none() { + if before != stable.verdict && changed.is_empty() { self.violations.push(format!( "the verdict on {} flipped from {before} to {} with nothing new", job.head, stable.verdict @@ -418,6 +419,8 @@ impl Sim { head_sha: job.head.clone(), created_at: at, body: "review".into(), + fingerprint: None, + holding: Vec::new(), }, ); } diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 688f45199..bb1846e4d 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -351,6 +351,10 @@ struct Session { /// How its check ends when the job ends without a new review: the /// conclusion and title (the summary is the job's reason). settled: Option<(&'static str, String)>, + /// Ending without a new verdict gives the commit back the check it showed + /// before this job: a person's comment, or a re-review with nothing + /// changed, says nothing about the verdict. + restore: bool, } /// The key a job's check is held under: the job's dedup key (what the @@ -376,6 +380,21 @@ fn check_target<'a>( } } +/// The commit carrying the job's check: the one it is pinned to, or the one the +/// gateway queued its check on. +fn check_head(msg: &ReviewMessage) -> &str { + if msg.head_sha.is_empty() { + &msg.check_head + } else { + &msg.head_sha + } +} + +/// What the job does, in the words of its check. +fn check_work(msg: &ReviewMessage) -> common::review_check::Work { + common::review_check::Work::of(&msg.trigger, msg.question.is_some()) +} + fn pr_page(state: &WorkerState, msg: &ReviewMessage) -> String { common::review_check::pr_page( common::public_urls::app_url(&state.config.stage), @@ -394,7 +413,7 @@ async fn close_waiting_check( title: &str, summary: &str, ) { - if msg.question.is_some() || msg.dedup_key.is_empty() { + if msg.dedup_key.is_empty() { return; } let close = common::review_check::Close { @@ -405,7 +424,7 @@ async fn close_waiting_check( }; common::review_check::close_waiting( github, - &check_target(msg, &msg.head_sha), + &check_target(msg, check_head(msg)), &msg.dedup_key, &close, ) @@ -488,30 +507,143 @@ impl LiveJob { } /// The job starts: take over the check the gateway queued for it on its - /// commit (a push, label, opened or ready event), in progress at once. - /// Nothing when no check waits for this job. + /// commit, in progress at once. Nothing when no check waits for this job, + /// or a reply the worker hasn't yet found is for CoderHelm. async fn start_check(&self, state: &WorkerState, github: &GitHubClient, msg: &ReviewMessage) { - if msg.question.is_some() || msg.head_sha.is_empty() || self.session().check.is_some() { + let head = check_head(msg); + if head.is_empty() || self.session().check.is_some() { return; } let Some(id) = common::review_check::start( github, - &check_target(msg, &msg.head_sha), + &check_target(msg, head), &msg.dedup_key, - &super::review_session::started_title(&msg.head_sha), + &common::review_check::started_title(check_work(msg), head), &pr_page(state, msg), ) .await else { return; }; - self.session().check = Some((id, msg.head_sha.clone())); + let mut s = self.session(); + s.check = Some((id, head.to_string())); + s.restore = msg.question.is_some(); + if msg.question.is_some() { + s.settled = Some(super::review_session::not_reviewed(NotReviewed::Answered { + head, + })); + } + } + + /// The job knows the PR's head now. A check queued on a commit the PR has + /// left goes back to what it showed. A person's ask with no check on the + /// head (a reply only the worker could tell was for CoderHelm, a head that + /// moved, a gateway that couldn't reach GitHub) shows it now. + async fn follow_head( + &self, + state: &WorkerState, + github: &GitHubClient, + msg: &ReviewMessage, + head: &str, + ) { + let held = self.session().check.clone(); + if let Some((id, old)) = held { + if old == head { + return; + } + let close = common::review_check::Close { + conclusion: "neutral", + title: format!( + "Replaced by the review of {}", + common::review_check::short(head) + ), + summary: format!( + "The pull request moved on to {} before this finished.", + common::review_check::short(head) + ), + details_url: Some(pr_page(state, msg)), + }; + common::review_check::close_restoring(github, &check_target(msg, &old), id, &close) + .await; + self.session().check = None; + } + if msg.head_sha.is_empty() && !msg.dedup_key.is_empty() && !head.is_empty() { + let work = check_work(msg); + let target = check_target(msg, head); + let details = pr_page(state, msg); + let now = chrono::Utc::now().timestamp(); + common::review_check::queue_work(github, &target, work, &msg.dedup_key, now, &details) + .await; + let mut with_head = msg.clone(); + with_head.check_head = head.to_string(); + self.start_check(state, github, &with_head).await; + } + } + + /// The session page exists now: the check links it, so the person can + /// watch what CoderHelm is doing. + async fn link_session(&self, state: &WorkerState, github: &GitHubClient, msg: &ReviewMessage) { + let held = self.session().check.clone(); + let Some((id, head)) = held else { + return; + }; + let title = common::review_check::started_title(check_work(msg), &head); + let key = check_key(msg, &self.id).to_string(); + self.say_on_check(state, github, msg, id, &head, &key, &title) + .await; + } + + /// The check says what the job does now, linking its session. + #[allow(clippy::too_many_arguments)] + async fn say_on_check( + &self, + state: &WorkerState, + github: &GitHubClient, + msg: &ReviewMessage, + id: u64, + head: &str, + key: &str, + title: &str, + ) { + let details = super::review_session::session_url( + common::public_urls::app_url(&state.config.stage), + &self.id, + ); + common::review_check::progress(github, &check_target(msg, head), id, key, title, &details) + .await; + } + + /// The reply is being answered. + async fn answering(&self, state: &WorkerState, github: &GitHubClient, msg: &ReviewMessage) { + let held = self.session().check.clone(); + if let Some((id, head)) = held { + let title = format!( + "Answering your reply on {}", + common::review_check::short(&head) + ); + let key = check_key(msg, &self.id).to_string(); + self.say_on_check(state, github, msg, id, &head, &key, &title) + .await; + } + } + + /// The job answered a person and the verdict stands: its check goes back + /// to the verdict the commit showed. + fn answered(&self, head: &str, why: &str) { + let mut s = self.session(); + s.settled = Some(super::review_session::not_reviewed(NotReviewed::Answered { + head, + })); + s.not_posted = Some(why.to_string()); + s.restore = true; } /// How the check ends if the job ends without a new review: `conclusion` /// and `title`, the job's reason as its summary. fn settle(&self, why: super::review_session::NotReviewed<'_>) { - self.session().settled = Some(super::review_session::not_reviewed(why)); + let mut s = self.session(); + s.settled = Some(super::review_session::not_reviewed(why)); + s.restore = false; } /// The job hands its review to job `next_key`, due at `due`: its check @@ -642,7 +774,7 @@ impl LiveJob { use super::review_session::CheckEnd; use common::review_live::Finished; use common::review_session as rs; - let (check, verdict, not_posted, settled, opened) = { + let (check, verdict, not_posted, settled, opened, restore) = { let s = self.session(); ( s.check.clone(), @@ -650,6 +782,7 @@ impl LiveJob { s.not_posted.clone(), s.settled.clone(), s.opened, + s.restore, ) }; // The session's status and last step, and the check's ending. @@ -748,6 +881,11 @@ impl LiveJob { msg.installation_id, &state.http, ) { + // No new verdict from a job that only answered: the commit + // shows the one that stands, and the job's link. + Ok(github) if restore && verdict.is_none() => { + common::review_check::close_restoring(&github, &target, id, &close).await + } Ok(github) => common::review_check::close(&github, &target, id, &close).await, Err(e) => { warn!(pr = msg.pr_number, error = %e, "Could not complete the CoderHelm review check") @@ -1185,6 +1323,16 @@ async fn run_once( dedup_key = %msg.dedup_key, "Skipping duplicate review job — this trigger was already processed" ); + // A redelivered webhook may have queued a check for it again; the + // copy that is running keeps its own. + close_waiting_check( + state, + &github, + &msg, + "Already handled", + "A repeat delivery of something CoderHelm already handled.", + ) + .await; return Ok(DONE); } } @@ -1235,6 +1383,7 @@ async fn run_once( msg.head_sha.clone() }; *reviewed_head = head_sha.clone(); + live_job.follow_head(state, &github, &msg, &head_sha).await; // CoderHelm's own push while its run is still fixing the PR: the run // asks for the verdict itself when CI is green, and hands the PR over @@ -1285,9 +1434,12 @@ async fn run_once( super::review_sweep::review_records(state, &msg.team_id, &repo_slug, msg.pr_number, 10) .await; if msg.question.is_none() { - if let super::review_policy::Start::ReturnExisting { verdict } = - super::review_policy::start(&msg.trigger, &head_sha, &records) - { + if let super::review_policy::Start::ReturnExisting { verdict } = super::review_policy::start( + &msg.trigger, + &head_sha, + &super::review_fingerprint::description_part(pr_body), + &records, + ) { info!(pr = msg.pr_number, head = %head_sha, trigger = %msg.trigger, verdict = %verdict, "Commit already reviewed — its verdict stands, not reviewed again"); live_job.settle(NotReviewed::AlreadyReviewed { head: &head_sha, @@ -1300,6 +1452,16 @@ async fn run_once( ), }); } + if super::review_policy::start( + &msg.trigger, + &head_sha, + &super::review_fingerprint::description_part(pr_body), + &records, + ) == super::review_policy::Start::DescriptionChanged + { + info!(pr = msg.pr_number, head = %head_sha, trigger = %msg.trigger, "Commit already reviewed, but its description changed — reviewed as a description edit"); + msg.trigger = common::review_description::TRIGGER.to_string(); + } } // A run's handoff and the PR's ready-for-review event can ask for the @@ -1339,6 +1501,7 @@ async fn run_once( // Real work starts here: the dashboard shows the PR as being reviewed. live_job.reviewing(state, &msg, &head_sha, title).await; + live_job.link_session(state, &github, &msg).await; // Build the diff (base...head compare gives per-file patches), bounded. let compare = github @@ -1435,6 +1598,9 @@ async fn run_once( let self_authored = pr_author.contains("coderhelm"); let standing = super::review_sweep::standing_review(&records); + // Where a re-review ask made in a thread is answered, if it is answered + // from the standing verdict. + let asked_in = msg.reply_to_comment_id; // What the person's comment asks for, read by a model in context: an // ask for another look or for the approval gets a formal review of the @@ -1486,6 +1652,7 @@ async fn run_once( // ── Reply-with-a-question mode: answer, don't vote. ── if let Some(question) = msg.question.as_ref().filter(|q| !q.trim().is_empty()) { + live_job.answering(state, &github, &msg).await; let system = reply_system_prompt( &msg.repo_owner, &msg.repo_name, @@ -1705,6 +1872,8 @@ async fn run_once( return Err(format!("the model call failed: {e}").into()); } }; + // An answer that hit its token limit ends on its last whole sentence. + answer = common::prose::end_on_sentence(&answer).to_string(); // What the answer concludes, judged by the model: whether CoderHelm's // formal verdict must follow it, and whether it drip-feeds new // non-blocking items after an earlier reply said the code was fine. @@ -1715,7 +1884,7 @@ async fn run_once( pr = msg.pr_number, "Reply dropped new non-blocking items raised after the code was called fine" ); - answer = c.revised_reply.clone(); + answer = common::prose::end_on_sentence(&c.revised_reply).to_string(); } let consulted = skills .as_ref() @@ -1727,10 +1896,25 @@ async fn run_once( .unwrap_or_default(); // The one verdict function decides whether the formal review must // follow this reply; if so it runs first, in this job. + // A reading of a comment can't clear or add a block: only something + // the verdict rests on, more than people's words, starts a formal + // review from a reply. + let more_than_words = match conclusion.as_ref().map(|c| c.verdict_change) { + Some(review_agent::VerdictChange::Clear | review_agent::VerdictChange::Block) => { + let now = read_fingerprint(state, &github, &msg, &head_sha, pr_body, base).await; + let stored = super::review_policy::review_of_head(&records, &head_sha) + .and_then(|r| r.fingerprint.as_ref()); + super::review_fingerprint::more_than_words(&super::review_fingerprint::changes( + stored, &now, + )) + } + _ => false, + }; let decision = conclusion.as_ref().map(|c| { super::review_verdict::decide( super::review_verdict::Input::Reply { change: c.verdict_change, + more_than_words, }, &super::review_verdict::Context { standing: standing.clone(), @@ -1783,6 +1967,7 @@ async fn run_once( standing = ?standing, "Reply conclusion differs from the standing verdict; formal review runs first" ); + live_job.not_posted("Re-reviewing because what the verdict rests on changed."); return Ok(Outcome::ReviewThenReply { review: Box::new(reconcile_message(&msg, &head_sha, &reason)), reply: Box::new(PendingReply { @@ -1793,6 +1978,18 @@ async fn run_once( }), }); } + // The answer reads otherwise than the verdict, and nothing it rests on + // changed: the verdict stands, and the answer says so. + if let (Some(c), Some(st)) = (&conclusion, &standing) { + if !self_authored && super::review_verdict::reply_disagrees(c.verdict_change, st) { + info!(pr = msg.pr_number, head = %head_sha, change = ?c.verdict_change, standing = %st.verdict, "Reply reads otherwise than the verdict; nothing it rests on changed, the verdict stands"); + answer = format!( + "{}\n\n{}", + answer.trim_end(), + super::review_policy::verdict_stands_note(&head_sha, &st.verdict) + ); + } + } send_reply( state, &github, &msg, &head_sha, &answer, &consulted, &applied, &usage, ) @@ -1800,11 +1997,55 @@ async fn run_once( live_job .step(state, &msg, "Answered on the pull request", "") .await; + live_job.answered( + &head_sha, + "CoderHelm answered on the pull request; the verdict on this commit is unchanged.", + ); return Ok(DONE); } // ── Verdict mode (agentic: walk the repo, structured findings, self-critique) ── + // What the verdict rests on, read before anything else: compared with what + // the last review of this commit rested on (never the commit alone), and + // the base of what this review stores. + let read_now = read_fingerprint(state, &github, &msg, &head_sha, pr_body, base).await; + let review_before = super::review_policy::review_of_head(&records, &head_sha).cloned(); + let changed_since = super::review_fingerprint::changes( + review_before.as_ref().and_then(|r| r.fingerprint.as_ref()), + &read_now, + ); + // A person asked again and nothing changed: the standing verdict is the + // answer, with no model review, and the threads stay as they are. + if super::review_policy::answers_from_standing( + &msg.trigger, + &changed_since, + review_before.is_some(), + ) { + if let Some(prev) = &review_before { + info!(pr = msg.pr_number, head = %head_sha, trigger = %msg.trigger, verdict = %prev.verdict, "Re-review ask with nothing changed — answered from the standing verdict, no model review"); + let answer = + super::review_policy::standing_answer(&head_sha, &prev.verdict, &prev.holding); + let mut asked = msg.clone(); + asked.reply_to_comment_id = asked_in; + send_reply(state, &github, &asked, &head_sha, &answer, "", &[], &usage).await?; + live_job + .step( + state, + &msg, + "Nothing changed: answered from the standing verdict", + "", + ) + .await; + live_job.answered( + &head_sha, + "Nothing the verdict rests on changed since CoderHelm's last review of this \ + commit, so it answered from that verdict without reviewing again.", + ); + return Ok(DONE); + } + } + // A person's re-review ask and a push review of the same commit used to // run together and post opposite verdicts seconds apart. The ask takes // the per-commit claim the gateway takes for push reviews: while another @@ -2772,28 +3013,13 @@ async fn run_once( let unconfirmed = review_agent::unconfirmed_external_facts(pr_body, &output.unconfirmed_facts); let verdict: &'static str = review_agent::decide_verdict(&findings, still_open_holding, &unconfirmed, verify_failed); - // Rule 2: on a commit already reviewed, the verdict changes only on new - // information, and says what it was. - let new_info: Option = if msg.trigger == common::review_description::TRIGGER { - Some("the description updated since my last review".to_string()) - } else if msg.trigger == "reconcile" { - Some( - msg.reconcile_note - .clone() - .filter(|n| !n.trim().is_empty()) - .unwrap_or_else(|| "a reply on this PR changed the facts".to_string()), - ) - } else { - same_head_before.as_ref().and_then(|prev| { - super::review_policy::person_spoke_since(&people_wrote, &prev.created_at) - .map(|who| format!("what {who} wrote since my last review")) - }) - }; + // Rule 2: a repeat review on an identical fingerprint doesn't flip on model + // noise; anything changed, the verdict follows what holds the merge now. let stable = super::review_policy::stabilize( same_head_before.as_ref(), verdict, &mut findings, - new_info.as_deref(), + &changed_since, &output.change_of_mind, super::review_policy::trigger_kind(&msg.trigger) == super::review_policy::TriggerKind::Explicit, @@ -2827,12 +3053,24 @@ async fn run_once( } } } - let verdict = super::review_severity::consistent_verdict(stable.verdict, &findings); - let verdict = if own_open.is_empty() { - verdict - } else { - "REQUEST_CHANGES" - }; + // The one verdict the rest of this review may use: what holds the merge, + // by name. Nothing named holding means approve, whatever came before. + let open_holding: Vec<(String, u64, String)> = prior_threads + .iter() + .filter(|t| !fixed_threads.iter().any(|f| f.id == t.id)) + .filter(|t| review_agent::thread_holds_merge(&t.body)) + .map(|t| (t.path.clone(), t.line, t.body.clone())) + .collect(); + let final_verdict = + super::review_verdict::Verdict::from_holding(super::review_policy::named_holding( + &findings, + &open_holding, + &unconfirmed, + verify_failed, + &own_open, + &stable.kept, + )); + let verdict = final_verdict.event(); // A hunks-only re-review never approves: the whole PR is reviewed first. if super::review_scope::needs_full_before_approval(since_review.is_some(), verdict) { let mut full = msg.clone(); @@ -2867,6 +3105,9 @@ async fn run_once( "Could not queue the full review — posting this one" ); } + // The description this review leaves: CoderHelm's own PR gets its open + // findings written into it. + let mut description_after = pr_body.to_string(); if self_authored { let section = super::own_review::section(&own_open); let updated = super::completeness::with_section( @@ -2880,6 +3121,8 @@ async fn run_once( .await { warn!(pr = msg.pr_number, error = %e, "Could not update the own PR's open review findings"); + } else { + description_after = updated; } } if !own_open.is_empty() { @@ -2918,24 +3161,10 @@ async fn run_once( // GitHub forbids APPROVE / REQUEST_CHANGES on your OWN PR → downgrade to COMMENT. let effective_event = if self_authored { "COMMENT" } else { verdict }; let verdict_line = review_agent::verdict_heading( - verdict, - &review_agent::HeadingCounts { - defects: findings - .iter() - .filter(|f| f.evidence() != review_agent::Evidence::Question && f.holds_merge()) - .count(), - own_open: own_open.len(), - blocking_questions: findings - .iter() - .filter(|f| f.evidence() == review_agent::Evidence::Question && f.holds_merge()) - .count(), - blocking_facts, - prior_open: still_open_holding, - verify_failed, - notes: findings.iter().filter(|f| !f.holds_merge()).count() - + (unconfirmed.len() - blocking_facts) - + held_late.len(), - }, + &final_verdict, + findings.iter().filter(|f| !f.holds_merge()).count() + + (unconfirmed.len() - blocking_facts) + + held_late.len(), ); let summary = if output.summary.trim().is_empty() { "Automated review complete.".to_string() @@ -3134,6 +3363,7 @@ async fn run_once( dismiss_stale, &full_body, &postable.inline, + &final_verdict, ) .await { @@ -3235,6 +3465,29 @@ async fn run_once( note_review_standards(state, &msg.team_id, &record_sk, &s.applied_names()).await; } note_review_details(state, &msg.team_id, &record_sk, title, &findings).await; + // What this verdict rests on, for the next ask: what it read, with its own + // threads as this review left them. + let rests_on = super::review_fingerprint::Fingerprint { + description: super::review_fingerprint::description_part(&description_after), + threads: match github + .list_bot_review_threads(&msg.repo_owner, &msg.repo_name, msg.pr_number) + .await + { + Ok(t) => Some(super::review_fingerprint::threads_part( + t.iter().map(|t| (t.id.clone(), t.resolved)), + )), + Err(_) => None, + }, + ..read_now.clone() + }; + note_review_state( + state, + &msg.team_id, + &record_sk, + &rests_on, + &final_verdict.names(), + ) + .await; live_job .verdict(state, &msg, verdict, findings.len(), &review_url) .await; @@ -3275,6 +3528,21 @@ async fn run_once( } ); + // A block changes what the auto-merge panel must name; it can't merge on it. + if verdict == "REQUEST_CHANGES" { + super::await_merge::refresh_panel( + state, + &msg.team_id, + msg.installation_id, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + &head_sha, + base_branch, + self_authored, + ) + .await; + } // ── Post-approval actions (opt-in, off by default) ── if verdict == "APPROVE" { // Self-authored (CoderHelm's own) PRs CAN auto-merge, but run_on_approve @@ -3460,8 +3728,17 @@ async fn carry_approval( msg.pr_number ) ); - if let Err(e) = - super::review_verdict::post(github, msg, head, event, dismiss_stale, &body, &[]).await + if let Err(e) = super::review_verdict::post( + github, + msg, + head, + event, + dismiss_stale, + &body, + &[], + &super::review_verdict::Verdict::approve(), + ) + .await { warn!(pr = msg.pr_number, head = %head, error = %e, "Could not post the carried approval"); return; @@ -3546,6 +3823,7 @@ pub async fn review_for_run( thread_root_id: None, mentioned: false, requested_by: String::new(), + check_head: String::new(), attempt: 0, wait_secs: 0, reconcile_note: None, @@ -4267,6 +4545,83 @@ fn findings_record(findings: &[review_agent::Finding]) -> String { /// Puts the PR's title and the structured findings on the review record, for /// its page. Best-effort, like the record itself. +/// What the verdict on this record rests on, and what holds it by name. +async fn note_review_state( + state: &WorkerState, + team_id: &str, + record_sk: &str, + rests_on: &super::review_fingerprint::Fingerprint, + holding: &[String], +) { + let as_json = |r: serde_json::Result| r.unwrap_or_default(); + let upd = state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(record_sk)) + .update_expression("SET fingerprint = :f, holding = :h") + .expression_attribute_values(":f", attr_s(&as_json(serde_json::to_string(rests_on)))) + .expression_attribute_values(":h", attr_s(&as_json(serde_json::to_string(holding)))) + .send() + .await; + if let Err(e) = upd { + warn!(error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "Could not store what the verdict rests on (the next ask reviews afresh)"); + } +} + +/// Reads everything a verdict rests on (`review_fingerprint`). A part that +/// can't be read is `None`, which counts as changed. +async fn read_fingerprint( + state: &WorkerState, + github: &GitHubClient, + msg: &ReviewMessage, + head: &str, + pr_body: &str, + base: &str, +) -> super::review_fingerprint::Fingerprint { + use super::review_fingerprint as fp; + let (owner, repo, pr) = (&msg.repo_owner, &msg.repo_name, msg.pr_number); + let threads = github + .list_bot_review_threads(owner, repo, pr) + .await + .ok() + .map(|t| fp::threads_part(t.iter().map(|t| (t.id.clone(), t.resolved)))); + let head_runs = github.list_check_runs_for_ref(owner, repo, head).await.ok(); + let base_failing = if base.is_empty() { + Some(Vec::new()) + } else { + github + .list_check_runs_for_ref(owner, repo, base) + .await + .ok() + .map(|v| super::review_policy::failing_checks(&v)) + }; + let plan = plan_evidence_for_pr(state, msg).await; + let results = match (head_runs, base_failing) { + (Some(h), Some(b)) => Some(fp::results_part(&h, &b, &plan)), + _ => None, + }; + let comments = github.list_issue_comments(owner, repo, pr).await.ok(); + let inline = github.get_review_comments(owner, repo, pr).await.ok(); + let reviews = github.list_pr_reviews(owner, repo, pr).await.ok(); + let people = match (comments, inline, reviews) { + (Some(mut all), Some(inline), Some(reviews)) => { + all.extend(inline); + all.extend(reviews.as_array().cloned().unwrap_or_default()); + Some(fp::people_part(&all)) + } + _ => None, + }; + fp::Fingerprint { + head: head.to_string(), + description: fp::description_part(pr_body), + threads, + results, + people, + } +} + async fn note_review_details( state: &WorkerState, team_id: &str, @@ -4695,7 +5050,7 @@ fn changed_files(compare: &serde_json::Value) -> std::collections::HashSet String { const MAX_SENTENCES: usize = 4; - const MAX_CHARS: usize = 700; + const MAX_BYTES: usize = 700; let prose: String = text .lines() .map(str::trim) @@ -4704,19 +5059,7 @@ fn short_overview(text: &str) -> String { }) .collect::>() .join(" "); - let mut out = String::new(); - for piece in prose.split_inclusive(['.', '!', '?']).take(MAX_SENTENCES) { - if out.len() + piece.len() > MAX_CHARS { - break; - } - out.push_str(piece); - } - let out = out.trim().to_string(); - if out.is_empty() { - common::truncate_str(&prose, MAX_CHARS).trim().to_string() - } else { - out - } + common::prose::first_sentences(&prose, MAX_SENTENCES, MAX_BYTES).to_string() } /// Whether the PR moved past the commit this review looked at. Unlike @@ -4753,6 +5096,30 @@ fn superseded(msg: &ReviewMessage, current_head: &str) -> bool { && current_head != msg.head_sha } +#[cfg(test)] +mod overview_tests { + use super::short_overview; + + /// The reported cut: every dot counted as a sentence end, so the fourth + /// "sentence" could stop inside a path. + #[test] + fn the_overview_never_stops_inside_a_path() { + let text = "This moves the upload into services/worker/src/main.rs and reads \ + lambda/handler.py from the source paths listed in deploy/config.yaml and \ + infra/lib/stack.ts. Nothing else changes."; + assert_eq!(short_overview(text), text); + } + + #[test] + fn the_overview_keeps_four_whole_sentences() { + let out = short_overview("One. Two. Three. Four. Five."); + assert_eq!(out, "One. Two. Three. Four."); + // Too long for the cap: whole sentences, or the one sentence whole. + let s = format!("{} end.", "word ".repeat(200)); + assert_eq!(short_overview(&s), s); + } +} + #[cfg(test)] mod superseded_tests { use super::{description_to_mark, moved_on, superseded}; @@ -4774,6 +5141,7 @@ mod superseded_tests { thread_root_id: None, mentioned: false, requested_by: String::new(), + check_head: String::new(), attempt: 0, wait_secs: 0, reconcile_note: None, @@ -4822,8 +5190,9 @@ mod superseded_tests { let s = super::short_overview(essay); assert_eq!(s, "The description now matches. But the change isn't only copy. It hardcodes a price. It adds policy claims."); assert_eq!(super::short_overview("Looks good."), "Looks good."); + // No sentence end to cut on: kept, never cut mid-sentence. let long = "word ".repeat(400); - assert!(super::short_overview(&long).len() <= 700); + assert_eq!(super::short_overview(&long), long.trim_end()); } #[test] @@ -5134,6 +5503,7 @@ mod failure_tests { thread_root_id: None, mentioned: false, requested_by: String::new(), + check_head: String::new(), attempt: 0, wait_secs: 0, reconcile_note: None, @@ -5210,7 +5580,8 @@ mod failure_tests { assert_eq!( decide( Input::Reply { - change: c.verdict_change + change: c.verdict_change, + more_than_words: true, }, &ctx ), diff --git a/services/worker/src/passes/review_scope.rs b/services/worker/src/passes/review_scope.rs index 8bf7f5f4c..2ef6817ae 100644 --- a/services/worker/src/passes/review_scope.rs +++ b/services/worker/src/passes/review_scope.rs @@ -327,6 +327,8 @@ mod tests { head_sha: head.into(), created_at: String::new(), body: "Looks good.".into(), + fingerprint: None, + holding: Vec::new(), } } diff --git a/services/worker/src/passes/review_session.rs b/services/worker/src/passes/review_session.rs index 6a97b9e05..0b8084cf9 100644 --- a/services/worker/src/passes/review_session.rs +++ b/services/worker/src/passes/review_session.rs @@ -64,11 +64,6 @@ pub(crate) fn reading_title(files: &[String], head: &str) -> String { } } -/// Pure: the title of a check its job has just taken over. -pub(crate) fn started_title(head: &str) -> String { - format!("Reviewing {}", rc::short(head)) -} - /// Why a job ended without a new review, for its check. #[derive(Debug, Clone, Copy)] pub(crate) enum NotReviewed<'a> { @@ -93,6 +88,9 @@ pub(crate) enum NotReviewed<'a> { /// A hunks-only re-review settled its findings; the full review /// follows (the check goes to it when it can). FullReviewFollows { head: &'a str }, + /// A person's comment was answered and the commit has no verdict to show + /// again (with one, the check goes back to it, see `close_restoring`). + Answered { head: &'a str }, } /// Pure: the conclusion and title of a check whose job ended without a new @@ -160,6 +158,13 @@ pub(crate) fn not_reviewed(why: NotReviewed<'_>) -> (&'static str, String) { rc::short(head) ), ), + NotReviewed::Answered { head } => ( + "neutral", + format!( + "Answered your reply on {}; no verdict on this commit yet", + rc::short(head) + ), + ), } } @@ -401,7 +406,10 @@ mod tests { reading_title(&["src/a.ts".into(), "src/b.ts".into(), "c".into()], head), "Reading 3 changed files at 9fceb02: src/a.ts and 2 more" ); - assert_eq!(started_title(head), "Reviewing 9fceb02"); + assert_eq!( + rc::started_title(rc::Work::Review, head), + "Reviewing 9fceb02" + ); assert_eq!( session_url("https://app.example", "j"), "https://app.example/reviewer/session?id=j" @@ -529,7 +537,14 @@ mod tests { let key = format!("head#{HEAD}"); // Job start: in progress at once, the same check. assert_eq!( - rc::start(&gh, &target(), &key, &started_title(HEAD), "pr-page").await, + rc::start( + &gh, + &target(), + &key, + &rc::started_title(rc::Work::Review, HEAD), + "pr-page" + ) + .await, Some(id) ); assert_eq!(gh.run(id)["status"], "in_progress"); @@ -574,7 +589,14 @@ mod tests { let gh = FakeChecks::default(); let id = queued(&gh).await; let key = format!("head#{HEAD}"); - rc::start(&gh, &target(), &key, &started_title(HEAD), "pr-page").await; + rc::start( + &gh, + &target(), + &key, + &rc::started_title(rc::Work::Review, HEAD), + "pr-page", + ) + .await; let (conclusion, title) = not_reviewed(why); let close = check_close( CheckEnd::Settled { @@ -599,7 +621,14 @@ mod tests { let gh = FakeChecks::default(); let id = queued(&gh).await; let key = format!("head#{HEAD}"); - rc::start(&gh, &target(), &key, &started_title(HEAD), "pr-page").await; + rc::start( + &gh, + &target(), + &key, + &rc::started_title(rc::Work::Review, HEAD), + "pr-page", + ) + .await; // A service error: the check waits for the retry, queued. let retry_key = format!("retry#1#head#{HEAD}"); let due = now() + 60; diff --git a/services/worker/src/passes/review_severity.rs b/services/worker/src/passes/review_severity.rs index f28b61677..f44b2ce0a 100644 --- a/services/worker/src/passes/review_severity.rs +++ b/services/worker/src/passes/review_severity.rs @@ -174,16 +174,6 @@ pub fn optional(f: &Finding) -> bool { matches!(classify(f), Class::Note(r) if r == PREFERENCE || r == OPTIONAL) } -/// The verdict as posted: never APPROVE while a finding holds the merge, -/// whatever decided it upstream. -pub fn consistent_verdict(verdict: &'static str, findings: &[Finding]) -> &'static str { - if verdict == "APPROVE" && findings.iter().any(Finding::holds_merge) { - "REQUEST_CHANGES" - } else { - verdict - } -} - /// The rubric. Pure over the finding's fields. pub fn classify(f: &Finding) -> Class { if f.note_only.is_some() { diff --git a/services/worker/src/passes/review_sweep.rs b/services/worker/src/passes/review_sweep.rs index 9ad56a860..58bb3d7fd 100644 --- a/services/worker/src/passes/review_sweep.rs +++ b/services/worker/src/passes/review_sweep.rs @@ -38,6 +38,11 @@ pub struct ReviewRecord { pub head_sha: String, pub created_at: String, pub body: String, + /// What the verdict rested on; `None` on a record older than fingerprints + /// (it counts as changed). + pub fingerprint: Option, + /// What held the merge, by name. + pub holding: Vec, } impl ReviewRecord { @@ -121,6 +126,8 @@ fn record_from_item(i: &HashMap) -> ReviewRecord { head_sha: s_of(i, "head_sha"), created_at: s_of(i, "created_at"), body: s_of(i, "body"), + fingerprint: serde_json::from_str(&s_of(i, "fingerprint")).ok(), + holding: serde_json::from_str(&s_of(i, "holding")).unwrap_or_default(), } } @@ -429,6 +436,7 @@ fn sweep_message( thread_root_id: None, mentioned: false, requested_by: String::new(), + check_head: String::new(), attempt: 0, wait_secs: 0, reconcile_note: None, @@ -454,6 +462,8 @@ mod tests { head_sha: "a1b2c3d".into(), created_at: at.into(), body: body.into(), + fingerprint: None, + holding: Vec::new(), } } diff --git a/services/worker/src/passes/review_verdict.rs b/services/worker/src/passes/review_verdict.rs index 149d71080..71e41c1d0 100644 --- a/services/worker/src/passes/review_verdict.rs +++ b/services/worker/src/passes/review_verdict.rs @@ -6,8 +6,13 @@ //! and the stuck-review sweep (which runs a review). The invariants it keeps: //! //! - A review that didn't finish never posts a formal verdict. -//! - A reply that concludes nothing blocks never stands next to CoderHelm's -//! own "changes requested": the formal review is re-run in the same job. +//! - A reply's reading of a comment can't clear or add a block: the formal +//! review re-runs only when something the verdict rests on changed, more than +//! people's words (`review_fingerprint`). Otherwise the verdict stands and the +//! reply says so. +//! - Changes are requested only with at least one named thing holding the +//! merge ([`Verdict`]): nothing holding means approve, whatever the earlier +//! verdict was, and [`post`] refuses anything else. //! - A finished review's formal verdict is APPROVE or REQUEST_CHANGES, never //! a bare COMMENT ([`binary`]). Only GitHub's rule against verdicts on the //! bot's own PR makes it a COMMENT there; answers to a person's question @@ -41,6 +46,83 @@ impl StandingReview { } } +/// What kind of thing holds the merge. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HoldKind { + Defect, + /// On CoderHelm's own PR: a finding it fixes itself before ready. + OwnFinding, + Question, + Fact, + /// An earlier thread of CoderHelm's still open. + EarlierThread, + Verification, + /// An item of the earlier review, held on an identical fingerprint. + KeptFromEarlier, +} + +/// One named thing holding the merge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Holding { + pub kind: HoldKind, + pub name: String, +} + +impl Holding { + pub fn new(kind: HoldKind, name: impl Into) -> Self { + Self { + kind, + name: name.into(), + } + } +} + +/// The verdict a review may post. The one way to get one is from what holds +/// the merge, so "changes requested" with nothing named can't be written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Verdict { + holding: Vec, +} + +impl Verdict { + /// Nothing named holds the merge: approve. Anything named: changes + /// requested, naming it. + pub fn from_holding(holding: Vec) -> Self { + let holding = holding + .into_iter() + .filter(|h| !h.name.trim().is_empty()) + .collect(); + Self { holding } + } + + pub fn approve() -> Self { + Self::from_holding(Vec::new()) + } + + /// The formal event: `REQUEST_CHANGES` exactly when something is named. + pub fn event(&self) -> &'static str { + if self.holding.is_empty() { + "APPROVE" + } else { + "REQUEST_CHANGES" + } + } + + pub fn holding(&self) -> &[Holding] { + &self.holding + } + + /// The names, for the record and the auto-merge panel. + pub fn names(&self) -> Vec { + self.holding.iter().map(|h| h.name.clone()).collect() + } +} + +/// The chokepoint's rule: request changes only with something named. +pub fn may_post(event: &str, verdict: &Verdict) -> bool { + event != "REQUEST_CHANGES" || verdict.event() == "REQUEST_CHANGES" +} + /// What happened that may change the formal review. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Input { @@ -65,7 +147,12 @@ pub enum Input { /// when commits are pushed. Carried, /// A reply CoderHelm is about to post, and what it concludes. - Reply { change: VerdictChange }, + /// `more_than_words`: something the verdict rests on changed, more than + /// what people wrote (`review_fingerprint::more_than_words`). + Reply { + change: VerdictChange, + more_than_words: bool, + }, } /// What CoderHelm's PR looks like for the decision. @@ -119,20 +206,21 @@ pub fn decide(input: Input, ctx: &Context) -> Decision { }, dismiss_stale: false, }, - Input::Reply { change } => { + Input::Reply { + change, + more_than_words, + } => { if ctx.self_authored { return Decision::Nothing; } let Some(st) = ctx.standing.as_ref() else { return Decision::Nothing; }; - let disagrees = match change { - VerdictChange::Clear => st.blocks(), - VerdictChange::Block => st.verdict == "APPROVE" && !st.failed, - // An error review stands on the PR: replace it. - VerdictChange::None => st.failed, - }; - if disagrees { + // An error review stands on the PR: replace it, it isn't a verdict. + if st.failed && change != VerdictChange::Block { + return Decision::Review; + } + if reply_disagrees(change, st) && more_than_words { Decision::Review } else { Decision::Nothing @@ -171,10 +259,20 @@ pub fn decide(input: Input, ctx: &Context) -> Decision { } } +/// Pure: a reply's conclusion says something other than the standing verdict. +pub fn reply_disagrees(change: VerdictChange, standing: &StandingReview) -> bool { + match change { + VerdictChange::Clear => standing.blocks(), + VerdictChange::Block => standing.verdict == "APPROVE" && !standing.failed, + VerdictChange::None => false, + } +} + /// Posts the formal review `decision` asked for: one batched review with /// inline comments, falling back to body-only when GitHub rejects an anchor. /// The only caller of the GitHub review endpoints. Returns the posted /// review's GitHub link (empty when GitHub sent none). +#[allow(clippy::too_many_arguments)] pub async fn post( github: &GitHubClient, msg: &ReviewMessage, @@ -183,7 +281,11 @@ pub async fn post( dismiss_stale: bool, body: &str, inline: &[InlineComment], + verdict: &Verdict, ) -> Result> { + if !may_post(event, verdict) { + return Err("refused to request changes with nothing named holding the merge".into()); + } let posted = github .create_pr_review_inline( &msg.repo_owner, @@ -400,6 +502,7 @@ mod tests { fn a_reply_that_disagrees_with_the_standing_verdict_reruns_the_review() { let clear = Input::Reply { change: VerdictChange::Clear, + more_than_words: true, }; let ctx = |s| Context { standing: s, @@ -420,6 +523,7 @@ mod tests { assert_eq!(decide(clear, &ctx(None)), Decision::Nothing); let block = Input::Reply { change: VerdictChange::Block, + more_than_words: true, }; assert_eq!( decide(block, &ctx(standing("APPROVE", false))), @@ -431,6 +535,7 @@ mod tests { ); let none = Input::Reply { change: VerdictChange::None, + more_than_words: true, }; assert_eq!( decide(none, &ctx(standing("REQUEST_CHANGES", true))),