diff --git a/docs/incidents/ry_reviews_tidy_between_reviews.md b/docs/incidents/ry_reviews_tidy_between_reviews.md new file mode 100644 index 000000000..477672751 --- /dev/null +++ b/docs/incidents/ry_reviews_tidy_between_reviews.md @@ -0,0 +1,7 @@ +# ry. `ry_reviews_tidy_between_reviews` + +**What happened:** A person reading two pull requests on a web app asked whether CoderHelm's approvals and resolved comments could go away after a while, because "it becomes too much". On the first, CoderHelm's "Approved with notes" review from four days earlier still stood in full: the file table, the "Why approved" line, a risk block, an FYI list, Verification, Tests, "Earlier comments" and the rating footer. A person's "Address the review" commit and a second review just as long sat under it. On the second, an inline thread of CoderHelm's from 18 hours earlier was still open: "Blocking (failing check): Lint & Type Check and Deploy Preview are red on this head … I could not read the logs". It was about an older head whose checks had passed since. CoderHelm only cleaned up its earlier reviews when it posted a new one. A push, checks going green, code leaving the diff and a merge all left everything as it was. + +**The guarantee:** CoderHelm's own reviews and threads are tidied on a push, when checks finish, on a merge or a close, and on the review sweep. A review body for an older commit than the head becomes one line, for example "✅ Approved `abc1234` (superseded by later commits)". The exception is a request for changes, which still holds the merge and keeps its reasons until the next review. On a merge or a close every body becomes one line and CoderHelm's resolved threads are hidden. A thread about failing checks resolves once the head's checks pass, and so does a thread whose file or lines left the diff (a required-rule thread is not resolved just because its lines moved). CoderHelm's comments in those threads are hidden. A new review keeps only its verdict, its reason and what holds the merge in sight; the overview, file table, risk, FYI, verification, tests and earlier comments go under one collapsed block. A person's review, a thread a person opened and an unanswered reply are never touched, and nothing is posted to announce the cleanup. + +**Where it's enforced:** `common::review_supersede` (`tidy`, `settled`, `checks_pass`, `fold`), carried out by `worker::passes::review_tidy` (the `review_tidy` message and the review sweep) and queued by `gateway::routes::github_webhook` (`queue_review_tidy` on `synchronize`, `closed` and `check_suite` `completed`). The body is folded in `review_pr`. diff --git a/services/common/contract/worker_messages.json b/services/common/contract/worker_messages.json index efebf1d51..0ac2ee2a3 100644 --- a/services/common/contract/worker_messages.json +++ b/services/common/contract/worker_messages.json @@ -27,6 +27,7 @@ "lesson": {"type":"lesson","team_id":"TEAM#team-a","installation_id":1,"run_id":"r1","repo_owner":"acme","repo_name":"widgets","pr_number":2,"trigger":"pr_closed"}, "reward_outcome": {"type":"reward_outcome","team_id":"TEAM#team-a","installation_id":1,"run_id":"r1","repo_owner":"acme","repo_name":"widgets","pr_number":2}, "stale_prs_preview": {"type":"stale_prs_preview","team_id":"TEAM#team-a","repo":"acme/widgets"}, + "review_tidy": {"type":"review_tidy","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","pr_number":2,"reason":"push"}, "security_event": {"type":"security_event","team_id":"TEAM#team-a","installation_id":1,"kind":"dependabot_alert","repo":"acme/widgets","action":"created","alert_number":88,"ghsa_id":"GHSA-q9fx-2w5c-8m4r"}, "review_lesson": {"type":"review_lesson","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","pr_number":2,"trigger":"reply","event_at":1}, "jira_comment": {"type":"jira_comment","team_id":"TEAM#team-a","installation_id":1,"ticket_id":"T-1","title":"t","run_id":"r1","run_status":"completed","pr_number":2,"repo_owner":"acme","repo_name":"widgets","author":"someone","comment":"c","context_hash":"h","action":{"type":"resume","team_id":"TEAM#team-a","run_id":"r1","installation_id":1}}, diff --git a/services/common/src/dlq.rs b/services/common/src/dlq.rs index 5324ec009..ede45349b 100644 --- a/services/common/src/dlq.rs +++ b/services/common/src/dlq.rs @@ -40,6 +40,8 @@ pub const WORKER_MESSAGE_TYPES: &[&str] = &[ "review", "review_reminder", "review_sweep", + // CoderHelm's own reviews and threads on one pull request tidied. + "review_tidy", "stale_prs_preview", "setup_analyze", // Security fixes: an alert, an advisory, a push or a check now. diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 941e0b017..11fbe97af 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -55,6 +55,11 @@ pub enum WorkerMessage { /// review that didn't finish (a service error) for the PR's current head. #[serde(rename = "review_sweep")] ReviewSweep, + /// CoderHelm's own reviews and threads on one pull request tidied now + /// (`worker::passes::review_tidy`): sent on a push, on checks finishing + /// and on a merge or a close; the review sweep covers the rest. + #[serde(rename = "review_tidy")] + ReviewTidy(ReviewTidyMessage), /// Work out one repository's stale pull request plan now, without /// changing anything (the dashboard's "Preview"). The scheduled cleanup /// rides on the review-reminder tick. @@ -427,6 +432,7 @@ impl WorkerMessage { | WorkerMessage::ReviewLesson(_) | WorkerMessage::ReviewReminder | WorkerMessage::ReviewSweep + | WorkerMessage::ReviewTidy(_) | WorkerMessage::StalePrsPreview(_) => f::REVIEW, WorkerMessage::SecurityEvent(_) => f::SECURITY, WorkerMessage::SkillSync(_) => f::SKILL_SYNC, @@ -494,6 +500,7 @@ impl WorkerMessage { | WorkerMessage::Review(_) | WorkerMessage::ReviewReminder | WorkerMessage::ReviewSweep + | WorkerMessage::ReviewTidy(_) | WorkerMessage::StalePrsPreview(_) | WorkerMessage::SetupAnalyze(_) | WorkerMessage::SecurityEvent(_) @@ -634,6 +641,19 @@ pub struct SecurityEventMessage { pub ticket: String, } +/// One pull request whose CoderHelm reviews and threads are tidied +/// (`crate::review_supersede::tidy`). +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] +pub struct ReviewTidyMessage { + pub team_id: String, + pub installation_id: u64, + pub repo_owner: String, + pub repo_name: String, + pub pr_number: u64, + /// What sent it: `push`, `checks`, `merged`, `closed`. + pub reason: String, +} + /// One repository's stale pull request preview (`common::stale_prs`). #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct StalePrsPreviewMessage { diff --git a/services/common/src/review_supersede.rs b/services/common/src/review_supersede.rs index 197e8d7e3..85c1fd401 100644 --- a/services/common/src/review_supersede.rs +++ b/services/common/src/review_supersede.rs @@ -16,6 +16,11 @@ //! - its own earlier request for changes is dismissed with //! [`DISMISS_MESSAGE`]. //! +//! Between reviews [`tidy`] keeps the rest true: an approval of an older +//! commit, every body on a merged or closed pull request, a thread whose +//! checks went green or whose code left the diff, and [`fold`] keeps a new +//! review short (only the verdict and what holds the merge in sight). +//! //! A person's review, comment or thread is never touched. /// What an earlier review of CoderHelm's says once superseded. @@ -32,6 +37,8 @@ pub struct Review { /// `APPROVED`, `CHANGES_REQUESTED`, `COMMENTED`, `DISMISSED`, `PENDING`. pub state: String, pub body: String, + /// The commit GitHub posted it on. + pub commit_id: String, } /// One comment in a review thread, oldest first. @@ -55,6 +62,14 @@ pub struct Thread { /// The first comment's text (the finding). pub first_body: String, pub comments: Vec, + /// GitHub marks the thread outdated: the lines it is on changed since. + pub outdated: bool, + /// The lines it was on are no longer in the pull request's diff (GitHub + /// has no current line for it). + pub line_gone: bool, + /// The reviewer's answer to "does this finding still hold at the + /// head?", when it was asked; `None` until it was. + pub holds_at_head: Option, } impl Thread { @@ -137,6 +152,321 @@ pub fn plan(reviews: &[Review], threads: &[Thread], new_id: u64, raised: &[Strin out } +// ── Tidy: kept tidy between reviews ────────────────────────────────────── +// +// A new review is not the only moment CoderHelm's words stop being true. A +// push makes its approval a verdict on older code; checks that went green +// make its "the checks are red" thread wrong; a merge makes every review +// body history. [`tidy`] decides, from the pull request as it is now, what +// of CoderHelm's own is cut to one line, resolved or hidden. It runs on a +// push, on checks finishing, on a merge or a close, and on the periodic +// sweep (`worker::passes::review_tidy`), and posts nothing. + +/// Marks a review body cut to one line by [`tidy`]; a body carrying it, or +/// [`OUTDATED_BODY`], is never cut again. +pub const COLLAPSED_MARK: &str = ""; + +/// The mark a review body brought up to date for a newer commit carries +/// (`worker::passes::review_verdict::UPDATED_MARK`, pinned equal by a test +/// there), followed by "_Updated for ``". +pub const UPDATED_MARK: &str = ""; + +/// The label CoderHelm's reviewer puts on a finding about a failing check +/// (`worker::passes::review_rules::mandatory_label`, pinned by a test there). +pub const FAILING_CHECK_LABEL: &str = "Blocking (failing check)"; + +/// The mark a required-rule finding carries +/// (`worker::passes::review_rules::REQUIRED_MARK`, pinned by a test there): +/// a missing test is not fixed by its line moving, so such a thread is +/// never resolved because its lines left the diff. +pub const REQUIRED_MARK: &str = ""; + +/// Where the pull request stands. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum PrState { + #[default] + Open, + Merged, + Closed, +} + +/// The pull request as it is now, as [`tidy`] reads it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PrNow { + pub owner: String, + pub repo: String, + pub number: u64, + pub head: String, + pub state: PrState, + /// The head's checks: `Some(true)` all finished and none failed, + /// `Some(false)` one failed, `None` still running or not read. + pub checks_pass: Option, + /// The files the pull request changes against its merge base, when read. + pub changed_paths: Option>, +} + +/// Why a thread of CoderHelm's is resolved without a new review. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Settled { + /// A failing-check finding whose checks now pass on the head. + ChecksPass, + /// The file left the pull request's diff. + FileGone, + /// The lines it was on left the diff. + LinesGone, + /// The reviewer read the head and the finding no longer holds. + FixedAtHead, +} + +/// What [`tidy`] decided. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Tidy { + /// Review bodies cut to one line: (review id, the new body). + pub collapse: Vec<(u64, String)>, + /// Threads to resolve (node id, why). + pub resolve: Vec<(String, Settled)>, + /// Own comments to hide as outdated (node ids). + pub minimize: Vec, +} + +impl Tidy { + pub fn is_empty(&self) -> bool { + self.collapse.is_empty() && self.resolve.is_empty() && self.minimize.is_empty() + } +} + +/// Already cut to one line (by [`tidy`] or by a later review). +pub fn collapsed(body: &str) -> bool { + body.trim() == OUTDATED_BODY || body.contains(COLLAPSED_MARK) +} + +/// The commit a review speaks for: the one it was brought up to date for +/// when its body says so, else the one it was posted on. +pub fn reviewed_sha(r: &Review) -> String { + if let Some(at) = r.body.find(UPDATED_MARK) { + let rest = &r.body[at + UPDATED_MARK.len()..]; + if let Some(start) = rest.find("_Updated for `") { + let rest = &rest[start + "_Updated for `".len()..]; + if let Some(end) = rest.find('`') { + let sha = rest[..end].trim(); + if sha.len() >= 7 && sha.chars().all(|c| c.is_ascii_hexdigit()) { + return sha.to_string(); + } + } + } + } + r.commit_id.clone() +} + +/// Whether `sha` (full or short) is the head. +fn is_head(sha: &str, head: &str) -> bool { + sha.len() >= 7 && head.len() >= 7 && (head.starts_with(sha) || sha.starts_with(head)) +} + +/// The verdict a review gave, in two words and an icon. +pub fn verdict_word(r: &Review) -> &'static str { + let b = r.body.as_str(); + match r.state.as_str() { + "APPROVED" if b.contains("Approved with notes") => "✅ Approved with notes", + "APPROVED" => "✅ Approved", + "CHANGES_REQUESTED" => "❌ Changes requested", + _ if b.contains("✅ **Approved with notes**") => "✅ Approved with notes", + _ if b.contains("✅ **Approved**") => "✅ Approved", + _ if b.contains("❌ **Changes requested**") => "❌ Changes requested", + _ => "💬 Reviewed", + } +} + +/// A review body cut to one line: the verdict, the commit it was of (a +/// link to it in the pull request) and why it no longer stands. +pub fn one_line(r: &Review, pr: &PrNow, why: &str) -> String { + let sha = reviewed_sha(r); + let short = &sha[..sha.len().min(7)]; + let at = if short.is_empty() { + String::new() + } else { + format!( + " [`{short}`](https://github.com/{}/{}/pull/{}/commits/{sha})", + pr.owner, pr.repo, pr.number + ) + }; + format!("{COLLAPSED_MARK}\n{}{at} ({why})", verdict_word(r)) +} + +/// What to tidy on the pull request now. Only CoderHelm's own reviews, +/// comments and threads are ever named; a thread a person opened, or one +/// where a person's reply waits for an answer, is left as it is. +/// +/// - Reviews: on a merged or closed pull request every own review body is +/// cut to one line. On an open one a body that speaks for an older commit +/// than the head is cut, except a request for changes (a formal one, or a +/// comment review saying so on CoderHelm's own pull request): it still +/// holds the merge, so its reasons stay readable until the next review +/// replaces it. +/// - Threads (open pull request): resolved, with CoderHelm's comments in +/// them hidden, once the finding no longer holds ([`Settled`]). +/// - Threads (merged or closed): CoderHelm's comments in its own resolved +/// threads are hidden. +pub fn tidy(reviews: &[Review], threads: &[Thread], pr: &PrNow) -> Tidy { + let mut out = Tidy::default(); + let done = pr.state != PrState::Open; + for r in reviews.iter().filter(|r| r.own && r.state != "PENDING") { + if r.body.trim().is_empty() || collapsed(&r.body) { + continue; + } + let why = match pr.state { + PrState::Merged => "merged", + PrState::Closed => "closed", + PrState::Open => { + let sha = reviewed_sha(r); + if pr.head.is_empty() + || sha.is_empty() + || is_head(&sha, &pr.head) + || verdict_word(r) == "❌ Changes requested" + { + continue; + } + "superseded by later commits" + } + }; + out.collapse.push((r.id, one_line(r, pr, why))); + } + for t in threads { + if !t.own() || t.person_waiting() { + continue; + } + let settled = if t.resolved || done { + None + } else { + settled(t, pr) + }; + if let Some(why) = settled { + out.resolve.push((t.id.clone(), why)); + } + if settled.is_some() || (done && t.resolved) { + out.minimize.extend( + t.comments + .iter() + .filter(|c| c.own && !c.minimized) + .map(|c| c.node_id.clone()), + ); + } + } + out +} + +/// Why an open thread of CoderHelm's no longer holds, if it doesn't. +pub fn settled(t: &Thread, pr: &PrNow) -> Option { + if t.holds_at_head == Some(false) { + return Some(Settled::FixedAtHead); + } + if t.holds_at_head == Some(true) { + return None; + } + if failing_check_finding(&t.first_body) && pr.checks_pass == Some(true) { + return Some(Settled::ChecksPass); + } + if let Some(paths) = &pr.changed_paths { + if !t.path.is_empty() && !paths.iter().any(|p| p == &t.path) { + return Some(Settled::FileGone); + } + } + if t.outdated && t.line_gone && !t.first_body.contains(REQUIRED_MARK) { + return Some(Settled::LinesGone); + } + None +} + +/// A finding about a failing check (its label, or the reviewer's words for +/// one). +pub fn failing_check_finding(body: &str) -> bool { + let first = body.to_ascii_lowercase(); + first.contains(&FAILING_CHECK_LABEL.to_ascii_lowercase()) + || first.contains("are red on this head") + || first.contains("is red on this head") +} + +/// A head's checks in one answer, from GitHub's check runs for it: +/// `Some(true)` every one finished and none failed, `Some(false)` one +/// failed, `None` one is still running or there are none. CoderHelm's own +/// review check is left out: it is about the review, not the code. +pub fn checks_pass(check_runs: &serde_json::Value) -> Option { + let runs: Vec<&serde_json::Value> = check_runs["check_runs"] + .as_array()? + .iter() + .filter(|c| { + !c["app"]["slug"] + .as_str() + .unwrap_or("") + .to_ascii_lowercase() + .contains("coderhelm") + }) + .collect(); + if runs.is_empty() { + return None; + } + if runs.iter().any(|c| { + matches!( + c["conclusion"].as_str(), + Some("failure" | "timed_out" | "cancelled" | "action_required" | "startup_failure") + ) + }) { + return Some(false); + } + if runs + .iter() + .any(|c| c["status"].as_str() != Some("completed")) + { + return None; + } + Some(true) +} + +// ── Short from the start ───────────────────────────────────────────────── + +/// A review body with only `visible` in sight and `details` folded under +/// one collapsed `
` block (GitHub renders it in review bodies; the +/// blank lines around the inside keep its markdown rendering), then +/// `footer`. The summary names the sections folded inside. +pub fn fold(visible: &str, details: &str, footer: &str) -> String { + let visible = visible.trim(); + let details = details.trim(); + let mut out = visible.to_string(); + if !details.is_empty() { + out.push_str(&format!( + "\n\n
\n{}\n\n{details}\n\n
", + fold_summary(details) + )); + } + out.push_str(footer); + out +} + +/// The `` of a folded block: the headings inside, else "Details". +pub fn fold_summary(details: &str) -> String { + let mut names: Vec = Vec::new(); + for l in details.lines() { + let l = l.trim(); + if !l.starts_with('#') { + continue; + } + let name = l.trim_start_matches('#').trim().trim_matches('*').trim(); + let name = name.split(':').next().unwrap_or("").trim(); + if !name.is_empty() && !names.iter().any(|n| n == name) { + names.push(name.to_string()); + } + } + if names.is_empty() { + return "Details".to_string(); + } + let shown = names.len().min(6); + let mut s = format!("Details: {}", names[..shown].join(" · ")); + if names.len() > shown { + s.push_str(&format!(" · {} more", names.len() - shown)); + } + s +} + #[cfg(test)] mod tests { use super::*; @@ -147,6 +477,7 @@ mod tests { own: true, state: state.into(), body: format!("Review {id}: the full verdict and its findings."), + ..Default::default() } } @@ -166,6 +497,7 @@ mod tests { path: path.into(), first_body: body.into(), comments, + ..Default::default() } } @@ -280,6 +612,7 @@ mod tests { own: false, state: "CHANGES_REQUESTED".into(), body: "Please rename this.".into(), + ..Default::default() }, own_review(8, "COMMENTED"), own_review(9, "COMMENTED"), @@ -297,4 +630,222 @@ mod tests { assert!(p.minimize.is_empty(), "{p:?}"); assert!(p.resolve.is_empty(), "{p:?}"); } + + fn pr(head: &str, state: PrState) -> PrNow { + PrNow { + owner: "acme".into(), + repo: "web".into(), + number: 7, + head: head.into(), + state, + ..Default::default() + } + } + + fn posted(id: u64, state: &str, commit: &str, body: &str) -> Review { + Review { + id, + own: true, + state: state.into(), + body: body.into(), + commit_id: commit.into(), + } + } + + const HEAD: &str = "bbbbbbb2222222222222222222222222222222222"; + const OLD: &str = "aaaaaaa1111111111111111111111111111111111"; + + /// An approval of an older commit is cut to one line naming the commit; + /// one of the head stays; running again does nothing. + #[test] + fn an_approval_of_an_older_commit_is_one_line() { + let r = vec![ + posted(1, "APPROVED", OLD, "✅ **Approved with notes**: ..."), + posted(2, "APPROVED", HEAD, "✅ **Approved**: nothing."), + ]; + let t = tidy(&r, &[], &pr(HEAD, PrState::Open)); + assert_eq!(t.collapse.len(), 1); + let (id, body) = &t.collapse[0]; + assert_eq!(*id, 1); + assert!(body.starts_with(COLLAPSED_MARK)); + assert!(body.ends_with( + "✅ Approved with notes [`aaaaaaa`](https://github.com/acme/web/pull/7/commits/aaaaaaa1111111111111111111111111111111111) (superseded by later commits)" + ), "{body}"); + let again = vec![posted(1, "APPROVED", OLD, body), r[1].clone()]; + assert!(tidy(&again, &[], &pr(HEAD, PrState::Open)).is_empty()); + } + + /// A body brought up to date for the head (a silent re-review) speaks + /// for the head, though GitHub keeps it on the older commit. + #[test] + fn a_body_brought_up_to_date_speaks_for_the_head() { + let body = format!("{UPDATED_MARK}\n_Updated for `bbbbbbb`: what this review said about `aaaaaaa` was replaced by the review of the current commit below._\n\n✅ **Approved**"); + let r = vec![posted(1, "APPROVED", OLD, &body)]; + assert_eq!(reviewed_sha(&r[0]), "bbbbbbb"); + assert!(tidy(&r, &[], &pr(HEAD, PrState::Open)).collapse.is_empty()); + } + + /// A request for changes on an older commit still holds the merge: its + /// reasons stay readable until a review replaces it. On a merge every + /// body is cut, that one too. + #[test] + fn a_standing_request_for_changes_stays_until_the_merge() { + let r = vec![posted( + 1, + "CHANGES_REQUESTED", + OLD, + "❌ **Changes requested**: ...", + )]; + assert!(tidy(&r, &[], &pr(HEAD, PrState::Open)).collapse.is_empty()); + let t = tidy(&r, &[], &pr(HEAD, PrState::Merged)); + assert!(t.collapse[0].1.ends_with("(merged)"), "{t:?}"); + assert!(t.collapse[0].1.contains("❌ Changes requested")); + let t = tidy(&r, &[], &pr(HEAD, PrState::Closed)); + assert!(t.collapse[0].1.ends_with("(closed)"), "{t:?}"); + } + + /// A person's review is never cut; a review with no body (a reply) or + /// one already cut by a later review is left. + #[test] + fn only_own_bodies_are_cut() { + let mut person = posted(1, "APPROVED", OLD, "LGTM"); + person.own = false; + let r = vec![ + person, + posted(2, "COMMENTED", OLD, ""), + posted(3, "COMMENTED", OLD, OUTDATED_BODY), + ]; + assert!(tidy(&r, &[], &pr(HEAD, PrState::Merged)) + .collapse + .is_empty()); + } + + fn own_thread(id: &str, path: &str, body: &str) -> Thread { + Thread { + id: id.into(), + path: path.into(), + first_body: body.into(), + comments: vec![c(&format!("{id}c"), true, 1)], + ..Default::default() + } + } + + /// A failing-check finding resolves once the head's checks pass, and + /// its comment is hidden; while they run or fail it stays. + #[test] + fn a_failing_check_finding_settles_when_the_checks_pass() { + let t = vec![own_thread( + "T1", + "e2e/camps.spec.ts", + "🔴 Blocking (failing check): Lint & Type Check and Deploy Preview are red on this head.", + )]; + let mut now = pr(HEAD, PrState::Open); + assert!(tidy(&[], &t, &now).is_empty()); + now.checks_pass = Some(false); + assert!(tidy(&[], &t, &now).is_empty()); + now.checks_pass = Some(true); + let d = tidy(&[], &t, &now); + assert_eq!(d.resolve, vec![("T1".to_string(), Settled::ChecksPass)]); + assert_eq!(d.minimize, vec!["T1c"]); + } + + /// Code gone from the diff: the file, or the lines (not for a required + /// rule, which its lines moving does not fix). The reviewer's answer + /// wins both ways. + #[test] + fn a_finding_whose_code_left_the_diff_settles() { + let mut now = pr(HEAD, PrState::Open); + now.changed_paths = Some(vec!["src/a.ts".into()]); + let gone = own_thread("T1", "src/b.ts", "Null check missing."); + assert_eq!(settled(&gone, &now), Some(Settled::FileGone)); + let mut lines = own_thread("T2", "src/a.ts", "Null check missing."); + assert_eq!(settled(&lines, &now), None); + lines.outdated = true; + assert_eq!(settled(&lines, &now), None); + lines.line_gone = true; + assert_eq!(settled(&lines, &now), Some(Settled::LinesGone)); + let mut required = lines.clone(); + required.first_body = format!("{REQUIRED_MARK}\nNo test covers the new branch."); + assert_eq!(settled(&required, &now), None); + required.holds_at_head = Some(false); + assert_eq!(settled(&required, &now), Some(Settled::FixedAtHead)); + lines.holds_at_head = Some(true); + assert_eq!(settled(&lines, &now), None); + } + + /// A thread a person opened, or one where a person's reply waits, is + /// never resolved or hidden, merged or not. + #[test] + fn a_persons_thread_or_reply_is_never_tidied() { + let mut now = pr(HEAD, PrState::Open); + now.checks_pass = Some(true); + let body = "🔴 Blocking (failing check): CI is red on this head."; + let mut waiting = own_thread("T1", "a.ts", body); + waiting.comments.push(c("P1", false, 0)); + let mut theirs = own_thread("T2", "a.ts", body); + theirs.comments.insert(0, c("P2", false, 9)); + theirs.resolved = true; + let threads = vec![waiting, theirs]; + assert!(tidy(&[], &threads, &now).is_empty()); + now.state = PrState::Merged; + assert!(tidy(&[], &threads, &now).is_empty()); + } + + /// On a merge CoderHelm's resolved threads are hidden; its open ones + /// stay as they are. + #[test] + fn a_merge_hides_own_resolved_threads() { + let mut done = own_thread("T1", "a.ts", "Null check missing."); + done.resolved = true; + let open = own_thread("T2", "a.ts", "Retry never ends."); + let d = tidy(&[], &[done, open], &pr(HEAD, PrState::Merged)); + assert!(d.resolve.is_empty()); + assert_eq!(d.minimize, vec!["T1c"]); + } + + /// Checks: CoderHelm's own review check is not the code's; a run in + /// progress is not a pass; a failure is a failure. + #[test] + fn the_heads_checks_in_one_answer() { + let runs = |v: serde_json::Value| serde_json::json!({ "check_runs": v }); + let ok = serde_json::json!({"status":"completed","conclusion":"success","app":{"slug":"github-actions"}}); + let own = serde_json::json!({"status":"in_progress","conclusion":null,"app":{"slug":"coderhelm"}}); + let running = serde_json::json!({"status":"in_progress","conclusion":null,"app":{"slug":"github-actions"}}); + let red = serde_json::json!({"status":"completed","conclusion":"failure","app":{"slug":"github-actions"}}); + assert_eq!(checks_pass(&runs(serde_json::json!([ok, own]))), Some(true)); + assert_eq!(checks_pass(&runs(serde_json::json!([ok, running]))), None); + assert_eq!( + checks_pass(&runs(serde_json::json!([running, red]))), + Some(false) + ); + assert_eq!(checks_pass(&runs(serde_json::json!([own]))), None); + } + + /// Folded: the verdict in sight, the rest in one collapsed block named + /// by its sections, the footer last. + #[test] + fn a_review_folds_its_details() { + let body = fold( + "✅ **Approved**: nothing in the change needs fixing.", + "## PR Overview\n| File | What |\n\n#### Risk: low\n\n#### Verification\n- ok", + "\n\n---\nfooter", + ); + assert!(body.starts_with("✅ **Approved**")); + assert!(body.contains( + "
\nDetails: PR Overview · Risk · Verification\n\n## PR Overview" + ), "{body}"); + assert!(body.ends_with("
\n\n---\nfooter")); + assert_eq!(fold("v", " ", ""), "v"); + // The review's style pass (`comment_style::tidy`) keeps the block. + let place = crate::conversation::Place::github("acme", "web", 7); + let kept = crate::comment_style::tidy(&body, &place); + for line in [ + "
", + "
", + "Details: PR Overview · Risk · Verification", + ] { + assert!(kept.lines().any(|l| l == line), "{line} lost from {kept}"); + } + assert_eq!(fold_summary("plain text"), "Details"); + } } diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 1c88858a0..78349c1df 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -1911,6 +1911,9 @@ async fn handle_pull_request( ) .await?; } + if let Some(reason) = tidy_reason("pull_request", action, false) { + queue_review_tidy(state, payload, installation_id, team_id, reason, "").await; + } return handle_review_trigger(state, payload, installation_id, team_id, action).await; } @@ -1924,6 +1927,11 @@ async fn handle_pull_request( if action != "closed" { return Ok(StatusCode::OK); } + // CoderHelm's review bodies on it become one line each, its resolved + // threads hidden (any pull request it reviewed, not only its own). + if let Some(reason) = tidy_reason("pull_request", action, merged) { + queue_review_tidy(state, payload, installation_id, team_id, reason, "").await; + } // A Tests setup pull request: record it and check the workflow again. super::tests_setup::on_pr_closed(state, payload, installation_id, team_id, merged).await; @@ -3262,6 +3270,15 @@ async fn handle_check_suite( "check suite completed", ) .await?; + // A thread of CoderHelm's about a failing check settles once the + // head's checks pass. + if let Some(reason) = tidy_reason("check_suite", action, false) { + let one = serde_json::json!({ + "repository": repo, + "pull_request": {"number": pr["number"]}, + }); + queue_review_tidy(state, &one, installation_id, team_id, reason, head_sha).await; + } } // CI result handling for CoderHelm's own runs is done by the @@ -4596,6 +4613,89 @@ async fn claim_review_slot( c.won_or_failed_open() } +/// Which events tidy CoderHelm's reviews on a pull request +/// (`worker::passes::review_tidy`), and the reason they carry. +fn tidy_reason(event: &str, action: &str, merged: bool) -> Option<&'static str> { + match (event, action) { + ("pull_request", "synchronize") => Some("push"), + ("pull_request", "closed") if merged => Some("merged"), + ("pull_request", "closed") => Some("closed"), + ("check_suite", "completed") => Some("checks"), + _ => None, + } +} + +/// How long a tidy waits after its event: a push lets GitHub mark the moved +/// lines outdated first, and several check suites finishing together fold +/// into one tidy ([`TIDY_COALESCE_SECS`]). +fn tidy_delay_secs(reason: &str) -> i32 { + match reason { + "push" | "checks" => 60, + _ => 15, + } +} + +/// Check suites finishing on the same head within this window send one tidy. +const TIDY_COALESCE_SECS: u64 = 60; + +/// Queues a tidy of CoderHelm's reviews on the event's pull request. Best +/// effort: a tidy not sent is caught by the review sweep. +async fn queue_review_tidy( + state: &AppState, + payload: &Value, + installation_id: u64, + team_id: &str, + reason: &'static str, + head_sha: &str, +) { + let repo = &payload["repository"]; + let owner = repo["owner"]["login"].as_str().unwrap_or(""); + let name = repo["name"].as_str().unwrap_or(""); + let pr_number = payload["pull_request"]["number"].as_u64().unwrap_or(0); + if owner.is_empty() || name.is_empty() || pr_number == 0 { + return; + } + if reason == "checks" { + let sk = format!("REVIEWTIDY#{owner}/{name}#{pr_number:0>6}#{head_sha}#checks"); + let c = common::claim::claim( + &state.dynamo, + &state.config.settings_table_name, + team_id, + &sk, + TIDY_COALESCE_SECS, + ) + .await; + if !c.won_or_failed_open() { + return; + } + } + let msg = WorkerMessage::ReviewTidy(common::messages::ReviewTidyMessage { + team_id: team_id.to_string(), + installation_id, + repo_owner: owner.to_string(), + repo_name: name.to_string(), + pr_number, + reason: reason.to_string(), + }); + if send_to_queue_after( + state, + &state.config.ticket_queue_url, + &msg, + tidy_delay_secs(reason), + ) + .await + .is_err() + { + warn!( + owner, + name, + pr_number, + reason, + "Could not queue a tidy of CoderHelm's reviews; the review sweep catches it" + ); + } +} + pub(crate) async fn send_to_queue( state: &AppState, queue_url: &str, @@ -5930,3 +6030,55 @@ mod restack_tests { } } } + +#[cfg(test)] +mod review_tidy_tests { + use super::{tidy_delay_secs, tidy_reason}; + + /// A push, checks finishing, a merge and a close each tidy CoderHelm's + /// reviews; other events do not. + #[test] + fn the_events_that_tidy_reviews() { + assert_eq!( + tidy_reason("pull_request", "synchronize", false), + Some("push") + ); + assert_eq!(tidy_reason("pull_request", "closed", true), Some("merged")); + assert_eq!(tidy_reason("pull_request", "closed", false), Some("closed")); + assert_eq!( + tidy_reason("check_suite", "completed", false), + Some("checks") + ); + for (event, action) in [ + ("pull_request", "opened"), + ("pull_request", "labeled"), + ("check_suite", "requested"), + ("check_run", "completed"), + ] { + assert_eq!(tidy_reason(event, action, false), None, "{event}/{action}"); + } + // A push waits for GitHub to mark moved lines outdated. + assert!(tidy_delay_secs("push") >= 30); + } + + /// Every trigger is wired where its event is handled. + #[test] + fn each_handler_queues_its_tidy() { + let src = include_str!("github_webhook.rs"); + let body = |name: &str| { + let start = src.find(&format!("async fn {name}(")).unwrap(); + let end = src[start + 10..] + .find("\nasync fn ") + .map(|e| start + 10 + e) + .unwrap_or(src.len()); + &src[start..end] + }; + assert!( + body("handle_pull_request") + .matches("queue_review_tidy(") + .count() + >= 2 + ); + assert!(body("handle_check_suite").contains("queue_review_tidy(")); + } +} diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 267068a1f..449ceca56 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -4063,7 +4063,8 @@ impl GitHubClient { /// Hides one of CoderHelm's own comments as outdated, or shows it again /// (`common::conversation_io::hide_request`). Only the conversation - /// layer calls it, for comments that carry CoderHelm's marker. + /// layer and the review tidy (`passes::review_tidy`) call it, for + /// CoderHelm's own comments. pub async fn hide_own_comment( &self, node_id: &str, @@ -4533,7 +4534,7 @@ impl GitHubClient { for _ in 0..10 { let data = self .graphql_read( - "query($owner:String!,$name:String!,$pr:Int!,$after:String){ repository(owner:$owner,name:$name){ pullRequest(number:$pr){ reviewThreads(first:100, after:$after){ pageInfo{ hasNextPage endCursor } nodes{ id isResolved path comments(first:50){ nodes{ id isMinimized body author{ login } pullRequestReview{ databaseId } } } } } } } }", + "query($owner:String!,$name:String!,$pr:Int!,$after:String){ repository(owner:$owner,name:$name){ pullRequest(number:$pr){ reviewThreads(first:100, after:$after){ pageInfo{ hasNextPage endCursor } nodes{ id isResolved isOutdated line path comments(first:50){ nodes{ id isMinimized body author{ login } pullRequestReview{ databaseId } } } } } } } }", serde_json::json!({ "owner": owner, "name": repo, "pr": pr_number, "after": cursor }), ) .await?; diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index c870aaf95..6d8c9ef0d 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -695,6 +695,11 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe let resumed = as_sweep(who::SWEEP_DEPLOYS, passes::deploy_stats::sweep(&state)).await; info!(resumed, "Deploys backfill sweep done"); } + models::WorkerMessage::ReviewTidy(msg) => { + if let Err(e) = passes::review_tidy::run(&state, &msg).await { + warn!(pr = msg.pr_number, reason = %msg.reason, error = %e, "Could not tidy CoderHelm's reviews on the pull request"); + } + } models::WorkerMessage::ReviewReminder => { info!("Running review-reminder sweep"); if let Err(e) = passes::review_reminder::run(&state).await { diff --git a/services/worker/src/passes/conversation.rs b/services/worker/src/passes/conversation.rs index ae8a67ad7..58da37edc 100644 --- a/services/worker/src/passes/conversation.rs +++ b/services/worker/src/passes/conversation.rs @@ -370,6 +370,7 @@ pub fn reviews_of(v: &Value) -> Vec { && own_login(r["user"]["login"].as_str().unwrap_or("")), state: r["state"].as_str().unwrap_or("").to_string(), body: r["body"].as_str().unwrap_or("").to_string(), + commit_id: r["commit_id"].as_str().unwrap_or("").to_string(), }) .collect() } @@ -401,6 +402,9 @@ pub fn threads_of(nodes: &[Value]) -> Vec { minimized: c["isMinimized"].as_bool().unwrap_or(false), }) .collect(), + outdated: t["isOutdated"].as_bool().unwrap_or(false), + line_gone: t["line"].is_null(), + holds_at_head: None, } }) .collect() @@ -465,6 +469,23 @@ pub async fn supersede_reviews( } } +/// Cuts CoderHelm's own review bodies to the one line +/// `common::review_supersede::tidy` decided (`review_tidy`), here with the +/// other rewrites of its earlier reviews. Best effort, logged. +pub async fn collapse_own_reviews( + gh: &GitHubClient, + owner: &str, + repo: &str, + number: u64, + collapse: &[(u64, String)], +) { + for (id, body) in collapse { + if let Err(e) = gh.update_review_body(owner, repo, number, *id, body).await { + tracing::info!(pr = number, review_id = id, error = %e, "Skipped cutting a review of CoderHelm's to one line"); + } + } +} + /// What CoderHelm last replied in each review thread (this process), so a /// retried round doesn't say the same thing in it twice. static REPLIED: LazyLock>> = diff --git a/services/worker/src/passes/incidents/ry_reviews_tidy_between_reviews.rs b/services/worker/src/passes/incidents/ry_reviews_tidy_between_reviews.rs new file mode 100644 index 000000000..feaeb3901 --- /dev/null +++ b/services/worker/src/passes/incidents/ry_reviews_tidy_between_reviews.rs @@ -0,0 +1,255 @@ +//! ry. Two pull requests on a web app, read by a person who asked whether +//! CoderHelm's approvals and resolved comments could go away after a while +//! because "it becomes too much". +//! +//! On the first, CoderHelm's "Approved with notes" review from four days +//! earlier still stood in full: the file table, the "Why approved" line, a +//! risk block with bars, an FYI list of unconfirmed items, Verification, +//! Tests, "Earlier comments" and the rating footer. Under it a person's +//! commit "Address the review", then the next review, as long again. The +//! earlier review only got out of the way when a new one was posted, and a +//! re-review with nothing new to say posts nothing. +//! +//! On the second, an inline thread of CoderHelm's 18 hours old was still +//! open: "Blocking (failing check): Lint & Type Check and Deploy Preview +//! are red on this head … I could not read the logs". It was about a head +//! two pushes back; the checks on the head had passed since. +//! +//! Guarantee: CoderHelm's own reviews and threads are tidied on a push, on +//! checks finishing, on a merge or a close and on the review sweep, not only +//! when a new review is posted (`review_supersede::tidy`, carried out by +//! `passes::review_tidy`, queued by the gateway's webhook handler). A body +//! of an older commit than the head becomes one line; on a merge every body +//! does and CoderHelm's resolved threads are hidden; a finding about failing +//! checks resolves once they pass, a finding whose code left the diff +//! resolves, and CoderHelm's comments in them are hidden. A new review keeps +//! only its verdict and what holds the merge in sight (`fold`). A person's +//! review, thread or unanswered reply is never touched, and nothing is +//! posted to announce it. + +use common::review_supersede::{self as rs, PrState, Settled}; +use serde_json::json; + +const OLD: &str = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678"; +const HEAD: &str = "f0e1d2c3b4a5968778695a4b3c2d1e0f98765432"; + +/// The approval as it stood: every section in sight. +fn long_approval() -> String { + [ + "## PR Overview", + "Adds the camp registration status to the camp cards.", + "| File | What |\n|---|---|\n| `apps/web/src/camps/card.tsx` | Shows the status |", + "✅ **Approved with notes**: nothing blocks the merge; 2 notes below are for a look.", + "_Why approved: nothing blocks (no required rule broken, no failing check)._", + "#### Risk: low\n`██░░░░░░░░` 2/10", + "#### FYI: facts worth confirming\n- The vendor's open date field.", + "#### Verification\n- typecheck passed", + "#### Tests\n- e2e covers the closed branch only", + "#### Earlier comments\n1 settled and resolved · 0 still open", + "---\n**Was this review right?** Rate it", + ] + .join("\n\n") +} + +fn reviews(body: &str) -> Vec { + super::super::conversation::reviews_of(&json!([ + {"id": 11, "state": "APPROVED", "body": body, "commit_id": OLD, + "user": {"login": "coderhelm[bot]", "type": "Bot"}}, + {"id": 12, "state": "COMMENTED", "body": "Looks fine to me.", "commit_id": OLD, + "user": {"login": "sam", "type": "User"}}, + ])) +} + +fn pr(state: PrState) -> rs::PrNow { + let mut p = super::super::review_tidy::pr_now( + "acme", + "web", + 42, + &json!({"state": "open", "head": {"sha": HEAD}}), + ); + p.state = state; + p +} + +/// The first screenshot: after the person's push the four-day-old approval +/// is one line naming the commit it approved; the person's review is not +/// touched; a second run does nothing. +#[test] +fn an_approval_of_an_older_commit_becomes_one_line_on_the_push() { + let r = reviews(&long_approval()); + let t = rs::tidy(&r, &[], &pr(PrState::Open)); + assert_eq!(t.collapse.len(), 1, "{t:?}"); + let (id, body) = &t.collapse[0]; + assert_eq!(*id, 11); + let shown = body.lines().last().unwrap(); + assert_eq!( + shown, + format!("✅ Approved with notes [`a1b2c3d`](https://github.com/acme/web/pull/42/commits/{OLD}) (superseded by later commits)") + ); + for gone in [ + "Risk", + "FYI", + "Verification", + "Tests", + "Earlier comments", + "Rate it", + "| File |", + ] { + assert!(!body.contains(gone), "{gone} still in {body}"); + } + let after = reviews(body); + assert!(rs::tidy(&after, &[], &pr(PrState::Open)).is_empty()); +} + +/// On the merge every body of CoderHelm's is one line, the approval of the +/// merged head too. +#[test] +fn the_merge_leaves_one_line_per_review() { + let mut r = reviews(&long_approval()); + r[0].commit_id = HEAD.into(); + assert!(rs::tidy(&r, &[], &pr(PrState::Open)).collapse.is_empty()); + let t = rs::tidy(&r, &[], &pr(PrState::Merged)); + assert_eq!(t.collapse.len(), 1); + assert!(t.collapse[0].1.ends_with("(merged)")); +} + +/// A new review is short from the start: the verdict and why in sight, the +/// overview, file table, risk, FYI, verification, tests and earlier +/// comments folded under one collapsed block; the review posts the folded +/// body (and so does the re-review that brings the standing one up to date). +#[test] +fn a_new_review_keeps_only_its_verdict_in_sight() { + let full = long_approval(); + let (head, rest): (Vec<&str>, Vec<&str>) = full + .split("\n\n") + .filter(|p| !p.starts_with("---")) + .partition(|p| p.starts_with("✅") || p.starts_with("_Why")); + let body = rs::fold( + &head.join("\n\n"), + &rest.join("\n\n"), + "\n\n---\n**Was this review right?** Rate it", + ); + let (shown, folded) = body.split_once("
").unwrap(); + assert!(shown.starts_with("✅ **Approved with notes**")); + assert!(shown.contains("_Why approved")); + for hidden in [ + "## PR Overview", + "| File |", + "#### Risk", + "#### FYI", + "#### Verification", + "#### Tests", + "#### Earlier comments", + ] { + assert!(!shown.contains(hidden), "{hidden} in sight"); + assert!(folded.contains(hidden), "{hidden} lost"); + } + let src = include_str!("../review_pr.rs"); + let at = src + .find("common::review_supersede::fold(") + .expect("the review folds its body"); + assert!(src[..at].contains("let mut visible = verdict_line;")); + // The overview lives only in the review body: no comment of its own is + // posted (or posted again) anywhere. + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut stack = vec![root.clone()]; + let mut callers = Vec::new(); + while let Some(dir) = stack.pop() { + for e in std::fs::read_dir(&dir).unwrap().flatten() { + let p = e.path(); + if p.is_dir() { + stack.push(p); + } else if p.extension().and_then(|x| x.to_str()) == Some("rs") + && !p.to_string_lossy().contains("incidents") + { + let s = std::fs::read_to_string(&p).unwrap(); + if s.contains("review_overview::markdown(") { + callers.push(p.strip_prefix(&root).unwrap().to_string_lossy().to_string()); + } + } + } + } + assert_eq!(callers, vec!["passes/review_pr.rs".to_string()]); +} + +fn failing_check_thread(person_reply: bool) -> Vec { + let mut comments = vec![json!({ + "id": "C1", "isMinimized": false, + "body": "🔴 **Blocking (failing check)**: Lint & Type Check and Deploy Preview are red on this head. I could not read the logs, so the cause is not confirmed.", + "author": {"login": "coderhelm"}, "pullRequestReview": {"databaseId": 11} + })]; + if person_reply { + comments.push(json!({ + "id": "P1", "isMinimized": false, "body": "Isn't this the flaky deploy?", + "author": {"login": "kim"}, "pullRequestReview": {"databaseId": 13} + })); + } + super::super::conversation::threads_of(&[json!({ + "id": "T1", "isResolved": false, "isOutdated": false, "line": 12, + "path": ".github/workflows/ci.yml", + "comments": {"nodes": comments} + })]) +} + +/// The second screenshot: once the head's checks pass, the failing-check +/// thread resolves and CoderHelm's comment in it is hidden, with no new +/// review. While the checks run, it stays. +#[test] +fn a_failing_check_thread_settles_when_the_head_goes_green() { + let threads = failing_check_thread(false); + let mut now = pr(PrState::Open); + now.checks_pass = rs::checks_pass(&json!({"check_runs": [ + {"name": "Lint & Type Check", "status": "completed", "conclusion": "success", "app": {"slug": "github-actions"}}, + {"name": "Deploy Preview", "status": "in_progress", "conclusion": null, "app": {"slug": "vercel"}}, + {"name": "CoderHelm review", "status": "in_progress", "conclusion": null, "app": {"slug": "coderhelm"}} + ]})); + assert!(rs::tidy(&[], &threads, &now).is_empty()); + now.checks_pass = rs::checks_pass(&json!({"check_runs": [ + {"name": "Lint & Type Check", "status": "completed", "conclusion": "success", "app": {"slug": "github-actions"}}, + {"name": "Deploy Preview", "status": "completed", "conclusion": "success", "app": {"slug": "vercel"}}, + {"name": "CoderHelm review", "status": "in_progress", "conclusion": null, "app": {"slug": "coderhelm"}} + ]})); + let t = rs::tidy(&[], &threads, &now); + assert_eq!(t.resolve, vec![("T1".to_string(), Settled::ChecksPass)]); + assert_eq!(t.minimize, vec!["C1".to_string()]); +} + +/// A person who answered in that thread keeps it in sight until CoderHelm +/// answers them. +#[test] +fn a_persons_unanswered_reply_keeps_the_thread() { + let threads = failing_check_thread(true); + let mut now = pr(PrState::Open); + now.checks_pass = Some(true); + assert!(rs::tidy(&[], &threads, &now).is_empty()); + now.state = PrState::Merged; + assert!(rs::tidy(&[], &threads, &now).is_empty()); +} + +/// A finding on a file the pull request no longer changes resolves. +#[test] +fn a_finding_on_code_that_left_the_diff_settles() { + let mut now = pr(PrState::Open); + now.changed_paths = Some(vec!["apps/web/src/camps/card.tsx".into()]); + let t = rs::tidy(&[], &failing_check_thread(false), &now); + assert_eq!(t.resolve, vec![("T1".to_string(), Settled::FileGone)]); +} + +/// Every trigger reaches the tidy: the worker runs it for its message and +/// on the sweep; the gateway queues it on a push, a merge or a close, and +/// checks finishing. +#[test] +fn every_trigger_reaches_the_tidy() { + let main = include_str!("../../main.rs"); + assert!(main.contains("WorkerMessage::ReviewTidy(msg) =>")); + assert!(main.contains("passes::review_tidy::run(&state, &msg)")); + let sweep = include_str!("../review_sweep.rs"); + assert!( + sweep.contains("super::review_tidy::pull_request(&github, owner, name, number, Some(pr))") + ); + let hook = include_str!("../../../../gateway/src/routes/github_webhook.rs"); + for reason in ["\"push\"", "\"merged\"", "\"closed\"", "\"checks\""] { + assert!(hook.contains(reason), "{reason}"); + } + assert!(hook.matches("queue_review_tidy(state,").count() >= 3); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index a8b22d42f..5adc9e33b 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1397,6 +1397,7 @@ pub(crate) mod review_session; pub mod review_severity; pub mod review_sweep; pub mod review_thread_reply; +pub mod review_tidy; pub mod review_verdict; mod reviewer_guide; pub mod rewards; diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 5097a1e1d..19aa912d7 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -4129,18 +4129,15 @@ async fn run_once( &common::review_overview::changed_files(&compare), ); let overview_md = common::review_overview::markdown(&overview); - let verdict_line = if overview_md.is_empty() { - verdict_line - } else { - format!("{overview_md}\n{verdict_line}") - }; - let mut full_body = match &stable.note { - Some(n) => format!( - "{verdict_line}\n\n{n}\n\n{summary}\n\n{}", - risk_report.markdown() - ), - None => format!("{verdict_line}\n\n{summary}\n\n{}", risk_report.markdown()), - }; + // Short from the start (`review_supersede::fold`): the verdict, what + // holds the merge and why stay in sight; the overview and its file + // table, the risk, the FYI and unconfirmed items, the verification, the + // tests and the earlier comments fold under one collapsed block. + let mut visible = verdict_line; + if let Some(n) = &stable.note { + visible.push_str(&format!("\n\n{n}")); + } + let mut full_body = format!("{overview_md}\n\n{summary}\n\n{}", risk_report.markdown()); full_body.push_str(&judge_note); full_body.push_str(&review_agent::unconfirmed_markdown(&unconfirmed)); // Memories the code of this change contradicts: noted on the review and @@ -4166,10 +4163,14 @@ async fn run_once( full_body.push_str(&format!("\n\n{verify_md}")); } if !postable.unanchored_md.is_empty() { - full_body.push_str(&format!( - "\n\n#### Additional findings\n{}", - postable.unanchored_md - )); + let findings_md = format!("\n\n#### Additional findings\n{}", postable.unanchored_md); + // Findings with no line to sit on stay in sight when something + // holds the merge: they may be what holds it. + if final_verdict.holding().is_empty() { + full_body.push_str(&findings_md); + } else { + visible.push_str(&findings_md); + } } if !held_late.is_empty() { full_body.push_str("\n\n#### Also worth a look\nOn code that hasn't changed since my previous review, so these are notes and don't change the verdict (they should have been raised then):\n"); @@ -4210,12 +4211,16 @@ async fn run_once( if let Some(s) = &skills { full_body.push_str(&s.consulted_markdown(super::skills::app_url(&state.config.stage))); } - full_body.push_str(&rating_footer( - common::public_urls::app_url(&state.config.stage), - &msg.repo_owner, - &msg.repo_name, - msg.pr_number, - )); + let full_body = common::review_supersede::fold( + &visible, + &full_body, + &rating_footer( + common::public_urls::app_url(&state.config.stage), + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + ), + ); // Check the head again before speaking: the review takes minutes, and a // commit pushed seconds before this one started may not have been the PR's diff --git a/services/worker/src/passes/review_sweep.rs b/services/worker/src/passes/review_sweep.rs index 3819e9e8b..9cebc43d2 100644 --- a/services/worker/src/passes/review_sweep.rs +++ b/services/worker/src/passes/review_sweep.rs @@ -377,6 +377,31 @@ async fn sweep_repo( info!(repo = %r.repo, pr = number, head, stale, "review_sweep: completed stale CoderHelm review checks"); } let records = review_records(state, &r.team_id, &r.repo, number, 10).await; + // A pull request CoderHelm reviewed is tidied once per head per + // window: what a push, checks finishing or a delivery that never + // came left standing (`review_tidy`). + if !records.is_empty() { + let sk = format!("REVIEWTIDY#{}#{number:0>6}#{head}", r.repo); + if super::review_pr::claim_once_ttl( + state, + &r.team_id, + &sk, + super::review_tidy::SWEEP_TIDY_TTL_SECS, + ) + .await + { + match super::review_tidy::pull_request(&github, owner, name, number, Some(pr)).await + { + Ok(t) if !t.is_empty() => { + info!(repo = %r.repo, pr = number, collapsed = t.collapse.len(), resolved = t.resolve.len(), hidden = t.minimize.len(), "review_sweep: tidied CoderHelm's reviews") + } + Ok(_) => {} + Err(e) => { + warn!(repo = %r.repo, pr = number, error = %e, "review_sweep: could not tidy CoderHelm's reviews") + } + } + } + } let note = failure_note(state, &r.team_id, &r.repo, number).await; let Some(why) = stuck(&records, note.as_ref(), head, now) else { continue; diff --git a/services/worker/src/passes/review_tidy.rs b/services/worker/src/passes/review_tidy.rs new file mode 100644 index 000000000..9879ff6ad --- /dev/null +++ b/services/worker/src/passes/review_tidy.rs @@ -0,0 +1,215 @@ +//! CoderHelm's own reviews and threads on a pull request, kept tidy between +//! reviews (`common::review_supersede::tidy` decides, this carries it out). +//! +//! Before this, CoderHelm's words only got out of the way when it posted a +//! new review. An approval four days old stood in full under every later +//! commit, and a "the checks are red on this head" thread stayed open after +//! the checks went green. Now the same tidy runs: +//! +//! - on a push (the gateway's `pull_request` / `synchronize`, after GitHub +//! has marked the moved lines outdated); +//! - when checks finish on the head (`check_suite` / `completed`); +//! - on a merge or a close (`pull_request` / `closed`); +//! - on the review sweep, once per head per [`SWEEP_TIDY_TTL_SECS`], for +//! every open pull request CoderHelm reviewed (a delivery that never came). +//! +//! It posts nothing and touches only CoderHelm's own reviews, comments and +//! threads. Cheap: a pull request CoderHelm never reviewed costs one read; +//! the checks and the changed files are read only when an open thread could +//! turn on them. Idempotent: a second run finds nothing to do. + +use crate::clients::github::GitHubClient; +use crate::WorkerState; +use common::messages::ReviewTidyMessage; +use common::review_supersede::{self as rs, PrNow, PrState, Tidy}; +use serde_json::Value; +use tracing::info; + +/// How often the sweep tidies the same pull request head. +pub const SWEEP_TIDY_TTL_SECS: u64 = 6 * 3600; + +/// GitHub lists at most this many changed files in one page; a pull request +/// at the limit may change more, so "the file left the diff" is not read. +const FILES_PAGE: usize = 100; + +type Error = Box; + +/// One event's tidy (a push, checks finishing, a merge or a close). +pub async fn run(state: &WorkerState, msg: &ReviewTidyMessage) -> Result { + let github = GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + msg.installation_id, + &state.http, + )?; + let done = pull_request( + &github, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + None, + ) + .await?; + if !done.is_empty() { + info!( + repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), + pr = msg.pr_number, + reason = %msg.reason, + collapsed = done.collapse.len(), + resolved = done.resolve.len(), + hidden = done.minimize.len(), + "Tidied CoderHelm's reviews on the pull request" + ); + } + Ok(done) +} + +/// Tidies one pull request: `pr` is GitHub's pull request when the caller +/// already read it (the sweep's list of open ones), else it is read here. +pub async fn pull_request( + github: &GitHubClient, + owner: &str, + repo: &str, + number: u64, + pr: Option<&Value>, +) -> Result { + let reviews = + super::conversation::reviews_of(&github.list_pr_reviews(owner, repo, number).await?); + // Never reviewed by CoderHelm: nothing of its own to tidy. + if !reviews.iter().any(|r| r.own) { + return Ok(Tidy::default()); + } + let read; + let pr = match pr { + Some(p) => p, + None => { + read = github.get_pull_request(owner, repo, number).await?; + &read + } + }; + let threads = super::conversation::threads_of( + &github + .list_review_threads_detail(owner, repo, number) + .await?, + ); + let mut now = pr_now(owner, repo, number, pr); + if now.state == PrState::Open { + let open: Vec<&rs::Thread> = threads + .iter() + .filter(|t| t.own() && !t.resolved && !t.person_waiting()) + .collect(); + if open + .iter() + .any(|t| rs::failing_check_finding(&t.first_body)) + { + now.checks_pass = github + .list_check_runs_for_ref(owner, repo, &now.head) + .await + .ok() + .and_then(|v| rs::checks_pass(&v)); + } + if !open.is_empty() { + now.changed_paths = github + .list_pull_files(owner, repo, number) + .await + .ok() + .filter(|f| f.len() < FILES_PAGE) + .map(|f| f.into_iter().map(|(path, _)| path).collect()); + } + } + let plan = rs::tidy(&reviews, &threads, &now); + apply(github, owner, repo, number, &plan).await; + Ok(plan) +} + +/// The pull request as the rules read it. +pub fn pr_now(owner: &str, repo: &str, number: u64, pr: &Value) -> PrNow { + let state = if pr["merged"].as_bool() == Some(true) || pr["merged_at"].is_string() { + PrState::Merged + } else if pr["state"].as_str() == Some("closed") { + PrState::Closed + } else { + PrState::Open + }; + PrNow { + owner: owner.to_string(), + repo: repo.to_string(), + number, + head: pr["head"]["sha"].as_str().unwrap_or("").to_string(), + state, + checks_pass: None, + changed_paths: None, + } +} + +/// Carries the plan out. Best effort: a step GitHub refuses is skipped with +/// a log line, and the next event or sweep tries it again. +async fn apply(github: &GitHubClient, owner: &str, repo: &str, number: u64, plan: &Tidy) { + super::conversation::collapse_own_reviews(github, owner, repo, number, &plan.collapse).await; + for (t, why) in &plan.resolve { + if let Err(e) = github.resolve_review_thread(t).await { + info!(pr = number, thread = %t, why = ?why, error = %e, "Skipped resolving a settled thread of CoderHelm's"); + } + } + for node in &plan.minimize { + if let Err(e) = github.hide_own_comment(node, true).await { + info!(pr = number, comment = %node, error = %e, "Skipped hiding a settled comment of CoderHelm's"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + /// The marks the common rules read are the ones the reviewer writes. + #[test] + fn the_rules_read_the_reviewers_own_marks() { + assert_eq!( + rs::UPDATED_MARK, + crate::passes::review_verdict::UPDATED_MARK + ); + assert_eq!( + rs::REQUIRED_MARK, + crate::passes::review_rules::REQUIRED_MARK + ); + let src = include_str!("review_rules.rs"); + assert!(src.contains(&format!("\"{}\"", rs::FAILING_CHECK_LABEL))); + // A body brought up to date is read back as the head it names. + let body = crate::passes::review_verdict::updated_body( + "✅ **Approved**", + "aaaaaaa111", + "bbbbbbb222", + ); + let r = rs::Review { + body, + commit_id: "aaaaaaa111".into(), + ..Default::default() + }; + assert_eq!(rs::reviewed_sha(&r), "bbbbbbb"); + } + + #[test] + fn the_pull_request_state_is_read_from_github() { + let open = json!({"state": "open", "head": {"sha": "abc1234"}}); + let merged = json!({"state": "closed", "merged": true, "head": {"sha": "abc1234"}}); + let closed = json!({"state": "closed", "merged_at": null, "head": {"sha": "abc1234"}}); + assert_eq!(pr_now("acme", "web", 1, &open).state, PrState::Open); + assert_eq!(pr_now("acme", "web", 1, &merged).state, PrState::Merged); + assert_eq!(pr_now("acme", "web", 1, &closed).state, PrState::Closed); + assert_eq!(pr_now("acme", "web", 1, &open).head, "abc1234"); + } + + /// The thread query asks GitHub for what the code-gone rule reads. + #[test] + fn the_thread_query_reads_outdated_lines() { + let src = include_str!("../clients/github.rs"); + assert!(src.contains("nodes{ id isResolved isOutdated line path comments(first:50)")); + let t = super::super::conversation::threads_of(&[json!({ + "id": "T1", "isResolved": false, "isOutdated": true, "line": null, "path": "a.ts", + "comments": {"nodes": [{"id": "C1", "isMinimized": false, "body": "x", "author": {"login": "coderhelm"}, "pullRequestReview": {"databaseId": 1}}]} + })]); + assert!(t[0].outdated && t[0].line_gone); + } +}