From 053adfa1627e9898fce0772f05a779e149c187c7 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 17 Nov 2026 14:22:50 -0500 Subject: [PATCH 1/2] One verdict per finding; every finding is raised in the first review A review listed findings under "Holding the merge" that the same review said no longer applied or kept as notes, and a review three rounds in raised two findings on code unchanged since the first review, each costing a push and a review. - review_one_verdict settles each finding's one state before the body is written (blocking, note, settled, no longer applies) and checks the finished body before it is posted. Resolved, settled and gone threads, late findings and earlier holds now called notes never hold. - A late finding is a note naming why: the previous review missed it, or the check that found it started after that review. On CoderHelm's own pull request it joins a round that has other work, never a hold. A miss is recorded (RewardKind::FindingMissed, the raise-early lesson). - The first review runs everything: the checks with no model run without the tree, the diff keeps every file and names the ones it cut, and a review that runs out of tool steps goes on in a second pass. - After the first review, smallest-change advice is a note; late notes never start a fix round, so a run with only notes left ends. The parallel-structure check reads both sides against the base. - Every head a run pushes gets the PR reviewer's review posted. - Incidents ow, ox and oy replay the two pull requests. --- docs/incidents/ow_one_verdict_per_finding.md | 7 + docs/incidents/ox_findings_raised_first.md | 7 + docs/incidents/oy_review_fix_loop_ends.md | 7 + services/common/src/rewards/event.rs | 7 + services/common/src/rewards/exemplars.rs | 3 + services/common/src/rewards/score.rs | 4 + services/worker/src/agent/anthropic.rs | 3 +- .../incidents/ow_one_verdict_per_finding.rs | 197 +++++ .../incidents/ox_findings_raised_first.rs | 255 ++++++ .../incidents/oy_review_fix_loop_ends.rs | 168 ++++ services/worker/src/passes/minimal_change.rs | 34 +- services/worker/src/passes/mod.rs | 1 + services/worker/src/passes/resume.rs | 11 +- services/worker/src/passes/review_agent.rs | 259 +++++- .../policy/late_blocker_round_three.json | 6 +- services/worker/src/passes/review_lessons.rs | 2 +- .../worker/src/passes/review_one_verdict.rs | 772 ++++++++++++++++++ services/worker/src/passes/review_policy.rs | 83 +- .../worker/src/passes/review_policy_eval.rs | 1 + services/worker/src/passes/review_pr.rs | 157 +++- services/worker/src/passes/review_rules.rs | 71 +- services/worker/src/passes/rewards.rs | 57 ++ 22 files changed, 2023 insertions(+), 89 deletions(-) create mode 100644 docs/incidents/ow_one_verdict_per_finding.md create mode 100644 docs/incidents/ox_findings_raised_first.md create mode 100644 docs/incidents/oy_review_fix_loop_ends.md create mode 100644 services/worker/src/passes/incidents/ow_one_verdict_per_finding.rs create mode 100644 services/worker/src/passes/incidents/ox_findings_raised_first.rs create mode 100644 services/worker/src/passes/incidents/oy_review_fix_loop_ends.rs create mode 100644 services/worker/src/passes/review_one_verdict.rs diff --git a/docs/incidents/ow_one_verdict_per_finding.md b/docs/incidents/ow_one_verdict_per_finding.md new file mode 100644 index 000000000..f61662045 --- /dev/null +++ b/docs/incidents/ow_one_verdict_per_finding.md @@ -0,0 +1,7 @@ +# ow. `ow_one_verdict_per_finding` + +**What happened:** CoderHelm's own pull request fixed a sport filter that listed one sport twice. A later review listed findings under "Holding the merge" that the same review said no longer applied: the earlier dropdown thread, whose code the fix rounds had replaced, and two findings the review itself kept as notes because they came late. On CoderHelm's own pull request each late note was also chained into its open work, which is named as holding the merge, so each of those findings had two verdicts in one review. + +**The guarantee:** Every finding has one state before the review is written: blocking, a note, settled, or no longer applying. A thread that is resolved, settled by this review or about code no longer in the change, a finding raised late, and an earlier hold the review now calls a note never hold the merge. "Holding the merge" lists only what still blocks at the head with its thread open. The finished body is checked before it is posted: no finding listed as holding is also called a note, settled or no longer applying. + +**Where it's enforced:** `passes::review_one_verdict` (`settle`, `check`, `enforce`), called by `review_pr` before the verdict is made and before the review is posted; `review_pr::closed_threads`; the `gone` thread status (`review_agent::GONE`, `review_rules::settles`). diff --git a/docs/incidents/ox_findings_raised_first.md b/docs/incidents/ox_findings_raised_first.md new file mode 100644 index 000000000..4b861a20e --- /dev/null +++ b/docs/incidents/ox_findings_raised_first.md @@ -0,0 +1,7 @@ +# ox. `ox_findings_raised_first` + +**What happened:** On the same pull request as `ow`, a review three rounds in raised "A parallel structure next to an existing one" and "A test out of proportion to the change" on code unchanged since the first review, and said they should have been raised then. On CoderHelm's own pull request each late note was still work that held the merge, so each cost a push and a review. The checks that find them started running after the earlier rounds were reviewed. Three more ways a first review left findings for later were open: the checks with no model ran only when the head's tree could be read, a diff over its room lost the files in its middle, and a review that ran out of tool steps answered as if it were done. + +**The guarantee:** Every check runs on every review, the first included, with or without the tree. The reviewer's diff names every changed file and lists the ones it cut. A review that runs out of steps goes on in a second pass over what it didn't reach. A finding a later review raises on lines unchanged since the previous one never blocks: it is a note saying the previous review missed it, or that the check that found it started after it. On CoderHelm's own pull request it is still sent to the coder in this round's work. A miss is recorded for the reviewer's rewards and lessons; a new check's finding is not. + +**Where it's enforced:** `review_policy::hold_late_blockers` (`Late::missed`, `NEW_CHECK_NOTE`), `review_rules::CHECKS_STARTED`, `rewards::record_missed` and `RewardKind::FindingMissed`, `review_agent::format_diff`, `review_agent::generate_review` (`ran_out_of_steps`, `continue_prompt`, `merge_review`), and the checks block in `review_pr`. diff --git a/docs/incidents/oy_review_fix_loop_ends.md b/docs/incidents/oy_review_fix_loop_ends.md new file mode 100644 index 000000000..f8a460e6a --- /dev/null +++ b/docs/incidents/oy_review_fix_loop_ends.md @@ -0,0 +1,7 @@ +# oy. `oy_review_fix_loop_ends` + +**What happened:** A data-pipeline run's own review raised something new each round: a model finding in round 2, "A test out of proportion to the change" in round 3, and in round 4 "A parallel structure next to an existing one" that named as new a function the main branch had had for months (the branch only added a parameter to it). Each held the merge, so the run went review, fix, review every ten minutes for nine fix rounds, past its spend ceiling. The review on the pull request stayed on an old head the whole time, and a person had to ask for a re-review. + +**The guarantee:** The parallel-structure check reads both sides against the base, so a definition the base already has is never new. After the first review, the smallest-change checks that a reason may keep give notes, and a finding on lines unchanged since the previous review is a note. Late notes join a round that has work that holds, and never start one, so the run ends once only notes are left. Every head the run pushes gets the PR reviewer's review posted, news or not. + +**Where it's enforced:** `minimal_change::parallel_structures`; `review_policy::hold_late_blockers` (`ADVISORY_LATE_NOTE`) and `review_rules::advisory_check`; the work list in `review_pr`; `review_pr::own_head_is_new`; the run's review step in `resume` (`review_for_run` on every head). diff --git a/services/common/src/rewards/event.rs b/services/common/src/rewards/event.rs index 6ffc882f8..8a54b3b0e 100644 --- a/services/common/src/rewards/event.rs +++ b/services/common/src/rewards/event.rs @@ -51,6 +51,10 @@ pub enum RewardKind { RereviewRequested, /// An alert named a merged CoderHelm change. IncidentLinked, + /// A review raised a finding late: on lines unchanged since an earlier + /// review of the same pull request had read them. The earlier review + /// missed it. + FindingMissed, } impl RewardKind { @@ -71,6 +75,7 @@ impl RewardKind { RewardKind::TimeToMerge, RewardKind::RereviewRequested, RewardKind::IncidentLinked, + RewardKind::FindingMissed, ]; pub fn key(self) -> &'static str { @@ -91,6 +96,7 @@ impl RewardKind { RewardKind::TimeToMerge => "time_to_merge", RewardKind::RereviewRequested => "rereview_requested", RewardKind::IncidentLinked => "incident_linked", + RewardKind::FindingMissed => "finding_missed", } } @@ -117,6 +123,7 @@ impl RewardKind { RewardKind::TimeToMerge => "Time to merge", RewardKind::RereviewRequested => "Re-review requested", RewardKind::IncidentLinked => "Alert tied to a merged change", + RewardKind::FindingMissed => "Review comment missed by an earlier review", } } diff --git a/services/common/src/rewards/exemplars.rs b/services/common/src/rewards/exemplars.rs index e4d5874c7..cfe455494 100644 --- a/services/common/src/rewards/exemplars.rs +++ b/services/common/src/rewards/exemplars.rs @@ -240,6 +240,9 @@ pub fn finding_reason(kind: RewardKind) -> String { RewardKind::FindingAccepted => "The author changed the code it pointed at", RewardKind::FindingDismissed => "The team pushed back and the comment was judged wrong", RewardKind::FindingIgnored => "Still open when the pull request closed", + RewardKind::FindingMissed => { + "Raised late, on code an earlier review of the same pull request had read" + } _ => "", } .to_string() diff --git a/services/common/src/rewards/score.rs b/services/common/src/rewards/score.rs index e3101be03..acf3fc7e3 100644 --- a/services/common/src/rewards/score.rs +++ b/services/common/src/rewards/score.rs @@ -47,6 +47,9 @@ pub fn default_weight(kind: RewardKind) -> f64 { // the team decides otherwise. RewardKind::RereviewRequested => 0.0, RewardKind::IncidentLinked => -2.5, + // Every finding belongs in the first review of the code: one raised + // rounds later cost the author a push and a review each round. + RewardKind::FindingMissed => -1.0, } } @@ -329,6 +332,7 @@ mod tests { RewardKind::PrReverted, RewardKind::CiFixRounds, RewardKind::IncidentLinked, + RewardKind::FindingMissed, ] { assert!(score(&ev("t", k, 1.0), &w) < 0.0, "{k:?}"); } diff --git a/services/worker/src/agent/anthropic.rs b/services/worker/src/agent/anthropic.rs index 17249d9f6..74d69c609 100644 --- a/services/worker/src/agent/anthropic.rs +++ b/services/worker/src/agent/anthropic.rs @@ -1261,7 +1261,8 @@ pub async fn converse_tool_loop( } /// The note the loop sends when every tool step is used. -const TOOLS_OFF_NOTE: &str = "[SYSTEM NOTE] You have used every tool step. Tools are now off. \ +pub(crate) const TOOLS_OFF_NOTE: &str = + "[SYSTEM NOTE] You have used every tool step. Tools are now off. \ Write your final answer NOW, in exactly the format you were asked for, using what you have \ already learned. Where something is still unknown, say so in the answer instead of guessing."; diff --git a/services/worker/src/passes/incidents/ow_one_verdict_per_finding.rs b/services/worker/src/passes/incidents/ow_one_verdict_per_finding.rs new file mode 100644 index 000000000..9baae5b9f --- /dev/null +++ b/services/worker/src/passes/incidents/ow_one_verdict_per_finding.rs @@ -0,0 +1,197 @@ +//! ow. CoderHelm's own pull request fixed a sport filter that listed one +//! sport twice. A later review of it listed findings under "Holding the +//! merge" that the same review said no longer applied: the earlier thread +//! about the dropdown, whose code the fix rounds had replaced, and two +//! findings the review itself had kept as notes ("on code that hasn't +//! changed since my previous review, so these are notes and don't change +//! the verdict"). On CoderHelm's own pull request every late note was also +//! chained into its open work, and that work is named as holding the merge, +//! so each of those findings had two verdicts in one review. +//! +//! Guarantee: one state per finding before the body is written +//! (`review_one_verdict::settle`): a thread that is resolved, settled by +//! this review or about code no longer in the change, a finding raised +//! late, and an earlier hold the review now calls a note never hold the +//! merge; "Holding the merge" is built only from what still blocks at the +//! head. The finished body is checked before it is posted +//! (`review_one_verdict::enforce`): no finding listed as holding is also +//! called a note, settled or no longer applying. + +use crate::passes::own_review; +use crate::passes::review_agent::{verdict_heading, Finding}; +use crate::passes::review_one_verdict::{self as one, Key, State}; +use crate::passes::review_policy::{self, demote, named_holding, LATE_NOTE}; +use crate::passes::review_verdict::{HoldKind, Verdict}; + +const FILTERS: &str = "apps/web/src/utils/filterMaps.ts"; +const TEST: &str = "apps/web/src/test/components/filter-nav-sport-grid.test.tsx"; + +/// The earlier thread: its code was replaced by the fix rounds. +fn earlier_thread_line() -> String { + own_review::thread_line( + FILTERS, + 632, + "**Drop-ins sport dropdown can now list one sport twice**\n\nTwo sport ids share a slug.", + ) +} + +/// The two findings the review raised late, as the checks wrote them. +fn late() -> Vec { + let mut out: Vec = crate::passes::review_rules::wider_findings(&[ + crate::passes::minimal_change::Widening { + kind: crate::passes::minimal_change::Kind::Parallel, + path: FILTERS.into(), + what: "`dedupeSportOptionsBySlug` next to the existing `dedupeSportsBySlug`".into(), + }, + crate::passes::minimal_change::Widening { + kind: crate::passes::minimal_change::Kind::TestSize, + path: TEST.into(), + what: "236 added lines against 41 lines of changed code".into(), + }, + ]); + for f in out.iter_mut() { + demote(f, LATE_NOTE); + } + out +} + +/// The model's summary, as it wrote it. +const SUMMARY: &str = "The fix keeps one option per sport slug. The earlier dropdown comment \ + on `apps/web/src/utils/filterMaps.ts` about listing one sport twice no longer applies: \ + the new helper replaced that code."; + +/// The review's body from its parts, the way `review_pr` writes them. +fn body(verdict: &Verdict, notes: usize, summary: &str, held_late: &[Finding]) -> String { + format!( + "{}\n\n_{}_\n\n{summary}{}", + verdict_heading(verdict, notes), + verdict.why(0, notes), + one::late_markdown(held_late) + ) +} + +/// What the review did: late notes chained into CoderHelm's open work, the +/// earlier thread still open, and every one named as holding. +#[test] +fn the_old_assembly_gave_findings_two_verdicts_and_the_check_names_them() { + let held = late(); + let own_open = own_review::required(&[], &held); + let open = [(FILTERS.to_string(), 632u64, earlier_thread_line())]; + let open: Vec<(String, u64, String)> = open + .iter() + .map(|(p, l, t)| (p.clone(), *l, format!("**{t}**"))) + .collect(); + let verdict = Verdict::from_holding(named_holding(&[], &open, &[], false, &own_open, &[])); + assert_eq!(verdict.holding().len(), 3); + let b = body(&verdict, held.len(), SUMMARY, &held); + let found = one::check(&b); + assert_eq!(found.len(), 3, "{found:#?}\n{b}"); + assert!(found.iter().any(|c| c.state == State::NoLongerApplies)); + assert_eq!( + found.iter().filter(|c| c.state == State::Note).count(), + 2, + "{found:#?}" + ); + // The last word before posting removes the words that contradict the + // hold, so even this body would never go out with two verdicts. + let (fixed, _) = one::enforce(&b); + assert!(one::check(&fixed).is_empty(), "{fixed}"); +} + +/// What the review does now: one state per finding, then the body. +#[test] +fn every_finding_has_one_verdict() { + let held = late(); + // Late findings are not part of the open work that holds the merge. + let own_open = own_review::required(&[], &[]); + assert!(own_open.is_empty()); + // On their own, late notes start no round: nothing holds, the draft + // isn't held, and the run ends (`review_pr` writes the work list only + // when something in it holds). + let own_late = one::late_lines(&held); + assert_eq!(own_late.len(), 2); + assert!(own_late.iter().all(|l| l.contains(one::LATE_MARK))); + let src = include_str!("../review_pr.rs"); + assert!(src.contains("let own_open: Vec = if own_open.is_empty() {")); + + let open = vec![(FILTERS.to_string(), 632u64, earlier_thread_line())]; + let late_keys: Vec = held.iter().map(Key::of_finding).collect(); + let settled = one::settle(one::Inputs { + holding: named_holding(&[], &open, &[], false, &own_open, &[]), + late: &late_keys, + prose: SUMMARY, + ..Default::default() + }); + assert!(settled.holding.is_empty(), "{:?}", settled.holding); + assert_eq!(settled.entries[0].state, State::NoLongerApplies); + let verdict = Verdict::from_holding(settled.holding); + assert_eq!(verdict.event(), "APPROVE"); + let b = body(&verdict, held.len(), &settled.prose, &held); + assert!(one::check(&b).is_empty(), "{b}"); + assert!(!b.contains(one::HOLDING_HEAD)); + assert!(b.contains("my previous review, which missed them")); +} + +/// A thread a person resolved, or one about a file the pull request no +/// longer changes, never holds; one the review called gone settles even a +/// required rule. +#[test] +fn resolved_and_gone_threads_never_hold() { + use crate::clients::github::BotReviewThread; + let thread = |id: &str, path: &str, resolved: bool| BotReviewThread { + id: id.into(), + root_id: 1, + path: path.into(), + line: 632, + outdated: false, + body: "**Drop-ins sport dropdown can now list one sport twice**".into(), + replies: vec![], + resolved, + resolved_by_person: resolved, + }; + let threads = vec![ + thread("t1", FILTERS, true), + thread("t2", "apps/web/src/old.ts", false), + ]; + let changed = vec![FILTERS.to_string()]; + let closed = crate::passes::review_pr::closed_threads(&threads, &[], &[], &changed); + assert_eq!(closed.len(), 2); + assert_eq!(closed[0].1, State::Settled); + assert_eq!(closed[1].1, State::NoLongerApplies); + assert!(crate::passes::review_rules::settles( + crate::passes::review_rules::REQUIRED_MARK, + crate::passes::review_agent::GONE + )); + let settled = one::settle(one::Inputs { + holding: vec![crate::passes::review_verdict::Holding::new( + HoldKind::KeptFromEarlier, + earlier_thread_line(), + )], + closed: &closed, + ..Default::default() + }); + assert!(settled.holding.is_empty()); +} + +/// The review settles before it writes, and checks the body before it +/// posts. +#[test] +fn the_review_settles_before_it_writes_and_checks_before_it_posts() { + let src = include_str!("../review_pr.rs"); + let settle = src.find("review_one_verdict::settle(").expect("settle"); + let verdict = src + .find("let mut final_verdict = super::review_verdict::Verdict::from_holding(one.holding)") + .expect("the verdict comes from the settled holds"); + assert!(settle < verdict); + let enforce = src + .find("review_one_verdict::enforce(&full_body)") + .expect("enforce"); + let post = src[enforce..] + .find("review_verdict::post(") + .expect("posted after the check"); + assert!(post > 0); + // Late findings are never chained into the open work that holds. + assert!(src.contains("super::own_review::required(&findings, &[])")); + assert!(!src.contains("super::own_review::required(&findings, &held_late)")); + let _ = review_policy::NEW_CHECK_NOTE; +} diff --git a/services/worker/src/passes/incidents/ox_findings_raised_first.rs b/services/worker/src/passes/incidents/ox_findings_raised_first.rs new file mode 100644 index 000000000..1d3ceea1e --- /dev/null +++ b/services/worker/src/passes/incidents/ox_findings_raised_first.rs @@ -0,0 +1,255 @@ +//! ox. On the same pull request as `ow`, a review three rounds in raised +//! "A parallel structure next to an existing one" and "A test out of +//! proportion to the change" on code that hadn't changed since the first +//! review, and said they "should have been raised then". On CoderHelm's own +//! pull request each late note was still chained into the work that holds +//! the merge, so each one cost a push and a review. Why they were late: +//! the checks that find them (#742's smallest-change checks, with no model) +//! started running after the earlier rounds were reviewed, so the review +//! blamed itself for a miss it couldn't have made; and three more ways a +//! first review leaves findings for later were open in the code: the +//! checks with no model ran only when the head's tree could be read, a diff +//! over its room lost the files in its middle, and a review that ran out of +//! tool steps answered with the tools off as if it were done. +//! +//! Guarantee: every check runs on every review, the first included, with +//! or without the tree; the diff the reviewer gets names every changed +//! file and lists the ones it cut; a review that runs out of steps goes on +//! in a second pass over what it didn't reach, in the same review. A +//! finding a later review raises on lines unchanged since the previous one +//! never blocks: it is a note that says why (that review missed it, or the +//! check that found it started after it). On CoderHelm's own pull request +//! it is still sent to the coder in this round's work, apart from what +//! holds. A miss is recorded as one (`rewards::record_missed`, the review +//! lessons' raise-early lesson); a new check's finding is not. + +use crate::passes::minimal_change::{Kind, Widening}; +use crate::passes::review_agent::{self, Finding}; +use crate::passes::review_one_verdict as one; +use crate::passes::review_policy::{hold_late_blockers, Round, UpFront, LATE_NOTE, NEW_CHECK_NOTE}; +use crate::passes::review_rules::wider_findings; +use std::collections::{HashMap, HashSet}; + +const FILTERS: &str = "apps/web/src/utils/filterMaps.ts"; +const TEST: &str = "apps/web/src/test/components/filter-nav-sport-grid.test.tsx"; + +fn the_two() -> Vec { + wider_findings(&[ + Widening { + kind: Kind::Parallel, + path: FILTERS.into(), + what: "`dedupeSportOptionsBySlug` next to the existing `dedupeSportsBySlug`".into(), + }, + Widening { + kind: Kind::TestSize, + path: TEST.into(), + what: "236 added lines against 41 lines of changed code".into(), + }, + ]) +} + +/// Round 4 changed only `FilterNav.tsx`; the two findings sit in files the +/// rounds since the previous review never touched. +fn changed_since_previous() -> HashMap> { + [( + "apps/web/src/components/blocks/FilterNav.tsx".to_string(), + HashSet::from([88, 89, 90]), + )] + .into() +} + +fn round4() -> Round { + Round { + number: 4, + previous_head: Some("395769a".into()), + } +} + +/// The previous review ran before the checks did: the findings are notes +/// saying so, and no miss is recorded. +#[test] +fn a_check_newer_than_the_previous_review_is_not_a_miss_and_never_blocks() { + let mut findings = the_two(); + assert!(findings.iter().all(Finding::holds_merge)); + let changed = changed_since_previous(); + let r = round4(); + let late = hold_late_blockers( + &mut findings, + &UpFront { + round: &r, + changed_since_previous: Some(&changed), + earlier_threads: &[], + person_spoke: false, + previous_review_at: "2026-11-16T23:21:58Z", + }, + ); + assert!(findings.is_empty()); + assert_eq!(late.held.len(), 2); + assert!(late.held.iter().all(|f| !f.holds_merge())); + assert!(late + .held + .iter() + .all(|f| f.note_only.as_deref() == Some(NEW_CHECK_NOTE))); + assert!(late.missed.is_empty()); + assert!(!late.self_lesson); + let md = one::late_markdown(&late.held); + assert!(md.contains("found by a check that started running after it")); + assert!(!md.contains("should have been raised")); +} + +/// The previous review ran with the checks: a finding raised now on lines +/// it read is its miss, a note here, recorded, and still the coder's work on +/// CoderHelm's own pull request. +#[test] +fn a_finding_the_previous_review_missed_is_a_recorded_note_and_this_rounds_work() { + let mut findings = the_two(); + let changed = changed_since_previous(); + let r = round4(); + let late = hold_late_blockers( + &mut findings, + &UpFront { + round: &r, + changed_since_previous: Some(&changed), + earlier_threads: &[], + person_spoke: false, + previous_review_at: "2026-11-18T10:00:00Z", + }, + ); + assert_eq!(late.missed.len(), 2); + assert!(late.self_lesson); + assert!(late + .held + .iter() + .all(|f| f.note_only.as_deref() == Some(LATE_NOTE) && !f.holds_merge())); + let work = one::late_lines(&late.held); + assert_eq!(work.len(), 2); + assert!(work.iter().all(|w| w.contains(one::LATE_MARK))); + // The note says the previous review missed it, never that it holds. + let md = one::late_markdown(&late.held); + assert!(md.contains("which missed them")); + // A miss weighs on the reviewer's score. + assert!( + common::rewards::score::default_weight(common::rewards::RewardKind::FindingMissed) < 0.0 + ); +} + +/// Round 1 has no previous review: nothing is held back, everything the +/// checks find blocks there. +#[test] +fn the_first_review_holds_back_nothing() { + let mut findings = the_two(); + let r = Round { + number: 1, + previous_head: None, + }; + let late = hold_late_blockers( + &mut findings, + &UpFront { + round: &r, + changed_since_previous: None, + earlier_threads: &[], + person_spoke: false, + previous_review_at: "", + }, + ); + assert!(late.held.is_empty()); + assert_eq!(findings.len(), 2); +} + +/// A diff over its room keeps every file, and names those it cut. +#[test] +fn a_long_diff_keeps_every_file() { + let big = "+x\n".repeat(30_000); + let files: Vec = (0..5) + .map(|i| { + serde_json::json!({ + "filename": format!("src/f{i}.ts"), + "status": "modified", + "additions": 1, + "deletions": 0, + "patch": if i == 2 { "+small change".to_string() } else { big.clone() }, + }) + }) + .collect(); + let compare = serde_json::json!({ "files": files }); + let d = review_agent::format_diff(&compare, 40_000); + assert!(d.len() <= 44_000, "{}", d.len()); + for i in 0..5 { + assert!(d.contains(&format!("### src/f{i}.ts")), "f{i} dropped"); + } + assert!(d.contains("+small change")); + assert!(d.contains("Read each of these at the PR head with read_file")); + assert!(d.contains("- `src/f0.ts`") && !d.contains("- `src/f2.ts`")); + // A diff that fits is unchanged. + let small = serde_json::json!({"files": [{"filename": "a.ts", "status": "added", "additions": 1, "deletions": 0, "patch": "+a"}]}); + assert_eq!( + review_agent::format_diff(&small, 40_000), + "\n### a.ts (added, +1/-0)\n+a\n" + ); +} + +/// A review that ran out of tool steps goes on over what it didn't read, +/// and the two passes are one answer. +#[test] +fn a_review_cut_by_its_steps_goes_on_in_a_second_pass() { + let messages = vec![ + ( + "assistant".to_string(), + vec![ + serde_json::json!({"type": "tool_use", "name": "read_file", "input": {"path": FILTERS}}), + ], + ), + ( + "user".to_string(), + vec![ + serde_json::json!({"type": "text", "text": crate::agent::anthropic::TOOLS_OFF_NOTE}), + ], + ), + ]; + assert!(review_agent::ran_out_of_steps(&messages)); + assert!(!review_agent::ran_out_of_steps(&messages[..1])); + assert_eq!(review_agent::opened_files(&messages), vec![FILTERS]); + let first: review_agent::ReviewOutput = serde_json::from_value(serde_json::json!({ + "summary": "First pass.", + "findings": [{"file": FILTERS, "line": 3, "title": "Dropdown lists one sport twice", "body": "b"}] + })) + .unwrap(); + let prompt = review_agent::continue_prompt("PR: x", &first, &[FILTERS.to_string()]); + assert!(prompt.contains("ran out of tool")); + assert!(prompt.contains("Dropdown lists one sport twice")); + let second: review_agent::ReviewOutput = serde_json::from_value(serde_json::json!({ + "summary": "Second pass.", + "findings": [ + {"file": FILTERS, "line": 3, "title": "Dropdown lists one sport twice", "body": "b"}, + {"file": TEST, "line": 9, "title": "Test asserts the old order", "body": "b"} + ] + })) + .unwrap(); + let merged = review_agent::merge_review(first, second); + assert_eq!(merged.findings.len(), 2); + assert_eq!(merged.summary, "First pass. Second pass."); +} + +/// The checks with no model run on every review, whether or not the +/// tree could be read, and a miss is recorded where it is found. +#[test] +fn every_check_runs_on_every_review_and_a_miss_is_recorded() { + let src = include_str!("../review_pr.rs"); + assert!( + !src.contains("if let Ok(tree) = github\n .get_tree("), + "the checks with no model are skipped when the tree can't be read" + ); + let tree = src.find("Could not read the head's tree").expect("tree"); + let smallest = src[tree..] + .find("smallest_change_gaps(") + .expect("smallest-change checks run after the tree read"); + assert!(smallest > 0); + // Nothing gates them on the round. + let around = &src[tree.saturating_sub(800)..tree + smallest]; + assert!(!around.contains("review_round.number")); + assert!(!around.contains("since_review")); + assert!(src.contains("super::rewards::record_missed(")); + assert!(src.contains("previous_review_at: &previous_review_at")); + let agent = include_str!("../review_agent.rs"); + assert!(agent.contains("if !ran_out_of_steps(&messages)")); +} diff --git a/services/worker/src/passes/incidents/oy_review_fix_loop_ends.rs b/services/worker/src/passes/incidents/oy_review_fix_loop_ends.rs new file mode 100644 index 000000000..62e08e7d2 --- /dev/null +++ b/services/worker/src/passes/incidents/oy_review_fix_loop_ends.rs @@ -0,0 +1,168 @@ +//! oy. A data-pipeline ticket's run fixed the sport a few camps land on. +//! After a merge of the base branch, each round of CoderHelm's own review +//! raised something new: round 2 a model finding, round 3 "A test out of +//! proportion to the change", round 4 "A parallel structure next to an +//! existing one" in the shared helpers, which named as new a function the +//! main branch had had for months (`get_sport_name_to_id_map`: the branch +//! only added a parameter to it; the real new builder was +//! `build_sport_name_map`). Every one held the merge, so the run went +//! review, fix, review every ten minutes, nine fix rounds and past its +//! spend ceiling. Meanwhile the review on the pull request stayed on an +//! old head: rounds driven by the run's own review pass never asked the PR +//! reviewer, and a review of CoderHelm's own push with the same verdict and +//! no new finding posted nothing. A person had to type "re-review". +//! +//! Guarantees: +//! - The parallel-structure check reads both sides against the base: a +//! definition the base already has is never new (a changed signature +//! shows as removed and added), and "existing" means on the base. +//! - After the first review, the smallest-change checks a reason may keep +//! (parallel structure, test size, log level, reporting) are notes, and a +//! finding on lines unchanged since the previous review is a note. +//! - Late notes ride along with a round that has work that holds; on their +//! own they start no round, so the run ends once only notes are left. +//! - Every head the run pushes gets the PR reviewer's review posted, news +//! or not. + +use crate::passes::minimal_change::{parallel_structures, Kind, Widening}; +use crate::passes::review_one_verdict as one; +use crate::passes::review_policy::{hold_late_blockers, Round, UpFront, ADVISORY_LATE_NOTE}; +use crate::passes::review_rules::wider_findings; +use std::collections::{HashMap, HashSet}; + +const COMMON: &str = "dags/utils/schedule_common.py"; + +/// The helpers file on the base branch. +const BASE: &str = "def get_sport_id_map(conn):\n return {}\n\n\ +def get_sport_name_to_id_map(conn):\n return {}\n\n\ +def extract_sport_from_class_name(name):\n return None\n"; + +/// The branch: a parameter added to the existing lookup, and a new builder. +const PATCH: &str = "@@ -4,5 +4,12 @@\n\ +-def get_sport_name_to_id_map(conn):\n\ ++def get_sport_name_to_id_map(conn, include_inactive=False):\n\ + return {}\n\ ++\n\ ++def build_sport_name_map(rows):\n\ ++ return {r[0]: r[1] for r in rows}\n"; + +#[test] +fn a_function_on_the_base_is_never_called_new() { + let found = parallel_structures( + &[(COMMON.into(), "modified".into(), PATCH.into())], + &[(COMMON.into(), BASE.into())], + ); + assert!( + !found + .iter() + .any(|w| w.what.starts_with("`get_sport_name_to_id_map` next to")), + "{found:?}" + ); + // What the branch really added is still read. + assert!( + found + .iter() + .all(|w| w.what.starts_with("`build_sport_name_map`")), + "{found:?}" + ); +} + +fn changed() -> HashMap> { + // The rounds since the previous review touched both files. + [ + (COMMON.to_string(), HashSet::from([4u64, 9])), + ( + "tests/test_exerp_camp_sport.py".to_string(), + HashSet::from([12u64]), + ), + ] + .into() +} + +#[test] +fn smallest_change_advice_after_the_first_review_never_holds_and_starts_no_round() { + for (n, kind, path) in [ + (3usize, Kind::TestSize, "tests/test_exerp_camp_sport.py"), + (4, Kind::Parallel, COMMON), + ] { + let mut findings = wider_findings(&[Widening { + kind, + path: path.into(), + what: "x".into(), + }]); + assert!(findings[0].holds_merge()); + let c = changed(); + let r = Round { + number: n, + previous_head: Some("aaaaaaa".into()), + }; + let late = hold_late_blockers( + &mut findings, + &UpFront { + round: &r, + changed_since_previous: Some(&c), + earlier_threads: &[], + person_spoke: false, + previous_review_at: "2026-11-17T17:58:00Z", + }, + ); + assert!(findings.is_empty(), "round {n}"); + assert_eq!(late.held.len(), 1); + assert!(!late.held[0].holds_merge()); + assert_eq!(late.held[0].note_only.as_deref(), Some(ADVISORY_LATE_NOTE)); + // Advice, not a miss of the previous review. + assert!(late.missed.is_empty()); + assert!(one::late_markdown(&late.held).contains("Advice from the smallest-change checks")); + } + // The first review: they block, so the coder takes them in round one. + let mut findings = wider_findings(&[Widening { + kind: Kind::TestSize, + path: "tests/test_exerp_camp_sport.py".into(), + what: "x".into(), + }]); + let r1 = Round { + number: 1, + previous_head: None, + }; + let late = hold_late_blockers( + &mut findings, + &UpFront { + round: &r1, + changed_since_previous: None, + earlier_threads: &[], + person_spoke: false, + previous_review_at: "", + }, + ); + assert!(late.held.is_empty() && findings[0].holds_merge()); + // A replacing write blocks whenever it is raised: only advice turns + // into notes. + let replacing = &wider_findings(&[Widening { + kind: Kind::Replacing, + path: COMMON.into(), + what: "`DELETE FROM`".into(), + }])[0]; + assert!(!crate::passes::review_rules::advisory_check(replacing)); +} + +#[test] +fn every_pushed_head_gets_its_review_posted() { + use crate::passes::review_pr::own_head_is_new; + assert!(own_head_is_new(Some("aaaaaaa"), "bbbbbbb")); + assert!(own_head_is_new(None, "bbbbbbb")); + assert!(!own_head_is_new(Some("bbbbbbb"), "bbbbbbb")); + let review = include_str!("../review_pr.rs"); + assert!(review.contains("has_news: has_news || new_human_commit || new_own_head,")); + // The run asks the PR reviewer on every head, not only when its own + // review pass passed. + let resume = include_str!("../resume.rs"); + let ask = resume + .find("super::review_pr::review_for_run(") + .expect("asked"); + let before = &resume[ask.saturating_sub(1200)..ask]; + assert!(before.contains("let own_pass_passed = review_result.passed;")); + assert!(!before.trim_end().ends_with("if review_result.passed {")); + assert!(resume.contains("if own_pass_passed && rr.blocks() {")); + // Late notes alone write no work list, so no round starts on them. + assert!(review.contains("let own_open: Vec = if own_open.is_empty() {")); +} diff --git a/services/worker/src/passes/minimal_change.rs b/services/worker/src/passes/minimal_change.rs index 1b682c336..bd4e7b769 100644 --- a/services/worker/src/passes/minimal_change.rs +++ b/services/worker/src/passes/minimal_change.rs @@ -438,6 +438,12 @@ pub fn parallel_in_edit(path: &str, old: &str, new: &str) -> Vec<(Def, Def)> { /// The parallel structures a diff adds: new top-level definitions next to /// a similar existing one in the same file's base (`base`, by path) or its /// patch's context, or in another changed file's base. +/// +/// Both sides are checked against the base: a definition the base already +/// has is never new (a changed signature shows as removed and added), and +/// when the file's base was read, "existing" means on the base. A review +/// once called a function that had been on the main branch for months the +/// new one, beside the builder the branch had really added. pub fn parallel_structures(diff: &Diff, base: &[(String, String)]) -> Vec { let mut out = Vec::new(); for (path, status, patch) in diff { @@ -448,25 +454,35 @@ pub fn parallel_structures(diff: &Diff, base: &[(String, String)]) -> Vec = base + let added: Vec = lines_of(patch, '+') + .into_iter() + .filter_map(|l| top_level_def(l, path)) + .collect(); + let base_read = base.iter().any(|(p, _)| p == path); + let on_base: Vec = base .iter() .filter(|(p, _)| p == path) .flat_map(|(_, t)| defs(t, path)) .collect(); + let mut existing: Vec = on_base.clone(); existing.extend( context_of(patch) .into_iter() - .filter_map(|l| top_level_def(l, path)), + .filter_map(|l| top_level_def(l, path)) + .filter(|d| !base_read || on_base.iter().any(|b| b.name == d.name)), ); - existing.retain(|e| !removed.iter().any(|r| r.name == e.name)); - for d in lines_of(patch, '+') - .into_iter() - .filter_map(|l| top_level_def(l, path)) - { - if existing.iter().any(|e| e.name == d.name) { + // Removed and not added back: gone. Removed and added back: its + // signature changed, and it is still the existing one. + existing.retain(|e| { + !removed.iter().any(|r| r.name == e.name) || added.iter().any(|a| a.name == e.name) + }); + for d in &added { + let was_there = on_base.iter().any(|b| b.name == d.name) + || removed.iter().any(|r| r.name == d.name); + if was_there || existing.iter().any(|e| e.name == d.name) { continue; } - if let Some(e) = existing.iter().find(|e| parallels(&d, e)) { + if let Some(e) = existing.iter().find(|e| parallels(d, e)) { let what = format!("`{}` next to the existing `{}`", d.name, e.name); if !out.iter().any(|w: &Widening| w.what == what) { out.push(Widening { diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index a8b22d42f..7cb5384de 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1384,6 +1384,7 @@ pub(crate) mod review_fingerprint; pub mod review_fix; pub mod review_labels; pub mod review_lessons; +pub mod review_one_verdict; pub mod review_policy; #[cfg(test)] mod review_policy_eval; diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 8546d77cf..4452503f3 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -3509,7 +3509,14 @@ pub async fn run( // Findings of CoderHelm's own review the run must fix before the PR // is marked ready (`own_review`). let mut own_open: Vec = Vec::new(); - if review_result.passed { + // The PR reviewer reviews every head the run pushes, whatever the + // run's own review pass said: its posted review is what people see, + // and a fix round driven by the run's own pass once left the posted + // review on an old head for nine rounds, until a person typed + // "re-review". Its verdict decides the run only when the run's own + // pass passed. + let own_pass_passed = review_result.passed; + { let budget = std::time::Duration::from_secs(super::remaining_secs(&start).saturating_sub(150)); if let Some(rr) = super::review_pr::review_for_run( @@ -3566,7 +3573,7 @@ pub async fn run( return Ok(()); } } - if rr.blocks() { + if own_pass_passed && rr.blocks() { info!( run_id = msg.run_id, open = rr.open_findings.len(), diff --git a/services/worker/src/passes/review_agent.rs b/services/worker/src/passes/review_agent.rs index bc12fcadf..bf56a6c44 100644 --- a/services/worker/src/passes/review_agent.rs +++ b/services/worker/src/passes/review_agent.rs @@ -383,16 +383,20 @@ impl<'de> Deserialize<'de> for UnconfirmedFact { #[derive(Debug, Clone, Deserialize)] pub struct PriorStatus { pub index: usize, - /// "fixed" | "answered" | "accepted" | "open" + /// "fixed" | "answered" | "accepted" | "gone" | "open" #[serde(default)] pub status: String, } +/// A thread's status when the code it was about is no longer in the change. +pub const GONE: &str = "gone"; + impl PriorStatus { /// Nothing is left to do on the thread: the code fixed it, a person's - /// reply answered it, or the author accepted or decided on a suggestion. + /// reply answered it, the author accepted or decided on a suggestion, + /// or the code it was about is no longer in the change. pub fn is_settled(&self) -> bool { - ["fixed", "answered", "accepted"] + ["fixed", "answered", "accepted", GONE] .iter() .any(|s| self.status.eq_ignore_ascii_case(s)) } @@ -1636,21 +1640,77 @@ pub fn fold_inline_into_body(body: &str, inline: &[InlineComment]) -> String { } /// Build a bounded diff string for the prompt (per-file patch, head+tail capped). +/// +/// Every changed file is in it, whatever its size: a diff over `cap` keeps +/// each file's header and gives each patch a fair share of the room (a +/// small patch whole, the large ones cut in the middle), then names the +/// files it cut so the reviewer reads them before its verdict. Cutting the +/// middle of the whole diff once dropped the files in the middle from the +/// first review, and their findings came rounds later, on code that review +/// had been given. pub fn format_diff(compare: &serde_json::Value, cap: usize) -> String { - let mut diff = String::new(); - if let Some(files) = compare["files"].as_array() { - for f in files { + let files: Vec<(String, String, String)> = compare["files"] + .as_array() + .map(|a| a.as_slice()) + .unwrap_or(&[]) + .iter() + .map(|f| { let path = f["filename"].as_str().unwrap_or(""); let status = f["status"].as_str().unwrap_or(""); let adds = f["additions"].as_u64().unwrap_or(0); let dels = f["deletions"].as_u64().unwrap_or(0); let patch = f["patch"].as_str().unwrap_or("(no textual diff)"); - diff.push_str(&format!( - "\n### {path} ({status}, +{adds}/-{dels})\n{patch}\n" - )); + ( + path.to_string(), + format!("\n### {path} ({status}, +{adds}/-{dels})\n"), + patch.to_string(), + ) + }) + .collect(); + let whole: usize = files.iter().map(|(_, h, p)| h.len() + p.len() + 1).sum(); + if whole <= cap { + return files.iter().map(|(_, h, p)| format!("{h}{p}\n")).collect(); + } + // Room for the patches once every header and the closing note are in. + let headers: usize = files.iter().map(|(_, h, _)| h.len() + 1).sum(); + let note_room = 200 + files.iter().map(|(p, _, _)| p.len() + 6).sum::(); + let mut room = cap.saturating_sub(headers + note_room); + // Fair shares, smallest first: a patch under its share is kept whole and + // leaves the rest to the others. + let mut order: Vec = (0..files.len()).collect(); + order.sort_by_key(|&i| files[i].2.len()); + let mut share = vec![0usize; files.len()]; + for (n, &i) in order.iter().enumerate() { + let left = files.len() - n; + let fair = room / left.max(1); + share[i] = files[i].2.len().min(fair); + room -= share[i]; + } + let mut out = String::new(); + let mut cut: Vec<&str> = Vec::new(); + for (i, (path, header, patch)) in files.iter().enumerate() { + out.push_str(header); + if patch.len() <= share[i] { + out.push_str(patch); + } else { + out.push_str(&common::head_tail_str(patch, share[i].max(400))); + cut.push(path); + } + out.push('\n'); + } + if !cut.is_empty() { + out.push_str(&format!( + "\n(The diff is longer than this review's room, so the middle of {} patch{} was cut \ + above. Read each of these at the PR head with read_file before your verdict: every \ + finding belongs in this review, not a later one.)\n", + cut.len(), + if cut.len() == 1 { "" } else { "es" } + )); + for p in cut { + out.push_str(&format!("- `{p}`\n")); } } - common::head_tail_str(&diff, cap) + out } /// What the reviewer is told: its job, the rules a finding must meet, and the @@ -1744,7 +1804,7 @@ pub fn review_system_prompt( \"caused_by_diff\": , \"tracked\": , \"prompted_by_reply\": ,\n \ \"body\": \"why it's a problem, be specific\", \"suggestion\": \"optional exact replacement code for the anchored line(s)\"\n }}],\n \ \"unconfirmed_facts\": [{{\"fact\": \"...\", \"blocks\": , \"why\": \"one short sentence\"}}] (each fact about a system the repository doesn't own that the PR's OWN description or evidence says is unconfirmed, unverified, not measured or never read from a real payload, in a few words, copying a listed fact's text as given; `blocks` and `why` per UNCONFIRMED FACTS; empty when it says none),\n \ - \"prior\": [{{\"index\": , \"status\": \"fixed\" | \"answered\" | \"open\"}}] (one per earlier unresolved comment listed, if any),\n \ + \"prior\": [{{\"index\": , \"status\": \"fixed\" | \"answered\" | \"gone\" | \"open\"}}] (one per earlier unresolved comment listed, if any; \"gone\" when the code it was about is no longer in the change. A comment you call settled or no longer applying in the summary gets that status here: one verdict per comment),\n \ \"labels\": [{{\"name\": \"label\", \"reason\": \"changed file(s) that need it\"}}] (only if a PR-labels section is given),\n \ \"tests_note\": \"which tests will run and where, or why none are needed\" (only if a PR-labels section is given),\n \ \"change_of_mind\": \"one sentence: the new information that changed your verdict\" (only when your previous review of this same commit is listed and your verdict differs)\n}}\n\ @@ -1836,10 +1896,6 @@ pub async fn generate_review( diff, &format!("{graph_context}{prior_context}{live_context}{skills_context}"), ); - let mut messages = vec![( - "user".to_string(), - vec![json!({"type": "text", "text": prompt})], - )]; let executor = PrReviewToolExecutor { github, owner, @@ -1879,34 +1935,161 @@ pub async fn generate_review( tools.extend(s.tools()); s.offer(&tools); } - let reply = provider::converse( - state, - provider, - common::agent_policy::Agent::Reviewer, - provider.review_model_id(), - &system, - &mut messages, - &tools, - &executor, - usage, - llm::ConverseOptions { - max_turns: 30, - max_tokens: 8192, - deadline: None, - effort: None, - }, - observer, - None, - ) - .await; + // A review that runs out of tool steps is asked for its answer with the + // tools off, and that answer reads as a whole review: the files it + // hadn't reached came up rounds later, on code it had been given. Such a + // review goes on in a second pass over what it didn't reach, in this same + // review, and the two are one answer. + let mut first: Option = None; + let mut prompt_now = prompt; + let result = loop { + let mut messages = vec![( + "user".to_string(), + vec![json!({"type": "text", "text": prompt_now.clone()})], + )]; + let reply = provider::converse( + state, + provider, + common::agent_policy::Agent::Reviewer, + provider.review_model_id(), + &system, + &mut messages, + &tools, + &executor, + usage, + llm::ConverseOptions { + max_turns: REVIEW_MAX_TURNS, + max_tokens: 8192, + deadline: None, + effort: None, + }, + observer, + None, + ) + .await; + let out = match (reply, first.take()) { + (Ok(text), earlier) => match (parse_review(&text), earlier) { + (Ok(o), Some(e)) => break Ok(merge_review(e, o)), + (Ok(o), None) => o, + (Err(_), Some(e)) => break Ok(e), + (Err(why), None) => break Err(why), + }, + (Err(_), Some(e)) => break Ok(e), + (Err(e), None) => break Err(format!("the model call failed: {e}")), + }; + if !ran_out_of_steps(&messages) { + break Ok(out); + } + tracing::info!( + owner, + repo, + findings = out.findings.len(), + "The review ran out of tool steps: a second pass reviews what it didn't reach" + ); + prompt_now = continue_prompt(&prompt_now, &out, &opened_files(&messages)); + first = Some(out); + }; if let Some(s) = skills { s.drain_usage_into(usage); } + result +} + +/// Tool steps one review pass has. +pub const REVIEW_MAX_TURNS: usize = 30; + +/// The pass was asked for its answer with the tools off: it ran out of +/// steps before it was done. +pub fn ran_out_of_steps(messages: &[(String, Vec)]) -> bool { + messages.iter().any(|(role, blocks)| { + role == "user" + && blocks.iter().any(|b| { + b["text"] + .as_str() + .is_some_and(|t| t == crate::agent::anthropic::TOOLS_OFF_NOTE) + }) + }) +} + +/// The files a pass opened with its read tools. +pub fn opened_files(messages: &[(String, Vec)]) -> Vec { + let mut out: Vec = Vec::new(); + for (_, blocks) in messages { + for b in blocks { + if b["type"].as_str() != Some("tool_use") { + continue; + } + if !matches!(b["name"].as_str(), Some("read_file" | "read_file_lines")) { + continue; + } + if let Some(p) = b["input"]["path"].as_str() { + if !out.iter().any(|o| o == p) { + out.push(p.to_string()); + } + } + } + } + out +} + +/// The second pass's prompt: the review so far, and what it hadn't read. +pub fn continue_prompt(prompt: &str, so_far: &ReviewOutput, opened: &[String]) -> String { + let found: Vec = so_far + .findings + .iter() + .map(|f| format!("- `{}:{}` {}", f.file, f.line, one_line(&f.title))) + .collect(); + let read = if opened.is_empty() { + "none".to_string() + } else { + opened + .iter() + .map(|p| format!("`{p}`")) + .collect::>() + .join(", ") + }; + format!( + "{prompt}\n\n## This review goes on\nA first pass of this same review ran out of tool \ + steps before it finished. Files it opened: {read}. What it found (don't repeat these):\n{}\n\ + Finish the review now: read the changed files and the callers it didn't reach, and give \ + every finding it missed in `findings`. Every finding belongs in this review: none is \ + left for a later round. Answer in the same JSON.", + if found.is_empty() { + "- nothing yet".to_string() + } else { + found.join("\n") + } + ) +} - match reply { - Ok(text) => parse_review(&text), - Err(e) => Err(format!("the model call failed: {e}")), +/// The two passes of one review as one answer: the first pass's findings +/// and statuses, the second's added where they are new. +pub fn merge_review(mut first: ReviewOutput, second: ReviewOutput) -> ReviewOutput { + for f in second.findings { + let dup = first + .findings + .iter() + .any(|e| e.file == f.file && e.title.eq_ignore_ascii_case(&f.title)); + if !dup { + first.findings.push(f); + } + } + for p in second.prior { + if !first.prior.iter().any(|e| e.index == p.index) { + first.prior.push(p); + } + } + for u in second.unconfirmed_facts { + if !first.unconfirmed_facts.iter().any(|e| e.fact == u.fact) { + first.unconfirmed_facts.push(u); + } + } + if !second.summary.trim().is_empty() { + first.summary = format!("{} {}", first.summary.trim(), second.summary.trim()) + .trim() + .to_string(); } + first } /// The review in the model's final answer, or why there is none. An answer diff --git a/services/worker/src/passes/review_cases/policy/late_blocker_round_three.json b/services/worker/src/passes/review_cases/policy/late_blocker_round_three.json index 19b81f7d6..2bf421e1f 100644 --- a/services/worker/src/passes/review_cases/policy/late_blocker_round_three.json +++ b/services/worker/src/passes/review_cases/policy/late_blocker_round_three.json @@ -1,5 +1,5 @@ { - "description": "Round 1 requested changes on one line; the author fixed it. Round 2 raised a new blocker on a file the fix never touched, and round 3 another: both were on code already reviewed. They become notes, the PR is approved, and round 3 teaches the reviewer to raise blockers up front.", + "description": "Round 1 requested changes on one line; the author fixed it. Round 2 raised a new blocker on a file the fix never touched, and round 3 another: both were on code already reviewed. They become notes, the PR is approved, and each one teaches the reviewer to raise blockers up front.", "steps": [ {"push": {"head": "e1e1e1e"}}, {"review": {"trigger": "synchronize", "dedup_key": "head#e1e1e1e", @@ -22,9 +22,9 @@ "formal": [["e1e1e1e", "REQUEST_CHANGES"], ["e2e2e2e", "APPROVE"], ["e3e3e3e", "REQUEST_CHANGES"]], "lessons": ["raiseblockersearly"], "body_contains": [ - [1, "should have been raised then"], + [1, "my previous review missed it"], [2, "Off by one in the new loop"], - [2, "should have been raised then"] + [2, "my previous review missed it"] ] } } diff --git a/services/worker/src/passes/review_lessons.rs b/services/worker/src/passes/review_lessons.rs index 942586d72..8082d15eb 100644 --- a/services/worker/src/passes/review_lessons.rs +++ b/services/worker/src/passes/review_lessons.rs @@ -743,7 +743,7 @@ async fn learn( } /// The lesson a review keeps when it held back a blocker raised late -/// (round 3 or later, on code already reviewed): one fixed lesson per +/// (a later round, on code an earlier review already read): one fixed lesson per /// repository, counted again each time instead of stored twice. pub fn raise_early_plan( existing: &[ReviewLesson], diff --git a/services/worker/src/passes/review_one_verdict.rs b/services/worker/src/passes/review_one_verdict.rs new file mode 100644 index 000000000..5ee5afb9c --- /dev/null +++ b/services/worker/src/passes/review_one_verdict.rs @@ -0,0 +1,772 @@ +//! One verdict per finding. +//! +//! A review of a pull request listed a finding under "Holding the merge" +//! while the same review said it no longer applied. Another listed two +//! findings it had kept as notes ("on code unchanged since my previous +//! review... they should have been raised then") and, on CoderHelm's own +//! pull request, listed the same two under "Holding the merge" as work to +//! finish before ready. Each finding had two verdicts in one review. +//! +//! [`settle`] gives every finding one state before the body is written: +//! blocking, a note, settled (its thread resolved, or this review found it +//! fixed or answered), or no longer applying (the code it was about is no +//! longer in the change). "Holding the merge" is built only from what is +//! still blocking at the head with its thread open: +//! +//! - an earlier thread that is resolved, or that this review settled, never +//! holds, whatever kind of hold named it (an open thread, the earlier +//! review's kept items, CoderHelm's own open work); +//! - a finding held back as a note because it came late (on lines unchanged +//! since the previous review) never holds, on any pull request: on +//! CoderHelm's own it is still work for this round's fix, listed apart +//! ([`late_lines`]); +//! - an earlier thread or a kept item this review now calls a note is a +//! note, unless a required rule holds it (only a fix settles those); +//! - a sentence of the review's own summary saying a holding finding no +//! longer applies, or is fixed or settled, settles an earlier thread or a +//! kept item; any other such sentence is dropped, since the hold rests on +//! the head. +//! +//! [`check`] reads the final body and names every finding listed under +//! "Holding the merge" that the same body also calls a note, settled or no +//! longer applying. [`enforce`] runs it on every review before it is +//! posted: the contradicting text is removed and the miss logged. The +//! tests assemble bodies the way the review does and fail the build on any +//! contradiction. + +use super::review_agent::Finding; +use super::review_verdict::{HoldKind, Holding}; + +/// The one state a finding has in a review. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum State { + Blocking, + Note, + /// Its thread is resolved, or this review found it fixed or answered. + Settled, + /// The code it was about is no longer in the change. + NoLongerApplies, +} + +impl State { + pub fn words(self) -> &'static str { + match self { + State::Blocking => "blocking", + State::Note => "a note", + State::Settled => "settled", + State::NoLongerApplies => "no longer applies", + } + } +} + +/// Where a finding is and what it says: enough to tell one finding from +/// another however a list words it (`` `a.ts:3` Title ``, `` Title (`a.ts:3`) ``). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Key { + pub path: String, + pub line: u64, + pub words: Vec, +} + +const STOP: &[&str] = &[ + "this", "that", "with", "from", "when", "then", "than", "into", "still", "does", "doesn", + "have", "been", "were", "will", "only", "also", "they", "them", "their", "there", "which", + "what", "should", "would", "could", "earlier", "review", "finding", "note", "block", "blocks", + "merge", "applies", "apply", "longer", "settled", "fixed", "resolved", +]; + +fn words(text: &str) -> Vec { + let mut out: Vec = text + .to_lowercase() + .split(|c: char| !c.is_alphanumeric()) + .filter(|w| w.len() >= 4 && !STOP.contains(w)) + .map(str::to_string) + .collect(); + out.sort(); + out.dedup(); + out +} + +/// A backticked `path` or `path:line` in `text`, with where it sits. +fn located(text: &str) -> Option<(usize, usize, String, u64)> { + let mut from = 0; + while let Some(a) = text[from..].find('`') { + let a = from + a; + let b = a + 1 + text[a + 1..].find('`')?; + let inner = &text[a + 1..b]; + let looks_like_path = !inner.is_empty() + && !inner.contains(char::is_whitespace) + && (inner.contains('/') || inner.contains('.')); + if looks_like_path { + let (path, line) = match inner.rsplit_once(':') { + Some((p, l)) if l.chars().all(|c| c.is_ascii_digit()) && !l.is_empty() => { + (p.to_string(), l.parse().unwrap_or(0)) + } + _ => (inner.to_string(), 0), + }; + return Some((a, b + 1, path, line)); + } + from = b + 1; + } + None +} + +impl Key { + pub fn new(path: &str, line: u64, title: &str) -> Self { + Self { + path: path.trim().to_string(), + line, + words: words(title), + } + } + + pub fn of_finding(f: &Finding) -> Self { + Self::new(&f.file, f.line, &f.title) + } + + /// A finding line as the review and the description write one. + pub fn of_line(text: &str) -> Self { + let text = text.trim().trim_start_matches(['-', '*', ' ']); + match located(text) { + Some((a, b, path, line)) => { + let mut rest = format!("{}{}", &text[..a], &text[b..]); + rest = rest.replace("()", " "); + // What follows the title in parentheses is why it holds or + // how to test it, never the finding. + let title = rest + .find(" (") + .map_or(rest.as_str(), |i| &rest[..i]) + .to_string(); + Self::new(&path, line, &title) + } + None => Self::new("", 0, text), + } + } + + /// The same finding: the same file, and most of the smaller title's + /// words. A later review words it differently and its line moves. + pub fn same(&self, other: &Key) -> bool { + if !self.path.is_empty() && !other.path.is_empty() && self.path != other.path { + return false; + } + let (small, big) = if self.words.len() <= other.words.len() { + (&self.words, &other.words) + } else { + (&other.words, &self.words) + }; + if small.is_empty() { + return !self.path.is_empty() + && self.path == other.path + && self.line > 0 + && self.line == other.line; + } + let shared = small.iter().filter(|w| big.contains(w)).count(); + if self.path.is_empty() || other.path.is_empty() { + // Prose that names no file: most of the title, and two words + // at least, so a common word never matches alone. + shared * 3 >= small.len() * 2 && shared >= small.len().min(2) + } else { + shared * 2 >= small.len() + } + } +} + +/// One finding's state, for the log and the tests. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + pub name: String, + pub state: State, + pub why: String, +} + +/// What [`settle`] reads. +#[derive(Debug, Default)] +pub struct Inputs<'a> { + /// Everything named as holding the merge (`review_policy::named_holding`). + pub holding: Vec, + /// Earlier threads that are closed, with their state: resolved on + /// GitHub or settled by this review ([`State::Settled`]), or about code + /// no longer in the change ([`State::NoLongerApplies`]). + pub closed: &'a [(Key, State)], + /// Findings held back as notes because they came late. + pub late: &'a [Key], + /// This review's other notes. + pub notes: &'a [Key], + /// The review's own summary. + pub prose: &'a str, +} + +/// What [`settle`] decided. +#[derive(Debug, Default)] +pub struct Settled { + /// What still holds the merge: the only list "Holding the merge" is + /// written from. + pub holding: Vec, + /// Every finding that was named as holding, with its one state. + pub entries: Vec, + /// The summary with no sentence that contradicts a hold. + pub prose: String, +} + +/// Phrases that say a finding doesn't hold. +pub const NOT_HOLDING: &[&str] = &[ + "no longer applies", + "no longer apply", + "no longer holds", + "no longer relevant", + "no longer an issue", + "no longer a problem", + "doesn't apply anymore", + "does not apply anymore", + "is settled", + "was settled", + "is resolved", + "was resolved", + "already fixed", + "is fixed", + "was fixed", + "has been fixed", + "are fixed", + "were fixed", + "don't change the verdict", + "doesn't change the verdict", + "not a block", + "doesn't hold the merge", + "does not hold the merge", + "don't hold the merge", +]; + +fn says_not_holding(text: &str) -> Option { + let t = text.to_lowercase(); + let hit = NOT_HOLDING.iter().find(|p| t.contains(*p))?; + Some(if hit.starts_with("no longer") || hit.contains("anymore") { + State::NoLongerApplies + } else if hit.contains("verdict") || hit.contains("block") || hit.contains("hold") { + State::Note + } else { + State::Settled + }) +} + +/// The sentences of a paragraph, each with its end punctuation. +fn sentences(text: &str) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + let chars: Vec = text.chars().collect(); + for (i, c) in chars.iter().enumerate() { + cur.push(*c); + let end = + matches!(c, '.' | '!' | '?') && chars.get(i + 1).is_none_or(|n| n.is_whitespace()); + if end || *c == '\n' { + out.push(std::mem::take(&mut cur)); + } + } + if !cur.is_empty() { + out.push(cur); + } + out +} + +/// One state for every finding named as holding the merge. +pub fn settle(inputs: Inputs<'_>) -> Settled { + let mut out = Settled::default(); + let mut prose_drops: Vec = Vec::new(); + let said: Vec<(String, State)> = sentences(inputs.prose) + .into_iter() + .filter_map(|s| says_not_holding(&s).map(|st| (s, st))) + .collect(); + for h in inputs.holding { + let key = Key::of_line(&h.name); + let named = |kind: State, why: &str| Entry { + name: h.name.clone(), + state: kind, + why: why.to_string(), + }; + // A failed verification run is no finding: nothing settles it. + if h.kind == HoldKind::Verification { + out.entries + .push(named(State::Blocking, "the verification run failed")); + out.holding.push(h); + continue; + } + if out + .holding + .iter() + .any(|kept| Key::of_line(&kept.name).same(&key)) + { + // Named twice: listed once. + continue; + } + if let Some((_, st)) = inputs.closed.iter().find(|(k, _)| k.same(&key)) { + out.entries.push(named( + *st, + "its thread is resolved or this review settled it", + )); + continue; + } + if inputs.late.iter().any(|k| k.same(&key)) { + out.entries.push(named( + State::Note, + "raised late, on code unchanged since the previous review", + )); + continue; + } + let earlier = matches!(h.kind, HoldKind::EarlierThread | HoldKind::KeptFromEarlier); + if earlier && inputs.notes.iter().any(|k| k.same(&key)) { + out.entries.push(named( + State::Note, + "this review calls it a note at the head", + )); + continue; + } + let prose = said + .iter() + .find(|(s, _)| Key::of_line(s).same(&key) || mentions(s, &key)); + if let Some((sentence, st)) = prose { + if earlier { + out.entries + .push(named(*st, "this review's summary settles it")); + continue; + } + // The hold rests on the head (a finding of this review, a rule, + // CoderHelm's own open work): the sentence goes. + prose_drops.push(sentence.clone()); + } + out.entries + .push(named(State::Blocking, "still holds at the head")); + out.holding.push(h); + } + out.prose = sentences(inputs.prose) + .into_iter() + .filter(|s| !prose_drops.contains(s)) + .collect::() + .trim() + .to_string(); + out +} + +/// A sentence that names the finding's file (with or without its line) and +/// shares most of its words. +fn mentions(sentence: &str, key: &Key) -> bool { + if key.path.is_empty() || !sentence.contains(&key.path) { + return false; + } + let w = words(sentence); + if key.words.is_empty() { + return true; + } + let shared = key.words.iter().filter(|k| w.contains(k)).count(); + shared * 2 >= key.words.len() +} + +/// CoderHelm's own pull request: the findings it fixes in this round, as +/// the description lists them. Late ones are work too, sent in the same +/// round, and marked so nobody reads them as holding the pull request. +pub fn late_lines(late: &[Finding]) -> Vec { + late.iter() + .map(|f| { + let at = if f.line > 0 { + format!("`{}:{}`", f.file, f.line) + } else { + format!("`{}`", f.file) + }; + let title = f.title.split_whitespace().collect::>().join(" "); + format!("{title} ({at}) ({LATE_MARK})") + }) + .collect() +} + +/// How a late finding is marked in CoderHelm's own work list. +pub const LATE_MARK: &str = "missed by an earlier review: a note, fixed in this round"; + +/// The review's section for findings held back because they came late, +/// each group saying why: the previous review missed them, a check that +/// started after it found them, or a smallest-change check gave advice +/// after the first review. +pub fn late_markdown(late: &[Finding]) -> String { + use super::review_policy::{ADVISORY_LATE_NOTE, NEW_CHECK_NOTE}; + if late.is_empty() { + return String::new(); + } + let line = |f: &Finding| { + if f.line > 0 { + format!("- `{}:{}` {}\n", f.file, f.line, f.title) + } else { + format!("- `{}` {}\n", f.file, f.title) + } + }; + fn note(f: &Finding) -> &str { + f.note_only.as_deref().unwrap_or("") + } + let mut s = String::from(LATE_HEAD); + for (pick, why) in [ + ( + None, + "\nOn code that hasn't changed since my previous review, which missed them. They are \ + notes, not part of the verdict:\n", + ), + ( + Some(NEW_CHECK_NOTE), + "\nOn code that hasn't changed since my previous review, found by a check that \ + started running after it. They are notes, not part of the verdict:\n", + ), + ( + Some(ADVISORY_LATE_NOTE), + "\nAdvice from the smallest-change checks after the first review. They are notes, \ + not part of the verdict:\n", + ), + ] { + let group: Vec<&Finding> = late + .iter() + .filter(|f| match pick { + Some(n) => note(f) == n, + None => note(f) != NEW_CHECK_NOTE && note(f) != ADVISORY_LATE_NOTE, + }) + .collect(); + if group.is_empty() { + continue; + } + s.push_str(why); + for f in group { + s.push_str(&line(f)); + } + } + s +} + +/// The heading of [`late_markdown`]'s section. +pub const LATE_HEAD: &str = "\n\n#### Also worth a look\n"; + +/// The heading the verdict lists what holds the merge under +/// (`review_agent::verdict_heading`). +pub const HOLDING_HEAD: &str = "**Holding the merge:**"; + +/// A finding the body lists as holding the merge and also calls something +/// else. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Contradiction { + /// The line under "Holding the merge". + pub holding: String, + /// The text that says otherwise. + pub said: String, + pub state: State, +} + +/// The items under "Holding the merge", and the span of that list. +fn holding_list(body: &str) -> (Vec, Option<(usize, usize)>) { + let Some(at) = body.find(HOLDING_HEAD) else { + return (Vec::new(), None); + }; + let start = at + HOLDING_HEAD.len(); + let mut end = start; + let mut items = Vec::new(); + for line in body[start..].split_inclusive('\n') { + let t = line.trim(); + if t.is_empty() && items.is_empty() { + end += line.len(); + continue; + } + match t.strip_prefix("- ") { + Some(item) => { + items.push(item.trim().to_string()); + end += line.len(); + } + None => break, + } + } + (items, Some((start, end))) +} + +/// Every finding the body lists under "Holding the merge" that the same +/// body also calls a note, settled or no longer applying. +pub fn check(body: &str) -> Vec { + let (items, span) = holding_list(body); + let Some((start, end)) = span else { + return Vec::new(); + }; + let rest = format!("{}\n{}", &body[..start], &body[end..]); + let mut out = Vec::new(); + let mut in_late = false; + for line in rest.lines() { + let t = line.trim(); + if t.starts_with("####") || (t.starts_with("**") && t.ends_with("**")) { + in_late = t == LATE_HEAD.trim(); + } + // The verdict's own one-line reason repeats what holds. + if t.starts_with("_Why changes requested") || t.is_empty() { + continue; + } + let state = if in_late && t.starts_with("- ") { + Some(State::Note) + } else { + says_not_holding(t) + }; + let Some(state) = state else { + continue; + }; + for part in sentences(t) { + if !in_late && says_not_holding(&part).is_none() { + continue; + } + let said = Key::of_line(&part); + for item in &items { + let key = Key::of_line(item); + if (key.same(&said) || mentions(&part, &key)) + && !out.iter().any(|c: &Contradiction| c.holding == *item) + { + out.push(Contradiction { + holding: item.clone(), + said: part.trim().to_string(), + state, + }); + } + } + } + } + out +} + +/// The body with no finding given two verdicts: every sentence or note +/// line that contradicts a hold is removed, so the posted verdict and its +/// words agree. The contradictions found are returned for the log; a +/// review assembled by [`settle`] has none. +pub fn enforce(body: &str) -> (String, Vec) { + let found = check(body); + if found.is_empty() { + return (body.to_string(), found); + } + let (_, span) = holding_list(body); + let Some((start, end)) = span else { + return (body.to_string(), found); + }; + let mut rest_before = body[..start].to_string(); + let mut rest_after = body[end..].to_string(); + for c in &found { + for part in [&mut rest_before, &mut rest_after] { + if let Some(i) = part.find(&c.said) { + part.replace_range(i..i + c.said.len(), ""); + } + } + } + let fixed = format!("{rest_before}{}{rest_after}", &body[start..end]); + // An emptied bullet goes too. + let fixed = fixed + .lines() + .filter(|l| l.trim() != "-") + .collect::>() + .join("\n"); + (fixed, found) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::passes::review_verdict::{HoldKind as K, Holding, Verdict}; + use serde_json::json; + + fn finding(file: &str, line: u64, title: &str) -> Finding { + serde_json::from_value(json!({"file": file, "line": line, "title": title, "body": "b"})) + .unwrap() + } + + #[test] + fn keys_read_every_way_a_finding_is_written() { + let a = Key::of_line("`src/a.ts:12` Sport dropdown lists Multi-Sport twice"); + let b = Key::of_line("Sport dropdown lists Multi-Sport twice (`src/a.ts:14`)"); + let c = Key::of_line( + "- `src/a.ts:12` Sport dropdown lists Multi-Sport twice (required: tests with behavior changes)", + ); + assert_eq!(a.path, "src/a.ts"); + assert_eq!(a.line, 12); + assert!(a.same(&b) && a.same(&c) && b.same(&c)); + let other = Key::of_line("`src/b.ts:12` Sport dropdown lists Multi-Sport twice"); + assert!(!a.same(&other)); + let prose = Key::of_line("The sport dropdown listing Multi-Sport twice no longer applies."); + assert!(prose.same(&a)); + let unrelated = Key::of_line("The camp list no longer applies."); + assert!(!unrelated.same(&a)); + } + + #[test] + fn a_resolved_or_settled_thread_never_holds() { + let closed = [( + Key::of_line("Sport dropdown lists Multi-Sport twice (`src/a.ts:12`)"), + State::Settled, + )]; + let s = settle(Inputs { + holding: vec![ + Holding::new( + K::EarlierThread, + "Sport dropdown lists Multi-Sport twice (`src/a.ts:12`)", + ), + Holding::new( + K::OwnFinding, + "Sport dropdown can list Multi-Sport twice (`src/a.ts:15`)", + ), + Holding::new(K::Defect, "`src/b.ts:3` Null deref"), + ], + closed: &closed, + ..Default::default() + }); + assert_eq!(s.holding.len(), 1); + assert_eq!(s.holding[0].name, "`src/b.ts:3` Null deref"); + assert_eq!( + s.entries + .iter() + .filter(|e| e.state == State::Settled) + .count(), + 2 + ); + } + + #[test] + fn a_late_finding_is_a_note_and_never_holds() { + let late = [Key::of_finding(&finding( + "apps/web/src/utils/filterMaps.ts", + 0, + "A parallel structure next to an existing one", + ))]; + let s = settle(Inputs { + holding: vec![Holding::new( + K::OwnFinding, + "A parallel structure next to an existing one (`apps/web/src/utils/filterMaps.ts`)", + )], + late: &late, + ..Default::default() + }); + assert!(s.holding.is_empty()); + assert_eq!(s.entries[0].state, State::Note); + } + + #[test] + fn the_summary_settles_an_earlier_thread_and_never_contradicts_a_head_hold() { + let prose = "The earlier comment on `src/a.ts` about the duplicate sport option no \ + longer applies. The `src/b.ts` null deref was fixed. Tests pass."; + let s = settle(Inputs { + holding: vec![ + Holding::new( + K::EarlierThread, + "Duplicate sport option in the dropdown (`src/a.ts:12`)", + ), + Holding::new(K::Defect, "`src/b.ts:3` Null deref"), + ], + prose, + ..Default::default() + }); + assert_eq!(s.holding.len(), 1); + assert_eq!(s.holding[0].name, "`src/b.ts:3` Null deref"); + assert_eq!(s.entries[0].state, State::NoLongerApplies); + assert!(!s.prose.contains("was fixed"), "{}", s.prose); + assert!(s.prose.contains("Tests pass.")); + } + + #[test] + fn a_required_thread_holds_over_a_note_and_verification_always_holds() { + let notes = [Key::of_line("`src/a.ts:12` Missing test for the dedupe")]; + let s = settle(Inputs { + holding: vec![ + Holding::new(K::Required, "Missing test for the dedupe (`src/a.ts:12`)"), + Holding::new(K::Verification, "The verification run failed"), + ], + notes: ¬es, + prose: "The verification run failed was fixed.", + ..Default::default() + }); + assert_eq!(s.holding.len(), 2); + } + + #[test] + fn check_names_a_finding_with_two_verdicts_and_enforce_removes_the_other_words() { + let v = Verdict::from_holding(vec![ + Holding::new( + K::OwnFinding, + "A test out of proportion to the change (`a.test.ts`)", + ), + Holding::new(K::Defect, "`src/b.ts:3` Null deref"), + ]); + let mut body = crate::passes::review_agent::verdict_heading(&v, 1); + body.push_str("\n\n_Why changes requested: A test out of proportion to the change; `src/b.ts:3` Null deref._"); + body.push_str("\n\nThe `src/b.ts` null deref no longer applies: the guard is back."); + body.push_str(&late_markdown(&[{ + let mut f = finding("a.test.ts", 0, "A test out of proportion to the change"); + crate::passes::review_policy::demote(&mut f, crate::passes::review_policy::LATE_NOTE); + f + }])); + let found = check(&body); + assert_eq!(found.len(), 2, "{found:?}"); + let (fixed, _) = enforce(&body); + assert!(check(&fixed).is_empty(), "{fixed}"); + assert!(fixed.contains(HOLDING_HEAD)); + assert!(fixed.contains("- `src/b.ts:3` Null deref")); + } + + #[test] + fn a_body_with_one_verdict_per_finding_passes() { + let v = Verdict::from_holding(vec![Holding::new(K::Defect, "`src/b.ts:3` Null deref")]); + let mut body = crate::passes::review_agent::verdict_heading(&v, 1); + body.push_str("\n\nThe earlier dropdown comment is fixed. Checked the guard."); + body.push_str(&late_markdown(&[{ + let mut f = finding("a.test.ts", 0, "A test out of proportion to the change"); + crate::passes::review_policy::demote(&mut f, crate::passes::review_policy::LATE_NOTE); + f + }])); + assert!(check(&body).is_empty(), "{body}"); + assert_eq!(enforce(&body).0, body); + } + + #[test] + fn late_lines_are_marked_as_notes_for_the_round() { + let l = late_lines(&[finding( + "a.ts", + 4, + "A parallel structure next to an existing one", + )]); + assert_eq!( + l, + vec![format!( + "A parallel structure next to an existing one (`a.ts:4`) ({LATE_MARK})" + )] + ); + } + + /// Every check the review runs with no model says when it started, so + /// a finding it raises on code an earlier review read is told apart + /// from a miss of that review. + #[test] + fn every_check_without_a_model_says_when_it_started() { + use crate::passes::minimal_change::{Kind, Widening}; + for kind in [ + Kind::Parallel, + Kind::Replacing, + Kind::LogLevel, + Kind::Reporting, + Kind::TestSize, + Kind::InventedPayload, + ] { + let w = Widening { + kind, + path: "a.ts".into(), + what: "x".into(), + }; + let f = &crate::passes::review_rules::wider_findings(&[w])[0]; + assert!( + crate::passes::review_rules::check_started(f).is_some(), + "{kind:?} has no start in CHECKS_STARTED" + ); + } + let flip = crate::passes::minimal_change::VendorFlip { + path: "e2e/a.spec.ts".into(), + removed: "a".into(), + added: "b".into(), + criterion: "c".into(), + }; + let f = &crate::passes::review_rules::vendor_flip_findings(&[flip])[0]; + assert!(crate::passes::review_rules::check_started(f).is_some()); + for (_, since) in crate::passes::review_rules::CHECKS_STARTED { + assert!( + chrono::DateTime::parse_from_rfc3339(since).is_ok(), + "{since}" + ); + } + } +} diff --git a/services/worker/src/passes/review_policy.rs b/services/worker/src/passes/review_policy.rs index f289a78d8..093b8146d 100644 --- a/services/worker/src/passes/review_policy.rs +++ b/services/worker/src/passes/review_policy.rs @@ -19,8 +19,10 @@ //! failures the base branch has too are notes ([`apply_blocking_policy`]). //! 4. Blockers up front: after the first reviewed head, a new blocker may //! only sit on lines changed since the previous reviewed head (or be one -//! a person's reply made relevant); any other is a note, and from round 3 -//! on it is also a lesson for the reviewer ([`hold_late_blockers`]). +//! a person's reply made relevant); any other is a note on every pull +//! request. One the previous review missed (not one a newer check found) +//! is also a lesson and a recorded miss for the reviewer +//! ([`hold_late_blockers`]). use super::review_agent::{Evidence, Finding}; use super::review_fingerprint::{in_words, Changed}; @@ -399,6 +401,9 @@ pub struct UpFront<'a> { pub earlier_threads: &'a [(String, u64)], /// A person wrote something since the previous review. pub person_spoke: bool, + /// When the previous review ran (RFC 3339; empty when unknown): a check + /// that started after it couldn't have raised what it finds now. + pub previous_review_at: &'a str, } /// What rule 4 held back. @@ -406,22 +411,28 @@ pub struct UpFront<'a> { pub struct Late { /// New blockers on code already reviewed, now notes, out of `findings`. pub held: Vec, - /// From round 3: the reviewer should have raised them earlier, and - /// learns so. + /// Of `held`, those the previous review missed: its model read the same + /// lines, or one of its checks ran on them. Each is a reviewer miss the + /// review lessons and rewards learn from (`review_lessons`, + /// `rewards::record_missed`). + pub missed: Vec, + /// The reviewer missed something earlier and learns so. pub self_lesson: bool, } pub const LATE_NOTE: &str = - "On code unchanged since my previous review, so a note, not a block: it should have been raised then."; + "On code unchanged since my previous review, so a note, not a block: my previous review missed it."; + +/// [`LATE_NOTE`] for a finding of a check that started running after the +/// previous review (`review_rules::check_newer_than`): not a miss. +pub const NEW_CHECK_NOTE: &str = + "On code unchanged since my previous review, so a note, not a block: the check that found it started running after that review."; /// Rule 4. Every blocker belongs in the first review of the code it is /// about. After the first reviewed head, a new blocker on lines unchanged /// since the previous reviewed head is held back as a note, unless it repeats /// an earlier thread or a person's reply since made it relevant. pub fn hold_late_blockers(findings: &mut Vec, ctx: &UpFront<'_>) -> Late { - let Some(changed) = ctx.changed_since_previous else { - return Late::default(); - }; if ctx.round.number < 2 { return Late::default(); } @@ -430,26 +441,55 @@ pub fn hold_late_blockers(findings: &mut Vec, ctx: &UpFront<'_>) -> Lat .iter() .any(|(p, l)| *p == f.file && l.abs_diff(f.line) <= NEAR_LINES) }; - let (mut held, keep): (Vec, Vec) = - std::mem::take(findings).into_iter().partition(|f| { - f.holds_merge() - // A required rule, a failing check and an unproven critical - // path hold until the change meets them, raised late or not. - && super::review_rules::mandatory(f).is_none() + // On lines unchanged since the previous reviewed head: that review read + // them. + let on_old_lines = |f: &Finding| { + ctx.changed_since_previous.is_some_and(|changed| { + super::review_rules::mandatory(f).is_none() && !on_changed_lines(f, changed) && !earlier(f) && !(ctx.person_spoke && f.prompted_by_reply == Some(true)) - }); + }) + }; + let (mut held, keep): (Vec, Vec) = std::mem::take(findings) + .into_iter() + .partition(|f| f.holds_merge() && (on_old_lines(f) || after_first_round(f))); *findings = keep; + let mut missed = Vec::new(); for f in held.iter_mut() { - demote(f, LATE_NOTE); + if !on_old_lines(f) { + demote(f, ADVISORY_LATE_NOTE); + } else if super::review_rules::check_newer_than(f, ctx.previous_review_at) { + demote(f, NEW_CHECK_NOTE); + } else { + demote(f, LATE_NOTE); + missed.push(f.clone()); + } } Late { - self_lesson: !held.is_empty() && ctx.round.number >= 3, + self_lesson: !missed.is_empty(), + missed, held, } } +/// A finding of a smallest-change check the coder may keep with a reason +/// (a parallel structure, a test out of proportion, a log level, reporting) +/// first raised after the first review. Those checks read the whole change, +/// so each fix round can tip one over: on one pull request each round's +/// review raised a new one (a test out of proportion, then a parallel +/// structure), every one held the merge, and the run went review, fix, +/// review for nine rounds past its spend ceiling. After the first review +/// they are notes. +fn after_first_round(f: &Finding) -> bool { + super::review_rules::advisory_check(f) +} + +/// [`LATE_NOTE`] for an advisory smallest-change finding raised after the +/// first review ([`after_first_round`]). +pub const ADVISORY_LATE_NOTE: &str = + "A note, not a block: the smallest-change checks raise what blocks in the first review; after it, what they find is advice."; + /// The lesson a review that raised a blocker late keeps for the repository. pub const RAISE_EARLY_LESSON: &str = "Raise every blocking finding in the first review of the code \ @@ -982,6 +1022,7 @@ mod tests { changed_since_previous: Some(&changed), earlier_threads: &threads, person_spoke: true, + previous_review_at: "2026-11-16T23:21:58Z", }, ); assert_eq!( @@ -1005,10 +1046,14 @@ mod tests { changed_since_previous: Some(&changed), earlier_threads: &[], person_spoke: false, + previous_review_at: "", }, ); assert_eq!(late.held.len(), 1); - assert!(!late.self_lesson); + // Missed in round 1 and found in round 2: a miss the reviewer + // learns from, in any later round. + assert!(late.self_lesson); + assert_eq!(late.missed.len(), 1); let mut fs = vec![defect("b.rs", 5, "high", "bug")]; let late = hold_late_blockers( &mut fs, @@ -1017,6 +1062,7 @@ mod tests { changed_since_previous: None, earlier_threads: &[], person_spoke: false, + previous_review_at: "", }, ); assert!(late.held.is_empty() && fs.len() == 1); @@ -1032,6 +1078,7 @@ mod tests { changed_since_previous: Some(&changed), earlier_threads: &[], person_spoke: false, + previous_review_at: "", }, ); assert_eq!(late.held.len(), 1); diff --git a/services/worker/src/passes/review_policy_eval.rs b/services/worker/src/passes/review_policy_eval.rs index 81231875f..b713fd11b 100644 --- a/services/worker/src/passes/review_policy_eval.rs +++ b/services/worker/src/passes/review_policy_eval.rs @@ -290,6 +290,7 @@ impl Sim { changed_since_previous: changed.as_ref(), earlier_threads: &earlier, person_spoke: spoke.is_some(), + previous_review_at: "", }, ); if late.self_lesson { diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 5097a1e1d..cd714161f 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -3585,11 +3585,21 @@ async fn run_once( // A change a person sees, in a repository with an end-to-end suite, // carries a spec for it: a finding by rule, read from the paths and the // tree, whatever the model said. - if let Ok(tree) = github - .get_tree(&msg.repo_owner, &msg.repo_name, &head_sha) - .await + // Every check with no model runs on every review, the first one + // included: a tree that can't be read leaves those that need it without + // their answer, never the others without a run (a check held for a later + // round raises its finding on code an earlier review already read). { - let tree: Vec = tree.into_iter().map(|e| e.path).collect(); + let tree: Vec = match github + .get_tree(&msg.repo_owner, &msg.repo_name, &head_sha) + .await + { + Ok(t) => t.into_iter().map(|e| e.path).collect(), + Err(e) => { + warn!(pr = msg.pr_number, error = %e, "Could not read the head's tree: the checks still run without it"); + Vec::new() + } + }; if let Some(f) = super::review_rules::e2e_finding(&changed_list, &tree) { info!( pr = msg.pr_number, @@ -3714,6 +3724,7 @@ async fn run_once( changed_since_previous: changed_since_previous.as_ref(), earlier_threads: &earlier_threads, person_spoke: spoke_since_previous.is_some(), + previous_review_at: &previous_review_at, }, ); if !late.held.is_empty() { @@ -3721,8 +3732,19 @@ async fn run_once( pr = msg.pr_number, round = review_round.number, held = late.held.len(), + missed = late.missed.len(), "New blockers on code unchanged since the previous review kept as notes" ); + // Each one the previous review missed is that review's miss: the + // reviewer's rewards and examples learn from it. + super::rewards::record_missed( + state, + &msg.team_id, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + msg.pr_number, + &late.missed, + ) + .await; if late.self_lesson { super::review_lessons::learn_raise_early( state, @@ -3842,8 +3864,16 @@ async fn run_once( findings.retain(|f| f.holds_merge() || !super::own_review::about_description(f)); } } + // Findings raised late are notes on every pull request; on CoderHelm's + // own they are still work, fixed in this round with the rest, and + // listed apart so they never hold the merge (`review_one_verdict`). let mut own_open = if self_authored { - super::own_review::required(&findings, &held_late) + super::own_review::required(&findings, &[]) + } else { + Vec::new() + }; + let own_late = if self_authored { + super::review_one_verdict::late_lines(&held_late) } else { Vec::new() }; @@ -3888,15 +3918,47 @@ async fn run_once( }) .map(|t| (t.path.clone(), t.line, t.body.clone())) .collect(); - let mut final_verdict = - super::review_verdict::Verdict::from_holding(super::review_policy::named_holding( + // One state per finding before anything is written: a thread that is + // resolved, settled by this review or about code no longer in the + // change, a finding raised late, and an earlier hold this review calls a + // note never hold the merge (`review_one_verdict`). + let closed = closed_threads(&bot_threads, &fixed_threads, &output.prior, &changed_list); + own_open.retain(|o| { + let k = super::review_one_verdict::Key::of_line(o); + !closed.iter().any(|(c, _)| c.same(&k)) + }); + let late_keys: Vec = held_late + .iter() + .map(super::review_one_verdict::Key::of_finding) + .collect(); + let note_keys: Vec = findings + .iter() + .filter(|f| !f.holds_merge()) + .map(super::review_one_verdict::Key::of_finding) + .collect(); + let one = super::review_one_verdict::settle(super::review_one_verdict::Inputs { + holding: super::review_policy::named_holding( &findings, &open_holding, &unconfirmed, verify_failed, &own_open, &stable.kept, - )); + ), + closed: &closed, + late: &late_keys, + notes: ¬e_keys, + prose: &output.summary, + }); + for e in one + .entries + .iter() + .filter(|e| e.state != super::review_one_verdict::State::Blocking) + { + info!(pr = msg.pr_number, finding = %e.name, state = e.state.words(), why = %e.why, "Named as holding the merge, but not blocking at the head: left out"); + } + output.summary = one.prose; + let mut final_verdict = super::review_verdict::Verdict::from_holding(one.holding); // A request for changes on someone's PR is a costly decision: the stop // judge sees the whole picture and either holds on a named correctness, // security or data-loss problem, or the review approves with the @@ -4013,6 +4075,14 @@ async fn run_once( } // The description this review leaves: CoderHelm's own PR gets its open // findings written into it. + // Late notes ride along with a round that has work that holds; on their + // own they start no round, so a run whose findings left are only notes + // ends. The verdict above was made without them. + let own_open: Vec = if own_open.is_empty() { + own_open + } else { + own_open.into_iter().chain(own_late).collect() + }; let mut description_after = pr_body.to_string(); if self_authored { let section = super::own_review::section(&own_open); @@ -4171,12 +4241,7 @@ async fn run_once( postable.unanchored_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"); - for f in &held_late { - full_body.push_str(&format!("- `{}:{}` {}\n", f.file, f.line, f.title)); - } - } + full_body.push_str(&super::review_one_verdict::late_markdown(&held_late)); full_body.push_str(&super::review_labels::markdown( labels_live, &label_decision, @@ -4216,6 +4281,14 @@ async fn run_once( &msg.repo_name, msg.pr_number, )); + // The last word before posting: no finding listed as holding the merge + // is also called a note, settled or no longer applying in the same + // review. + let (one_body, two_verdicts) = super::review_one_verdict::enforce(&full_body); + if !two_verdicts.is_empty() { + warn!(pr = msg.pr_number, contradictions = ?two_verdicts, "A finding had two verdicts in the review body; the words that contradict the hold were removed"); + } + let full_body = one_body; // 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 @@ -4274,6 +4347,12 @@ async fn run_once( // A push and a re-review ask for the same commit run two reviews; the // first to finish speaks for both. // A person's ask is never silenced by it: it always gets its own answer. + // CoderHelm's own pull request: every head its fix rounds push gets its + // own review posted, news or not, so the review on the pull request is + // always of the head (the older ones collapse under it). A person never + // has to ask for a re-review to see where it stands. + let new_own_head = + self_authored && own_head_is_new(prev.as_ref().map(|p| p.head_sha.as_str()), &head_sha); let already_answered = !explicit && prev .as_ref() @@ -4281,7 +4360,7 @@ async fn run_once( let decision = super::review_verdict::decide( super::review_verdict::Input::Review { verdict, - has_news: has_news || new_human_commit, + has_news: has_news || new_human_commit || new_own_head, explicit, already_answered, }, @@ -4659,6 +4738,12 @@ async fn run_once( }) } +/// On CoderHelm's own pull request, the head reviewed now isn't the one its +/// last review was of (or there was none): the review is posted. +pub(crate) fn own_head_is_new(last_reviewed: Option<&str>, head: &str) -> bool { + !head.is_empty() && last_reviewed != Some(head) +} + /// The trigger of a review a ticket run asks for on its own PR before it /// completes (see [`review_for_run`]). pub(crate) const TRIGGER_RUN: &str = "run"; @@ -6424,6 +6509,48 @@ fn settled_prior_threads<'a>( .collect() } +/// CoderHelm's earlier threads that hold nothing at this head, each with +/// its state: resolved on GitHub or settled by this review (settled), or +/// about code no longer in the change (the review called it gone, or the +/// pull request no longer changes its file). `changed` is the PR's changed +/// files at the head. +pub(crate) fn closed_threads( + threads: &[crate::clients::github::BotReviewThread], + settled_now: &[&crate::clients::github::BotReviewThread], + statuses: &[review_agent::PriorStatus], + changed: &[String], +) -> Vec<( + super::review_one_verdict::Key, + super::review_one_verdict::State, +)> { + use super::review_one_verdict::{Key, State}; + let gone_now: Vec<&str> = { + let open: Vec<&crate::clients::github::BotReviewThread> = + threads.iter().filter(|t| !t.resolved).collect(); + statuses + .iter() + .filter(|s| s.status.eq_ignore_ascii_case(review_agent::GONE)) + .filter_map(|s| open.get(s.index).map(|t| t.id.as_str())) + .collect() + }; + threads + .iter() + .filter_map(|t| { + let key = Key::of_line(&super::own_review::thread_line(&t.path, t.line, &t.body)); + let state = if gone_now.contains(&t.id.as_str()) + || (!t.path.is_empty() && !changed.contains(&t.path)) + { + State::NoLongerApplies + } else if t.resolved || settled_now.iter().any(|s| s.id == t.id) { + State::Settled + } else { + return None; + }; + Some((key, state)) + }) + .collect() +} + /// What the stop judge sees for a proposed request for changes: the PR's /// title and description, the files it changes, every finding as evidence /// (checked when it blocks and traces its mechanism), the verification run, diff --git a/services/worker/src/passes/review_rules.rs b/services/worker/src/passes/review_rules.rs index 4248bcbd0..fba1e65e6 100644 --- a/services/worker/src/passes/review_rules.rs +++ b/services/worker/src/passes/review_rules.rs @@ -122,6 +122,71 @@ pub fn wider_findings(found: &[super::minimal_change::Widening]) -> Vec .collect() } +/// When each check the review runs with no model started running (the +/// merge of the change that added it), by the title its findings carry. +/// A finding such a check raises on code an earlier review read is new to +/// the review because the check is, not because that review missed it +/// ([`check_started`]). Add a row with every new check. +pub const CHECKS_STARTED: &[(&str, &str)] = &[ + ( + "A parallel structure next to an existing one", + "2026-11-17T14:31:17Z", + ), + ( + "Deletes or overwrites where the code only added", + "2026-11-17T14:31:17Z", + ), + ("A log level changed", "2026-11-17T14:31:17Z"), + ( + "Reporting the ticket doesn't ask for", + "2026-11-17T14:31:17Z", + ), + ( + "A test out of proportion to the change", + "2026-11-17T14:31:17Z", + ), + ("A test payload nobody observed", "2026-11-17T14:31:17Z"), + ( + "A test changed to the outside page's behaviour against a criterion", + "2026-11-17T14:31:17Z", + ), + ( + "No end-to-end spec for a change a person sees", + "2026-11-17T03:33:40Z", + ), +]; + +/// When the check that raised `f` started running, for a finding of a +/// check with no model; `None` for the model's own findings. +pub fn check_started(f: &Finding) -> Option<&'static str> { + CHECKS_STARTED + .iter() + .find(|(title, _)| f.title == *title) + .map(|(_, since)| *since) +} + +/// A finding of a smallest-change check that a reason in the coder's notes +/// may keep (`minimal_change::Widening::excusable`): advice once the first +/// review has run (`review_policy::hold_late_blockers`). +pub fn advisory_check(f: &Finding) -> bool { + check_started(f).is_some() && f.required.is_none() +} + +/// Whether the check behind `f` started after `previous_review_at` (an +/// RFC 3339 time): the earlier review could not have raised it. +pub fn check_newer_than(f: &Finding, previous_review_at: &str) -> bool { + let Some(since) = check_started(f) else { + return false; + }; + match ( + chrono::DateTime::parse_from_rfc3339(since), + chrono::DateTime::parse_from_rfc3339(previous_review_at), + ) { + (Ok(s), Ok(p)) => s > p, + _ => false, + } +} + /// The review's findings for test assertions changed to match another /// company's page while an acceptance criterion says otherwise: the /// product changes first. @@ -693,10 +758,12 @@ pub fn mandatory_label(f: &Finding) -> Option { /// thread for a required rule is settled only by a fix: an answer that /// explains why the test is missing leaves the rule broken. pub fn settles(thread_body: &str, status: &str) -> bool { + let gone = super::review_agent::GONE; if thread_body.contains(REQUIRED_MARK) { - status.eq_ignore_ascii_case("fixed") + // Code no longer in the change breaks no rule either. + status.eq_ignore_ascii_case("fixed") || status.eq_ignore_ascii_case(gone) } else { - ["fixed", "answered", "accepted"] + ["fixed", "answered", "accepted", gone] .iter() .any(|s| status.eq_ignore_ascii_case(s)) } diff --git a/services/worker/src/passes/rewards.rs b/services/worker/src/passes/rewards.rs index 7c701e3d3..0cf6d3454 100644 --- a/services/worker/src/passes/rewards.rs +++ b/services/worker/src/passes/rewards.rs @@ -811,6 +811,63 @@ pub async fn record_dismissed( } } +/// Records each finding a review raised late, on lines an earlier review of +/// the same pull request had read, as that review's miss +/// (`review_policy::Late::missed`): the reviewer's score drops, and the +/// finding is kept as an example of what a first review must raise. +pub async fn record_missed( + state: &WorkerState, + team_id: &str, + repo: &str, + pr: u64, + missed: &[Finding], +) { + if missed.is_empty() { + return; + } + // The earlier review that missed it: this one isn't recorded yet. + let review = latest_review(state, team_id, repo, pr).await; + let at = chrono::Utc::now().to_rfc3339(); + let st = store(state); + let weights = st.weights(team_id).await; + for f in missed { + let dedup = common::review_supersede::finding_key(&f.file, &f.title); + let mut e = RewardEvent::new( + team_id, + RewardKind::FindingMissed, + rev::AGENT_REVIEWER, + &at, + &format!("finding_missed#{repo}#{pr}#{dedup}"), + ) + .with_repo(repo, pr) + .with_detail(&format!( + "{} (`{}`): raised late, on lines an earlier review had read", + f.title, f.file + )) + .with_source("worker:review_pr"); + e.category = f.category.trim().to_ascii_lowercase(); + credit(&mut e, &review); + match st.record(&e).await { + Ok(true) => { + let ex = Exemplar { + id: exemplars::id_for(repo, pr, &dedup), + repo: repo.to_string(), + kind: exemplars::KIND_FINDING.into(), + category: e.category.clone(), + area: rev::file_area(&f.file), + pr, + reason: exemplars::finding_reason(RewardKind::FindingMissed), + ..Default::default() + } + .with_text(&f.title, common::truncate_str(&f.body, 4000)); + add_example(state, team_id, ex, score::score(&e, &weights)).await; + } + Ok(false) => {} + Err(err) => warn!(error = %err, "Could not record the missed review comment"), + } + } +} + // ── What the agents are given ───────────────────────────────────────── /// What the reviewer is given for one review. From cf3f35e54c8d1750cce7b0314282b9723abf48c0 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 17 Nov 2026 15:30:12 -0500 Subject: [PATCH 2/2] The reviewer converges: only actionable findings block, and an approval follows proven criteria A pull request's fix was right by its third commit, with CI and the preview's end-to-end run green, and the review requested changes for six more rounds on two generic findings. review_discipline::judge runs on every review before the verdict: - a blocking finding names its file, its line and what it conflicts with or asks for (smallest-change findings are anchored on their line); - a generic finding raised before on another file doesn't move; - a finding that asks the opposite of an earlier request is a note; - a finding CoderHelm's own rounds deferred holds only with new code; - a person's answer on the PR or the ticket decides scope; - with each criterion proven both ways (the run's e2e proofs) and CI green, what isn't a shown defect is a follow-up on an approval. A deferred finding's thread no longer holds the merge. Incident oz replays the whole sequence. --- docs/incidents/oz_reviewer_converges.md | 13 + .../incidents/bt_proof_answer_closes.rs | 19 +- .../passes/incidents/oz_reviewer_converges.rs | 236 ++++++++ services/worker/src/passes/mod.rs | 1 + .../worker/src/passes/review_discipline.rs | 505 ++++++++++++++++++ services/worker/src/passes/review_pr.rs | 108 +++- services/worker/src/passes/review_rules.rs | 39 ++ 7 files changed, 907 insertions(+), 14 deletions(-) create mode 100644 docs/incidents/oz_reviewer_converges.md create mode 100644 services/worker/src/passes/incidents/oz_reviewer_converges.rs create mode 100644 services/worker/src/passes/review_discipline.rs diff --git a/docs/incidents/oz_reviewer_converges.md b/docs/incidents/oz_reviewer_converges.md new file mode 100644 index 000000000..199b361cc --- /dev/null +++ b/docs/incidents/oz_reviewer_converges.md @@ -0,0 +1,13 @@ +# oz. `oz_reviewer_converges` + +**What happened:** The fix on the pull request of `ow` and `ox` was right by its third commit. CI and the preview's end-to-end run were green, and a person's product answers were built. The review still requested changes for six more rounds on two generic findings. "A parallel structure next to an existing one" never named the function it duplicated. "A test out of proportion to the change" moved from one test file to the next as each was trimmed, and landed on a test whose cases the review had asked to restore. CoderHelm's own fix rounds deferred both as making no progress, and the review kept blocking. A person had answered that the path pages should cover both rows; the run reverted that work as out of scope, and a later review called it missing. + +**The guarantee:** On every review, before the verdict: +- a blocking finding names its file, its line, and what it conflicts with or asks for; +- a generic finding doesn't move to another file; +- a finding never asks the opposite of an earlier request; +- a finding CoderHelm's own rounds deferred holds no more unless new code gives it new evidence; +- a person's answer decides scope; +- once each ticket criterion is proven both ways with CI green, whatever is left that isn't a shown defect is a follow-up note on an approval. + +**Where it's enforced:** `passes::review_discipline` (`judge` and its rules, `criteria_met` reading the run's two-way proofs), called by `review_pr` after the severity pass; `review_rules::anchor_line`; `review_pr::settle_own_findings` (a deferred finding's thread no longer holds). diff --git a/services/worker/src/passes/incidents/bt_proof_answer_closes.rs b/services/worker/src/passes/incidents/bt_proof_answer_closes.rs index ade6cb1ef..51b085974 100644 --- a/services/worker/src/passes/incidents/bt_proof_answer_closes.rs +++ b/services/worker/src/passes/incidents/bt_proof_answer_closes.rs @@ -237,8 +237,23 @@ fn what_is_left_after_every_approach_is_a_note_on_a_ready_pull_request() { let mut own_open = open.clone(); let settled = crate::passes::review_pr::settle_own_findings(&l, &mut findings, &mut own_open); assert!(own_open.is_empty()); - assert!(settled.is_empty(), "a note never clears the merge hold"); - assert!(findings[0].holds_merge()); + // Deferred after every approach with no progress, it holds the merge no + // more: its thread is settled, and the review makes the finding a + // follow-up unless new code gives it new evidence (`review_discipline`). + assert_eq!( + settled.len(), + 1, + "a deferred note no longer holds the merge" + ); + let deferred = crate::passes::review_discipline::deferred_items(&l); + crate::passes::review_discipline::judge( + &mut findings, + &crate::passes::review_discipline::Facts { + deferred: &deferred, + ..Default::default() + }, + ); + assert!(!findings[0].holds_merge()); // A completion on that verdict completes: nothing more to do. assert_eq!( ledger::completion(Some(("REQUEST_CHANGES", HEAD)), HEAD, &l), diff --git a/services/worker/src/passes/incidents/oz_reviewer_converges.rs b/services/worker/src/passes/incidents/oz_reviewer_converges.rs new file mode 100644 index 000000000..c266d15cb --- /dev/null +++ b/services/worker/src/passes/incidents/oz_reviewer_converges.rs @@ -0,0 +1,236 @@ +//! oz. The pull request of `ow` and `ox`, its whole review history. The +//! fix was right by its third commit; CI and the preview's end-to-end run +//! (71 of 71) were green, and a person's product answers were built. The +//! review still requested changes for six more rounds on two generic +//! findings. "A parallel structure next to an existing one" never named the +//! function it duplicated across three rewrites of the file. "A test out of +//! proportion to the change" moved from one test file to the next as each +//! was trimmed, and landed on a test whose selected-chip and row-order +//! cases the review had asked to restore. CoderHelm's own fix rounds +//! deferred both as making no progress, and the review kept blocking. A +//! person had answered that the `/classes/` path pages should cover +//! both rows; the run reverted that work as out of scope, and a later +//! review called it missing. +//! +//! Guarantee (`review_discipline::judge`, run on every review before the +//! verdict): a blocking finding names its file, its line and what it +//! conflicts with or asks for; a generic finding doesn't move to another +//! file; a finding never asks the opposite of an earlier request; a +//! finding CoderHelm's rounds deferred holds no more unless new code gives +//! it new evidence; a person's answer decides scope; and once each ticket +//! criterion is proven both ways with CI green, what is left that isn't a +//! shown defect is a follow-up note on an approval. + +use crate::passes::review_agent::{verdict_heading, Finding}; +use crate::passes::review_discipline::{self as d, Earlier, Facts}; +use crate::passes::review_one_verdict as one; +use crate::passes::review_policy::named_holding; +use crate::passes::review_verdict::Verdict; +use serde_json::json; + +const MAPS: &str = "apps/web/src/utils/filterMaps.ts"; +const MAPS_TEST: &str = "apps/web/src/test/utils/filterMaps.test.ts"; +const GRID_TEST: &str = "apps/web/src/test/components/filter-nav-sport-grid.test.tsx"; +const DEDUPE_TEST: &str = "apps/web/src/test/components/sports-filter-dedupe.test.tsx"; +const VALIDATION_TEST: &str = + "apps/web/src/test/components/classes-block-filter-validation.test.tsx"; +const PARALLEL: &str = "A parallel structure next to an existing one"; +const TEST_SIZE: &str = "A test out of proportion to the change"; + +/// The person's answer on the ticket, the day before. +const ANSWER: &str = "Yes: the /classes/ path pages should cover both rows too, the \ + sport chip and the class list."; + +fn finding(v: serde_json::Value) -> Finding { + let mut base = json!({"line": 1, "severity": "blocking", "evidence": "verified-defect", + "category": "scope", "caused_by_diff": true, "body": "b"}); + for (k, val) in v.as_object().unwrap() { + base[k] = val.clone(); + } + serde_json::from_value(base).unwrap() +} + +fn size(file: &str) -> Finding { + finding( + json!({"file": file, "line": 4, "category": "tests", "title": TEST_SIZE, + "body": "The tests are 236 added lines against 41 lines of changed code for this change. Cut them to the cases the ticket names."}), + ) +} + +fn facts<'a>(earlier: &'a [Earlier], deferred: &'a [String], people: &'a [String]) -> Facts<'a> { + Facts { + earlier, + deferred, + changed_since_previous: None, + people, + criteria_proven: false, + ci_green: true, + } +} + +#[test] +fn the_parallel_structure_that_names_nothing_never_blocks() { + // As it was posted on every rewrite of the file: no line, no function. + let mut fs = vec![finding(json!({"file": MAPS, "line": 0, "title": PARALLEL, + "body": "Extend the existing one (add the entries or the parameter there) and remove the new one."}))]; + let made = d::judge(&mut fs, &facts(&[], &[], &[])); + assert_eq!(made.len(), 1); + assert!(!fs[0].holds_merge()); + // Named and anchored, the same check blocks in a first review. + let mut named = vec![finding( + json!({"file": MAPS, "line": 640, "title": PARALLEL, + "body": "`apps/web/src/utils/filterMaps.ts` adds `dedupeSportOptionsBySlug` next to the existing `dedupeSportsBySlug`."}), + )]; + assert!(d::judge(&mut named, &facts(&[], &[], &[])).is_empty()); + assert!(named[0].note_only.is_none()); + // The check anchors it on the new definition's line. + let patch = "@@ -630,3 +630,9 @@ export const x = 1;\n context\n+export function dedupeSportOptionsBySlug(o) {\n+ return o;\n+}\n"; + assert_eq!( + crate::passes::review_rules::anchor_line(patch, &named[0].body), + 631 + ); +} + +#[test] +fn the_test_size_finding_doesnt_move_and_never_undoes_a_request() { + // Rounds 3 to 6: each test trimmed, the finding moved to the next one. + let mut earlier = vec![Earlier::of_item(&format!("{TEST_SIZE} (`{MAPS_TEST}`)"))]; + for next in [GRID_TEST, DEDUPE_TEST, VALIDATION_TEST] { + let mut fs = vec![size(next)]; + let made = d::judge(&mut fs, &facts(&earlier, &[], &[])); + assert_eq!(made.len(), 1, "{next}"); + assert!(made[0].why.contains("raised before on"), "{}", made[0].why); + assert!(!fs[0].holds_merge()); + earlier.push(Earlier::of_item(&format!("{TEST_SIZE} (`{next}`)"))); + } + // The review's own earlier request on the dedupe test. + let asked = vec![Earlier::of_thread( + DEDUPE_TEST, + "**Should fix: Restore the selected-chip and row-order cases**\n\nThe rewrite dropped them; put back both cases.", + )]; + let mut fs = vec![size(DEDUPE_TEST)]; + let made = d::judge(&mut fs, &facts(&asked, &[], &[])); + assert_eq!(made.len(), 1); + assert!(made[0].why.contains("would undo my earlier request")); + assert!(made[0].why.contains("Restore the selected-chip")); +} + +#[test] +fn a_finding_the_rounds_deferred_holds_no_more_without_new_code() { + let deferred = vec![ + format!("{PARALLEL} (`{MAPS}`)"), + format!("{TEST_SIZE} (`{VALIDATION_TEST}`)"), + ]; + let mut fs = vec![ + finding(json!({"file": MAPS, "line": 640, "title": PARALLEL, + "body": "`x` next to the existing `y`."})), + size(VALIDATION_TEST), + ]; + let made = d::judge(&mut fs, &facts(&[], &deferred, &[])); + assert_eq!(made.len(), 2); + assert!(made.iter().all(|m| m.why.contains("deferred"))); + // New code on the line is new evidence: it may hold again. + let changed: std::collections::HashMap> = + [(MAPS.to_string(), std::collections::HashSet::from([641u64]))].into(); + let mut again = vec![finding( + json!({"file": MAPS, "line": 640, "title": PARALLEL, + "body": "`x` next to the existing `y`."}), + )]; + let f = Facts { + changed_since_previous: Some(&changed), + ..facts(&[], &deferred, &[]) + }; + assert!(d::judge(&mut again, &f).is_empty()); + // The thread of a deferred finding holds the merge no more either. + let src = include_str!("../review_pr.rs"); + let settle = &src[src.find("pub(crate) fn settle_own_findings(").unwrap()..]; + assert!(settle[..1600].contains("settled.push(line);\n continue;")); +} + +#[test] +fn a_persons_answer_decides_scope() { + let people = vec![ANSWER.to_string()]; + let mut out = vec![finding( + json!({"file": "apps/web/src/components/sanity-blocks/classes-block.tsx", "line": 30, + "title": "Path-page changes are outside the ticket", + "body": "The /classes/ path pages changes are out of scope for a summer camps chip fix; revert them."}), + )]; + let made = d::judge(&mut out, &facts(&[], &[], &people)); + assert_eq!(made.len(), 1); + assert!(made[0].why.contains("a person asked for this")); + // Called missing after the revert: it says whose answer it was. + let mut missing = vec![finding( + json!({"file": "apps/web/src/components/sanity-blocks/classes-block.tsx", "line": 30, + "category": "correctness", "defeats_goal": true, + "title": "Path pages no longer cover both rows", + "body": "The /classes/ path pages are missing the sport chip dedupe."}), + )]; + d::judge(&mut missing, &facts(&[], &[], &people)); + assert!(missing[0].body.contains("A person asked for this")); + assert!(missing[0] + .body + .contains("path pages should cover both rows")); +} + +#[test] +fn the_last_round_approves_with_follow_up_notes_once_the_criteria_pass() { + let proofs = json!([ + {"criterion": "One Multi-Sport chip on the summer camps page", "test": "e2e/camps.spec.ts › one chip", + "record": {"head": "e4599595a1", "base": {"ran": true, "passed": 0, "failed": 1}, "change": {"ran": true, "passed": 1, "failed": 0}}}, + {"criterion": "Path pages cover both rows", "test": "e2e/classes.spec.ts › both rows", + "record": {"head": "e4599595a1", "base": {"ran": true, "passed": 0, "failed": 1}, "change": {"ran": true, "passed": 3, "failed": 0}}} + ]) + .to_string(); + let proven = d::criteria_met(&proofs, "e4599595a1").unwrap(); + assert!(proven); + // What the last review still raised: the two generic findings, anchored + // and named this time, and a concern it couldn't show. + let mut fs = vec![ + finding(json!({"file": MAPS, "line": 640, "title": PARALLEL, + "body": "`a.ts` adds `x` next to the existing `y`."})), + size(VALIDATION_TEST), + finding(json!({"file": MAPS, "line": 12, "category": "correctness", + "evidence": "unverified-concern", "title": "Inactive sports may still show", + "body": "Could a hidden sport still render?"})), + ]; + let f = Facts { + criteria_proven: proven, + ..facts(&[], &[], &[]) + }; + let made = d::judge(&mut fs, &f); + assert_eq!(made.len(), 3, "{made:?}"); + assert!(made.iter().all(|m| m.why.starts_with("Follow-up"))); + // On CoderHelm's own pull request nothing of it is work that holds it. + let own_open = crate::passes::own_review::required(&fs, &[]); + assert!(own_open.is_empty(), "{own_open:?}"); + let verdict = Verdict::from_holding(named_holding(&fs, &[], &[], false, &own_open, &[])); + assert_eq!(verdict.event(), "APPROVE"); + let body = format!( + "{}\n\nThe chip shows once.", + verdict_heading(&verdict, fs.len()) + ); + assert!(body.starts_with("✅ **Approved with notes**")); + assert!(one::check(&body).is_empty()); + // A shown defect still holds, criteria or not. + let mut defect = vec![finding(json!({"file": MAPS, "line": 12, "category": "bug", + "title": "Crash on an empty sport list", "body": "`sports[0].id` throws on []."}))]; + assert!(d::judge(&mut defect, &f).is_empty()); + assert!(defect[0].holds_merge()); +} + +/// The rules run on every review, after the findings are graded and before +/// the verdict, with the run's own ledger, people's words and proofs. +#[test] +fn the_review_runs_the_rules_before_its_verdict() { + let src = include_str!("../review_pr.rs"); + let finalize = src + .find("super::review_severity::finalize(&mut findings);") + .unwrap(); + let judge = src.find("super::review_discipline::judge(").unwrap(); + let verdict = src.find("review_agent::decide_verdict(&findings").unwrap(); + assert!(finalize < judge && judge < verdict); + let block = &src[finalize..judge]; + assert!(block.contains("deferred_items")); + assert!(block.contains("people.push(ticket_context.clone())")); + assert!(block.contains("criteria_met(&j, &head_sha)")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 7cb5384de..1ff273c31 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1378,6 +1378,7 @@ pub mod review_activity; pub mod review_agent; pub mod review_ci; pub mod review_configs; +pub mod review_discipline; #[cfg(test)] mod review_eval; pub(crate) mod review_fingerprint; diff --git a/services/worker/src/passes/review_discipline.rs b/services/worker/src/passes/review_discipline.rs new file mode 100644 index 000000000..4d526927e --- /dev/null +++ b/services/worker/src/passes/review_discipline.rs @@ -0,0 +1,505 @@ +//! What may hold the merge, decided from facts the review already has. +//! +//! A pull request's fix was right by its third commit: CI and the preview's +//! end-to-end run were green and a person's product answers were built. +//! CoderHelm's review still requested changes for six more rounds on two +//! generic findings, "A parallel structure next to an existing one" and "A +//! test out of proportion to the change". The parallel structure never +//! named the function it duplicated, across three rewrites of the file. The +//! test-size finding moved from one test file to the next as each was +//! trimmed, and landed on a test whose cases the review itself had asked to +//! restore. CoderHelm's own fix rounds deferred both as making no +//! progress, and the review kept blocking on them. A person had answered +//! that the path pages should be covered; the work was reverted as out of +//! scope and a later review called it missing. +//! +//! [`judge`] runs on every review, after the findings are graded and before +//! the verdict is made. Each rule makes a finding a note with its reason, +//! never drops it silently: +//! +//! 1. **A blocking finding is actionable** ([`unactionable`]): it names its +//! file and line, and a smallest-change finding names the existing code +//! it duplicates or what its size is out of proportion to. +//! 2. **A finding doesn't move to another file** ([`moved`]): a generic +//! finding raised before on another file was about that file's code; the +//! same words on the next file are a new claim the review hasn't shown. +//! 3. **No opposite requests** ([`opposite`]): a finding that asks to take +//! out what an earlier finding on the same file asked to add (or the +//! other way round) doesn't hold; the review names the request it would +//! undo. +//! 4. **A finding CoderHelm's own rounds deferred holds no more** +//! ([`deferred`]), unless it is on code changed since the previous +//! review: new code is new evidence. +//! 5. **A person's answer decides scope** ([`against_people`]): a finding +//! that calls work out of scope a person asked for is a note; one that +//! calls missing what a person asked for says so. +//! 6. **Approve when the pull request does what the ticket asks** +//! ([`criteria_met`]): once each criterion is proven both ways and CI is +//! green, what is left that isn't a shown defect is a follow-up note. + +use super::review_agent::{Evidence, Finding}; +use super::review_policy::demote; + +/// An earlier finding of CoderHelm's on this pull request: a review thread +/// (resolved or not) or an item of its own fix rounds. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Earlier { + pub path: String, + pub title: String, + pub body: String, +} + +impl Earlier { + /// From a review thread's first comment. + pub fn of_thread(path: &str, body: &str) -> Self { + let title = body + .lines() + .map(|l| { + l.trim() + .trim_matches(|c| c == '*' || c == '#' || c == '_') + .trim() + }) + .find(|l| !l.is_empty()) + .unwrap_or("") + .to_string(); + // A severity label leads some titles ("Should fix: ..."). + let title = title + .split_once(": ") + .filter(|(head, _)| head.split_whitespace().count() <= 2) + .map_or(title.clone(), |(_, t)| t.trim().to_string()); + Self { + path: path.to_string(), + title, + body: body.to_string(), + } + } + + /// From a fix round's item, `title (`path:line`)`. + pub fn of_item(item: &str) -> Self { + let k = super::review_one_verdict::Key::of_line(item); + let title = item + .rsplit_once("(`") + .map_or(item, |(t, _)| t) + .trim() + .to_string(); + Self { + path: k.path, + title: title.clone(), + body: title, + } + } +} + +/// What [`judge`] knows besides the findings. +#[derive(Debug, Default)] +pub struct Facts<'a> { + pub earlier: &'a [Earlier], + /// Items CoderHelm's own fix rounds deferred (no progress after every + /// approach, or a person-gate reason). + pub deferred: &'a [String], + /// Right-side lines changed since the previous reviewed head, by file. + pub changed_since_previous: + Option<&'a std::collections::HashMap>>, + /// What people wrote on the pull request and on the ticket. + pub people: &'a [String], + /// Each ticket criterion is proven ([`criteria_met`]). + pub criteria_proven: bool, + /// No check fails on the head. + pub ci_green: bool, +} + +/// A finding [`judge`] made a note, and why. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Made { + pub title: String, + pub file: String, + pub why: String, +} + +/// The rules, in order, over the findings that hold the merge. +pub fn judge(findings: &mut [Finding], facts: &Facts<'_>) -> Vec { + let mut made = Vec::new(); + for f in findings.iter_mut() { + against_people(f, facts.people); + // Every finding is judged, not only those that hold: on CoderHelm's + // own pull request a note is still work that holds it + // (`own_review::required`), unless a policy made it a note, which + // is what each rule here does. + if f.note_only.is_some() && !f.holds_merge() { + continue; + } + let actionable_matters = f.holds_merge() || super::review_rules::check_started(f).is_some(); + let why = actionable_matters + .then(|| unactionable(f)) + .flatten() + .or_else(|| moved(f, facts.earlier)) + .or_else(|| opposite(f, facts.earlier)) + .or_else(|| deferred(f, facts.deferred, facts.changed_since_previous)) + .or_else(|| out_of_scope_asked(f, facts.people)) + .or_else(|| follow_up(f, facts.criteria_proven, facts.ci_green)); + if let Some(why) = why { + demote(f, &why); + made.push(Made { + title: f.title.clone(), + file: f.file.clone(), + why, + }); + } + } + made +} + +/// Rules that a by-rule finding (a rule the repository requires, a failing +/// check, an unproven critical path) answers to as well: only the +/// smallest-change rule's, which are generic. +fn by_repo_rule(f: &Finding) -> bool { + super::review_rules::mandatory(f).is_some() + && f.required.as_deref() != Some(super::review_rules::SMALLEST_RULE) +} + +/// Rule 1: why a blocking finding isn't actionable, if it isn't. +pub fn unactionable(f: &Finding) -> Option { + if by_repo_rule(f) { + return None; + } + if f.file.trim().is_empty() { + return Some( + "A note, not a block: it names no file. A blocking finding names its file and line." + .into(), + ); + } + if f.line == 0 { + return Some(format!( + "A note, not a block: it names no line in `{}`. A blocking finding names its file and line.", + f.file + )); + } + let text = format!("{} {}", f.title, f.body); + if f.title == PARALLEL && !text.contains("the existing `") { + return Some( + "A note, not a block: it doesn't name the existing code this duplicates.".into(), + ); + } + if f.title == TEST_SIZE && !text.contains(" against ") && !text.contains("remove") { + return Some( + "A note, not a block: it names neither the cases to remove nor what the tests are out of proportion to." + .into(), + ); + } + None +} + +const PARALLEL: &str = "A parallel structure next to an existing one"; +const TEST_SIZE: &str = "A test out of proportion to the change"; + +/// Rule 2: a generic finding raised before on another file. +pub fn moved(f: &Finding, earlier: &[Earlier]) -> Option { + super::review_rules::check_started(f)?; + let before = earlier + .iter() + .find(|e| e.title.eq_ignore_ascii_case(f.title.trim()) && e.path != f.file)?; + Some(format!( + "A note, not a block: this was raised before on `{}`, and that code has changed since; the same words on `{}` are a new claim this review hasn't shown.", + before.path, f.file + )) +} + +/// Which way a finding asks the code to go. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Way { + More, + Less, +} + +fn way(text: &str) -> Option { + let t = text.to_lowercase(); + const LESS: &[&str] = &[ + "out of proportion", + "too large", + "too big", + "too many", + "trim", + "cut them", + "remove the", + "drop the", + "fewer", + ]; + const MORE: &[&str] = &[ + "restore", + "add a test", + "add a case", + "add the case", + "missing test", + "no test", + "doesn't test", + "does not test", + "not covered", + "keep the case", + "put back", + ]; + if LESS.iter().any(|w| t.contains(w)) { + Some(Way::Less) + } else if MORE.iter().any(|w| t.contains(w)) { + Some(Way::More) + } else { + None + } +} + +/// Rule 3: a finding asking the opposite of an earlier one on its file. +pub fn opposite(f: &Finding, earlier: &[Earlier]) -> Option { + let now = way(&format!("{} {}", f.title, f.body))?; + let before = earlier.iter().find(|e| { + e.path == f.file + && !e.title.eq_ignore_ascii_case(f.title.trim()) + && way(&format!("{} {}", e.title, e.body)).is_some_and(|w| w != now) + })?; + Some(format!( + "A note, not a block: it would undo my earlier request on `{}` (\"{}\"), which stands.", + f.file, before.title + )) +} + +/// Rule 4: a finding CoderHelm's own rounds deferred, on code that hasn't +/// changed since the previous review. +pub fn deferred( + f: &Finding, + items: &[String], + changed: Option<&std::collections::HashMap>>, +) -> Option { + let line = super::own_review::thread_line(&f.file, f.line, &f.title); + let hit = items + .iter() + .find(|i| super::own_review_ledger::same_finding(i, &line))?; + let new_code = changed.is_some_and(|c| { + c.get(&f.file).is_some_and(|lines| { + f.line > 0 + && lines + .iter() + .any(|l| l.abs_diff(f.line) <= 3 || *l == super::review_policy::WHOLE_FILE) + }) + }); + if new_code { + return None; + } + let what = hit.rsplit_once(" (`").map_or(hit.as_str(), |(t, _)| t); + Some(format!( + "A note, not a block: CoderHelm's own fix rounds deferred \"{what}\" after making no progress, and nothing it applies to changed since. It stays a follow-up." + )) +} + +/// Significant words of a person's text or a finding. +fn words(text: &str) -> Vec { + const STOP: &[&str] = &[ + "about", "after", "again", "should", "would", "could", "there", "these", "those", "which", + "while", "where", "their", "being", "other", "change", "changes", "pull", "request", + "review", "finding", "please", "thanks", + ]; + let mut out: Vec = text + .to_lowercase() + .split(|c: char| !c.is_alphanumeric()) + .filter(|w| w.len() >= 5 && !STOP.contains(w)) + .map(str::to_string) + .collect(); + out.sort(); + out.dedup(); + out +} + +/// The person's words that speak to a finding: at least three significant +/// words shared. +fn answer_for<'a>(f: &Finding, people: &'a [String]) -> Option<&'a String> { + let fw = words(&format!("{} {}", f.title, f.body)); + people.iter().find(|p| { + let pw = words(p); + fw.iter().filter(|w| pw.contains(w)).count() >= 3 + }) +} + +fn says_out_of_scope(f: &Finding) -> bool { + let t = format!("{} {}", f.title, f.body).to_lowercase(); + let generic_check = super::review_rules::check_started(f).is_some(); + (f.category.eq_ignore_ascii_case("scope") && !generic_check) + || [ + "out of scope", + "outside the ticket", + "not asked", + "unrelated", + "beyond the ticket", + "isn't part of the ticket", + ] + .iter() + .any(|p| t.contains(p)) +} + +fn says_missing(f: &Finding) -> bool { + let t = format!("{} {}", f.title, f.body).to_lowercase(); + f.defeats_goal == Some(true) + || [ + "missing", + "not covered", + "no longer covers", + "was removed", + "doesn't cover", + ] + .iter() + .any(|p| t.contains(p)) +} + +/// The quote a finding carries when a person's answer bears on it. +fn quote(answer: &str) -> String { + let one = answer.split_whitespace().collect::>().join(" "); + common::truncate_str(&one, 240).to_string() +} + +/// Rule 5, for a finding that calls missing what a person asked for: it +/// says so (whether it holds or not), so nobody reads it as new. +pub fn against_people(f: &mut Finding, people: &[String]) { + if says_out_of_scope(f) || !says_missing(f) { + return; + } + let Some(a) = answer_for(f, people) else { + return; + }; + let note = format!( + "A person asked for this on the pull request or the ticket (\"{}\"); the change doesn't do it, so this is that answer not being built, not a new request.", + quote(a) + ); + if !f.body.contains(¬e) { + f.body = format!("{}\n\n_{note}_", f.body.trim_end()); + } +} + +/// Rule 5, for a finding that calls out of scope what a person asked for. +pub fn out_of_scope_asked(f: &Finding, people: &[String]) -> Option { + if !says_out_of_scope(f) { + return None; + } + let a = answer_for(f, people)?; + Some(format!( + "A note, not a block: a person asked for this (\"{}\"), so it is in scope.", + quote(a) + )) +} + +/// Rule 6: with the ticket's criteria proven and CI green, what holds that +/// isn't a shown defect is a follow-up. +pub fn follow_up(f: &Finding, criteria_proven: bool, ci_green: bool) -> Option { + if !(criteria_proven && ci_green) || by_repo_rule(f) { + return None; + } + let advice = super::review_rules::check_started(f).is_some() + && f.required.as_deref() != Some(super::review_rules::SMALLEST_RULE) + || super::review_severity::pure_style(f) + || f.evidence() != Evidence::VerifiedDefect; + advice.then(|| { + "Follow-up, not a block: the pull request does what the ticket asks (each criterion proven end to end, CI green).".to_string() + }) +} + +/// Whether the ticket's criteria are proven on `head`, from the run's +/// two-way proofs (`e2e_proof` on the run, as `common::e2e_proof` keeps +/// them: each criterion's test fails on staging and passes on the preview). +/// `None` when the run keeps none. Read from the JSON so this works before +/// and after that module lands. +pub fn criteria_met(proofs_json: &str, head: &str) -> Option { + let v: serde_json::Value = serde_json::from_str(proofs_json).ok()?; + let on_head: Vec<&serde_json::Value> = v + .as_array()? + .iter() + .filter(|p| { + let h = p["record"]["head"].as_str().unwrap_or(""); + !h.is_empty() && !head.is_empty() && (h.starts_with(head) || head.starts_with(h)) + }) + .collect(); + if on_head.is_empty() { + return None; + } + let leg = |p: &serde_json::Value, side: &str| { + let l = &p["record"][side]; + ( + l["ran"].as_bool().unwrap_or(false), + l["passed"].as_u64().unwrap_or(0), + l["failed"].as_u64().unwrap_or(0), + ) + }; + Some(on_head.iter().all(|p| { + let (b_ran, _, b_failed) = leg(p, "base"); + let (c_ran, c_passed, c_failed) = leg(p, "change"); + !p["test"].as_str().unwrap_or("").is_empty() + && b_ran + && b_failed > 0 + && c_ran + && c_failed == 0 + && c_passed > 0 + })) +} + +/// The items CoderHelm's own rounds deferred, from its ledger. +pub fn deferred_items(ledger: &super::own_review_ledger::Ledger) -> Vec { + use super::own_review_ledger::Settled; + ledger + .findings + .iter() + .filter(|t| { + matches!( + t.settled, + Some(Settled::Noted { .. }) | Some(Settled::Deferred { .. }) + ) + }) + .map(|t| t.item.clone()) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn f(v: serde_json::Value) -> Finding { + let mut base = json!({"file": "a.ts", "line": 3, "title": "t", "body": "b", + "severity": "blocking", "evidence": "verified-defect", "category": "bug"}); + for (k, val) in v.as_object().unwrap() { + base[k] = val.clone(); + } + serde_json::from_value(base).unwrap() + } + + #[test] + fn a_blocking_finding_names_its_file_line_and_what_it_conflicts_with() { + assert!(unactionable(&f(json!({}))).is_none()); + assert!(unactionable(&f(json!({"line": 0}))).is_some()); + assert!(unactionable(&f(json!({"file": ""}))).is_some()); + let par = f(json!({"title": PARALLEL, "body": "Extend it."})); + assert!(unactionable(&par).is_some()); + let named = + f(json!({"title": PARALLEL, "body": "`a.ts` adds `x` next to the existing `y`."})); + assert!(unactionable(&named).is_none()); + } + + #[test] + fn opposite_requests_and_moved_findings_are_notes() { + let earlier = vec![ + Earlier::of_thread( + "t/b.test.tsx", + "**Should fix: Restore the selected-chip case**\n\nPut back the case.", + ), + Earlier::of_item("A test out of proportion to the change (`t/a.test.ts`)"), + ]; + let size = f( + json!({"file": "t/b.test.tsx", "line": 4, "title": TEST_SIZE, + "body": "The tests are 300 added lines against 40 lines of changed code for this change. Cut them."}), + ); + assert!(moved(&size, &earlier).is_some()); + assert!(opposite(&size, &earlier).is_some()); + } + + #[test] + fn criteria_are_met_only_when_every_proof_on_the_head_holds_both_ways() { + let ok = json!([{"criterion": "c", "test": "e2e/a.spec.ts › one", "record": {"head": "abc123", "base": {"ran": true, "passed": 0, "failed": 1}, "change": {"ran": true, "passed": 1, "failed": 0}}}]).to_string(); + assert_eq!(criteria_met(&ok, "abc123"), Some(true)); + assert_eq!(criteria_met(&ok, "fff"), None); + let both_green = json!([{"criterion": "c", "test": "e2e/a.spec.ts › one", "record": {"head": "abc123", "base": {"ran": true, "passed": 1, "failed": 0}, "change": {"ran": true, "passed": 1, "failed": 0}}}]).to_string(); + assert_eq!(criteria_met(&both_green, "abc123"), Some(false)); + } +} diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index cd714161f..c67c10ae0 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -344,6 +344,13 @@ async fn smallest_change_gaps( let mut out = super::review_rules::wider_findings(&super::minimal_change::check( &files, &base, ticket, has_probe, )); + // Each one names the line it is about, or it can't block + // (`review_discipline::unactionable`). + for f in out.iter_mut() { + if let Some((_, _, patch)) = files.iter().find(|(p, _, _)| *p == f.file) { + f.line = super::review_rules::anchor_line(patch, &f.body); + } + } let criteria = super::stop_judge::acceptance(ticket); if !criteria.is_empty() { let own = super::web_check::team_domains(state, team_id).await; @@ -3772,6 +3779,65 @@ async fn run_once( ) .await; super::review_severity::finalize(&mut findings); + // What may hold the merge, from facts this review already has: a + // blocking finding is actionable, doesn't move to another file, doesn't + // undo an earlier request, isn't one CoderHelm's rounds deferred on + // unchanged code, doesn't call out of scope what a person asked for, and + // once the ticket's criteria are proven with CI green what is left that + // isn't a shown defect is a follow-up (`review_discipline`). + let own_ledger = match (&own_run, self_authored) { + (Some(run_id), true) => { + Some(Box::pin(super::own_review_ledger::load(state, &msg.team_id, run_id)).await) + } + _ => None, + }; + { + let mut earlier: Vec = bot_threads + .iter() + .map(|t| super::review_discipline::Earlier::of_thread(&t.path, &t.body)) + .collect(); + if let Some(l) = &own_ledger { + earlier.extend( + l.findings + .iter() + .map(|t| super::review_discipline::Earlier::of_item(&t.item)), + ); + } + let deferred = own_ledger + .as_ref() + .map(super::review_discipline::deferred_items) + .unwrap_or_default(); + let mut people: Vec = people_wrote + .iter() + .filter(|c| super::review_policy::is_person(&c["user"])) + .filter_map(|c| c["body"].as_str().map(str::to_string)) + .collect(); + people.push(ticket_context.clone()); + let criteria_proven = match &own_run { + Some(run_id) => run_e2e_proofs(state, &msg.team_id, run_id) + .await + .and_then(|j| super::review_discipline::criteria_met(&j, &head_sha)) + .unwrap_or(false), + None => false, + }; + let ci_green = !findings.iter().any(|f| { + super::review_rules::mandatory(f) == Some(super::review_rules::FAILING_CHECK_WHY) + }) && base_failing.is_empty(); + let made = super::review_discipline::judge( + &mut findings, + &super::review_discipline::Facts { + earlier: &earlier, + deferred: &deferred, + changed_since_previous: changed_since_previous.as_ref(), + people: &people, + criteria_proven, + ci_green, + }, + ); + for m in &made { + info!(pr = msg.pr_number, file = %m.file, title = %m.title, why = %m.why, "A finding that would hold the merge made a note"); + } + } info!( pr = msg.pr_number, checked = second.checked, @@ -3894,13 +3960,9 @@ async fn run_once( // On CoderHelm's own pull request, a finding its fix loop settled with a // reason (the ticket rules it out, or only a person can do it) is a note // naming that reason, never a request for changes on the head. - let settled_by_run = match (&own_run, self_authored) { - (Some(run_id), true) => { - let ledger = - Box::pin(super::own_review_ledger::load(state, &msg.team_id, run_id)).await; - settle_own_findings(&ledger, &mut findings, &mut own_open) - } - _ => Vec::new(), + let settled_by_run = match &own_ledger { + Some(ledger) => settle_own_findings(ledger, &mut findings, &mut own_open), + None => Vec::new(), }; // The one verdict the rest of this review may use: what holds the merge, // by name. Nothing named holding means approve, whatever came before. @@ -4738,6 +4800,26 @@ async fn run_once( }) } +/// The run's two-way end-to-end proofs as JSON (`e2e_proof` on the run, +/// kept by `common::e2e_proof` once that lands), if it has any. +async fn run_e2e_proofs(state: &WorkerState, team_id: &str, run_id: &str) -> Option { + state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("e2e_proof") + .send() + .await + .ok()? + .item? + .get("e2e_proof")? + .as_s() + .ok() + .cloned() +} + /// On CoderHelm's own pull request, the head reviewed now isn't the one its /// last review was of (or there was none): the review is posted. pub(crate) fn own_head_is_new(last_reviewed: Option<&str>, head: &str) -> bool { @@ -5557,9 +5639,11 @@ pub(crate) fn settle_own_findings( for f in findings.iter_mut() { let line = super::own_review::thread_line(&f.file, f.line, &f.title); if let Some(s) = ledger.settled_item(&line) { - // CoderHelm's own note: listed on the ready pull request, still - // a finding of this review, never approved over. + // CoderHelm's own note (its rounds made no progress on it): a + // follow-up, not a hold. A finding of it on code changed since + // is new evidence and holds on its own (`review_discipline`). if matches!(s, Settled::Noted { .. }) { + settled.push(line); continue; } super::review_policy::demote(f, &why(s)); @@ -5568,9 +5652,9 @@ pub(crate) fn settle_own_findings( } own_open.retain(|o| { let s = ledger.settled_item(o); - // A noted finding leaves the list that holds the draft, and keeps - // holding the merge (its thread stays open). - if s.is_some_and(|s| !matches!(s, Settled::Noted { .. })) && !settled.contains(o) { + // A settled or noted finding leaves the list that holds the draft, + // and its thread holds the merge no more. + if s.is_some() && !settled.contains(o) { settled.push(o.clone()); } s.is_none() diff --git a/services/worker/src/passes/review_rules.rs b/services/worker/src/passes/review_rules.rs index fba1e65e6..6a53a3dc5 100644 --- a/services/worker/src/passes/review_rules.rs +++ b/services/worker/src/passes/review_rules.rs @@ -165,6 +165,45 @@ pub fn check_started(f: &Finding) -> Option<&'static str> { .map(|(_, since)| *since) } +/// The head line a check's finding is about in `patch`: the added line that +/// carries the first backticked name its `body` gives (the new definition), +/// else the first added line. 0 when the patch adds nothing. +pub fn anchor_line(patch: &str, body: &str) -> u64 { + let names: Vec<&str> = body + .split('`') + .skip(1) + .step_by(2) + .filter(|n| !n.contains('/') && !n.is_empty()) + .collect(); + let mut line = 0u64; + let mut first_added = 0u64; + for l in patch.lines() { + if let Some(hdr) = l.strip_prefix("@@") { + line = hdr + .split('+') + .nth(1) + .and_then(|p| p.trim().split([',', ' ']).next()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0); + continue; + } + match l.chars().next() { + Some('+') => { + if first_added == 0 { + first_added = line.max(1); + } + if names.first().is_some_and(|n| l.contains(n)) { + return line.max(1); + } + line += 1; + } + Some('-') | Some('\\') => {} + _ => line += 1, + } + } + first_added +} + /// A finding of a smallest-change check that a reason in the coder's notes /// may keep (`minimal_change::Widening::excusable`): advice once the first /// review has run (`review_policy::hold_late_blockers`).