diff --git a/docs/incidents/xm_every_ask_seen_and_answered.md b/docs/incidents/xm_every_ask_seen_and_answered.md new file mode 100644 index 00000000..10b52bbf --- /dev/null +++ b/docs/incidents/xm_every_ask_seen_and_answered.md @@ -0,0 +1,9 @@ +# xm. `xm_every_ask_seen_and_answered` + +**What happened:** The owner commented `@CoderHelm re-review` on a person's pull request and nothing visibly happened. He asked again by pasting the mention, and GitHub's editor had turned it into the link it rendered: `https://github.com/CoderHelm re-review`. That second comment was not read as addressed to CoderHelm at all. + +**Why:** The parser only knew the text `@coderhelm`, so a pasted link to the organization or the app was no command. An accepted command showed nothing in the conversation until its answer posted, so a re-review that waited behind another review of the same commit, or ran long, looked exactly like one that was lost. A command refused because its author has no standing in the repository, or because the reviewer is off for the repository, was refused in a log line only. A person whose login contains the name was taken for the app, and their command was dropped. + +**The guarantee:** Every way a person addresses CoderHelm counts: `@coderhelm`, `@CoderHelm`, `@coderhelm[bot]`, the app's slug, the pasted link to the organization or the app, and a Markdown link to either, in any case and with any punctuation around it. A link alone, or one inside a sentence, is a reference and not a command, and neither an email address nor a link to a repository addresses CoderHelm. When a person's command is accepted, the gateway puts πŸ‘€ on their comment before the work is queued. The review that answers it swaps πŸ‘€ for πŸš€. A refused command gets one short reply saying why, once per comment. A re-review ask that comes while an identical review of the same commit is running keeps its πŸ‘€ and is answered by that review's verdict, so two quick asks make one review and never zero. An ask the running review did not answer (it failed, it reviewed another commit, or it posted nothing new) runs its own review after its waits. A person's re-review ask is always a fresh model review, even when nothing on the commit changed: asking means they want a real second look. Only automatic triggers return the standing verdict without one. An edit that makes a comment a command runs it once, under its own job key, so it is never mistaken for a repeat of the comment's first version. + +**Where it's enforced:** `common::address::{parse_ask, ask_added_by_edit, ask_key, strip_address}`. `common::review_ack::{Ack, see, swap, register, to_settle, collapsed, mark_answered, refusal_line, refusal_sk}` and `common::claim::claimed_at`. The gateway's `github_webhook::{handle_issue_comment, handle_review_comment, send_review_job, acknowledge, refuse}`. The worker's `review_pr::{run_once, store_review_record, settle_acks, collapsed_ask}` and `review_policy::{start, claim_still_running}`. diff --git a/services/common/src/address.rs b/services/common/src/address.rs new file mode 100644 index 00000000..08f7b530 --- /dev/null +++ b/services/common/src/address.rs @@ -0,0 +1,489 @@ +//! How a person addresses CoderHelm in a GitHub comment, and what they ask. +//! +//! People reach CoderHelm by several names: `@coderhelm`, `@CoderHelm` (the +//! organization, which GitHub autocompletes), the app's bot account +//! `@coderhelm[bot]` and the app's slug (`@coderhelm-app`). When a rendered +//! mention is copied and pasted, GitHub's editor turns it into the link it +//! rendered: `https://github.com/CoderHelm re-review`, or a Markdown link +//! such as `[@CoderHelm](https://github.com/CoderHelm) re-review`. Every one +//! of these counts, in any case and with any punctuation around it. +//! +//! A mention counts anywhere outside quoted text and code. A link counts +//! when it opens a line and words follow it: a link alone, or one inside a +//! sentence ("thanks to https://github.com/CoderHelm"), is a reference to +//! the page, not a command. A link to a repository under the organization +//! (`https://github.com/CoderHelm/some-repo`) never addresses CoderHelm, and +//! neither does an email address. + +/// A comment addressed to the reviewer, and what it asks. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReviewerAsk { + /// The exact re-review command (`re-review`, `re review`, `rereview`, + /// `review`, `review again`, or the bare mention): a fast path that + /// skips the worker's model classification. + pub rereview: bool, + /// The mention alone, with no words. On CoderHelm's own PR with work + /// still held or unfinished it resumes that work; otherwise it is the + /// re-review command (see `held_work`). + pub bare: bool, + /// Anything else, as written. What it asks for (another look, the + /// approval, a question, a fix) is decided by the worker's model, never + /// by keywords here. + pub question: Option, +} + +/// The name every CoderHelm account starts with (the organization, the app +/// and its bot account). +const NAME: &[u8] = b"coderhelm"; + +/// The slash command, at the start of a comment. +pub const SLASH: &str = "/coderhelm"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Form { + /// `@coderhelm…`, also as a Markdown link's text. + Mention, + /// A link to the organization's or the app's page. + Link, +} + +#[derive(Debug, Clone, Copy)] +struct Token { + start: usize, + end: usize, + form: Form, +} + +/// The comment without quoted lines (`> …`), fenced code blocks and inline +/// code: a mention someone quoted or pasted is not addressed to CoderHelm. +pub fn addressed_text(body: &str) -> String { + let mut out = String::with_capacity(body.len()); + let mut in_fence = false; + for line in body.lines() { + let t = line.trim_start(); + if t.starts_with("```") || t.starts_with("~~~") { + in_fence = !in_fence; + continue; + } + if in_fence || t.starts_with('>') { + continue; + } + // Drop `inline code` spans (every other piece between backticks). + for (i, part) in line.split('`').enumerate() { + if i % 2 == 0 { + out.push_str(part); + } + } + out.push('\n'); + } + out +} + +fn word_byte(c: u8) -> bool { + c.is_ascii_alphanumeric() || c == b'_' +} + +/// After `coderhelm`: the rest of an account name (`-app`, `-dev`), never +/// a trailing hyphen. +fn name_rest(b: &[u8], mut j: usize) -> usize { + while j + 1 < b.len() && b[j] == b'-' && b[j + 1].is_ascii_alphanumeric() { + j += 1; + while j < b.len() && b[j].is_ascii_alphanumeric() { + j += 1; + } + } + j +} + +/// What follows an address may be a space, punctuation or the end, never +/// more of a word or a domain (`@coderhelm.dev`). +fn ends_cleanly(b: &[u8], j: usize) -> bool { + match b.get(j) { + None => true, + Some(&c) if word_byte(c) => false, + Some(b'.') => !b.get(j + 1).is_some_and(|c| c.is_ascii_alphanumeric()), + Some(_) => true, + } +} + +/// `@coderhelm`, `@coderhelm[bot]`, `@coderhelm-app` at `i`. +fn mention_at(b: &[u8], i: usize) -> Option { + if b.get(i) != Some(&b'@') || !b[i + 1..].starts_with(NAME) { + return None; + } + // Part of an email address or another word: not a mention. + if i > 0 && (word_byte(b[i - 1]) || matches!(b[i - 1], b'.' | b'-' | b'+')) { + return None; + } + let mut j = name_rest(b, i + 1 + NAME.len()); + if b[j..].starts_with(b"[bot]") { + j += b"[bot]".len(); + } + ends_cleanly(b, j).then_some(Token { + start: i, + end: j, + form: Form::Mention, + }) +} + +/// A link to the organization's or the app's page at `i`: +/// `https://github.com/coderhelm`, `github.com/apps/coderhelm-app/`. +fn url_at(b: &[u8], i: usize) -> Option { + if i > 0 && (word_byte(b[i - 1]) || matches!(b[i - 1], b'/' | b'.' | b'-' | b'@')) { + return None; + } + let mut j = i; + for scheme in [&b"https://"[..], &b"http://"[..]] { + if b[j..].starts_with(scheme) { + j += scheme.len(); + break; + } + } + if b[j..].starts_with(b"www.") { + j += 4; + } + if !b[j..].starts_with(b"github.com/") { + return None; + } + j += b"github.com/".len(); + // The app's page carries its slug (`coderhelm-app`); the organization's + // name is exactly `coderhelm`. + let app = b[j..].starts_with(b"apps/"); + if app { + j += b"apps/".len(); + } + if !b[j..].starts_with(NAME) { + return None; + } + j += NAME.len(); + if app { + j = name_rest(b, j); + } + if b.get(j) == Some(&b'/') { + // A repository or another page under the organization. + if b.get(j + 1).is_some_and(|c| word_byte(*c) || *c == b'-') { + return None; + } + j += 1; + } + if matches!(b.get(j), Some(b'-' | b'/' | b'?' | b'#')) { + return None; + } + ends_cleanly(b, j).then_some(Token { + start: i, + end: j, + form: Form::Link, + }) +} + +/// A Markdown link to the organization's or the app's page at `i`: +/// `[@CoderHelm](https://github.com/CoderHelm)`. Its text decides its form. +fn markdown_link_at(b: &[u8], i: usize) -> Option { + if b.get(i) != Some(&b'[') { + return None; + } + let close = b[i + 1..] + .iter() + .take(200) + .position(|&c| c == b']' || c == b'\n') + .map(|p| i + 1 + p)?; + if b[close] != b']' || b.get(close + 1) != Some(&b'(') { + return None; + } + let url = url_at(b, close + 2)?; + if b.get(url.end) != Some(&b')') { + return None; + } + let text = &b[i + 1..close]; + let mentions = (0..text.len()).any(|k| mention_at(text, k).is_some()); + Some(Token { + start: i, + end: url.end + 1, + form: if mentions { Form::Mention } else { Form::Link }, + }) +} + +/// Every address in `text`, in order. +fn tokens(text: &str) -> Vec { + let b = text.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < b.len() { + let found = markdown_link_at(b, i) + .or_else(|| mention_at(b, i)) + .or_else(|| url_at(b, i)); + match found { + Some(t) => { + i = t.end; + out.push(t); + } + None => i += 1, + } + } + out +} + +/// Only spaces and punctuation (a list bullet, say) before `at` on its line. +fn opens_line(text: &str, at: usize) -> bool { + let line_start = text[..at].rfind('\n').map(|p| p + 1).unwrap_or(0); + text[line_start..at] + .bytes() + .all(|c| c.is_ascii_whitespace() || c.is_ascii_punctuation()) +} + +/// `text` with every address replaced by a space. +pub fn strip_address(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut at = 0; + // ASCII lowercasing keeps byte offsets, so the tokens found in the + // lowered copy cut the text as written. + for t in tokens(&text.to_ascii_lowercase()) { + out.push_str(&text[at..t.start]); + out.push(' '); + at = t.end; + } + out.push_str(&text[at..]); + out +} + +/// What a command looks like once the address is gone: no punctuation or +/// space around it, single spaces inside, lower case. +fn command_words(text: &str) -> String { + text.trim_matches(|c: char| c.is_ascii_punctuation() || c.is_whitespace()) + .split_whitespace() + .collect::>() + .join(" ") + .to_lowercase() +} + +/// The exact re-review commands (after the address is stripped). +pub fn is_rereview_command(text: &str) -> bool { + matches!( + command_words(text).as_str(), + "" | "re-review" | "re review" | "rereview" | "review" | "review again" + ) +} + +/// Whether the comment addresses CoderHelm, and what it asks. +pub fn parse_ask(body: &str) -> Option { + // Addressed only outside quotes and code. ASCII lowercasing keeps byte + // offsets identical to the text it lowers. + let addressed = addressed_text(body).to_ascii_lowercase(); + let slash = addressed.trim_start().starts_with(SLASH); + let found = tokens(&addressed); + let mention = found.iter().any(|t| t.form == Form::Mention); + let link = found + .iter() + .any(|t| t.form == Form::Link && opens_line(&addressed, t.start)); + if !slash && !mention && !link { + return None; + } + // The ask as written, without the quoted lines it replies to. + let body: String = body + .lines() + .filter(|l| !l.trim_start().starts_with('>')) + .collect::>() + .join("\n"); + let mut cleaned = strip_address(body.trim()).trim().to_string(); + if cleaned.to_ascii_lowercase().starts_with(SLASH) { + cleaned = cleaned[SLASH.len()..].trim().to_string(); + } + // Punctuation that only joined the address to the words. + let cleaned = cleaned + .trim_start_matches(|c: char| matches!(c, ',' | ':' | ';') || c.is_whitespace()) + .to_string(); + let bare = cleaned + .trim_matches(|c: char| c.is_ascii_punctuation() || c.is_whitespace()) + .is_empty(); + // A link with nothing after it is a reference to the page. + if bare && !slash && !mention { + return None; + } + let rereview = is_rereview_command(&cleaned); + Some(ReviewerAsk { + rereview, + bare, + question: if rereview { None } else { Some(cleaned) }, + }) +} + +/// For an `edited` comment: the ask when the edit made it a command, so an +/// edit runs a command once and a typo fix to a comment that already asked +/// doesn't ask again. The edit makes it a command when the old text didn't +/// address CoderHelm, or when it turned a question into the re-review +/// command. +pub fn ask_added_by_edit(old_body: &str, new_body: &str) -> Option { + let new = parse_ask(new_body)?; + match parse_ask(old_body) { + None => Some(new), + Some(old) if new.rereview && !old.rereview => Some(new), + Some(_) => None, + } +} + +/// The job key of an ask in a comment. A repeat delivery of the same comment +/// gives the same key (one job); an edit that made the comment a command +/// gets its own key from the moment GitHub stamped on that edit, so it is +/// never read as a repeat of the comment's first version. +pub fn ask_key(comment_id: u64, edited_at: Option<&str>) -> String { + match edited_at.map(str::trim).filter(|s| !s.is_empty()) { + Some(at) => format!("reply#{comment_id}#edit#{at}"), + None => format!("reply#{comment_id}"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn rereview() -> Option { + Some(ReviewerAsk { + rereview: true, + bare: false, + question: None, + }) + } + + #[test] + fn every_name_and_case_addresses_coderhelm() { + for body in [ + "@coderhelm re-review", + "@CoderHelm re-review", + "@CODERHELM re-review", + "@coderhelm[bot] re-review", + "@CoderHelm[bot] re-review", + "@coderhelm-app re-review", + "@coderhelm-app[bot] re-review", + "(@CoderHelm) re-review", + "@CoderHelm: re-review", + "@CoderHelm, re-review.", + "re-review @CoderHelm", + "re-review, @CoderHelm!", + ] { + assert_eq!(parse_ask(body), rereview(), "{body}"); + } + } + + #[test] + fn a_pasted_link_with_a_command_addresses_coderhelm() { + for body in [ + "https://github.com/CoderHelm re-review", + "https://github.com/coderhelm re-review", + "http://github.com/CoderHelm re-review", + "https://www.github.com/CoderHelm/ re-review", + "github.com/CoderHelm re-review", + "https://github.com/apps/coderhelm re-review", + "https://github.com/apps/coderhelm-app re-review", + " re-review", + "[@CoderHelm](https://github.com/CoderHelm) re-review", + "[CoderHelm](https://github.com/apps/coderhelm) re-review", + "[@coderhelm[bot]](https://github.com/apps/coderhelm) re-review", + "- https://github.com/CoderHelm re-review", + "please [@CoderHelm](https://github.com/CoderHelm) re-review", + ] { + let ask = parse_ask(body); + assert!(ask.is_some(), "{body}"); + } + assert_eq!( + parse_ask("https://github.com/CoderHelm re-review"), + rereview() + ); + assert_eq!( + parse_ask("[@CoderHelm](https://github.com/CoderHelm) re-review"), + rereview() + ); + assert_eq!( + parse_ask("https://github.com/CoderHelm why does this block?"), + Some(ReviewerAsk { + rereview: false, + bare: false, + question: Some("why does this block?".into()), + }) + ); + } + + #[test] + fn a_link_alone_or_in_a_sentence_is_not_a_command() { + for body in [ + "https://github.com/CoderHelm", + " https://github.com/CoderHelm/ ", + "[CoderHelm](https://github.com/CoderHelm)", + "thanks to https://github.com/CoderHelm for the review", + "see [the app](https://github.com/apps/coderhelm) for details", + "https://github.com/CoderHelm/coderhelm-platform re-review", + "https://github.com/CoderHelm-fans re-review", + "https://github.com/CoderHelm/issues re-review", + "write to help@coderhelm.dev re-review", + "user@coderhelm re-review", + "@coderhelmbot re-review", + "see coderhelm docs", + ] { + assert_eq!(parse_ask(body), None, "{body}"); + } + } + + #[test] + fn the_bare_mention_stays_the_bare_mention() { + let bare = Some(ReviewerAsk { + rereview: true, + bare: true, + question: None, + }); + assert_eq!(parse_ask("@CoderHelm"), bare); + assert_eq!( + parse_ask("[@CoderHelm](https://github.com/CoderHelm)"), + bare + ); + assert_eq!(parse_ask("/coderhelm"), bare); + } + + #[test] + fn quoted_and_code_addresses_are_not_addressed() { + assert_eq!(parse_ask("> https://github.com/CoderHelm re-review"), None); + assert_eq!( + parse_ask("`https://github.com/CoderHelm re-review` is how"), + None + ); + } + + #[test] + fn an_edit_counts_when_it_makes_the_comment_a_command() { + assert_eq!( + ask_added_by_edit("looks good", "https://github.com/CoderHelm re-review"), + rereview() + ); + assert_eq!( + ask_added_by_edit("@coderhelm is this safe?", "@coderhelm re-review"), + rereview() + ); + assert_eq!( + ask_added_by_edit("@coderhelm re-review", "@coderhelm re-review!"), + None + ); + assert_eq!( + ask_added_by_edit("@coderhelm re-review", "@coderhelm also, why?"), + None + ); + } + + #[test] + fn an_edit_has_its_own_key() { + assert_eq!(ask_key(7, None), "reply#7"); + assert_eq!(ask_key(7, Some("")), "reply#7"); + assert_ne!( + ask_key(7, Some("2030-01-01T10:00:00Z")), + ask_key(7, Some("2030-01-01T10:05:00Z")) + ); + assert_ne!(ask_key(7, Some("2030-01-01T10:00:00Z")), ask_key(7, None)); + } + + #[test] + fn stripping_removes_every_address() { + assert_eq!( + strip_address("[@CoderHelm](https://github.com/CoderHelm) why?").trim(), + "why?" + ); + assert_eq!(strip_address("@coderhelm[bot] ok").trim(), "ok"); + assert_eq!(strip_address("ΒΏ@CoderHelm? πŸš€").trim(), "ΒΏ ? πŸš€"); + } +} diff --git a/services/common/src/claim.rs b/services/common/src/claim.rs index 589f7b22..384cb752 100644 --- a/services/common/src/claim.rs +++ b/services/common/src/claim.rs @@ -87,6 +87,29 @@ pub async fn extend(dynamo: &DynamoClient, table: &str, pk: &str, sk: &str, ttl_ .await; } +/// When the live claim `(pk, sk)` was taken (RFC 3339), if one is held. +pub async fn claimed_at(dynamo: &DynamoClient, table: &str, pk: &str, sk: &str) -> Option { + let out = dynamo + .get_item() + .table_name(table) + .key("pk", AttributeValue::S(pk.to_string())) + .key("sk", AttributeValue::S(sk.to_string())) + .send() + .await + .ok()?; + let item = out.item()?; + let now = chrono::Utc::now().timestamp().max(0) as u64; + let live = item + .get("ttl") + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse::().ok()) + .is_some_and(|ttl| ttl >= now); + if !live { + return None; + } + item.get("claimed_at").and_then(|v| v.as_s().ok()).cloned() +} + /// Drop a claim so the same action can run again. Best-effort. pub async fn release(dynamo: &DynamoClient, table: &str, pk: &str, sk: &str) { let _ = dynamo diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 9eb718d5..09d6d4b3 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -39,9 +39,15 @@ pub mod nfr_check; /// Each acceptance criterion traced to the code, the tests and the proof. pub mod trace; +/// How a person addresses CoderHelm in a GitHub comment (every name and +/// the links GitHub makes of them), and what the comment asks. +pub mod address; /// Expiring once-only claims (dedup markers, leases) on the settings table. /// Shared so every claim compares its expiry the same way. pub mod claim; +/// A person's command acknowledged at once (πŸ‘€) and again when it is +/// answered (πŸš€); a refused one gets one short reply. +pub mod review_ack; // The customer details guard: public pull request text carries no install's // identifiers, read from CoderHelm's own records and kept in memory only. pub mod customer_guard; diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index ffd4340b..5623a22e 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -1129,6 +1129,11 @@ pub struct ReviewMessage { /// approval always rests on a full review. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub full_review: bool, + /// The person's comment that asked for this job, with the reaction + /// CoderHelm put on it when the gateway accepted it + /// (`review_ack`): whatever this job posts answers it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ack: Option, /// A review read in parts (`review_parts`): the parts and the keys of /// the answers the ones already read left in the store (never the /// answers themselves), carried from one invocation to the next on the diff --git a/services/common/src/review_ack.rs b/services/common/src/review_ack.rs new file mode 100644 index 00000000..b86a0925 --- /dev/null +++ b/services/common/src/review_ack.rs @@ -0,0 +1,515 @@ +//! A person's command to CoderHelm is acknowledged the moment it is +//! accepted, and the acknowledgement follows it to its answer. +//! +//! The gateway puts πŸ‘€ on the comment before it queues the work and records +//! the ask as waiting. When a review posts its verdict, every re-review ask +//! waiting on that commit is answered by it: its πŸ‘€ becomes πŸš€. A second +//! ask that came while an identical review was running is answered by that +//! review and doesn't start one of its own (two quick asks, one review), +//! and an ask the running review didn't answer (it failed, or it reviewed +//! another commit) runs its own review: never zero. A command that is +//! refused gets one short reply saying why. + +use aws_sdk_dynamodb::types::AttributeValue; +use aws_sdk_dynamodb::Client as DynamoClient; +use serde::{Deserialize, Serialize}; + +/// Seen: the command was accepted and its work is queued or running. +pub const SEEN: &str = "eyes"; +/// Answered: the review (or the answer) is posted. +pub const ANSWERED: &str = "rocket"; + +/// How long a waiting ask is kept: well past the longest wait of an ask. +pub const TTL_SECS: u64 = 3 * 24 * 3600; +/// A refusal is said once per comment. +pub const REFUSAL_TTL_SECS: u64 = 30 * 24 * 3600; + +const WAITING: &str = "waiting"; +const DONE: &str = "answered"; + +/// The comment that asked, and CoderHelm's reaction on it. +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] +pub struct Ack { + pub comment_id: u64, + /// A review (line) comment; otherwise a conversation comment. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub line: bool, + /// The πŸ‘€ reaction CoderHelm put on the comment, when GitHub said its id. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reaction_id: Option, + /// The ask is the re-review command, so any verdict on its commit + /// answers it. A question is answered only by its own job. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub rereview: bool, +} + +impl Ack { + pub fn new(comment_id: u64, line: bool, rereview: bool) -> Self { + Ack { + comment_id, + line, + reaction_id: None, + rereview, + } + } + + /// The comment's reactions, under the repository's API path. + pub fn reactions_path(&self, owner: &str, repo: &str) -> String { + let kind = if self.line { "pulls" } else { "issues" }; + format!( + "/repos/{owner}/{repo}/{kind}/comments/{}/reactions", + self.comment_id + ) + } + + fn same_comment(&self, other: &Ack) -> bool { + self.comment_id == other.comment_id && self.line == other.line + } +} + +/// Every waiting ask of a pull request starts with this key. +pub fn pr_prefix(owner: &str, name: &str, pr: u64) -> String { + format!("REVIEWACK#{owner}/{name}#{pr:06}#") +} + +/// The record of one ask. +pub fn ack_sk(owner: &str, name: &str, pr: u64, ack: &Ack) -> String { + format!( + "{}{}{}", + pr_prefix(owner, name, pr), + if ack.line { 'l' } else { 'c' }, + ack.comment_id + ) +} + +/// An ask on record. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Waiting { + pub sk: String, + pub ack: Ack, + /// The commit the pull request was on when the person asked (empty when + /// it couldn't be read). + pub head: String, + pub answered: bool, +} + +/// The asks a stored review answers. Its own ask, always (whatever it +/// posted is the answer to it). Other re-review asks waiting on the same +/// commit, when it posted a verdict: the person asked for another look at +/// that commit and the review gave one. A question is never answered by +/// someone else's review. An ask whose record is missing (the gateway +/// couldn't write it) is still answered when it is the job's own. +pub fn to_settle( + owner: &str, + name: &str, + pr: u64, + waiting: &[Waiting], + own: Option<&Ack>, + head: &str, + posted_verdict: bool, +) -> Vec { + let mut out: Vec = waiting + .iter() + .filter(|w| !w.answered) + .filter(|w| { + own.is_some_and(|o| o.same_comment(&w.ack)) + || (posted_verdict + && w.ack.rereview + && (w.head.is_empty() || head.is_empty() || w.head == head)) + }) + .cloned() + .collect(); + if let Some(o) = own { + let on_record = waiting.iter().any(|w| w.ack.same_comment(o)); + if !on_record { + out.push(Waiting { + sk: ack_sk(owner, name, pr, o), + ack: o.clone(), + head: head.to_string(), + answered: false, + }); + } + } + out +} + +/// A re-review ask whose record says another review already answered it: +/// it doesn't run a review of its own. +pub fn collapsed(own: &Ack, record: Option<&Waiting>) -> bool { + own.rereview && record.is_some_and(|w| w.answered) +} + +/// The reaction calls, so the same steps run against GitHub and in tests. +pub trait Reactions: Sync { + /// Add `content` to the comment; the reaction's id. + fn add( + &self, + owner: &str, + repo: &str, + ack: &Ack, + content: &str, + ) -> impl std::future::Future> + Send; + /// Remove reaction `id` from the comment. + fn remove( + &self, + owner: &str, + repo: &str, + ack: &Ack, + id: u64, + ) -> impl std::future::Future + Send; +} + +/// πŸ‘€ on the comment; the ack carries the reaction's id. +pub async fn see(r: &R, owner: &str, repo: &str, ack: &mut Ack) { + ack.reaction_id = r.add(owner, repo, ack, SEEN).await; +} + +/// πŸ‘€ becomes πŸš€: the answer is posted. +pub async fn swap(r: &R, owner: &str, repo: &str, ack: &Ack) { + if let Some(id) = ack.reaction_id { + r.remove(owner, repo, ack, id).await; + } + r.add(owner, repo, ack, ANSWERED).await; +} + +/// The reaction calls with an installation token. +pub struct TokenReactions<'a> { + pub http: &'a reqwest::Client, + pub token: String, +} + +const API: &str = "https://api.github.com"; + +impl Reactions for TokenReactions<'_> { + async fn add(&self, owner: &str, repo: &str, ack: &Ack, content: &str) -> Option { + let url = format!("{API}{}", ack.reactions_path(owner, repo)); + let resp = self + .http + .post(url) + .header("Authorization", format!("Bearer {}", self.token)) + .header("Accept", "application/vnd.github+json") + .header("User-Agent", "Coderhelm-bot") + .timeout(std::time::Duration::from_secs(5)) + .json(&serde_json::json!({ "content": content })) + .send() + .await + .ok()?; + if !resp.status().is_success() { + tracing::warn!( + owner, + repo, + comment = ack.comment_id, + status = resp.status().as_u16(), + "GitHub refused a reaction" + ); + return None; + } + resp.json::().await.ok()?["id"].as_u64() + } + + async fn remove(&self, owner: &str, repo: &str, ack: &Ack, id: u64) -> bool { + let url = format!("{API}{}/{id}", ack.reactions_path(owner, repo)); + self.http + .delete(url) + .header("Authorization", format!("Bearer {}", self.token)) + .header("Accept", "application/vnd.github+json") + .header("User-Agent", "Coderhelm-bot") + .timeout(std::time::Duration::from_secs(5)) + .send() + .await + .is_ok_and(|r| r.status().is_success()) + } +} + +/// Why a person's command was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Refusal { + /// The author has no write access to the repository and isn't on the + /// team that installed CoderHelm. + NoStanding, + /// The reviewer is off for the repository, and the command needs it. + ReviewerOff, +} + +/// The one short reply to a refused command. +pub fn refusal_line(r: Refusal) -> &'static str { + match r { + Refusal::NoStanding => { + "I can't act on this comment: only people with write access to this repository, \ + or on the CoderHelm team that installed it, can ask me for work here." + } + Refusal::ReviewerOff => { + "I can't review here: the CoderHelm reviewer is off for this repository. Someone \ + on the team can turn it on in CoderHelm, then ask again." + } + } +} + +/// Said once per comment: a repeat delivery or an edit doesn't say it again. +pub fn refusal_sk(owner: &str, name: &str, ack: &Ack) -> String { + format!( + "ASKREFUSED#{owner}/{name}#{}{}", + if ack.line { 'l' } else { 'c' }, + ack.comment_id + ) +} + +fn now() -> i64 { + chrono::Utc::now().timestamp() +} + +/// Records the ask as waiting. A repeat delivery keeps the first record (an +/// answered ask is never made waiting again). +#[allow(clippy::too_many_arguments)] +pub async fn register( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + owner: &str, + name: &str, + pr: u64, + ack: &Ack, + head: &str, +) { + let mut req = dynamo + .put_item() + .table_name(table) + .item("pk", AttributeValue::S(team_id.to_string())) + .item("sk", AttributeValue::S(ack_sk(owner, name, pr, ack))) + .item("comment_id", AttributeValue::N(ack.comment_id.to_string())) + .item("line", AttributeValue::Bool(ack.line)) + .item("rereview", AttributeValue::Bool(ack.rereview)) + .item("head", AttributeValue::S(head.to_string())) + .item("ack_state", AttributeValue::S(WAITING.into())) + .item("asked_at", AttributeValue::N(now().to_string())) + .item( + "ttl", + AttributeValue::N((now() as u64 + TTL_SECS).to_string()), + ) + .condition_expression("attribute_not_exists(sk)"); + if let Some(id) = ack.reaction_id { + req = req.item("reaction_id", AttributeValue::N(id.to_string())); + } + if let Err(e) = req.send().await { + let repeat = e + .as_service_error() + .is_some_and(|se| se.is_conditional_check_failed_exception()); + if !repeat { + tracing::warn!(owner, name, pr, error = %e, "Could not record the ask as waiting"); + } + } +} + +fn from_item(item: &std::collections::HashMap) -> Option { + let s = |k: &str| item.get(k).and_then(|v| v.as_s().ok()).cloned(); + let n = |k: &str| { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse::().ok()) + }; + let b = |k: &str| item.get(k).and_then(|v| v.as_bool().ok()).copied(); + Some(Waiting { + sk: s("sk")?, + ack: Ack { + comment_id: n("comment_id")?, + line: b("line").unwrap_or(false), + reaction_id: n("reaction_id"), + rereview: b("rereview").unwrap_or(false), + }, + head: s("head").unwrap_or_default(), + answered: s("ack_state").as_deref() == Some(DONE), + }) +} + +/// The asks on record for a pull request. +pub async fn on_pr( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + owner: &str, + name: &str, + pr: u64, +) -> Vec { + match dynamo + .query() + .table_name(table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", AttributeValue::S(team_id.to_string())) + .expression_attribute_values(":p", AttributeValue::S(pr_prefix(owner, name, pr))) + .send() + .await + { + Ok(out) => out.items().iter().filter_map(from_item).collect(), + Err(e) => { + tracing::warn!(owner, name, pr, error = %e, "Could not read the asks waiting on the PR"); + Vec::new() + } + } +} + +/// The record of one ask. +pub async fn get(dynamo: &DynamoClient, table: &str, team_id: &str, sk: &str) -> Option { + let out = dynamo + .get_item() + .table_name(table) + .key("pk", AttributeValue::S(team_id.to_string())) + .key("sk", AttributeValue::S(sk.to_string())) + .send() + .await + .ok()?; + out.item().and_then(from_item) +} + +/// Marks the ask answered. True for the one caller that did it, so two +/// reviews finishing together swap the reaction once. +pub async fn mark_answered(dynamo: &DynamoClient, table: &str, team_id: &str, w: &Waiting) -> bool { + let req = dynamo + .update_item() + .table_name(table) + .key("pk", AttributeValue::S(team_id.to_string())) + .key("sk", AttributeValue::S(w.sk.clone())) + .update_expression( + "SET ack_state = :done, comment_id = :c, line = :l, rereview = :r, #ttl = :ttl", + ) + .condition_expression("attribute_not_exists(ack_state) OR ack_state = :waiting") + .expression_attribute_names("#ttl", "ttl") + .expression_attribute_values(":done", AttributeValue::S(DONE.into())) + .expression_attribute_values(":waiting", AttributeValue::S(WAITING.into())) + .expression_attribute_values(":c", AttributeValue::N(w.ack.comment_id.to_string())) + .expression_attribute_values(":l", AttributeValue::Bool(w.ack.line)) + .expression_attribute_values(":r", AttributeValue::Bool(w.ack.rereview)) + .expression_attribute_values( + ":ttl", + AttributeValue::N((now() as u64 + TTL_SECS).to_string()), + ); + match req.send().await { + Ok(_) => true, + Err(e) => { + let taken = e + .as_service_error() + .is_some_and(|se| se.is_conditional_check_failed_exception()); + if !taken { + // Unknown: swap anyway. A second πŸš€ is GitHub's no-op; a + // lost one leaves the person without an answer. + tracing::warn!(sk = %w.sk, error = %e, "Could not mark the ask answered"); + return true; + } + false + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + + #[derive(Default)] + struct Fake { + calls: Mutex>, + } + + impl Reactions for Fake { + async fn add(&self, _o: &str, _r: &str, ack: &Ack, content: &str) -> Option { + let mut c = self.calls.lock().unwrap(); + c.push(format!("add {content} on {}", ack.comment_id)); + Some(100 + c.len() as u64) + } + async fn remove(&self, _o: &str, _r: &str, ack: &Ack, id: u64) -> bool { + self.calls + .lock() + .unwrap() + .push(format!("remove {id} on {}", ack.comment_id)); + true + } + } + + fn waiting(id: u64, head: &str, rereview: bool, answered: bool) -> Waiting { + let ack = Ack::new(id, false, rereview); + Waiting { + sk: ack_sk("acme", "shop", 7, &ack), + ack, + head: head.into(), + answered, + } + } + + #[tokio::test] + async fn seen_then_answered_swaps_the_reaction() { + let fake = Fake::default(); + let mut ack = Ack::new(41, false, true); + see(&fake, "acme", "shop", &mut ack).await; + assert_eq!(ack.reaction_id, Some(101)); + swap(&fake, "acme", "shop", &ack).await; + assert_eq!( + *fake.calls.lock().unwrap(), + vec!["add eyes on 41", "remove 101 on 41", "add rocket on 41"] + ); + } + + #[test] + fn a_verdict_answers_every_rereview_waiting_on_its_commit() { + let w = vec![ + waiting(1, "h1", true, false), + waiting(2, "h1", false, false), + waiting(3, "h2", true, false), + waiting(4, "", true, false), + waiting(5, "h1", true, true), + ]; + let got: Vec = to_settle("acme", "shop", 7, &w, None, "h1", true) + .iter() + .map(|w| w.ack.comment_id) + .collect(); + assert_eq!(got, vec![1, 4]); + // Nothing posted: only the job's own ask. + let own = Ack::new(2, false, false); + let got: Vec = to_settle("acme", "shop", 7, &w, Some(&own), "h1", false) + .iter() + .map(|w| w.ack.comment_id) + .collect(); + assert_eq!(got, vec![2]); + } + + #[test] + fn the_jobs_own_ask_is_answered_without_a_record() { + let own = Ack::new(9, true, true); + let got = to_settle("acme", "shop", 7, &[], Some(&own), "h1", false); + assert_eq!(got.len(), 1); + assert_eq!(got[0].sk, ack_sk("acme", "shop", 7, &own)); + } + + #[test] + fn only_an_answered_rereview_collapses() { + let own = Ack::new(1, false, true); + assert!(collapsed(&own, Some(&waiting(1, "h1", true, true)))); + assert!(!collapsed(&own, Some(&waiting(1, "h1", true, false)))); + assert!(!collapsed(&own, None)); + let question = Ack::new(1, false, false); + assert!(!collapsed(&question, Some(&waiting(1, "h1", false, true)))); + } + + #[test] + fn keys_tell_comment_kinds_apart() { + let c = Ack::new(5, false, true); + let l = Ack::new(5, true, true); + assert_ne!(ack_sk("o", "r", 1, &c), ack_sk("o", "r", 1, &l)); + assert!(ack_sk("o", "r", 1, &c).starts_with(&pr_prefix("o", "r", 1))); + assert_ne!(refusal_sk("o", "r", &c), refusal_sk("o", "r", &l)); + assert_eq!( + c.reactions_path("o", "r"), + "/repos/o/r/issues/comments/5/reactions" + ); + assert_eq!( + l.reactions_path("o", "r"), + "/repos/o/r/pulls/comments/5/reactions" + ); + } + + #[test] + fn a_refusal_is_one_short_line() { + for r in [Refusal::NoStanding, Refusal::ReviewerOff] { + let line = refusal_line(r); + assert!(!line.contains('\n') && line.len() < 200, "{line}"); + } + } +} diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 5f49ad5a..b2a28f2f 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -667,122 +667,13 @@ async fn handle_issue_event( send_to_queue(state, &state.config.ticket_queue_url, &message).await } -/// A comment addressed to the reviewer: `@coderhelm …` anywhere outside -/// quoted text and code (any case β€” GitHub autocompletes the display name, -/// e.g. `@CoderHelm`), or `/coderhelm …` at the start. One parser for every -/// surface: conversation comments, inline thread replies, review bodies. -#[derive(Debug, PartialEq, Eq)] -pub(crate) struct ReviewerAsk { - /// The exact re-review command (`re-review`, `re review`, `rereview`, - /// `review`, `review again`, or the bare mention): a fast path that - /// skips the worker's model classification. - pub rereview: bool, - /// The mention alone, with no words. On CoderHelm's own PR with work - /// still held or unfinished it resumes that work; otherwise it is the - /// re-review command (see `common::held_work`). - pub bare: bool, - /// Anything else, as written. What it asks for (another look, the - /// approval, a question, a fix) is decided by the worker's model, never - /// by keywords here. - pub question: Option, -} - -/// The comment without quoted lines (`> …`), fenced code blocks and inline -/// code: a mention someone quoted or pasted is not addressed to CoderHelm. -pub(crate) fn addressed_text(body: &str) -> String { - let mut out = String::with_capacity(body.len()); - let mut in_fence = false; - for line in body.lines() { - let t = line.trim_start(); - if t.starts_with("```") || t.starts_with("~~~") { - in_fence = !in_fence; - continue; - } - if in_fence || t.starts_with('>') { - continue; - } - // Drop `inline code` spans (every other piece between backticks). - for (i, part) in line.split('`').enumerate() { - if i % 2 == 0 { - out.push_str(part); - } - } - out.push('\n'); - } - out -} - -/// The exact re-review commands (after the mention is stripped). -fn is_rereview_command(text: &str) -> bool { - let t = text - .trim() - .trim_end_matches(['.', '!', '?']) - .trim() - .to_lowercase(); - matches!( - t.as_str(), - "" | "re-review" | "re review" | "rereview" | "review" | "review again" - ) -} - -pub(crate) fn parse_reviewer_ask(body: &str) -> Option { - const MENTION: &str = "@coderhelm"; - const SLASH: &str = "/coderhelm"; - // Addressed only when the mention is outside quotes and code. - let addressed = addressed_text(body).to_ascii_lowercase(); - if !addressed.trim_start().starts_with(SLASH) && !addressed.contains(MENTION) { - return None; - } - // The ask as written, without the quoted lines it replies to. - let body: String = body - .lines() - .filter(|l| !l.trim_start().starts_with('>')) - .collect::>() - .join("\n"); - let body = body.trim(); - // ASCII lowercasing keeps byte offsets identical to `body`. - let lower = body.to_ascii_lowercase(); - // Strip every address token (and a trailing "[bot]") to recover the message. - let mut cleaned = String::with_capacity(body.len()); - let mut i = 0; - while i < body.len() { - if lower[i..].starts_with(MENTION) { - i += MENTION.len(); - if lower[i..].starts_with("[bot]") { - i += "[bot]".len(); - } - cleaned.push(' '); - continue; - } - let ch = body[i..].chars().next().unwrap_or(' '); - cleaned.push(ch); - i += ch.len_utf8(); - } - let mut cleaned = cleaned.trim().to_string(); - if cleaned.to_ascii_lowercase().starts_with(SLASH) { - cleaned = cleaned[SLASH.len()..].trim().to_string(); - } - let rereview = is_rereview_command(&cleaned); - let bare = cleaned - .trim() - .trim_matches(|c: char| c.is_ascii_punctuation() || c.is_whitespace()) - .is_empty(); - Some(ReviewerAsk { - rereview, - bare, - question: if rereview { None } else { Some(cleaned) }, - }) -} - -/// For an `edited` comment: the ask only when the edit added it (the old -/// text had none), so an edit runs a command once and a typo fix to a -/// comment that already asked doesn't ask again. -pub(crate) fn ask_added_by_edit(old_body: &str, new_body: &str) -> Option { - if parse_reviewer_ask(old_body).is_some() { - return None; - } - parse_reviewer_ask(new_body) -} +/// A comment addressed to the reviewer, by any of CoderHelm's names or the +/// link GitHub makes of them, outside quoted text and code, or +/// `/coderhelm …` at the start. One parser for every surface: conversation +/// comments, inline thread replies, review bodies (`common::address`). +pub(crate) use common::address::{ + addressed_text, ask_added_by_edit, parse_ask as parse_reviewer_ask, ReviewerAsk, +}; /// A CoderHelm account (the app's bot user), read from GitHub's structured /// user type and the app's login. A person whose login happens to contain @@ -794,7 +685,7 @@ pub(crate) fn is_coderhelm_user(user: &Value) -> bool { } /// What a reply's words say, for telling two versions of a reply apart: -/// the text without quoted lines and without any `@coderhelm` address, +/// the text without quoted lines and without any address to CoderHelm, /// lower case, letters and digits only. Adding or removing a mention, a /// space or punctuation leaves it unchanged. pub(crate) fn reply_fingerprint(body: &str) -> String { @@ -803,11 +694,10 @@ pub(crate) fn reply_fingerprint(body: &str) -> String { .lines() .filter(|l| !l.trim_start().starts_with('>')) .collect::>() - .join("\n") + .join("\n"); + let text = common::address::strip_address(&text) .to_ascii_lowercase() - .replace("@coderhelm[bot]", " ") - .replace("@coderhelm", " ") - .replace("/coderhelm", " "); + .replace(common::address::SLASH, " "); let key: String = text.chars().filter(|c| c.is_alphanumeric()).collect(); hex::encode(&Sha256::digest(key.as_bytes())[..6]) } @@ -963,6 +853,20 @@ async fn handle_review_comment( ) .await { + if ask.is_some() { + let line = common::review_ack::Ack::new(comment_id, true, false); + refuse( + state, + team_id, + installation_id, + owner, + name, + pr_number, + &line, + common::review_ack::Refusal::NoStanding, + ) + .await; + } return ignored("the author has no standing in the repository or on the team"); } if let Some(control) = ask @@ -994,6 +898,20 @@ async fn handle_review_comment( } let cfg = load_review_config(state, team_id, owner, name).await?; if !cfg.enabled || cfg.killed || pr_number == 0 { + if ask.is_some() { + let line = common::review_ack::Ack::new(comment_id, true, false); + refuse( + state, + team_id, + installation_id, + owner, + name, + pr_number, + &line, + common::review_ack::Refusal::ReviewerOff, + ) + .await; + } return ignored("review is off for this repo"); } if let Some(reason) = check_run_budget(state, team_id).await { @@ -1037,6 +955,11 @@ async fn handle_review_comment( thread_root_id: Some(root), mentioned: ask.is_some(), requested_by: commenter.to_string(), + // A reply that addressed CoderHelm is a command: seen, then + // answered. One that didn't may not be for CoderHelm. + ack: ask + .is_some() + .then(|| common::review_ack::Ack::new(comment_id, true, false)), ..Default::default() } } @@ -1051,16 +974,9 @@ async fn handle_review_comment( is_rereview = ask.rereview, "Reviewer: thread reply: review job" ); + let dedup_key = common::address::ask_key(comment_id, edited_at(payload)); if ask.rereview { - record_rereview( - state, - team_id, - owner, - name, - pr_number, - &format!("reply#{comment_id}"), - ) - .await; + record_rereview(state, team_id, owner, name, pr_number, &dedup_key).await; } ReviewMessage { team_id: team_id.to_string(), @@ -1070,9 +986,10 @@ async fn handle_review_comment( pr_number, head_sha: String::new(), label: cfg.label, + ack: Some(common::review_ack::Ack::new(comment_id, true, ask.rereview)), question: ask.question, trigger: "reply".to_string(), - dedup_key: format!("reply#{comment_id}"), + dedup_key, reply_to_comment_id: Some(comment_id), mentioned: true, requested_by: commenter.to_string(), @@ -1321,8 +1238,12 @@ async fn handle_issue_comment( let body = payload["comment"]["body"].as_str().unwrap_or(""); let commenter = payload["comment"]["user"]["login"].as_str().unwrap_or(""); - // A comment addressed to the bot ("@CoderHelm …" in any case, or "/coderhelm …"). - let ask = if commenter.contains("coderhelm") { + // A comment addressed to the bot (any of its names or the link GitHub + // makes of them, in any case, or "/coderhelm …"). Only CoderHelm's own + // account is CoderHelm: a person whose login contains the name is a + // person, and their command counts. + let from_coderhelm = is_coderhelm_user(&payload["comment"]["user"]); + let ask = if from_coderhelm { None } else { parse_reviewer_ask(body) @@ -1384,11 +1305,8 @@ async fn handle_issue_comment( .as_str() .unwrap_or("") .contains("coderhelm") - && !commenter.contains("coderhelm"); - let lower = body.to_ascii_lowercase(); - let addressed = ask.is_some() - || lower.trim_start().starts_with("/coderhelm") - || lower.contains("@coderhelm"); + && !from_coderhelm; + let addressed = ask.is_some(); if !on_bot_pr && !addressed { // A person writing on an issue a run is working on is talking to // that run, mention or not (an answer to its questions). @@ -1423,6 +1341,18 @@ async fn handle_issue_comment( ) .await { + // A command from someone who may not ask is told why, once; other + // conversation on CoderHelm's PR is left alone. + if ask.is_some() { + refuse_comment( + state, + team_id, + installation_id, + payload, + common::review_ack::Refusal::NoStanding, + ) + .await; + } return Ok(StatusCode::OK); } @@ -1434,7 +1364,7 @@ async fn handle_issue_comment( // straight to the fix loop, as before. if payload["issue"]["pull_request"].is_object() { let pr_user = payload["issue"]["user"]["login"].as_str().unwrap_or(""); - let bot_pr = pr_user.contains("coderhelm") && !commenter.contains("coderhelm"); + let bot_pr = pr_user.contains("coderhelm") && !from_coderhelm; // Work a round left held or unfinished on CoderHelm's own PR comes // first (common::held_work): a bare mention resumes it, and words // are read by the model told about it. Only an explicit review @@ -1470,6 +1400,7 @@ async fn handle_issue_comment( if let (common::held_work::MentionRoute::ResumeWork, Some((run_id, work))) = (route, &outstanding) { + see_comment(state, installation_id, payload).await; return resume_outstanding(state, payload, installation_id, team_id, run_id, work) .await; } @@ -1566,6 +1497,10 @@ async fn handle_issue_comment( info!(team_id, "PR comment feedback skipped β€” token limit reached"); return Ok(StatusCode::OK); } + // A person's command is seen before its work is queued. + if ask.is_some() { + see_comment(state, installation_id, payload).await; + } return send_to_queue(state, &state.config.feedback_queue_url, &message).await; } @@ -1597,18 +1532,12 @@ async fn handle_issue_comment( // Idempotency key = this comment's id. A webhook GitHub delivers // more than once (at-least-once) carries the SAME comment id, so // the worker runs the review exactly once; a genuinely new - // `@coderhelm re-review` comment has a new id and re-runs. + // `@coderhelm re-review` comment has a new id and re-runs, and + // an edit that made the comment a command has its own key. let comment_id = payload["comment"]["id"].as_u64().unwrap_or(0); + let dedup_key = common::address::ask_key(comment_id, edited_at(payload)); if is_rereview { - record_rereview( - state, - team_id, - owner, - name, - pr_number, - &format!("reply#{comment_id}"), - ) - .await; + record_rereview(state, team_id, owner, name, pr_number, &dedup_key).await; } let message = ReviewMessage { team_id: team_id.to_string(), @@ -1620,10 +1549,13 @@ async fn handle_issue_comment( label: cfg.label, question, trigger: "reply".to_string(), - dedup_key: format!("reply#{comment_id}"), + dedup_key, reply_to_comment_id: None, requested_by: commenter.to_string(), outstanding_work: outstanding.as_ref().map(|(_, w)| w.note()), + // Seen (πŸ‘€) before it is queued, answered (πŸš€) when the + // review posts. + ack: Some(common::review_ack::Ack::new(comment_id, false, is_rereview)), ..Default::default() }; return send_review_job(state, message, "", 0).await; @@ -1632,18 +1564,23 @@ async fn handle_issue_comment( owner, name, pr_number, - "Reviewer: @coderhelm reply ignored β€” review is off for this repo" + "Reviewer: @coderhelm reply refused β€” review is off for this repo" ); + refuse_comment( + state, + team_id, + installation_id, + payload, + common::review_ack::Refusal::ReviewerOff, + ) + .await; } return Ok(StatusCode::OK); } } - // Trigger on `/coderhelm` slash command or @coderhelm mention (issues or non-bot PRs) - let lower_body = body.to_ascii_lowercase(); - let is_slash = lower_body.trim_start().starts_with("/coderhelm"); - let is_mention = lower_body.contains("@coderhelm"); - if !is_slash && !is_mention { + // Trigger on a comment addressed to CoderHelm (issues or non-bot PRs). + if ask.is_none() { return Ok(StatusCode::OK); } @@ -1726,9 +1663,164 @@ async fn handle_issue_comment( return Ok(StatusCode::OK); } + // A person's command is seen before its run is queued. + see_comment(state, installation_id, payload).await; send_to_queue(state, &state.config.ticket_queue_url, &message).await } +/// When GitHub stamped an `edited` comment's edit (`None` for a new one). +fn edited_at(payload: &Value) -> Option<&str> { + (payload["action"].as_str() == Some("edited")) + .then(|| payload["comment"]["updated_at"].as_str()) + .flatten() +} + +/// How long acknowledging a command may hold its webhook up. +const ACK_BUDGET_SECS: u64 = 4; + +/// The installation's reaction calls; `None` without a token. +async fn reaction_calls( + state: &AppState, + installation_id: u64, +) -> Option> { + match crate::auth::github_app::get_installation_token(state, installation_id).await { + Ok(token) => Some(common::review_ack::TokenReactions { + http: &state.http, + token, + }), + Err(e) => { + warn!(installation_id, error = %e, "No installation token to acknowledge a command"); + None + } + } +} + +/// πŸ‘€ on a person's accepted command, before its work is queued; the ack +/// carries the reaction's id so the answer can swap it. Bounded, so a slow +/// GitHub never holds the webhook up, and never stops the work. +pub(crate) async fn acknowledge( + state: &AppState, + installation_id: u64, + owner: &str, + name: &str, + ack: &mut common::review_ack::Ack, +) { + if ack.comment_id == 0 || owner.is_empty() || name.is_empty() { + return; + } + let Some(calls) = reaction_calls(state, installation_id).await else { + return; + }; + let seen = tokio::time::timeout( + std::time::Duration::from_secs(ACK_BUDGET_SECS), + common::review_ack::see(&calls, owner, name, ack), + ) + .await; + if seen.is_err() { + warn!( + owner, + name, + comment = ack.comment_id, + "Acknowledging the command took too long; its work goes on" + ); + } +} + +/// πŸ‘€ on the conversation comment of `payload`: a command whose work is not +/// a review (a run, a fix round). +async fn see_comment(state: &AppState, installation_id: u64, payload: &Value) { + let repo = &payload["repository"]; + let mut ack = + common::review_ack::Ack::new(payload["comment"]["id"].as_u64().unwrap_or(0), false, false); + acknowledge( + state, + installation_id, + repo["owner"]["login"].as_str().unwrap_or(""), + repo["name"].as_str().unwrap_or(""), + &mut ack, + ) + .await; +} + +/// The one short reply to a refused command, said once per comment (a +/// repeat delivery or an edit doesn't say it again), in the pull request's +/// or issue's conversation. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn refuse( + state: &AppState, + team_id: &str, + installation_id: u64, + owner: &str, + name: &str, + number: u64, + ack: &common::review_ack::Ack, + why: common::review_ack::Refusal, +) { + use common::review_ack as ra; + if ack.comment_id == 0 || number == 0 || owner.is_empty() || name.is_empty() { + return; + } + let once = common::claim::claim( + &state.dynamo, + &state.config.settings_table_name, + team_id, + &ra::refusal_sk(owner, name, ack), + ra::REFUSAL_TTL_SECS, + ) + .await; + if once == common::claim::Claim::Held { + return; + } + let token = match crate::auth::github_app::get_installation_token(state, installation_id).await + { + Ok(t) => t, + Err(e) => { + warn!(owner, name, number, error = %e, "No installation token to answer a refused command"); + return; + } + }; + let line = ra::refusal_line(why); + info!(owner, name, number, comment = ack.comment_id, why = ?why, "Command refused: said why"); + // Through the conversation layer, as every reply to a person is. + let facts = common::reply_compose::Facts::default() + .github_pr(&format!("{owner}/{name}"), number, "", "open") + .gate(format!( + "A person's command to CoderHelm was refused: {line}" + )); + let say = common::conversation::Say::reply_all("command-refused", line.to_string()); + if let Err(e) = Box::pin(super::conversation::reply_github( + state, team_id, &token, owner, name, number, say, &facts, + )) + .await + { + warn!(owner, name, number, error = %e, "Could not answer a refused command"); + } +} + +/// [`refuse`] for the conversation comment of an `issue_comment` payload. +async fn refuse_comment( + state: &AppState, + team_id: &str, + installation_id: u64, + payload: &Value, + why: common::review_ack::Refusal, +) { + let repo = &payload["repository"]; + let ack = + common::review_ack::Ack::new(payload["comment"]["id"].as_u64().unwrap_or(0), false, false); + refuse( + state, + team_id, + installation_id, + repo["owner"]["login"].as_str().unwrap_or(""), + repo["name"].as_str().unwrap_or(""), + payload["issue"]["number"].as_u64().unwrap_or(0), + &ack, + why, + ) + .await; +} + /// What an `@coderhelm` / `/coderhelm` command on a GitHub issue carries /// when the issue's last run ended on a merge (it merged, or the /// merged-ticket check ended it: `common::merged_ticket`): a person asking @@ -4884,12 +4976,28 @@ pub(crate) fn pr_event_asks_review(cfg: &ReviewConfig, action: &str, payload: &V /// 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`. +/// +/// A person's command (`message.ack`) is seen first: πŸ‘€ on their comment +/// before anything else, and the ask recorded as waiting on the commit, so +/// the review that answers it (this one, or an identical one already +/// running) swaps it for πŸš€ (`common::review_ack`). pub(crate) async fn send_review_job( state: &AppState, mut message: ReviewMessage, head: &str, delay_secs: i32, ) -> Result { + if let Some(mut ack) = message.ack.take() { + acknowledge( + state, + message.installation_id, + &message.repo_owner, + &message.repo_name, + &mut ack, + ) + .await; + message.ack = Some(ack); + } 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 { @@ -4912,6 +5020,24 @@ pub(crate) async fn send_review_job( if let Some((_, head)) = &shown { message.check_head = head.clone(); } + if let Some(ack) = &message.ack { + let asked_on = if message.check_head.is_empty() { + head + } else { + &message.check_head + }; + common::review_ack::register( + &state.dynamo, + &state.config.settings_table_name, + &message.team_id, + &message.repo_owner, + &message.repo_name, + message.pr_number, + ack, + asked_on, + ) + .await; + } let sent = send_to_queue_after( state, &state.config.ticket_queue_url, diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 659d71a8..1de5a516 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -4419,6 +4419,22 @@ impl GitHubClient { .await } + /// Takes CoderHelm's reaction `reaction_id` off a comment. + pub async fn remove_reaction( + &self, + owner: &str, + repo: &str, + comment_id: u64, + line: bool, + reaction_id: u64, + ) -> Result<(), Box> { + let kind = if line { "pulls" } else { "issues" }; + let url = format!( + "{API_BASE}/repos/{owner}/{repo}/{kind}/comments/{comment_id}/reactions/{reaction_id}" + ); + self.delete_url(&url).await + } + /// Add one or more labels to an issue/PR. Additive (GitHub keeps existing /// labels) and creates any label that doesn't exist yet. Used to hand a PR /// off to the repo's own label-triggered CI (e.g. a deploy workflow). @@ -7977,3 +7993,38 @@ pub(crate) mod budget_tests { assert!(!core_spent(404, Some("core"), Some("0"))); } } + +/// A person's command is answered with the same reaction calls the gateway +/// acknowledged it with (`common::review_ack`). +impl common::review_ack::Reactions for GitHubClient { + async fn add( + &self, + owner: &str, + repo: &str, + ack: &common::review_ack::Ack, + content: &str, + ) -> Option { + match self + .add_reaction(owner, repo, ack.comment_id, ack.line, content) + .await + { + Ok(v) => v["id"].as_u64(), + Err(e) => { + tracing::warn!(owner, repo, comment = ack.comment_id, error = %e, "Could not react to the comment"); + None + } + } + } + + async fn remove( + &self, + owner: &str, + repo: &str, + ack: &common::review_ack::Ack, + id: u64, + ) -> bool { + self.remove_reaction(owner, repo, ack.comment_id, ack.line, id) + .await + .is_ok() + } +} diff --git a/services/worker/src/passes/incidents/xm_every_ask_seen_and_answered.rs b/services/worker/src/passes/incidents/xm_every_ask_seen_and_answered.rs new file mode 100644 index 00000000..d98fbfd8 --- /dev/null +++ b/services/worker/src/passes/incidents/xm_every_ask_seen_and_answered.rs @@ -0,0 +1,370 @@ +//! xm. The owner commented `@CoderHelm re-review` on a person's pull +//! request and nothing visibly happened. He asked again, pasting the +//! mention, and GitHub's editor had turned it into the link it rendered: +//! `https://github.com/CoderHelm re-review`. That comment wasn't read as +//! addressed to CoderHelm at all. +//! +//! Why: the parser only knew the text `@coderhelm`, so the pasted link was +//! no command. And an accepted command showed nothing in the conversation +//! until its answer posted: a re-review that waited behind another review +//! of the same commit, or ran long, looked exactly like one that was lost. +//! A command refused for its author's standing, or because the reviewer is +//! off for the repository, was refused in a log line only, and a person +//! whose login contains the name was taken for the app. +//! +//! Guarantee: every way a person addresses CoderHelm counts: `@coderhelm`, +//! `@CoderHelm`, `@coderhelm[bot]`, the app's slug, the pasted link to the +//! organization or the app, a Markdown link to either, in any case, with +//! any punctuation around it. A link alone, or in a sentence, is not a +//! command, and neither is an email address or a repository link. An +//! accepted command gets πŸ‘€ from the gateway before its work is queued; the +//! review that answers it swaps πŸ‘€ for πŸš€. A refused one gets one short +//! reply saying why. A re-review ask that comes while an identical review +//! of the commit is running is answered by that review's verdict: two quick +//! asks are one review, never zero. A person's re-review ask is always a +//! fresh model review, even when nothing on the commit changed; only +//! automatic triggers return the standing verdict without one. An edit that +//! makes a comment a command runs it, under its own job key. + +use super::fixture::fn_src; +use crate::passes::review_policy::{claim_still_running, start, Start}; +use crate::passes::review_sweep::ReviewRecord; +use common::address::{ask_added_by_edit, ask_key, parse_ask}; +use common::review_ack::{ + ack_sk, collapsed, refusal_line, see, swap, to_settle, Ack, Reactions, Refusal, Waiting, + ANSWERED, SEEN, +}; +use std::sync::Mutex; + +const OWNER: &str = "acme-shop"; +const REPO: &str = "storefront"; +const PR: u64 = 214; +const HEAD: &str = "c0ffee1d00d2"; + +fn webhook() -> &'static str { + include_str!("../../../../gateway/src/routes/github_webhook.rs") +} +fn reviewer() -> &'static str { + include_str!("../review_pr.rs") +} + +/// GitHub's reactions on the person's comments, as a list of calls. +#[derive(Default)] +struct Comments { + calls: Mutex>, + on: Mutex>, +} + +impl Comments { + fn reactions_on(&self, comment: u64) -> Vec { + self.on + .lock() + .unwrap() + .iter() + .filter(|(c, _)| *c == comment) + .map(|(_, r)| r.clone()) + .collect() + } +} + +impl Reactions for Comments { + async fn add(&self, _o: &str, _r: &str, ack: &Ack, content: &str) -> Option { + let mut on = self.on.lock().unwrap(); + on.push((ack.comment_id, content.to_string())); + self.calls + .lock() + .unwrap() + .push(format!("add {content} {}", ack.comment_id)); + Some(on.len() as u64) + } + async fn remove(&self, _o: &str, _r: &str, ack: &Ack, id: u64) -> bool { + let mut on = self.on.lock().unwrap(); + // Reaction ids are positions here; drop the one asked for. + if let Some(slot) = on.get_mut(id as usize - 1) { + slot.1 = format!("removed {}", slot.1); + } + self.calls + .lock() + .unwrap() + .push(format!("remove {id} {}", ack.comment_id)); + true + } +} + +fn record(head: &str, at: &str) -> ReviewRecord { + ReviewRecord { + verdict: "APPROVE".into(), + posted_as: "APPROVE".into(), + head_sha: head.into(), + created_at: at.into(), + body: "Looks right.".into(), + fingerprint: None, + holding: Vec::new(), + posted_body: String::new(), + reviewer_build: crate::passes::review_build::REVIEWER_BUILD.into(), + } +} + +fn waiting(ack: &Ack, head: &str) -> Waiting { + Waiting { + sk: ack_sk(OWNER, REPO, PR, ack), + ack: ack.clone(), + head: head.into(), + answered: false, + } +} + +#[test] +fn both_of_the_owners_comments_are_re_review_commands() { + // The two comments as written. + for body in [ + "@CoderHelm re-review", + "https://github.com/CoderHelm re-review", + ] { + let ask = parse_ask(body).unwrap_or_else(|| panic!("{body} was not read as a command")); + assert!( + ask.rereview && !ask.bare && ask.question.is_none(), + "{body}" + ); + } +} + +#[test] +fn every_way_to_address_coderhelm_counts() { + for body in [ + "@coderhelm re-review", + "@CoderHelm re-review", + "@CODERHELM Re-Review", + "@coderhelm[bot] re-review", + "@coderhelm-app re-review", + "@CoderHelm, re-review.", + "(@CoderHelm) re-review!", + "re-review @CoderHelm", + "https://github.com/CoderHelm re-review", + "https://github.com/CoderHelm/ re-review", + "github.com/CoderHelm re-review", + " re-review", + "https://github.com/apps/coderhelm re-review", + "[@CoderHelm](https://github.com/CoderHelm) re-review", + "[CoderHelm](https://github.com/apps/coderhelm) re-review", + "> earlier words\nhttps://github.com/CoderHelm re-review", + "/coderhelm re-review", + ] { + assert!( + parse_ask(body).is_some_and(|a| a.rereview), + "{body:?} should be the re-review command" + ); + } + // Words after the link are a question for the model, as after a mention. + let q = parse_ask("https://github.com/CoderHelm is the null check needed?").unwrap(); + assert_eq!(q.question.as_deref(), Some("is the null check needed?")); +} + +#[test] +fn a_reference_is_not_a_command() { + for body in [ + "https://github.com/CoderHelm", + "[CoderHelm](https://github.com/CoderHelm)", + "the review came from https://github.com/CoderHelm, thanks", + "https://github.com/CoderHelm/storefront re-review", + "mail help@coderhelm.dev to re-review", + "> @CoderHelm re-review\nthat was the old ask", + "`@CoderHelm re-review`", + ] { + assert_eq!(parse_ask(body), None, "{body:?} is not a command"); + } +} + +#[test] +fn an_edit_that_makes_a_command_runs_once_under_its_own_key() { + assert!(ask_added_by_edit("lgtm", "https://github.com/CoderHelm re-review").is_some()); + assert!(ask_added_by_edit("@CoderHelm why this?", "@CoderHelm re-review").is_some()); + assert!(ask_added_by_edit("@CoderHelm re-review", "@CoderHelm re-review.").is_none()); + // The comment's first version and the edit are two jobs; a repeat + // delivery of either is the same job. + let first = ask_key(1501, None); + let edit = ask_key(1501, Some("2030-05-02T10:04:00Z")); + assert_ne!(first, edit); + assert_eq!(edit, ask_key(1501, Some("2030-05-02T10:04:00Z"))); + // The gateway keys both surfaces' asks this way. + let hook = webhook(); + assert!( + hook.matches("common::address::ask_key(comment_id, edited_at(payload))") + .count() + >= 2 + ); +} + +#[tokio::test] +async fn an_accepted_ask_is_seen_then_answered() { + let gh = Comments::default(); + let mut ack = Ack::new(1501, false, true); + see(&gh, OWNER, REPO, &mut ack).await; + assert_eq!(gh.reactions_on(1501), vec![SEEN]); + // The review posts its verdict on the head the person asked about. + let settle = to_settle( + OWNER, + REPO, + PR, + &[waiting(&ack, HEAD)], + Some(&ack), + HEAD, + true, + ); + assert_eq!(settle.len(), 1); + for w in &settle { + swap(&gh, OWNER, REPO, &w.ack).await; + } + assert_eq!( + gh.reactions_on(1501), + vec![format!("removed {SEEN}"), ANSWERED.to_string()] + ); +} + +#[tokio::test] +async fn two_quick_asks_are_one_review_never_zero() { + let gh = Comments::default(); + // First ask starts the review; the second comes while it runs. + let mut first = Ack::new(1501, false, true); + let mut second = Ack::new(1502, false, true); + see(&gh, OWNER, REPO, &mut first).await; + see(&gh, OWNER, REPO, &mut second).await; + let on_record = vec![waiting(&first, HEAD), waiting(&second, HEAD)]; + + // The second ask finds the commit's claim taken after the last finished + // review: the review is running, so it waits for it with its πŸ‘€. + let earlier = vec![record(HEAD, "2030-05-02T09:00:00Z")]; + assert!(claim_still_running( + Some("2030-05-02T10:00:00Z"), + &earlier, + HEAD + )); + assert!(claim_still_running(None, &[], HEAD)); + + // The first review posts its verdict: both asks are answered by it. + let settled = to_settle(OWNER, REPO, PR, &on_record, Some(&first), HEAD, true); + let ids: Vec = settled.iter().map(|w| w.ack.comment_id).collect(); + assert_eq!(ids, vec![1501, 1502]); + for w in &settled { + swap(&gh, OWNER, REPO, &w.ack).await; + } + for c in [1501, 1502] { + assert_eq!( + gh.reactions_on(c).last().map(String::as_str), + Some(ANSWERED) + ); + } + + // The second ask's job looks again: answered, so no second review. + let mut answered = waiting(&second, HEAD); + answered.answered = true; + assert!(collapsed(&second, Some(&answered))); + + // The claim is now older than the finished review: a third ask runs. + let done = vec![record(HEAD, "2030-05-02T10:06:00Z")]; + assert!(!claim_still_running( + Some("2030-05-02T10:00:00Z"), + &done, + HEAD + )); +} + +#[test] +fn a_persons_reask_is_a_fresh_review_even_when_nothing_changed() { + // The commit was reviewed and nothing it rests on changed since. + let done = vec![record(HEAD, "2030-05-02T10:06:00Z")]; + // A person asking, by comment or by GitHub's re-request: a fresh review. + assert_eq!(start("reply", HEAD, "", &done), Start::Review); + assert_eq!(start("rerequest", HEAD, "", &done), Start::Review); + // An automatic trigger keeps the cheap path: the verdict stands. + assert!(matches!( + start("synchronize", HEAD, "", &done), + Start::ReturnExisting { .. } + )); + // No path in the review answers a person's ask from the standing + // verdict without a model review. + let once = fn_src(reviewer(), "async fn run_once("); + assert!(!once.contains("standing_answer(")); + assert!(!once.contains("answers_from_standing(")); +} + +#[test] +fn an_ask_the_running_review_didnt_answer_runs_its_own() { + let ask = Ack::new(1502, false, true); + let on_record = vec![waiting(&ask, HEAD)]; + // The running review failed: nothing stored, nothing settled. + assert!(!collapsed(&ask, on_record.first())); + // It reviewed another commit: the ask isn't answered by it. + assert!(to_settle(OWNER, REPO, PR, &on_record, None, "beef0000", true).is_empty()); + // It posted nothing new (an automatic review with no news). + assert!(to_settle(OWNER, REPO, PR, &on_record, None, HEAD, false).is_empty()); + // A question is answered only by its own job, never by a verdict. + let question = Ack::new(1503, false, false); + assert!(to_settle( + OWNER, + REPO, + PR, + &[waiting(&question, HEAD)], + None, + HEAD, + true + ) + .is_empty()); + // After its waits the ask runs anyway (`deferred_ask` stops deferring). + let mut msg = crate::models::ReviewMessage { + trigger: "reply".into(), + dedup_key: "reply#1502".into(), + ..Default::default() + }; + for _ in 0..crate::passes::review_policy::ASK_MAX_WAITS { + msg = crate::passes::review_policy::deferred_ask(&msg).expect("waits"); + } + assert!(crate::passes::review_policy::deferred_ask(&msg).is_none()); +} + +#[test] +fn a_refused_command_is_told_why_once() { + for r in [Refusal::NoStanding, Refusal::ReviewerOff] { + let line = refusal_line(r); + assert!(!line.is_empty() && !line.contains('\n')); + } + let hook = webhook(); + // Said once per comment, on both surfaces, for both reasons. + let refuse = fn_src(hook, "pub(crate) async fn refuse("); + assert!(refuse.contains("refusal_sk") && refuse.contains("Claim::Held")); + let issue = fn_src(hook, "async fn handle_issue_comment("); + assert!(issue.contains("Refusal::NoStanding") && issue.contains("Refusal::ReviewerOff")); + let line = fn_src(hook, "async fn handle_review_comment("); + assert!(line.contains("Refusal::NoStanding") && line.contains("Refusal::ReviewerOff")); +} + +#[test] +fn the_gateway_sees_the_ask_before_queueing_and_the_review_answers_it() { + let hook = webhook(); + let send = fn_src(hook, "pub(crate) async fn send_review_job("); + let seen = send.find("acknowledge(").expect("πŸ‘€ in send_review_job"); + let recorded = send + .find("review_ack::register(") + .expect("the ask recorded"); + let queued = send.find("send_to_queue_after(").expect("queued"); + assert!(seen < queued && recorded < queued); + // Both surfaces carry the ask to the job. + let issue = fn_src(hook, "async fn handle_issue_comment("); + assert!( + issue.contains("ack: Some(common::review_ack::Ack::new(comment_id, false, is_rereview))") + ); + let line = fn_src(hook, "async fn handle_review_comment("); + assert!( + line.contains("ack: Some(common::review_ack::Ack::new(comment_id, true, ask.rereview))") + ); + // A person whose login contains the name is a person. + assert!(issue.contains("is_coderhelm_user(&payload[\"comment\"][\"user\"])")); + assert!(!issue.contains("commenter.contains(\"coderhelm\")")); + + let rev = reviewer(); + let store = fn_src(rev, "async fn store_review_record("); + assert!(store.contains("settle_acks(")); + let once = fn_src(rev, "async fn run_once("); + assert!(once.contains("collapsed_ask(state, &msg)")); + assert!(once.contains("claim_still_running(")); +} diff --git a/services/worker/src/passes/replay/mod.rs b/services/worker/src/passes/replay/mod.rs index 2b9d176f..69fbc6e7 100644 --- a/services/worker/src/passes/replay/mod.rs +++ b/services/worker/src/passes/replay/mod.rs @@ -466,18 +466,12 @@ fn run_review_settled(c: &Case, _: &Model) -> Result<(), String> { fn run_blocker_comment(c: &Case, _: &Model) -> Result<(), String> { use crate::passes::review_agent::VerdictChange; - use crate::passes::review_policy::{ - answers_from_standing, standing_answer, verdict_stands_note, - }; + use crate::passes::review_policy::verdict_stands_note; use crate::passes::review_verdict::{self as rv, Context, Decision, Input, StandingReview}; let i = &c.input; let head = s(i, "head"); let standing = s(i, "standing"); let comment = s(i, "comment"); - let holding = strings(&i["holding"]); - // Nothing the verdict rests on changed: only words. - let changed: Vec = Vec::new(); - let from_standing = answers_from_standing(s(i, "trigger"), &changed, true); let ctx = Context { standing: Some(StandingReview { verdict: standing.to_string(), @@ -502,16 +496,12 @@ fn run_blocker_comment(c: &Case, _: &Model) -> Result<(), String> { if e["second_review"].as_bool() == Some(false) && matches!(d, Decision::Review) { return Err("a second paid review".into()); } - if e["answered"].as_bool() == Some(true) && !from_standing && s(i, "trigger") != "reply" { + if e["answered"].as_bool() == Some(true) && s(i, "trigger") != "reply" { return Err("no answer".into()); } // The answer is whole: fixed words from facts, never a person's words // spliced into a template. - let answer = if from_standing { - standing_answer(head, standing, &holding) - } else { - verdict_stands_note(head, standing) - }; + let answer = verdict_stands_note(head, standing); if e["no_spliced_text"].as_bool() == Some(true) { let snippet: String = comment.chars().take(24).collect(); if !snippet.trim().is_empty() && answer.contains(snippet.trim()) { diff --git a/services/worker/src/passes/review_eval.rs b/services/worker/src/passes/review_eval.rs index 8b337987..ca9027f2 100644 --- a/services/worker/src/passes/review_eval.rs +++ b/services/worker/src/passes/review_eval.rs @@ -386,6 +386,7 @@ impl Sim { outstanding_work: None, description_hash: None, full_review: false, + ack: None, review_checkpoint: None, } } diff --git a/services/worker/src/passes/review_policy.rs b/services/worker/src/passes/review_policy.rs index 825d2587..4ac008fc 100644 --- a/services/worker/src/passes/review_policy.rs +++ b/services/worker/src/passes/review_policy.rs @@ -9,8 +9,9 @@ //! kind) so two jobs can't both post ([`verdict_claim_sk`]). //! 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`]). +//! alone) doesn't flip on model noise. A person's re-review ask always +//! runs a fresh model review; only automatic triggers return the +//! standing verdict without one ([`start`]). //! 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 @@ -112,6 +113,22 @@ pub fn deferred_ask(msg: &crate::models::ReviewMessage) -> Option, records: &[ReviewRecord], head: &str) -> bool { + let Some(last) = review_of_head(records, head) else { + return true; + }; + let parse = |t: &str| chrono::DateTime::parse_from_rfc3339(t).ok(); + match (claimed_at.and_then(parse), parse(&last.created_at)) { + (Some(claimed), Some(finished)) => claimed > finished, + _ => false, + } +} + /// CoderHelm's finished review of `head`, if it has one (newest first). pub fn review_of_head<'a>(records: &'a [ReviewRecord], head: &str) -> Option<&'a ReviewRecord> { records.iter().find(|r| { @@ -140,8 +157,7 @@ pub enum Start { /// Rule 1: an automatic trigger for an already-reviewed commit returns the /// 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 +/// always gets a fresh model review; 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. @@ -162,35 +178,6 @@ pub fn start(trigger: &str, head: &str, description: &str, records: &[ReviewReco } } -/// 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. @@ -1348,13 +1335,18 @@ mod tests { } /// 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. + /// from its source: a person's re-review ask goes straight on to a fresh + /// review (no answer from the standing verdict) 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() { + fn run_once_reviews_a_persons_ask_afresh_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!(!src.contains(concat!("review_policy::answers_from", "_standing("))); + let answer = at(concat!( + "A person who asks for a re-review gets", + " a fresh model review" + )); 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); @@ -1365,31 +1357,16 @@ mod tests { } #[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 + fn a_persons_reask_always_gets_a_fresh_review() { + // Reviewed, nothing changed: a person's ask still reviews afresh. + let records = vec![rec("h1", "APPROVE", "2026-10-01T00:00:00Z")]; + assert_eq!(start("reply", "h1", "", &records), Start::Review); + assert_eq!(start("rerequest", "h1", "", &records), Start::Review); + // An automatic trigger keeps the cheap path: the verdict stands. + assert!(matches!( + start("synchronize", "h1", "", &records), + Start::ReturnExisting { .. } )); - 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!( - 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")); } #[test] @@ -1550,15 +1527,14 @@ mod tests { 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. + /// A re-review ask on an identical fingerprint: a fresh model review + /// runs (a person asked), and the verdict it reaches is stable. #[test] - fn replay_a_rereview_ask_with_nothing_changed_stays_as_it_was() { + fn replay_a_rereview_ask_with_nothing_changed_reviews_afresh() { let state = state_of(true); let prev = stored( "REQUEST_CHANGES", @@ -1566,10 +1542,11 @@ mod tests { &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")); + assert!(changed.is_empty()); + assert_eq!( + start("rerequest", &prev.head_sha, "", std::slice::from_ref(&prev)), + Start::Review + ); // A bare ask is no new words either. let mut with_ask = state.clone(); with_ask.people = Some(fp::people_part(&[serde_json::json!({ @@ -1731,7 +1708,6 @@ mod tests { 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 diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index fbb6b900..10fae1e4 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -2152,6 +2152,25 @@ async fn run_once( } } + // A person's re-review ask that the running review already answered + // (its verdict swapped the ask's πŸ‘€ for πŸš€) is done: one review for two + // quick asks, never zero. An ask it didn't answer goes on. + if !resuming_job(&msg) && collapsed_ask(state, &msg).await { + info!(pr = msg.pr_number, dedup_key = %msg.dedup_key, "Re-review ask answered by the review that was running when it came"); + close_waiting_check( + state, + &github, + &msg, + "Answered by the review that was running", + "Another review of this commit was running when this was asked; its verdict is the \ + answer.", + ) + .await; + live_job + .not_posted("answered by the review of this commit that was running when it was asked"); + return Ok(DONE); + } + // The commit's check, queued when the review was scheduled, shows the // job in progress from its first step; every ending below completes it. live_job.start_check(state, &github, &msg).await; @@ -2509,9 +2528,6 @@ 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 @@ -2953,47 +2969,10 @@ async fn run_once( { changed_since.push(super::review_fingerprint::Changed::Reviewer); } - // 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, - live_job, - &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 who asks for a re-review gets a fresh model review, even when + // nothing the verdict rests on changed: asking means they want a real + // second look. Automatic triggers on a reviewed commit return its verdict + // before any model work (`review_policy::start`). // 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 @@ -3015,11 +2994,24 @@ async fn run_once( ) .await { - // Another review of this commit is still running. The person's - // ask is answered after it, with its own visible verdict: the - // ask waits and runs again (and runs anyway after the last wait). + // Another review of this commit is still running (its claim is + // newer than the last finished review of the commit). The + // person's ask is answered by it: the ask's πŸ‘€ waits for that + // verdict, and the ask looks again after it (and runs anyway + // after the last wait, so it is never left unanswered). common::claim::Claim::Held - if super::review_policy::review_of_head(&records, &head_sha).is_none() => + if super::review_policy::claim_still_running( + common::claim::claimed_at( + &state.dynamo, + &state.config.settings_table_name, + &msg.team_id, + &sk, + ) + .await + .as_deref(), + &records, + &head_sha, + ) => { if let Some(later) = super::review_policy::deferred_ask(&msg) { if enqueue_review(state, &later, super::review_policy::ASK_WAIT_SECS).await { @@ -5756,6 +5748,7 @@ pub async fn review_for_run( outstanding_work: None, description_hash: None, full_review: false, + ack: None, review_checkpoint: None, }; let mut reviewed_head = head_sha.to_string(); @@ -7345,9 +7338,103 @@ async fn store_review_record( { warn!(pr = msg.pr_number, error = %e, "Failed to count the reviewed PR (non-fatal)"); } + // What was posted answers the person who asked: their πŸ‘€ becomes πŸš€, + // and a posted verdict answers every re-review ask waiting on this + // commit (an identical review was running when they asked). + if counts.posted || msg.ack.is_some() { + settle_acks(state, msg, head_sha, counts.posted && verdict != "QUESTION").await; + } sk } +/// The asks a stored review answers get πŸš€ in place of πŸ‘€, each once +/// (`common::review_ack::to_settle`). Best effort: a failure here never +/// fails the review. +async fn settle_acks(state: &WorkerState, msg: &ReviewMessage, head: &str, posted_verdict: bool) { + use common::review_ack as ra; + let table = &state.config.settings_table_name; + let waiting = ra::on_pr( + &state.dynamo, + table, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + ) + .await; + let settle = ra::to_settle( + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + &waiting, + msg.ack.as_ref(), + head, + posted_verdict, + ); + if settle.is_empty() { + return; + } + let github = match GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + msg.installation_id, + &state.http, + ) { + Ok(g) => g, + Err(e) => { + warn!(pr = msg.pr_number, error = %e, "Could not answer the asks' reactions"); + return; + } + }; + for w in settle { + if ra::mark_answered(&state.dynamo, table, &msg.team_id, &w).await { + // The job's own ack knows the πŸ‘€ id even when its record doesn't. + let mut ack = w.ack.clone(); + if ack.reaction_id.is_none() { + ack.reaction_id = msg + .ack + .as_ref() + .filter(|o| o.comment_id == ack.comment_id && o.line == ack.line) + .and_then(|o| o.reaction_id); + } + ra::swap(&github, &msg.repo_owner, &msg.repo_name, &ack).await; + info!( + pr = msg.pr_number, + head, + comment = ack.comment_id, + "Ask answered: πŸ‘€ swapped for πŸš€" + ); + } + } +} + +/// A job going on from its checkpoint is the same review, never a second. +fn resuming_job(msg: &ReviewMessage) -> bool { + msg.review_checkpoint.is_some() +} + +/// A person's re-review ask that came while an identical review of the +/// commit was running, and that review's verdict answered it: the ask's +/// job ends without a second review (two quick asks, one review). +async fn collapsed_ask(state: &WorkerState, msg: &ReviewMessage) -> bool { + use common::review_ack as ra; + let Some(own) = &msg.ack else { + return false; + }; + if !own.rereview { + return false; + } + let sk = ra::ack_sk(&msg.repo_owner, &msg.repo_name, msg.pr_number, own); + let record = ra::get( + &state.dynamo, + &state.config.settings_table_name, + &msg.team_id, + &sk, + ) + .await; + ra::collapsed(own, record.as_ref()) +} + /// Names the team standards a review was given in full on its record, for /// its page. Nothing is written when there were none. async fn note_review_standards( @@ -8159,6 +8246,7 @@ mod superseded_tests { outstanding_work: None, description_hash: None, full_review: false, + ack: None, review_checkpoint: None, } } @@ -8584,6 +8672,7 @@ mod failure_tests { outstanding_work: None, description_hash: None, full_review: false, + ack: None, review_checkpoint: None, } } diff --git a/services/worker/src/passes/review_sweep.rs b/services/worker/src/passes/review_sweep.rs index 9aad3eee..7e872b24 100644 --- a/services/worker/src/passes/review_sweep.rs +++ b/services/worker/src/passes/review_sweep.rs @@ -528,6 +528,7 @@ fn sweep_message( outstanding_work: None, description_hash: None, full_review: false, + ack: None, review_checkpoint: None, } }