From 422526353d71172ae1c8d14ea84e5b9c1c2d738f Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 13 Nov 2026 12:07:22 -0500 Subject: [PATCH] A pull request's description is rebuilt from its head; every app a dependency change can break is built A dependency run's pull request had the right code after a review round and the wrong description: its table still showed the plan (packages as major version jumps the final manifest no longer makes), its count of fixed advisories was never compared with the final lockfile, the round that fixed the code said it could not edit the description, and a second app no CI job builds was never built. - common::dep_head: what the lockfile on the head resolves for each package version line, compared with the base branch. The dependency description's table and headline are written from it; an advisory is fixed only at or past its patched version; what can't be read is said as not known and the plan is marked as a plan. - passes::description: the one place a description is written from (save), the one rebuild every path that moves the head calls (head_moved), and a source test that fails on a body write anywhere else. - common::description_handoff: fix rounds are told the description is rebuilt for them; a round's sentence that hands it to a person is taken out and becomes the rebuild. Feedback rounds with no person behind them now have the description tool they were told to call. - common::file_claims and passes::file_claims: a sentence a run writes into a prose file that says a check passes needs that check's recorded passing result, or it is taken out before the run finishes. - runtime_proof: every workspace project whose dependencies bring in a changed package line is built when its manifest declares a build, and the project of every other lockfile with bumps; a project that can't be proven is named with why. - Incident case aj and its row in docs/incidents.md. --- docs/incidents.md | 1 + services/common/src/dep_head.rs | 629 ++++++++++++++++++ services/common/src/description_handoff.rs | 203 ++++++ services/common/src/file_claims.rs | 461 +++++++++++++ services/common/src/lib.rs | 3 + services/common/src/prose.rs | 18 + services/common/src/reachability.rs | 443 +++++++++++- services/common/src/runtime_proof.rs | 536 ++++++++++++++- services/common/src/security_fixes.rs | 237 +++++-- services/worker/src/passes/covering.rs | 6 +- services/worker/src/passes/dep_fix.rs | 138 +++- services/worker/src/passes/description.rs | 317 +++++++++ services/worker/src/passes/feedback.rs | 130 +++- services/worker/src/passes/file_claims.rs | 221 ++++++ services/worker/src/passes/implement.rs | 3 +- .../incidents/ah_dep_run_choice_and_proof.rs | 2 +- .../incidents/aj_description_from_the_head.rs | 325 +++++++++ .../src/passes/incidents/h_pr_updates.rs | 2 +- services/worker/src/passes/incidents/mod.rs | 1 + services/worker/src/passes/link_checks.rs | 10 +- services/worker/src/passes/mod.rs | 24 + services/worker/src/passes/outside_exec.rs | 2 +- services/worker/src/passes/pr.rs | 27 +- services/worker/src/passes/ready.rs | 14 +- services/worker/src/passes/release_run.rs | 4 +- services/worker/src/passes/resume.rs | 117 +++- services/worker/src/passes/review_fix/mod.rs | 5 +- services/worker/src/passes/review_pr.rs | 22 +- services/worker/src/passes/security_fixes.rs | 168 ++++- services/worker/src/passes/stack.rs | 2 +- services/worker/src/passes/stop_pr.rs | 22 +- 31 files changed, 3908 insertions(+), 185 deletions(-) create mode 100644 services/common/src/dep_head.rs create mode 100644 services/common/src/description_handoff.rs create mode 100644 services/common/src/file_claims.rs create mode 100644 services/worker/src/passes/description.rs create mode 100644 services/worker/src/passes/file_claims.rs create mode 100644 services/worker/src/passes/incidents/aj_description_from_the_head.rs diff --git a/docs/incidents.md b/docs/incidents.md index 3db737cd7..bec59e004 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -64,6 +64,7 @@ pipeline still calls it there. | ag. `ag_red_ci_ships_what_passes` | Three ways were left for a run to end badly over red checks or a refused landing. A dependency fix whose CI stayed red was taken apart by planned task (one task per lockfile, so a lockfile went back without its manifest), and after three reverts the run ended failed with bumps left in that passed on their own. A run stopped after its work opened its pull request with manifests changed and lockfiles unwritten, and waited for CI to fail first. A review fix or feedback round whose finished work GitHub refused to land was recorded as unfinished at once. | Red checks after every fix take out only what breaks them. A dependency fix takes out its newest commit of verified bumps, defers those bumps with what CI printed, holds their findings out of later bundles and keeps the commits before it, again while CI stays red, never emptying the pull request. Any other run is taken apart task by task (up to eight reverts) down to the part that passes; what ships is green with the rest under "Deferred". A stopped run's lockfiles are written by their package managers before its pull request opens, and one that can't be written is named without stopping it. Every kind of fix round takes one classified decision about a fault (`round::plan_for_fault`): while it may continue it runs again in a fresh step, keeping its work when only the landing failed and starting from the pull request's head otherwise. | | ah. `ah_dep_run_choice_and_proof` | A dependency security run of 64 packages finished with its checks passed. Two packages had been forced onto a new major version through an override although a patched release existed on the installed line (a unit listed one bump per package, to the highest target of all of the package's copies); CoderHelm's reviewer caught it and a fix round pinned them back. Four overrides did have to cross a major version and nothing showed their parents work on it: the sandbox ran the install, the type check, the linter and the unit tests, never the application's build or its start. One pull request carried all 64 bumps, and it did not say how many advisories stayed open or why. | A bump stays on its installed version line with that line's lowest patched release, one bump per package and line; it crosses a major version only when the advisory data lists no patched release on the line, and says which advisory. A fix that crosses a major version is a pull request of its own from the start (a person who asks for one pull request still gets one), its release notes read before any patch bump's, with the parent of a transitive package named and the range it declares. After the batches, the repository's real build (the command its CI runs, else its build script) and its declared start command run in a sandbox build of their own with a full time window, on the base branch and on the branch; what passes on the base and fails with the bumps takes out the newest commit of bumps and defers it with the cause, and only the set whose removal made it pass is held as breaking. What did not run is said, never claimed. The description ends with the advisories that stay open, counted by reason. | | ai. `ai_open_items_settled` | A dependency update finished completed with five Open items on its pull request for a person: the package manager's audit never ran so the advisory counts were unknown (listed twice, in different words), nothing showed that the packages an override moved still built and passed their tests, a README line claimed checks no run had made (and was still listed after a later round rewrote it), and the plan had no end-to-end checklist for a change with nothing to deploy. The coder's full checks had been refused twice for lack of time after two lockfile regenerations in one step, and nothing carried them anywhere. | A run settles its own open items before it finishes (`settle`). Each item is classified: CoderHelm runs it in its sandbox, the repository's CI settles it, it does not apply to the run, or only a person has what it needs (a reason on the human-only list). What CoderHelm can run it runs in a step with a full sandbox window, a fresh step when this one has too little time, and a check the coder was refused for lack of time is owed whether or not an item names it. A change to the dependencies is always audited by its package manager after the bumps (`common::dep_audit`, one row per manager) and the counts left are quoted. A passing result closes the item and is quoted under "Checked by CoderHelm"; a failing one takes out a dependency fix's newest verified set of bumps, or gives any other run a fix round with the real output. An end-to-end checklist is not raised for upkeep, the same missing fact is one item, every item names the head it was written on, and a run about to finish with items of an earlier head derives them again first. What stays says why. Lockfiles are regenerated once per state of the branch. | +| aj. `aj_description_from_the_head` | A dependency security run's pull request had the right code after a review round and the wrong description. Its table still showed the plan (five packages as major version jumps the final manifest no longer makes, a headline counting twenty major versions), its count of fixed advisories had never been compared with the final lockfile, the round that fixed the code wrote that it could not edit the description and left the corrections to a person, and the repository's second app (a CMS studio no CI job builds) took a package an override moved to a new major and was never built. | The description is a function of the head. A dependency pull request's table and headline are what the lockfile on the head resolves compared with the base branch; an advisory counts as fixed only at or past its patched version; what can't be read is said as not known and the plan is marked as a plan. Every write of a description goes through `description::save`, every path that moves the head rebuilds it through `description::head_moved`, and a round's sentence that hands the description to a person is taken out and becomes the rebuild. A sentence a run writes into a file that says a check passes needs that check's recorded passing result, or it is taken out. Every workspace project that takes a changed package line is built when its manifest declares a build, CI job or not; a project that can't be proven in the sandbox is named with why, and a build only the bumps break feeds the take-out. | ## Adding a case diff --git a/services/common/src/dep_head.rs b/services/common/src/dep_head.rs new file mode 100644 index 000000000..1eca2fffb --- /dev/null +++ b/services/common/src/dep_head.rs @@ -0,0 +1,629 @@ +//! What a dependency pull request's head resolves, read from its lockfiles. +//! +//! A dependency run planned five packages as major version jumps. A review +//! round then kept each of them inside its current major with a scoped +//! override, and the code was right. The description still showed the plan: +//! its table listed the five as "(major)", its headline counted twenty major +//! versions, and its count of fixed advisories had never been compared with +//! what the final lockfile installs. +//! +//! The description of a dependency pull request is written from the head, +//! never from the plan: +//! +//! - [`resolve`] compares each lockfile on the base branch with the same +//! lockfile on the head, one answer per package and version line of the +//! plan: where the line's copies are now, whether that crosses a major +//! version, whether the line is gone, or that it did not move. +//! - [`HeadFacts::fixed`] counts an advisory as fixed only when every copy +//! left on its line is at or past the advisory's patched version (or the +//! line is no longer installed). +//! - What can't be read is said as not known ([`Resolved::Unknown`], with +//! why). The plan's numbers are then shown as a plan, never as a result. +//! +//! Everything here is pure; the worker reads the lockfiles +//! (`worker::passes::security_fixes::head_facts`). + +use std::cmp::Ordering; + +use crate::security_fixes::{ + compare_versions, in_bump, is_major_bump, version_line, Finding, FindingState, FixUnit, +}; + +/// One lockfile as the base branch and the head have it. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct LockAt { + pub path: String, + /// Every copy it installs on the base branch (name, version); `None` + /// when it could not be read there. + pub base: Option>, + /// The same on the head. + pub head: Option>, + /// Why a side could not be read; empty when both were. + pub why: String, +} + +/// Where one package and version line of the plan stands on the head. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Resolved { + /// The line's lowest copy moved from `from` to `to`. + Moved { + from: String, + to: String, + major: bool, + }, + /// The head installs the same version as the base branch. + NotMoved { at: String }, + /// The head no longer installs the package at all. + Removed { from: String }, + /// The lockfile could not be read on one side. + Unknown { why: String }, +} + +/// One line of the plan with what the head resolves for it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HeadLine { + pub package: String, + pub planned_from: String, + pub planned_to: String, + pub resolved: Resolved, +} + +/// Whether the head fixes one advisory. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Fixed { + Yes, + No, + Unknown, +} + +/// What the head of a dependency pull request resolves: one [`HeadLine`] +/// per bump of the unit, in the unit's order. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct HeadFacts { + /// The head commit the lockfiles were read on. + pub sha: String, + pub lines: Vec, +} + +fn lowest<'a>(versions: impl Iterator) -> Option<&'a str> { + versions.min_by(|a, b| compare_versions(a, b)) +} + +fn versions_of<'a>(copies: &'a [(String, String)], package: &str) -> Vec<&'a str> { + copies + .iter() + .filter(|(n, _)| n.eq_ignore_ascii_case(package)) + .map(|(_, v)| v.as_str()) + .collect() +} + +fn resolve_line(package: &str, planned_from: &str, lock: &LockAt) -> Resolved { + let (Some(base), Some(head)) = (&lock.base, &lock.head) else { + return Resolved::Unknown { + why: if lock.why.is_empty() { + format!("`{}` could not be read", lock.path) + } else { + lock.why.clone() + }, + }; + }; + let line = version_line(planned_from); + let on_line = |v: &&str| version_line(v) == line; + let base_all = versions_of(base, package); + let head_all = versions_of(head, package); + // The line's weakest copy on the base branch is where it starts. + let from = lowest(base_all.iter().copied().filter(on_line)) + .unwrap_or(planned_from) + .to_string(); + if head_all.is_empty() { + return Resolved::Removed { from }; + } + // Still on its line: the weakest copy left decides what is fixed. + if let Some(to) = lowest(head_all.iter().copied().filter(on_line)) { + return if compare_versions(to, &from) == Ordering::Equal { + Resolved::NotMoved { at: from } + } else { + Resolved::Moved { + major: false, + to: to.to_string(), + from, + } + }; + } + // The line is gone and the package is still installed: its copies moved + // to another line. The version the head has and the base did not is + // where they went; with none new, they joined a line already installed. + let new = lowest( + head_all + .iter() + .copied() + .filter(|v| !base_all.iter().any(|b| b == v)), + ); + let above = lowest( + head_all + .iter() + .copied() + .filter(|v| compare_versions(v, &from) == Ordering::Greater), + ); + let to = new + .or(above) + .or_else(|| lowest(head_all.iter().copied())) + .unwrap_or_default() + .to_string(); + Resolved::Moved { + major: is_major_bump(&from, &to), + from, + to, + } +} + +/// What the head resolves for each bump of `unit`. `locks`: the +/// repository's lockfiles as read on the base branch and on `sha`. +pub fn resolve(unit: &FixUnit, sha: &str, locks: &[LockAt]) -> HeadFacts { + let paths: Vec = locks.iter().map(|l| l.path.clone()).collect(); + let lines = unit + .bumps + .iter() + .map(|b| { + let lock = match crate::dep_fix::lockfile_for(&b.manifest, &paths) { + Some(p) => locks.iter().find(|l| l.path == p), + None if locks.len() == 1 => locks.first(), + None => None, + }; + let resolved = match lock { + Some(l) => resolve_line(&b.package, &b.from, l), + None => Resolved::Unknown { + why: if b.manifest.is_empty() { + "the lockfile that installs it is not known".to_string() + } else { + format!( + "the lockfile that installs it could not be told from `{}`", + b.manifest + ) + }, + }, + }; + HeadLine { + package: b.package.clone(), + planned_from: b.from.clone(), + planned_to: b.to.clone(), + resolved, + } + }) + .collect(); + HeadFacts { + sha: sha.to_string(), + lines, + } +} + +/// The facts when nothing could be read: every line unknown, with why. +pub fn unknown(unit: &FixUnit, why: &str) -> HeadFacts { + HeadFacts { + sha: String::new(), + lines: unit + .bumps + .iter() + .map(|b| HeadLine { + package: b.package.clone(), + planned_from: b.from.clone(), + planned_to: b.to.clone(), + resolved: Resolved::Unknown { + why: why.to_string(), + }, + }) + .collect(), + } +} + +fn plural(n: usize, one: &str, many: &str) -> String { + format!("{n} {}", if n == 1 { one } else { many }) +} + +impl HeadFacts { + /// The table's Version cell for the unit's bump `i`. + pub fn version_cell(&self, i: usize) -> String { + match self.lines.get(i).map(|l| (&l.resolved, l)) { + Some((Resolved::Moved { from, to, major }, _)) => { + format!("{from} to {to}{}", if *major { " (major)" } else { "" }) + } + Some((Resolved::NotMoved { at }, _)) => format!("{at}, not moved on the head"), + Some((Resolved::Removed { from }, _)) => format!("{from}, no longer installed"), + Some((Resolved::Unknown { .. }, l)) => format!( + "{} to {} planned; not read from the head", + l.planned_from, l.planned_to + ), + None => "not known".to_string(), + } + } + + /// `unit` with each bump as the head resolves it: the real versions and + /// whether it crosses a major. A line that could not be read keeps the + /// plan's (the table marks it as a plan). + pub fn unit_at_head(&self, unit: &FixUnit) -> FixUnit { + let mut out = unit.clone(); + for (b, l) in out.bumps.iter_mut().zip(&self.lines) { + match &l.resolved { + Resolved::Moved { from, to, major } => { + b.from = from.clone(); + b.to = to.clone(); + b.major = *major; + } + Resolved::NotMoved { at } => { + b.from = at.clone(); + b.to = at.clone(); + b.major = false; + } + Resolved::Removed { from } => { + b.from = from.clone(); + b.major = false; + } + Resolved::Unknown { .. } => {} + } + } + out + } + + /// Lines the head moves across a major version. + pub fn majors(&self) -> usize { + self.lines + .iter() + .filter(|l| matches!(l.resolved, Resolved::Moved { major: true, .. })) + .count() + } + + /// Lines the head could not be read for, with the first reason. + pub fn unknown_lines(&self) -> (usize, &str) { + let mut why = ""; + let mut n = 0; + for l in &self.lines { + if let Resolved::Unknown { why: w } = &l.resolved { + n += 1; + if why.is_empty() { + why = w; + } + } + } + (n, why) + } + + /// Whether the head fixes `f`: every copy left on its line is at or + /// past the advisory's patched version, or the line is gone. + pub fn fixed(&self, unit: &FixUnit, f: &Finding) -> Fixed { + let Some(line) = unit + .bumps + .iter() + .position(|b| in_bump(b, f)) + .and_then(|i| self.lines.get(i)) + else { + return Fixed::Unknown; + }; + let at = match &line.resolved { + Resolved::Removed { .. } => return Fixed::Yes, + Resolved::Unknown { .. } => return Fixed::Unknown, + Resolved::NotMoved { at } => at, + Resolved::Moved { to, .. } => to, + }; + match f.fixed_version.as_deref().filter(|v| !v.is_empty()) { + // No patched version is recorded for it: a move alone proves + // nothing. + None => Fixed::Unknown, + Some(patched) if compare_versions(at, patched) != Ordering::Less => Fixed::Yes, + Some(_) => Fixed::No, + } + } + + /// Each advisory of `members` once, with whether the head fixes it: an + /// advisory in several places is fixed only when every place is. + pub fn advisories( + &self, + unit: &FixUnit, + members: &[(&Finding, &FindingState)], + ) -> Vec<(String, Fixed)> { + let mut out: Vec<(String, Fixed)> = vec![]; + for (f, _) in members { + let id = f.advisory.primary.clone(); + let now = self.fixed(unit, f); + match out.iter_mut().find(|(i, _)| *i == id) { + Some((_, was)) => { + *was = match (*was, now) { + (Fixed::No, _) | (_, Fixed::No) => Fixed::No, + (Fixed::Unknown, _) | (_, Fixed::Unknown) => Fixed::Unknown, + _ => Fixed::Yes, + } + } + None => out.push((id, now)), + } + } + out + } + + /// The description's first sentences: how many advisories the head + /// fixes, in how many package version lines, how many of those cross a + /// major version, and what is not fixed or not known. + pub fn headline(&self, unit: &FixUnit, members: &[(&Finding, &FindingState)]) -> String { + let advisories = self.advisories(unit, members); + let count = |want: Fixed| advisories.iter().filter(|(_, f)| *f == want).count(); + let (fixed, open, unknown) = (count(Fixed::Yes), count(Fixed::No), count(Fixed::Unknown)); + let (unread, why) = self.unknown_lines(); + let at = if self.sha.is_empty() { + "the head".to_string() + } else { + format!("the head `{}`", &self.sha[..self.sha.len().min(7)]) + }; + if unread == self.lines.len() && !self.lines.is_empty() { + return format!( + "What {at} installs is not known: {why}. No count of fixed advisories is claimed \ + here, and the versions in the table are the run's plan, marked as such." + ); + } + let moved = self + .lines + .iter() + .filter(|l| { + matches!( + l.resolved, + Resolved::Moved { .. } | Resolved::Removed { .. } + ) + }) + .count(); + let majors = self.majors(); + let mut s = format!( + "Fixes {} of {} in {} ({} a major version), read from the lockfile on {at}.", + fixed, + plural(advisories.len(), "advisory", "advisories"), + plural(moved, "package version line", "package version lines"), + if majors == 1 { + "1 crosses".to_string() + } else { + format!("{majors} cross") + }, + ); + if open > 0 { + let ids: Vec<&str> = advisories + .iter() + .filter(|(_, f)| *f == Fixed::No) + .map(|(i, _)| i.as_str()) + .take(5) + .collect(); + s.push_str(&format!( + " Not fixed on the head: {}{} (the version installed is below the patched one).", + ids.join(", "), + if open > ids.len() { + format!(" and {} more", open - ids.len()) + } else { + String::new() + } + )); + } + if unknown > 0 { + s.push_str(&format!( + " Not known for {}: {}.", + plural(unknown, "advisory", "advisories"), + if unread > 0 { + why + } else { + "no patched version is recorded for it" + } + )); + } + s + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::security_fixes::{Advisory, Bump}; + + fn copies(v: &[(&str, &str)]) -> Option> { + Some( + v.iter() + .map(|(n, v)| (n.to_string(), v.to_string())) + .collect(), + ) + } + + fn bump(package: &str, from: &str, to: &str) -> Bump { + Bump { + package: package.into(), + from: from.into(), + to: to.into(), + major: is_major_bump(from, to), + manifest: "pnpm-lock.yaml".into(), + } + } + + fn finding(id: &str, package: &str, version: &str, patched: Option<&str>) -> Finding { + Finding { + id: format!("f-{id}"), + package: package.into(), + version: version.into(), + fixed_version: patched.map(String::from), + manifest: "pnpm-lock.yaml".into(), + advisory: Advisory { + primary: id.into(), + ids: vec![id.into()], + ..Default::default() + }, + ..Default::default() + } + } + + /// The plan said a major version for each; the head keeps each on its + /// line through a scoped override. + fn planned_major_stays_on_its_line() -> (FixUnit, HeadFacts, Vec) { + let unit = FixUnit { + bundle: true, + bumps: vec![ + bump("glob-walk", "2.3.1", "4.0.4"), + bump("path-match", "3.1.2", "11.0.1"), + bump("left-trim", "1.0.2", "1.0.5"), + ], + ..Default::default() + }; + let lock = LockAt { + path: "pnpm-lock.yaml".into(), + base: copies(&[ + ("glob-walk", "2.3.1"), + ("glob-walk", "4.0.1"), + ("path-match", "3.1.2"), + ("left-trim", "1.0.2"), + ]), + head: copies(&[ + ("glob-walk", "2.3.2"), + ("glob-walk", "4.0.1"), + ("path-match", "3.1.5"), + ("left-trim", "1.0.5"), + ]), + why: String::new(), + }; + let facts = resolve(&unit, "abc1234def", &[lock]); + let findings = vec![ + finding("GHSA-aaaa", "glob-walk", "2.3.1", Some("2.3.2")), + finding("GHSA-bbbb", "path-match", "3.1.2", Some("3.1.5")), + finding("GHSA-cccc", "left-trim", "1.0.2", Some("1.0.5")), + ]; + (unit, facts, findings) + } + + #[test] + fn a_line_the_plan_called_major_is_shown_as_the_head_resolves_it() { + let (unit, facts, findings) = planned_major_stays_on_its_line(); + assert_eq!(facts.version_cell(0), "2.3.1 to 2.3.2"); + assert_eq!(facts.version_cell(1), "3.1.2 to 3.1.5"); + assert_eq!(facts.majors(), 0); + let at_head = facts.unit_at_head(&unit); + assert!(at_head.bumps.iter().all(|b| !b.major), "{at_head:?}"); + assert_eq!(at_head.bumps[0].to, "2.3.2"); + let st = FindingState::default(); + let members: Vec<(&Finding, &FindingState)> = findings.iter().map(|f| (f, &st)).collect(); + let h = facts.headline(&unit, &members); + assert_eq!( + h, + "Fixes 3 of 3 advisories in 3 package version lines (0 cross a major version), read \ + from the lockfile on the head `abc1234`." + ); + assert!(!h.contains("4.0.4") && !h.contains("11.0.1")); + } + + #[test] + fn a_line_that_really_crosses_a_major_is_counted_as_one() { + let unit = FixUnit { + bumps: vec![bump("glob-walk", "2.3.1", "2.3.2")], + ..Default::default() + }; + let lock = LockAt { + path: "pnpm-lock.yaml".into(), + base: copies(&[("glob-walk", "2.3.1")]), + head: copies(&[("glob-walk", "4.0.4")]), + why: String::new(), + }; + let facts = resolve(&unit, "", &[lock]); + assert_eq!(facts.version_cell(0), "2.3.1 to 4.0.4 (major)"); + assert_eq!(facts.majors(), 1); + assert!(facts.unit_at_head(&unit).bumps[0].major); + } + + #[test] + fn an_advisory_is_fixed_only_at_or_past_its_patched_version() { + let unit = FixUnit { + bumps: vec![ + bump("glob-walk", "2.3.1", "2.3.4"), + bump("path-match", "3.1.2", "3.1.5"), + bump("old-dep", "0.4.0", "0.4.2"), + bump("no-patch", "1.0.0", "1.0.1"), + ], + ..Default::default() + }; + let lock = LockAt { + path: "pnpm-lock.yaml".into(), + base: copies(&[ + ("glob-walk", "2.3.1"), + ("path-match", "3.1.2"), + ("old-dep", "0.4.0"), + ("no-patch", "1.0.0"), + ]), + // glob-walk moved, but short of the patch; path-match did not + // move; old-dep is gone; no-patch moved with no patched version + // on record. + head: copies(&[ + ("glob-walk", "2.3.2"), + ("path-match", "3.1.2"), + ("no-patch", "1.0.1"), + ]), + why: String::new(), + }; + let facts = resolve(&unit, "f00", &[lock]); + let fs = [ + finding("GHSA-1", "glob-walk", "2.3.1", Some("2.3.4")), + finding("GHSA-2", "path-match", "3.1.2", Some("3.1.5")), + finding("GHSA-3", "old-dep", "0.4.0", Some("0.4.2")), + finding("GHSA-4", "no-patch", "1.0.0", None), + ]; + assert_eq!(facts.fixed(&unit, &fs[0]), Fixed::No); + assert_eq!(facts.fixed(&unit, &fs[1]), Fixed::No); + assert_eq!(facts.fixed(&unit, &fs[2]), Fixed::Yes); + assert_eq!(facts.fixed(&unit, &fs[3]), Fixed::Unknown); + assert_eq!(facts.version_cell(1), "3.1.2, not moved on the head"); + assert_eq!(facts.version_cell(2), "0.4.0, no longer installed"); + let st = FindingState::default(); + let members: Vec<(&Finding, &FindingState)> = fs.iter().map(|f| (f, &st)).collect(); + let h = facts.headline(&unit, &members); + assert!( + h.starts_with("Fixes 1 of 4 advisories in 3 package version lines"), + "{h}" + ); + assert!(h.contains("Not fixed on the head: GHSA-1, GHSA-2"), "{h}"); + assert!(h.contains("Not known for 1 advisory"), "{h}"); + } + + #[test] + fn what_cannot_be_read_is_said_as_not_known_never_as_the_plan() { + let unit = FixUnit { + bumps: vec![bump("glob-walk", "2.3.1", "4.0.4")], + ..Default::default() + }; + let lock = LockAt { + path: "pnpm-lock.yaml".into(), + base: copies(&[("glob-walk", "2.3.1")]), + head: None, + why: "`pnpm-lock.yaml` could not be read on the head (too large)".into(), + }; + let facts = resolve(&unit, "abc", &[lock]); + assert_eq!( + facts.version_cell(0), + "2.3.1 to 4.0.4 planned; not read from the head" + ); + let f = finding("GHSA-1", "glob-walk", "2.3.1", Some("2.3.2")); + let st = FindingState::default(); + let h = facts.headline(&unit, &[(&f, &st)]); + assert!( + h.starts_with("What the head `abc` installs is not known"), + "{h}" + ); + assert!(!h.contains("Fixes"), "{h}"); + assert_eq!( + facts.majors(), + 0, + "an unread line is never counted as a major" + ); + // A bump whose lockfile can't be told is unknown too. + let mut other = unit.clone(); + other.bumps[0].manifest = "sbom".into(); + let two = [ + LockAt { + path: "a/yarn.lock".into(), + ..Default::default() + }, + LockAt { + path: "b/yarn.lock".into(), + ..Default::default() + }, + ]; + assert!(matches!( + resolve(&other, "abc", &two).lines[0].resolved, + Resolved::Unknown { .. } + )); + } +} diff --git a/services/common/src/description_handoff.rs b/services/common/src/description_handoff.rs new file mode 100644 index 000000000..7cdc5b044 --- /dev/null +++ b/services/common/src/description_handoff.rs @@ -0,0 +1,203 @@ +//! A round never hands the pull request's description to a person. +//! +//! A fix round corrected the code a review asked about, then ended its +//! account with "I can't edit the PR description from here" and listed the +//! corrections for a person to make. The description stayed wrong. +//! +//! The description is CoderHelm's: after every push it is rebuilt from the +//! branch (`worker::passes::description`). A round has no tool that writes +//! it and needs none, so the round is told that ([`ROUND_NOTE`]) and its +//! account is checked ([`handoffs`]): a sentence that says the description +//! can't be edited, or leaves an edit of it to a person, is taken out +//! ([`scrub`]) and the rebuild runs, whether or not the round pushed code. +//! +//! The check is narrow on purpose. It reads one sentence at a time and needs +//! both the description as the thing edited and either an inability or a +//! person asked to do it; a sentence that only mentions the description +//! passes. + +use std::sync::OnceLock; + +use regex::Regex; + +/// What every fix round is told about the description. +pub const ROUND_NOTE: &str = "The pull request's description is kept by CoderHelm: right after \ + this round it is rebuilt from the branch as it stands (the versions the lockfile resolves, \ + the counts, the changes, the verification and the open items). You have no tool that writes \ + it and need none. When a finding says the description is wrong, fix what is wrong in the \ + code if anything is, and say in your account which statement was wrong; never write that \ + you cannot edit the description, and never leave an edit of it to a person."; + +/// What replaces a handed-off edit in a round's account. +pub const REBUILT: &str = + "CoderHelm rebuilds the pull request's description from the branch after this round."; + +/// The description, as the object of an edit: `the PR description`, `the +/// table in the description`. +const OBJECT: &str = r"(?:(?:the|this|that|its|their|my|our|pr|pr's|prs|pull|request|request's|current|existing)\s+){0,5}(?:description|pr body|pull request body)\b"; +const IN_OBJECT: &str = r"[^.;!?]{0,60}?\b(?:in|of|from) (?:(?:the|this|that|its|pr|pr's|pull|request|request's)\s+){0,4}(?:description|pr body|pull request body)\b"; +const EDIT: &str = r"(?:edit|update|change|modify|rewrite|fix|correct|amend|touch|adjust|revise)"; +const EDITED: &str = + r"(?:edited|updated|changed|modified|rewritten|fixed|corrected|amended|adjusted|revised)"; +const CANNOT: &str = r"(?:can't|cannot|can not|couldn't|could not|won't be able to|am unable to|was unable to|unable to|am not able to|not able to|have no way to|no way to|don't have (?:a |the |any )?(?:way|tool|tools|access|permission|permissions|ability) to|do not have (?:a |the |any )?(?:way|tool|tools|access|permission|permissions|ability) to|have no (?:tool|tools|access|permission|ability) to|lack (?:a |the )?(?:tool|tools|access|permission|ability) to)"; +const PERSON: &str = r"(?:you|someone|somebody|a person|a human|a maintainer|the maintainer|the author|a reviewer|the reviewer|the team|a teammate)"; + +fn patterns() -> &'static [Regex] { + static P: OnceLock> = OnceLock::new(); + P.get_or_init(|| { + [ + // "I can't edit the PR description from here." + format!(r"(?i)\b{CANNOT}\s+(?:\w+\s+){{0,2}}?{EDIT}\s+(?:{OBJECT}|{IN_OBJECT})"), + // "The description can't be changed from this round." + format!(r"(?i)\b(?:description|pr body|pull request body)\b[^.;!?]{{0,40}}?\b(?:can't|cannot|can not|could not|couldn't) be {EDITED}"), + // "You will need to update the description." + format!(r"(?i)\b{PERSON}(?:'ll| will| would| should| must| may| can)?(?: need to| needs to| have to| has to| want to)?\s+(?:please\s+)?(?:manually\s+)?{EDIT}\s+(?:{OBJECT}|{IN_OBJECT})"), + // "Please fix the count in the description." + format!(r"(?i)\bplease\s+(?:manually\s+)?{EDIT}\s+(?:{OBJECT}|{IN_OBJECT})"), + // "The description needs a manual update." + r"(?i)\b(?:description|pr body|pull request body)\b[^.;!?]{0,60}?\b(?:needs?|requires?|will need|still needs?) (?:a |to be )?(?:manual|manually|hand|human)".to_string(), + // "The description must be updated by hand." + format!(r"(?i)\b(?:description|pr body|pull request body)\b[^.;!?]{{0,60}}?\b{EDITED} (?:by hand|manually|by a person|by someone|by a maintainer|by the author)"), + // "I left the description corrections for you." + format!(r"(?i)\b(?:left|leave|leaving)\b[^.;!?]{{0,50}}?\b(?:description|pr body|pull request body)\b[^.;!?]{{0,50}}?\b(?:for|to) {PERSON}"), + ] + .iter() + .map(|p| Regex::new(p).expect("a fixed pattern")) + .collect() + }) +} + +fn hands_off(sentence: &str) -> bool { + let s = sentence.replace('\u{2019}', "'"); + // An instruction not to ("never write that you cannot edit the + // description") is the rule itself, not a handoff. + let lower = s.to_ascii_lowercase(); + if lower.contains("never ") { + return false; + } + patterns().iter().any(|p| p.is_match(&s)) +} + +/// Each line's sentences, as (line index, byte range in the line). +fn spans(text: &str) -> Vec<(usize, usize, usize)> { + let mut out = vec![]; + for (i, line) in text.lines().enumerate() { + for (a, b) in crate::prose::sentence_spans(line) { + out.push((i, a, b)); + } + } + out +} + +/// The sentences of a round's account that say the description can't be +/// edited or leave an edit of it to a person. +pub fn handoffs(text: &str) -> Vec { + let lines: Vec<&str> = text.lines().collect(); + spans(text) + .into_iter() + .map(|(i, a, b)| lines[i][a..b].trim()) + .filter(|s| hands_off(s)) + .map(String::from) + .collect() +} + +/// `text` without its [`handoffs`], [`REBUILT`] in place of the first. +/// `None` when it has none, so a caller rebuilds only when there is cause. +pub fn scrub(text: &str) -> Option { + let mut found = false; + let mut out: Vec = vec![]; + for line in text.lines() { + let mut kept = String::new(); + let mut cut = false; + for (a, b) in crate::prose::sentence_spans(line) { + let piece = &line[a..b]; + if !hands_off(piece.trim()) { + kept.push_str(piece); + continue; + } + cut = true; + if !found { + // Keep the sentence's lead (indent, bullet) with the text + // that replaces it. + let lead: String = piece + .chars() + .take_while(|c| c.is_whitespace() || matches!(c, '-' | '*' | '>')) + .collect(); + kept.push_str(&lead); + kept.push_str(REBUILT); + found = true; + } + } + if !cut { + out.push(line.to_string()); + } else if !kept.trim().trim_matches(['-', '*', '>']).trim().is_empty() { + out.push(kept); + } + } + found.then(|| out.join("\n")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_round_that_hands_the_description_to_a_person_is_caught() { + for s in [ + "I can't edit the PR description from here.", + "I cannot update the pull request description in this round, so it still lists the old versions.", + "I don't have a tool to change the description.", + "I was unable to fix the table in the PR description.", + "The description can't be changed from this round.", + "You will need to update the PR description: the table still says 4.0.4.", + "Please correct the count in the description.", + "The PR description needs a manual update.", + "The description should be corrected by hand.", + "I left the description corrections for the author.", + "Someone should fix the headline in the PR body.", + "I can\u{2019}t edit the PR description from here.", + ] { + assert_eq!(handoffs(s), vec![s.to_string()], "{s}"); + } + } + + #[test] + fn a_sentence_that_only_mentions_the_description_passes() { + for s in [ + "Updated the description as asked.", + "The description said five packages cross a major version; the manifest keeps each on its line.", + "I can't reproduce the failure the description mentions.", + "You should update the tests the ticket's description lists.", + "The table in the description was wrong about glob-walk.", + "Please review the override for path-match.", + "I could not run the build in the sandbox.", + "The description of the `retry` option in the README is unchanged.", + "CoderHelm rebuilds the pull request's description from the branch after this round.", + "No change to the meta description tag was needed.", + ] { + assert!(handoffs(s).is_empty(), "{s}: {:?}", handoffs(s)); + } + } + + #[test] + fn the_handoff_is_replaced_by_the_rebuild_once() { + let account = "Kept glob-walk on the 2 line with a scoped override.\n\ + - I can't edit the PR description from here. Please update the table in the description.\n\ + - The lockfile was written by the sandbox."; + let out = scrub(account).unwrap(); + assert_eq!( + out, + format!( + "Kept glob-walk on the 2 line with a scoped override.\n- {REBUILT}\n- The lockfile was written by the sandbox." + ) + ); + assert!(handoffs(&out).is_empty()); + assert_eq!(scrub("Kept glob-walk on the 2 line."), None); + // The round's note itself is never read as a handoff. + assert!( + handoffs(ROUND_NOTE).is_empty(), + "{:?}", + handoffs(ROUND_NOTE) + ); + } +} diff --git a/services/common/src/file_claims.rs b/services/common/src/file_claims.rs new file mode 100644 index 000000000..677e377bc --- /dev/null +++ b/services/common/src/file_claims.rs @@ -0,0 +1,461 @@ +//! A sentence a run writes into the repository is held to the same proof as +//! one it writes on the pull request. +//! +//! A run that edits a README, a changelog or a docs page can write "the +//! build passes with these versions" there, and the file is then merged with +//! a claim nothing checked. The pull request's own sections say only what a +//! check recorded; a file the run writes must too. +//! +//! - [`claims_in_patch`] reads the lines a change adds to a prose file and +//! returns each sentence that states, as a fact, that the build, the +//! tests, the linter or the type check passes. +//! - [`unproven`] keeps the ones no recorded passing result covers on this +//! head. The run then runs the check, or takes the sentence out +//! ([`without`]) before it finishes. +//! +//! The reading is narrow on purpose, since most prose that names a build or +//! a test is not a claim: an instruction ("make sure the tests pass"), a +//! condition ("once CI is green"), a plan ("the build should pass"), a +//! question, a heading, a command, a negative ("the tests fail on Node 18") +//! and a sentence where the word is something else ("the build passes +//! options to the bundler") are all left alone. Only a plain statement with +//! the check as its subject and a passing result as what is said of it +//! counts. + +use std::sync::OnceLock; + +use regex::Regex; +use serde::{Deserialize, Serialize}; + +/// The kinds of check a sentence can claim. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ClaimKind { + Build, + Tests, + Lint, + Typecheck, +} + +impl ClaimKind { + /// The name the run's check records use (`checks::CheckKind::name`). + pub fn name(self) -> &'static str { + match self { + ClaimKind::Build => "build", + ClaimKind::Tests => "tests", + ClaimKind::Lint => "lint", + ClaimKind::Typecheck => "typecheck", + } + } + + fn words(self) -> &'static str { + match self { + ClaimKind::Build => "the build", + ClaimKind::Tests => "the tests", + ClaimKind::Lint => "the linter", + ClaimKind::Typecheck => "the type check", + } + } +} + +/// One sentence a change adds to a file that claims a check passes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Claim { + pub path: String, + /// The line in the new file. + pub line: u64, + pub sentence: String, + pub kinds: Vec, +} + +impl Claim { + /// What the claim says passes, in words (`the build and the tests`). + pub fn what(&self) -> String { + let w: Vec<&str> = self.kinds.iter().map(|k| k.words()).collect(); + match w.as_slice() { + [] => String::new(), + [one] => one.to_string(), + [init @ .., last] => format!("{} and {last}", init.join(", ")), + } + } +} + +/// A file whose added sentences are read: prose a person reads as fact. +pub fn is_prose_path(path: &str) -> bool { + let lower = path.to_ascii_lowercase(); + let name = lower.rsplit('/').next().unwrap_or(&lower); + [".md", ".mdx", ".rst", ".adoc", ".txt"] + .iter() + .any(|e| name.ends_with(e)) + || matches!( + name, + "readme" | "changelog" | "changes" | "history" | "news" + ) +} + +struct Patterns { + subjects: Vec<(ClaimKind, Regex)>, + /// A word that makes the sentence something other than a statement of + /// fact about now: an instruction, a plan, a requirement. + not_a_fact: Regex, + /// A word that, before the check's name, makes what follows a + /// condition ("once the build is green") and not a statement. + condition: Regex, + negative: Regex, + /// "0 failed", "no failures": a pass said through its failures. + zero_failures: Regex, +} + +/// What may follow the check's name before the passing word: a few plain +/// words ("now", "and lint", "of the web app"), never a clause. +const GAP: &str = r"(?:,?[ \t]+(?:and|&|or|plus)?[ \t]*[\w`'./@:-]+){0,4}?,?[ \t]+"; +/// The passing word, and what may follow `pass`: a sentence end or a word +/// that continues the result ("on Node 22", "with these versions"). `pass` +/// with an object ("passes options to") is another verb. +const PASSES: &str = r"(?:(?:(?:all|both|now|still|again|also)[ \t]+)*(?:pass(?:es|ed)?|succeeds?|succeeded)(?:[ \t]+(?:on|with|in|for|again|now|locally|cleanly|successfully|after|against|at|under|and|too|here|there|everywhere)\b|[ \t]*(?:$|[.,;:!)]))|(?:is|are|was|were|stays?|remains?|came back|comes back|runs?|ran)[ \t]+(?:(?:all|now|still|again)[ \t]+)*(?:green|clean|passing|successful)\b|(?:builds?|compiles?|built|compiled)[ \t]+(?:successfully|cleanly|without (?:errors?|warnings?)|with no errors?)\b)"; + +fn patterns() -> &'static Patterns { + static P: OnceLock = OnceLock::new(); + P.get_or_init(|| { + let re = |p: &str| Regex::new(p).expect("a fixed pattern"); + let subject = |names: &str| re(&format!(r"(?i)\b(?:{names})\b{GAP}{PASSES}")); + Patterns { + subjects: vec![ + ( + ClaimKind::Build, + subject(r"build|production build|app build|compilation|compile"), + ), + ( + ClaimKind::Tests, + subject(r"tests|test suite|unit tests|integration tests|end-to-end tests|e2e tests|specs|suite"), + ), + ( + ClaimKind::Lint, + subject(r"lint|linter|linting|eslint|clippy|lint check"), + ), + ( + ClaimKind::Typecheck, + subject(r"type[- ]?check|type[- ]?checks|type[- ]?checking|typecheck|tsc"), + ), + ], + not_a_fact: re( + r"(?i)\b(?:should|must|shall|will|would|could|might|may|can|need|needs|needed|want|wants|expect|expects|expected|require|requires|required|ensure|verify|check that|confirm|make sure|whether|so that|in order|to make|to get|to keep|todo|tbd|try|please|let's|how to|example|e\.g)\b", + ), + condition: re(r"(?i)\b(?:if|when|whenever|once|until|unless|before|after|while|as soon as)\b"), + negative: re(r"(?i)(?:\b(?:not|never|no longer|fail|fails|failed|failing|broken|breaks|flaky|red)\b|n't\b)"), + zero_failures: re(r"(?i)\b(?:0|zero|no)[ \t]+(?:failed|failures?|errors?)\b|\bwithout (?:failures?|errors?|warnings?)\b|\bwith no errors?\b"), + } + }) +} + +/// The builds a sentence names with the `builds successfully` form, where +/// the check's name and the passing word are one word. +fn build_verb() -> &'static Regex { + static R: OnceLock = OnceLock::new(); + R.get_or_init(|| { + Regex::new( + r"(?i)\b(?:builds?|compiles?|built|compiled)[ \t]+(?:successfully|cleanly|without (?:errors?|warnings?)|with no errors?)\b", + ) + .expect("a fixed pattern") + }) +} + +/// The kinds of check `sentence` states as passing; empty when it is not +/// such a statement. +pub fn claimed(sentence: &str) -> Vec { + let p = patterns(); + let s = sentence.trim(); + if s.is_empty() || s.ends_with('?') || p.not_a_fact.is_match(s) { + return vec![]; + } + // A pass said through its failures ("0 failed") is not a negative. + let plain = p.zero_failures.replace_all(s, " "); + if p.negative.is_match(&plain) { + return vec![]; + } + let stated = |re: &Regex| { + re.find(s) + .is_some_and(|m| !p.condition.is_match(&s[..m.start()])) + }; + let mut kinds: Vec = p + .subjects + .iter() + .filter(|(_, re)| stated(re)) + .map(|(k, _)| *k) + .collect(); + if !kinds.contains(&ClaimKind::Build) && stated(build_verb()) { + kinds.insert(0, ClaimKind::Build); + } + kinds +} + +/// A line that is not prose: a heading, a command, a table rule, an image +/// or badge, a quoted line of someone else's text. +fn skipped_line(line: &str) -> bool { + let t = line.trim_start(); + t.starts_with('#') + || t.starts_with('$') + || t.starts_with("![") + || t.starts_with("[![") + || t.starts_with('>') + || t.starts_with("|-") + || t.starts_with("- [ ]") + || t.starts_with("* [ ]") + || line.starts_with(" ") + || line.starts_with('\t') +} + +/// The text of a line with its inline code taken out: a command in +/// backticks is not a sentence's words. +fn without_inline_code(line: &str) -> String { + let mut out = String::new(); + let mut code = false; + for c in line.chars() { + if c == '`' { + code = !code; + out.push('`'); + } else if !code { + out.push(c); + } + } + out +} + +/// The claims a change adds to `path`, read from its patch (a unified diff +/// as GitHub's compare gives it). Nothing for a file that is not prose. +pub fn claims_in_patch(path: &str, patch: &str) -> Vec { + if !is_prose_path(path) { + return vec![]; + } + let mut out = vec![]; + let mut line_no: u64 = 0; + let mut fenced = false; + for raw in patch.lines() { + if let Some(rest) = raw.strip_prefix("@@") { + // `@@ -a,b +c,d @@`: the new file's line the hunk starts at. A + // hunk never starts inside a fence this reader has seen open. + line_no = rest + .split('+') + .nth(1) + .and_then(|s| s.split([',', ' ']).next()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(1); + fenced = false; + continue; + } + let (added, text) = match raw.chars().next() { + Some('+') => (true, &raw[1..]), + Some('-') | Some('\\') => continue, + Some(' ') => (false, &raw[1..]), + _ => (false, raw), + }; + let here = line_no; + line_no += 1; + let t = text.trim_start(); + if t.starts_with("```") || t.starts_with("~~~") { + fenced = !fenced; + continue; + } + if !added || fenced || skipped_line(text) { + continue; + } + for (a, b) in crate::prose::sentence_spans(text) { + // The sentence as the file has it, without its bullet. + let sentence = text[a..b] + .trim() + .trim_start_matches(['-', '*', '+']) + .trim_start(); + let kinds = claimed(&without_inline_code(sentence)); + if kinds.is_empty() { + continue; + } + out.push(Claim { + path: path.to_string(), + line: here, + sentence: sentence.to_string(), + kinds, + }); + } + } + out +} + +/// The claims no recorded passing result covers: `proven` holds the kinds +/// of check with a passing result recorded on this head. +pub fn unproven(claims: &[Claim], proven: &[ClaimKind]) -> Vec { + claims + .iter() + .filter(|c| c.kinds.iter().any(|k| !proven.contains(k))) + .cloned() + .collect() +} + +/// `text` (the file at `path`) without the sentences of `claims` that are +/// in it. A line left with nothing but its bullet goes too. Returns `None` +/// when no sentence was found, so nothing is written for nothing. +pub fn without(path: &str, text: &str, claims: &[Claim]) -> Option { + let mine: Vec<&Claim> = claims.iter().filter(|c| c.path == path).collect(); + let mut changed = false; + let mut out: Vec = vec![]; + for line in text.lines() { + if !mine.iter().any(|c| line.contains(c.sentence.as_str())) { + out.push(line.to_string()); + continue; + } + let mut kept = line.to_string(); + for c in &mine { + if let Some(at) = kept.find(c.sentence.as_str()) { + let end = at + c.sentence.len(); + // The space that joined it to the next sentence goes with it. + let end = if kept[end..].starts_with(' ') { + end + 1 + } else { + end + }; + kept.replace_range(at..end, ""); + changed = true; + } + } + let bare = kept + .trim() + .trim_start_matches(['-', '*', '+']) + .trim_start_matches(|c: char| c.is_ascii_digit() || c == '.') + .trim(); + if !bare.is_empty() { + out.push(kept.trim_end().to_string()); + } + } + if !changed { + return None; + } + let mut joined = out.join("\n"); + if text.ends_with('\n') { + joined.push('\n'); + } + Some(joined) +} + +#[cfg(test)] +mod tests { + use super::*; + use ClaimKind::*; + + #[test] + fn a_plain_statement_that_a_check_passes_is_a_claim() { + for (s, want) in [ + ("All tests pass.", vec![Tests]), + ("The build passes with these versions.", vec![Build]), + ("Lint and type check are clean.", vec![Lint, Typecheck]), + ("The test suite is green on Node 22.", vec![Tests]), + ("Verified: the production build succeeds.", vec![Build]), + ( + "The app builds successfully after the upgrade.", + vec![Build], + ), + ("Build, lint and tests all pass.", vec![Build, Tests, Lint]), + ( + "The unit tests ran clean (212 passed, 0 failed).", + vec![Tests], + ), + ("tsc passes.", vec![Typecheck]), + ("The e2e tests passed against staging.", vec![Tests]), + ("The build passes after the upgrade.", vec![Build]), + ] { + assert_eq!(claimed(s), want, "{s}"); + } + } + + #[test] + fn ordinary_prose_about_builds_and_tests_is_not_a_claim() { + for s in [ + // Instructions, conditions, plans, requirements. + "Make sure the tests pass before you open a pull request.", + "Run `pnpm build` and check that the build passes.", + "Once the build is green, deploy from the release branch.", + "After the tests pass, the release job tags the commit.", + "The build should pass on Node 20 and later.", + "A pull request needs the tests passing to merge.", + "If the linter is clean, the hook lets the commit through.", + "Tests must pass on every supported version.", + "Does the build pass on Windows?", + // Negatives. + "The tests fail on Node 18.", + "The build does not pass without the env file.", + "Type checking isn't clean yet for the legacy folder.", + // The word means something else. + "The build passes options to the bundler through `--config`.", + "Each test passes a fixture to the handler.", + "The suite passes the locale to every spec.", + "The linter is configured in `eslint.config.js`.", + "Tests live in `packages/*/test`.", + "Bumped the build tooling to version 5.", + "Fixed the failing tests for the date parser.", + "The build step runs after lint in CI.", + "Added a test for the retry option.", + "The types are generated from the schema.", + "This release changes how the build output is cached.", + "", + ] { + assert!(claimed(s).is_empty(), "{s}: {:?}", claimed(s)); + } + } + + const PATCH: &str = "@@ -10,6 +10,12 @@ ## Upgrading\n context line\n+## Verified: the build passes\n+The build passes with these versions. Path matching is unchanged.\n+- All tests pass.\n+\n+```sh\n+pnpm build # the build passes\n+```\n+Make sure the tests pass before releasing.\n-An old line where the tests pass.\n unchanged: the tests pass.\n"; + + #[test] + fn only_added_prose_lines_of_prose_files_are_read() { + let found = claims_in_patch("docs/upgrading.md", PATCH); + let got: Vec<(u64, &str, &[ClaimKind])> = found + .iter() + .map(|c| (c.line, c.sentence.as_str(), c.kinds.as_slice())) + .collect(); + assert_eq!( + got, + vec![ + (12, "The build passes with these versions.", &[Build][..]), + (13, "All tests pass.", &[Tests][..]), + ], + "the heading, the fenced command, the instruction, the removed line and the \ + unchanged line are not claims this change adds" + ); + assert!(claims_in_patch("src/build.ts", PATCH).is_empty()); + assert!(is_prose_path("CHANGELOG") && is_prose_path("apps/web/README.md")); + assert!(!is_prose_path("package.json")); + } + + #[test] + fn a_claim_stands_only_with_a_recorded_passing_result() { + let found = claims_in_patch("README.md", PATCH); + assert_eq!(unproven(&found, &[Build, Tests]), vec![]); + let open = unproven(&found, &[Tests]); + assert_eq!(open.len(), 1); + assert_eq!(open[0].what(), "the build"); + assert_eq!(unproven(&found, &[]).len(), 2); + } + + #[test] + fn an_unproven_claim_is_taken_out_and_the_rest_of_the_file_stays() { + let file = "## Upgrading\n\nThe build passes with these versions. Path matching is unchanged.\n- All tests pass.\n- Node 20 or later.\n"; + let found = vec![ + Claim { + path: "README.md".into(), + line: 3, + sentence: "The build passes with these versions.".into(), + kinds: vec![Build], + }, + Claim { + path: "README.md".into(), + line: 4, + sentence: "All tests pass.".into(), + kinds: vec![Tests], + }, + ]; + assert_eq!( + without("README.md", file, &found).unwrap(), + "## Upgrading\n\nPath matching is unchanged.\n- Node 20 or later.\n" + ); + assert_eq!(without("docs/other.md", file, &found), None); + assert_eq!(without("README.md", "Nothing here.\n", &found), None); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 77e2dad8a..a47f00bd6 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -43,11 +43,14 @@ pub mod deliveries_rollup; /// bisect, resumable state. pub mod dep_audit; pub mod dep_fix; +pub mod dep_head; +pub mod description_handoff; /// The shared dead-letter queue: whose each failed message is, whether the /// worker can read it, and when the cleanup archives it. pub mod dlq; /// One DNS TXT lookup through the system resolver (the email check's DMARC). pub mod dns_txt; +pub mod file_claims; /// Hybrid self-hosting: CoderHelm addresses, the event relay, the token /// broker and the signatures between an install and the hosted side. pub mod hybrid; diff --git a/services/common/src/prose.rs b/services/common/src/prose.rs index eb96b0018..401275ff3 100644 --- a/services/common/src/prose.rs +++ b/services/common/src/prose.rs @@ -52,6 +52,24 @@ pub fn sentence_ends(text: &str) -> Vec { ends } +/// The sentences of `text`, each with its byte range: every stretch up to a +/// sentence end ([`sentence_ends`]), and what is left after the last one. +/// Leading whitespace belongs to the sentence it precedes. +pub fn sentence_spans(text: &str) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + let mut start = 0; + for end in sentence_ends(text) { + if !text[start..end].trim().is_empty() { + out.push((start, end)); + } + start = end; + } + if !text[start..].trim().is_empty() { + out.push((start, text.len())); + } + out +} + /// At most `max_sentences` whole sentences and about `max_bytes`. A first /// sentence longer than `max_bytes` is kept whole: the cap never splits it. /// Text with no sentence end is returned as it is. diff --git a/services/common/src/reachability.rs b/services/common/src/reachability.rs index a6c9185c7..81c462e42 100644 --- a/services/common/src/reachability.rs +++ b/services/common/src/reachability.rs @@ -1303,6 +1303,192 @@ struct Graph { edges: Vec>, /// (direct dependency name, its node) roots: Vec<(String, usize)>, + /// The workspace projects the lockfile installs for: each one's folder + /// from the lockfile's folder (`""` for the root) and the nodes it + /// depends on directly. + projects: Vec<(String, Vec)>, + /// (project, a workspace project it depends on), by index in `projects`. + project_links: Vec<(usize, usize)>, +} + +/// `rel` from the folder `base`, with `.` and `..` resolved (`apps/web` and +/// `../studio` is `apps/studio`). +fn join_rel(base: &str, rel: &str) -> String { + let mut parts: Vec<&str> = base.split('/').filter(|p| !p.is_empty()).collect(); + for seg in rel.split('/') { + match seg { + "" | "." => {} + ".." => { + parts.pop(); + } + s => parts.push(s), + } + } + parts.join("/") +} + +/// One workspace project of a lockfile, and which of the packages asked +/// about its dependencies bring in. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct LockProject { + /// Its folder, from the lockfile's folder (`""`: the lockfile's own). + pub dir: String, + /// The packages asked about that it installs, directly or through a + /// dependency or another workspace project, as `name@version`. + pub uses: Vec, +} + +fn graph_of(path: &str, text: &str, manifests: &[(String, String)]) -> Option { + let name = path.rsplit('/').next().unwrap_or(path); + match name { + "pnpm-lock.yaml" => pnpm_graph(text), + "package-lock.json" | "npm-shrinkwrap.json" => npm_graph(text), + "yarn.lock" => yarn_projects(text, manifests), + _ => None, + } +} + +/// Every installed copy a lockfile resolves, as (name, version). `None` for +/// a lockfile this can't read: the caller then says the versions are not +/// known, never a guess. +pub fn lock_copies(path: &str, text: &str) -> Option> { + let name = path.rsplit('/').next().unwrap_or(path); + let mut out: Vec<(String, String)> = match name { + "pnpm-lock.yaml" | "package-lock.json" | "npm-shrinkwrap.json" | "yarn.lock" => { + graph_of(path, text, &[])?.nodes + } + "Cargo.lock" | "poetry.lock" | "uv.lock" => toml_copies(text), + "Gemfile.lock" => gem_copies(text), + _ => return None, + }; + out.retain(|(n, v)| !n.is_empty() && !v.is_empty()); + out.sort(); + out.dedup(); + (!out.is_empty()).then_some(out) +} + +/// The `[[package]]` tables of a TOML lockfile (`Cargo.lock`, `poetry.lock`, +/// `uv.lock`): each one's `name` and `version`. +fn toml_copies(text: &str) -> Vec<(String, String)> { + let mut out = vec![]; + let mut cur: Option<(String, String)> = None; + let value = |l: &str, key: &str| -> Option { + let rest = l.strip_prefix(key)?.trim_start().strip_prefix('=')?; + Some(rest.trim().trim_matches('"').to_string()) + }; + for line in text.lines() { + let t = line.trim(); + if t.starts_with('[') { + if let Some(c) = cur.take() { + out.push(c); + } + if t == "[[package]]" { + cur = Some((String::new(), String::new())); + } + continue; + } + if let Some(c) = cur.as_mut() { + if let Some(v) = value(t, "name") { + c.0 = v; + } else if let Some(v) = value(t, "version") { + c.1 = v; + } + } + } + out.extend(cur); + out +} + +/// The gems a `Gemfile.lock` resolves: the `name (version)` lines of its +/// `specs:` lists (a dependency's own requirements sit deeper and carry a +/// range, never a single version). +fn gem_copies(text: &str) -> Vec<(String, String)> { + let mut out = vec![]; + for line in text.lines() { + let Some(rest) = line.strip_prefix(" ") else { + continue; + }; + if rest.starts_with(' ') { + continue; + } + let Some((name, ver)) = rest.split_once(" (") else { + continue; + }; + let ver = ver.trim_end_matches(')'); + if ver.chars().next().is_some_and(|c| c.is_ascii_digit()) && !ver.contains(' ') { + out.push((name.to_string(), ver.to_string())); + } + } + out +} + +/// The workspace projects of a lockfile, each with the packages of `asked` +/// (name and a version on the line asked about) that its dependencies bring +/// in: the projects a change to those packages can break. `manifests`: each +/// workspace project's folder (from the lockfile's folder) and its +/// `package.json`; only `yarn.lock`, which does not list its projects, +/// needs them. `None` for a lockfile this can't read. +pub fn lock_projects( + path: &str, + text: &str, + manifests: &[(String, String)], + asked: &[(String, String)], +) -> Option> { + let g = graph_of(path, text, manifests)?; + if g.projects.is_empty() { + return None; + } + let mut out = vec![]; + for (pi, (dir, _)) in g.projects.iter().enumerate() { + // This project and every workspace project it depends on. + let mut mine = vec![pi]; + let mut i = 0; + while i < mine.len() { + for (from, to) in &g.project_links { + if *from == mine[i] && !mine.contains(to) { + mine.push(*to); + } + } + i += 1; + } + let mut seen: HashSet = HashSet::new(); + let mut queue: VecDeque = VecDeque::new(); + for p in &mine { + for n in &g.projects[*p].1 { + if seen.insert(*n) { + queue.push_back(*n); + } + } + } + while let Some(n) = queue.pop_front() { + for to in &g.edges[n] { + if seen.insert(*to) { + queue.push_back(*to); + } + } + } + let mut uses: Vec = seen + .iter() + .map(|n| &g.nodes[*n]) + .filter(|(name, ver)| { + asked.iter().any(|(an, av)| { + an == name + && !ver.is_empty() + && crate::security_fixes::version_line(av) + == crate::security_fixes::version_line(ver) + }) + }) + .map(|(name, ver)| format!("{name}@{ver}")) + .collect(); + uses.sort(); + uses.dedup(); + out.push(LockProject { + dir: dir.clone(), + uses, + }); + } + out.sort_by(|a, b| a.dir.cmp(&b.dir)); + Some(out) } impl Graph { @@ -1454,13 +1640,18 @@ fn pnpm_graph(text: &str) -> Option { } } // The direct dependencies: each importer's, or the top level's. - let mut importers: Vec<&serde_yaml::Value> = vec![]; + let mut importers: Vec<(String, &serde_yaml::Value)> = vec![]; if let Some(m) = doc.get("importers") { - importers.extend(yaml_map(m).into_iter().map(|(_, v)| v)); + importers.extend(yaml_map(m)); } else { - importers.push(&doc); - } - for imp in importers { + importers.push((".".to_string(), &doc)); + } + // (project, the folder of the workspace project it links to) + let mut links: Vec<(usize, String)> = vec![]; + for (key, imp) in importers { + let dir = join_rel("", &key); + let pi = g.projects.len(); + g.projects.push((dir.clone(), vec![])); for field in ["dependencies", "devDependencies", "optionalDependencies"] { let Some(m) = imp.get(field) else { continue }; for (dn, dv) in yaml_map(m) { @@ -1469,14 +1660,24 @@ fn pnpm_graph(text: &str) -> Option { other => yaml_str(other), }; let Some(value) = value else { continue }; + if let Some(to) = value.strip_prefix("link:") { + links.push((pi, join_rel(&dir, to))); + continue; + } if let Some(t) = pnpm_target(&dn, &value, v5) { if let Some(n) = node(&mut g, &t) { g.roots.push((dn.clone(), n)); + g.projects[pi].1.push(n); } } } } } + for (from, dir) in links { + if let Some(to) = g.projects.iter().position(|(d, _)| *d == dir) { + g.project_links.push((from, to)); + } + } Some(g) } @@ -1521,18 +1722,92 @@ fn npm_graph(text: &str) -> Option { } } } + // The workspace projects: every location outside `node_modules`. A + // dependency that resolves to a link is another workspace project. + let project_locs: Vec<&str> = packages + .keys() + .map(String::as_str) + .filter(|l| !l.contains("node_modules/")) + .collect(); + let mut loc_of: Vec<&str> = vec![""; g.nodes.len()]; + for (loc, i) in &index { + loc_of[*i] = loc; + } + for loc in &project_locs { + let pi = g.projects.len(); + g.projects.push((loc.to_string(), vec![])); + for to in g.edges[index[*loc]].clone() { + match packages.get(loc_of[to]) { + Some(p) if p["link"].as_bool() == Some(true) => { + let dir = p["resolved"].as_str().unwrap_or("").trim_matches('/'); + if let Some(at) = project_locs.iter().position(|l| *l == dir) { + g.project_links.push((pi, at)); + } + } + _ => g.projects[pi].1.push(to), + } + } + } Some(g) } +fn yarn_spec(name: &str, range: &str) -> String { + let r = range.trim().trim_matches('"'); + let r = r.strip_prefix("npm:").unwrap_or(r); + format!("{name}@{r}") +} + fn yarn_graph(text: &str, direct_names: &[String]) -> Option { + let (mut g, _) = yarn_parse(text)?; + // The project's own dependencies: every copy of a name it lists. + for d in direct_names { + for (i, (n, _)) in g.nodes.iter().enumerate() { + if n == d { + g.roots.push((d.clone(), i)); + } + } + } + Some(g) +} + +/// A `yarn.lock` with its workspace projects, which the lockfile itself +/// does not list: each project's `package.json` names what it depends on, +/// and the lockfile says which copy each range resolves to. +fn yarn_projects(text: &str, manifests: &[(String, String)]) -> Option { + let (mut g, spec_to) = yarn_parse(text)?; + let parsed: Vec<(String, Value)> = manifests + .iter() + .filter_map(|(dir, t)| Some((join_rel("", dir), serde_json::from_str::(t).ok()?))) + .collect(); + for (dir, _) in &parsed { + g.projects.push((dir.clone(), vec![])); + } + for (pi, (_, m)) in parsed.iter().enumerate() { + for field in ["dependencies", "devDependencies", "optionalDependencies"] { + for (dep, range) in m[field].as_object().into_iter().flatten() { + let range = range.as_str().unwrap_or(""); + if let Some(n) = spec_to.get(&yarn_spec(dep, range)) { + g.roots.push((dep.clone(), *n)); + g.projects[pi].1.push(*n); + } else if let Some(to) = parsed + .iter() + .position(|(_, o)| o["name"].as_str() == Some(dep.as_str())) + { + g.project_links.push((pi, to)); + } + } + } + } + Some(g) +} + +/// The copies and edges of a `yarn.lock` (classic and berry), and which +/// copy each `name@range` resolves to. +fn yarn_parse(text: &str) -> Option<(Graph, HashMap)> { let mut g = Graph::default(); let mut spec_to: HashMap = HashMap::new(); let mut pending: Vec<(usize, String, String)> = vec![]; - let norm = |name: &str, range: &str| { - let r = range.trim().trim_matches('"'); - let r = r.strip_prefix("npm:").unwrap_or(r); - format!("{name}@{r}") - }; + let norm = yarn_spec; let split_spec = |spec: &str| -> Option<(String, String)> { let s = spec.trim().trim_matches('"'); let at = s[1..].find('@')? + 1; @@ -1595,18 +1870,10 @@ fn yarn_graph(text: &str, direct_names: &[String]) -> Option { g.edges[from].push(*to); } } - // The project's own dependencies: every copy of a name it lists. - for d in direct_names { - for (i, (n, _)) in g.nodes.iter().enumerate() { - if n == d { - g.roots.push((d.clone(), i)); - } - } - } if g.nodes.is_empty() { return None; } - Some(g) + Some((g, spec_to)) } /// The names a `package.json` lists as dependencies. @@ -1968,6 +2235,144 @@ snapshots: assert_eq!(a.parents.iter().cloned().collect::>(), ["a"]); } + // ── The workspace projects a changed package can break ───────────── + + fn asked() -> Vec<(String, String)> { + vec![ + ("glob-walk".to_string(), "2.3.1".to_string()), + ("path-match".to_string(), "3.1.2".to_string()), + ] + } + + fn uses(projects: &[LockProject]) -> Vec<(&str, Vec<&str>)> { + projects + .iter() + .map(|p| (p.dir.as_str(), p.uses.iter().map(String::as_str).collect())) + .collect() + } + + /// A site, a studio no CI job builds, a shared package the site links, + /// and a docs project that takes neither changed package. + #[test] + fn pnpm_workspace_projects_that_consume_a_changed_line_are_found() { + let lock = "lockfileVersion: '9.0'\nimporters:\n .:\n devDependencies:\n turbo:\n specifier: ^2.0.0\n version: 2.0.1\n apps/web:\n dependencies:\n '@acme/ui':\n specifier: workspace:*\n version: link:../../packages/ui\n next-ish:\n specifier: ^14.0.0\n version: 14.1.0\n apps/studio:\n dependencies:\n studio-kit:\n specifier: ^3.0.0\n version: 3.2.0\n apps/docs:\n dependencies:\n glob-walk:\n specifier: ^4.0.0\n version: 4.0.1\n packages/ui:\n dependencies:\n path-match:\n specifier: ^3.1.0\n version: 3.1.2\npackages:\n glob-walk@2.3.1: {}\n glob-walk@4.0.1: {}\n path-match@3.1.2: {}\n next-ish@14.1.0: {}\n studio-kit@3.2.0: {}\n studio-cli@1.0.0: {}\n turbo@2.0.1: {}\nsnapshots:\n glob-walk@2.3.1: {}\n glob-walk@4.0.1: {}\n path-match@3.1.2: {}\n next-ish@14.1.0: {}\n studio-kit@3.2.0:\n dependencies:\n studio-cli: 1.0.0\n studio-cli@1.0.0:\n dependencies:\n glob-walk: 2.3.1\n turbo@2.0.1: {}\n"; + let projects = lock_projects("pnpm-lock.yaml", lock, &[], &asked()).unwrap(); + assert_eq!( + uses(&projects), + vec![ + ("", vec![]), + // Two levels down, through the studio's tooling. + ("apps/docs", vec![]), + ("apps/studio", vec!["glob-walk@2.3.1"]), + // Through the workspace package it links. + ("apps/web", vec!["path-match@3.1.2"]), + ("packages/ui", vec!["path-match@3.1.2"]), + ], + "the docs project has glob-walk on the 4 line only, which did not change" + ); + let copies = lock_copies("pnpm-lock.yaml", lock).unwrap(); + assert!(copies.contains(&("glob-walk".into(), "2.3.1".into()))); + assert!(copies.contains(&("glob-walk".into(), "4.0.1".into()))); + } + + #[test] + fn npm_workspace_projects_that_consume_a_changed_line_are_found() { + let lock = r#"{"lockfileVersion":3,"packages":{ + "":{"name":"site","workspaces":["apps/*","packages/*"],"devDependencies":{"turbo":"^2.0.0"}}, + "apps/web":{"name":"web","dependencies":{"@acme/ui":"*","next-ish":"^14.0.0"}}, + "apps/studio":{"name":"studio","dependencies":{"studio-kit":"^3.0.0"}}, + "packages/ui":{"name":"@acme/ui","dependencies":{"path-match":"^3.1.0"}}, + "node_modules/@acme/ui":{"resolved":"packages/ui","link":true}, + "node_modules/web":{"resolved":"apps/web","link":true}, + "node_modules/studio":{"resolved":"apps/studio","link":true}, + "node_modules/turbo":{"version":"2.0.1","dev":true}, + "node_modules/next-ish":{"version":"14.1.0"}, + "node_modules/path-match":{"version":"3.1.2"}, + "node_modules/studio-kit":{"version":"3.2.0","dependencies":{"glob-walk":"^2.3.0"}}, + "node_modules/glob-walk":{"version":"4.0.1"}, + "node_modules/studio-kit/node_modules/glob-walk":{"version":"2.3.1"}}}"#; + let projects = lock_projects("package-lock.json", lock, &[], &asked()).unwrap(); + assert_eq!( + uses(&projects), + vec![ + ("", vec![]), + ("apps/studio", vec!["glob-walk@2.3.1"]), + ("apps/web", vec!["path-match@3.1.2"]), + ("packages/ui", vec!["path-match@3.1.2"]), + ] + ); + let copies = lock_copies("package-lock.json", lock).unwrap(); + assert!(copies.contains(&("glob-walk".into(), "2.3.1".into()))); + assert!(!copies.iter().any(|(n, _)| n == "web"), "a link is no copy"); + } + + #[test] + fn yarn_workspace_projects_are_read_from_their_manifests() { + let manifests = vec![ + ( + "".to_string(), + r#"{"name":"site","private":true,"workspaces":["apps/*","packages/*"]}"# + .to_string(), + ), + ( + "apps/web".to_string(), + r#"{"name":"web","dependencies":{"@acme/ui":"*","next-ish":"^14.0.0"}}"# + .to_string(), + ), + ( + "apps/studio".to_string(), + r#"{"name":"studio","devDependencies":{"studio-kit":"^3.0.0"}}"#.to_string(), + ), + ( + "packages/ui".to_string(), + r#"{"name":"@acme/ui","dependencies":{"path-match":"^3.1.0"}}"#.to_string(), + ), + ]; + let classic = "# yarn lockfile v1\n\nglob-walk@^2.3.0:\n version \"2.3.1\"\n\nglob-walk@^4.0.0:\n version \"4.0.1\"\n\nnext-ish@^14.0.0:\n version \"14.1.0\"\n\npath-match@^3.1.0:\n version \"3.1.2\"\n\nstudio-kit@^3.0.0:\n version \"3.2.0\"\n dependencies:\n glob-walk \"^2.3.0\"\n"; + let berry = "__metadata:\n version: 8\n\n\"glob-walk@npm:^2.3.0\":\n version: 2.3.1\n resolution: \"glob-walk@npm:2.3.1\"\n\n\"next-ish@npm:^14.0.0\":\n version: 14.1.0\n resolution: \"next-ish@npm:14.1.0\"\n\n\"path-match@npm:^3.1.0\":\n version: 3.1.2\n resolution: \"path-match@npm:3.1.2\"\n\n\"studio-kit@npm:^3.0.0\":\n version: 3.2.0\n resolution: \"studio-kit@npm:3.2.0\"\n dependencies:\n glob-walk: \"npm:^2.3.0\"\n"; + for lock in [classic, berry] { + let projects = lock_projects("yarn.lock", lock, &manifests, &asked()).unwrap(); + assert_eq!( + uses(&projects), + vec![ + ("", vec![]), + ("apps/studio", vec!["glob-walk@2.3.1"]), + ("apps/web", vec!["path-match@3.1.2"]), + ("packages/ui", vec!["path-match@3.1.2"]), + ], + "{lock}" + ); + } + // Without its projects' manifests a yarn.lock names no project. + assert_eq!(lock_projects("yarn.lock", classic, &[], &asked()), None); + assert_eq!(lock_projects("Cargo.lock", "", &[], &asked()), None); + } + + #[test] + fn the_copies_of_other_lockfiles_are_read_or_said_unreadable() { + let cargo = "version = 3\n\n[[package]]\nname = \"serde\"\nversion = \"1.0.200\"\nsource = \"registry\"\n\n[[package]]\nname = \"time\"\nversion = \"0.3.36\"\n"; + assert_eq!( + lock_copies("Cargo.lock", cargo).unwrap(), + vec![ + ("serde".to_string(), "1.0.200".to_string()), + ("time".to_string(), "0.3.36".to_string()) + ] + ); + let gems = "GEM\n remote: https://rubygems.org/\n specs:\n rack (2.2.8)\n sinatra (3.1.0)\n rack (~> 2.2, >= 2.2.4)\n\nDEPENDENCIES\n sinatra\n"; + assert_eq!( + lock_copies("Gemfile.lock", gems).unwrap(), + vec![ + ("rack".to_string(), "2.2.8".to_string()), + ("sinatra".to_string(), "3.1.0".to_string()) + ] + ); + assert_eq!( + lock_copies("go.sum", "example.com/x v1.0.0 h1:abc=\n"), + None + ); + assert_eq!(lock_copies("pnpm-lock.yaml", "not: [a lockfile"), None); + } + // ── Tiers move with what is learned ─────────────────────────────── use crate::security_fixes::{ diff --git a/services/common/src/runtime_proof.rs b/services/common/src/runtime_proof.rs index d0d5306df..c6fe045ec 100644 --- a/services/common/src/runtime_proof.rs +++ b/services/common/src/runtime_proof.rs @@ -29,6 +29,16 @@ //! - [`report`] writes what ran and what it came to. A part that did not run //! says so with the reason; nothing is claimed that did not run. //! +//! - Every project the bumps can break is built, not only the one with the +//! most bumps. In a workspace, [`add_projects`] adds the build of each +//! project whose dependencies bring in a changed package line (read from +//! the lockfile, `reachability::lock_projects`), whether or not any CI job +//! builds it; [`add_lockfile`] adds the project of every other lockfile +//! the run bumped. A project that is not built, or whose build fails on +//! the base branch too, is named as not proven with the reason +//! ([`unproven_projects`]); a project build that passes on the base +//! branch and fails with the bumps is blamed like any other. +//! //! Everything here is pure; the sandbox run is the worker's //! (`worker::passes::dep_fix`). @@ -49,8 +59,11 @@ pub const PORT: u16 = 38411; pub const COMMON_PORTS: &[u16] = &[3000, 8080, 8000, 5000, 4173, 5173, 4321, 4200]; /// How long the start command gets to answer, in two-second polls. pub const START_POLLS: u32 = 45; -/// Build commands one proof runs. +/// Build commands one proof runs for the main project. pub const MAX_BUILDS: usize = 3; +/// Builds of other affected projects one proof runs beside them: the whole +/// proof is one sandbox run inside one step's time. +pub const MAX_PROJECT_BUILDS: usize = 5; /// The paths requested once the application answers: its root page and the /// health endpoints servers commonly have. pub const PATHS: &[&str] = &["/", "/healthz", "/health", "/api/health"]; @@ -152,6 +165,9 @@ pub struct ProofCmd { pub dir: String, /// Where the command was found, in words (`` `ci.yml`, job `build` ``). pub source: String, + /// The build of another affected project: it is judged on its own and + /// never keeps the main project's start from running. + pub extra: bool, } /// What a proof runs, found once per run. @@ -170,6 +186,246 @@ pub struct ProofPlan { /// Other lockfiles the run bumped packages in, whose projects this /// proof does not build. pub not_covered: Vec, + /// The other projects the bumps can break: each workspace project that + /// takes a changed package line, and the project of each other lockfile + /// with bumps. Each is built, or named as not proven with why. + pub projects: Vec, + /// Why the workspace projects that take the changed packages could not + /// be worked out; empty when they were (or the project is no workspace). + pub projects_unknown: String, +} + +/// One project the bumps can break, beside the main one. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct ProjectProof { + /// Its folder from the repository root. + pub dir: String, + /// Why it is affected, in words (`takes glob-walk@2.3.1`). + pub because: String, + /// Its builds, as indices into the plan's `builds`. + pub builds: Vec, + /// Why it is not built here; empty when it is. + pub not_built: String, +} + +/// A workspace project whose dependencies bring in a changed package line. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct AffectedProject { + /// Its folder from the repository root. + pub dir: String, + /// The changed packages it installs, as `name@version`. + pub uses: Vec, + /// Its scripts manifest (`package.json`), when it has one. + pub manifest: Option, +} + +fn because(uses: &[String]) -> String { + let shown: Vec = uses.iter().take(4).map(|u| format!("`{u}`")).collect(); + format!( + "takes {}{}", + shown.join(", "), + if uses.len() > shown.len() { + format!(" and {} more changed packages", uses.len() - shown.len()) + } else { + String::new() + } + ) +} + +fn project_builds(plan: &ProofPlan) -> usize { + plan.projects.iter().map(|p| p.builds.len()).sum() +} + +/// Adds to `plan` (the proof of `lockfile`'s project) every workspace +/// project the bumps can break: a project a build of the plan already runs +/// in is covered by it; one whose manifest declares a `build` script gets +/// that build, whether or not CI builds it; one that declares none is named +/// as not built. The lockfile's own folder is the plan's main project. +pub fn add_projects(plan: &mut ProofPlan, lockfile: &str, projects: &[AffectedProject]) { + let Some(m) = manager_of(lockfile) else { + return; + }; + for p in projects { + if p.dir == plan.dir || plan.projects.iter().any(|x| x.dir == p.dir) { + continue; + } + let mut proof = ProjectProof { + dir: p.dir.clone(), + because: because(&p.uses), + ..Default::default() + }; + let covered: Vec = plan + .builds + .iter() + .enumerate() + .filter(|(_, b)| b.dir == p.dir) + .map(|(i, _)| i) + .collect(); + let scripted = p + .manifest + .as_deref() + .and_then(|t| script_of(t, "build")) + .is_some(); + if !covered.is_empty() { + proof.builds = covered; + } else if !is_plain_path(&p.dir) { + proof.not_built = "its folder can't be named in a sandbox command".into(); + } else if let (true, Some(run), Some(name)) = (scripted, m.run_script, m.scripts_in) { + if project_builds(plan) >= MAX_PROJECT_BUILDS { + proof.not_built = format!( + "one proof builds at most {MAX_PROJECT_BUILDS} projects beside the main one" + ); + } else { + plan.builds.push(ProofCmd { + cmd: format!("{run} build"), + dir: p.dir.clone(), + source: format!("the `build` script of `{}`", under(&p.dir, name)), + extra: true, + }); + proof.builds = vec![plan.builds.len() - 1]; + } + } else { + proof.not_built = match m.scripts_in { + Some(name) => format!("`{}` declares no `build` script", under(&p.dir, name)), + None => format!("{} has no build per project", m.name), + }; + } + plan.projects.push(proof); + } +} + +/// Adds to `plan` the project of another lockfile the run bumped packages +/// in, as `other` (its own [`discover`]) found it: each of its builds runs +/// after that project's own install. A project with no build is named as +/// not built, with why. +pub fn add_lockfile(plan: &mut ProofPlan, lockfile: &str, bumps: usize, other: &ProofPlan) { + let mut proof = ProjectProof { + dir: other.dir.clone(), + because: format!("has its own lockfile `{lockfile}` with {bumps} of the bumps"), + ..Default::default() + }; + if other.builds.is_empty() { + proof.not_built = other.no_build.clone(); + } else if project_builds(plan) + other.builds.len() > MAX_PROJECT_BUILDS { + proof.not_built = + format!("one proof builds at most {MAX_PROJECT_BUILDS} projects beside the main one"); + } else { + for b in &other.builds { + // The project's own install first, in the lockfile's folder. + let install = if b.dir == other.dir { + other.install.clone() + } else { + format!("( cd \"$CH_ROOT\" && {}{} )", cd(&other.dir), other.install) + }; + plan.builds.push(ProofCmd { + cmd: format!("{install} && {}", b.cmd), + dir: b.dir.clone(), + source: format!("{}, after the install of `{lockfile}`", b.source), + extra: true, + }); + proof.builds.push(plan.builds.len() - 1); + } + } + plan.projects.push(proof); +} + +/// The workspace folders a root `package.json` names (`workspaces`, as a +/// list or under `packages`), among the folders of `tree` that hold a +/// `package.json`. `root`: the folder of the root manifest. Folders are +/// returned from `root`. `*` matches one folder name, `**` any depth. +pub fn workspace_dirs(root_manifest: &str, tree: &[String], root: &str) -> Vec { + let Ok(v) = serde_json::from_str::(root_manifest) else { + return vec![]; + }; + let ws = &v["workspaces"]; + let globs: Vec<&str> = ws + .as_array() + .or_else(|| ws["packages"].as_array()) + .map(|a| a.iter().filter_map(|g| g.as_str()).collect()) + .unwrap_or_default(); + fn matches(glob: &[&str], dir: &[&str]) -> bool { + match (glob.first(), dir.first()) { + (None, None) => true, + (Some(&"**"), _) => { + matches(&glob[1..], dir) || (!dir.is_empty() && matches(glob, &dir[1..])) + } + (Some(g), Some(d)) => { + let one = match g.split_once('*') { + Some((pre, post)) => { + d.len() >= pre.len() + post.len() && d.starts_with(pre) && d.ends_with(post) + } + None => g == d, + }; + one && matches(&glob[1..], &dir[1..]) + } + _ => false, + } + } + let prefix = if root.is_empty() { + String::new() + } else { + format!("{root}/") + }; + let mut out: Vec = tree + .iter() + .filter_map(|p| p.strip_prefix(prefix.as_str())) + .filter_map(|p| p.strip_suffix("/package.json")) + .filter(|d| !d.split('/').any(|s| s == "node_modules")) + .filter(|d| { + let segs: Vec<&str> = d.split('/').collect(); + globs.iter().any(|g| { + let g = g.trim_start_matches("./").trim_end_matches('/'); + !g.starts_with('!') && matches(&g.split('/').collect::>(), &segs) + }) + }) + .map(String::from) + .collect(); + out.sort(); + out.dedup(); + out +} + +/// The projects the proof does not prove, each with why: one that is not +/// built, one whose build gave no result, and one whose build fails on the +/// base branch too (the sandbox has no secrets or services, so that says +/// nothing about the bumps). A project whose build passes with the bumps, +/// or fails only with them, is not here: the first is proven, the second +/// is blamed ([`blamed`]). +pub fn unproven_projects( + plan: &ProofPlan, + base: Option<&ProofResult>, + head: Option<&ProofResult>, +) -> Vec<(String, String)> { + let code = |r: Option<&ProofResult>, i: usize| -> Option { + r.filter(|r| r.ran) + .and_then(|r| r.builds.get(i).copied().flatten()) + }; + let mut out = vec![]; + for p in &plan.projects { + if !p.not_built.is_empty() { + out.push((p.dir.clone(), p.not_built.clone())); + continue; + } + let why = p.builds.iter().find_map(|&i| { + let cmd = plan.builds.get(i).map(|b| b.cmd.as_str()).unwrap_or(""); + match (code(base, i), code(head, i)) { + (_, Some(0)) => None, + (Some(0), Some(_)) => None, + (Some(b), Some(_)) => Some(format!( + "its build `{cmd}` fails on the base branch too in the sandbox (exit {b}), which has no secrets or services, so the result says nothing about the bumps" + )), + (None, Some(c)) => Some(format!( + "its build `{cmd}` fails (exit {c}) and did not run on the base branch, so the bumps can't be told from what was already failing" + )), + (_, None) => Some(format!("its build `{cmd}` gave no result in the sandbox")), + } + }); + if let Some(why) = why { + out.push((p.dir.clone(), why)); + } + } + out } impl ProofPlan { @@ -285,6 +541,7 @@ pub fn discover(lockfile: &str, ci: &[CiBuild], files: &[(String, String)]) -> P } else { format!("the CI workflow `{}`, job `{}`", c.workflow, c.job) }, + extra: false, }); if plan.builds.len() >= MAX_BUILDS { break; @@ -297,6 +554,7 @@ pub fn discover(lockfile: &str, ci: &[CiBuild], files: &[(String, String)]) -> P cmd: format!("{run} build"), dir: dir.clone(), source: format!("the `build` script of `{}`", under(&dir, name)), + extra: false, }), _ => None, }; @@ -304,6 +562,7 @@ pub fn discover(lockfile: &str, ci: &[CiBuild], files: &[(String, String)]) -> P cmd: b.to_string(), dir: dir.clone(), source: format!("{}'s own build", m.name), + extra: false, }); match scripted.or(own) { Some(b) => plan.builds.push(b), @@ -328,11 +587,13 @@ pub fn discover(lockfile: &str, ci: &[CiBuild], files: &[(String, String)]) -> P cmd, dir: dir.clone(), source: format!("the `web` entry of `{}`", under(&dir, "Procfile")), + extra: false, }), (None, Some(run), Some(name), Some(text)) => script_of(text, "start").map(|_| ProofCmd { cmd: format!("{run} start"), dir: dir.clone(), source: format!("the `start` script of `{}`", under(&dir, name)), + extra: false, }), _ => None, }; @@ -364,6 +625,9 @@ fn cd(dir: &str) -> String { /// exits 0; the verdict is read from its marker lines. pub fn script(plan: &ProofPlan) -> String { let mut s = String::new(); + if plan.builds.iter().any(|b| b.cmd.contains("$CH_ROOT")) { + s.push_str("export CH_ROOT=\"$(pwd)\"\n"); + } s.push_str(&format!( "( {}{} ) > /tmp/coderhelm-proof-install.log 2>&1; ch_install=$?\n", cd(&plan.dir), @@ -375,10 +639,11 @@ pub fn script(plan: &ProofPlan) -> String { let n = i + 1; s.push_str(&format!( "if [ $ch_install -eq 0 ]; then ( {}{} ) > /tmp/coderhelm-proof-build-{n}.log 2>&1; ch_b{n}=$?; \ - if [ $ch_b{n} -ne 0 ]; then ch_built=1; echo \"--- build {n} failed (exit $ch_b{n}), last output ---\"; tail -c 1200 /tmp/coderhelm-proof-build-{n}.log; echo; fi; \ + if [ $ch_b{n} -ne 0 ]; then {gate}echo \"--- build {n} failed (exit $ch_b{n}), last output ---\"; tail -c 1200 /tmp/coderhelm-proof-build-{n}.log; echo; fi; \ echo \"{STEP_MARK} build {n} $ch_b{n}\"; fi\n", cd(&b.dir), - b.cmd + b.cmd, + gate = if b.extra { "" } else { "ch_built=1; " }, )); } s.push_str("ch_start=skipped; ch_port=0\n"); @@ -623,6 +888,38 @@ pub fn report(plan: &ProofPlan, base: Option<&ProofResult>, head: Option<&ProofR .join(", ") )); } + if !plan.projects_unknown.is_empty() { + s.push_str(&format!( + "- Which workspace projects take the changed packages is not known ({}), so only the builds below were run; a project they don't cover is not proven here.\n", + plan.projects_unknown + )); + } + for p in &plan.projects { + if p.not_built.is_empty() { + s.push_str(&format!( + "- Project `{}` {}: built here ({}).\n", + p.dir, + p.because, + p.builds + .iter() + .filter_map(|&i| plan.builds.get(i)) + .map(|b| format!("`{}`", b.cmd)) + .collect::>() + .join(", ") + )); + } + } + for (dir, why) in unproven_projects(plan, base, head) { + let because = plan + .projects + .iter() + .find(|p| p.dir == dir) + .map(|p| p.because.as_str()) + .unwrap_or(""); + s.push_str(&format!( + "- Project `{dir}` {because}: **not proven here**: {why}. CI on this pull request, or a build by hand, is the check.\n" + )); + } let head = match head { Some(h) if h.ran => h, other => { @@ -751,6 +1048,239 @@ mod tests { )] } + // ── Every project the bumps can break ────────────────────────────── + + fn affected(dir: &str, uses: &[&str], scripts: Option<&str>) -> AffectedProject { + AffectedProject { + dir: dir.into(), + uses: uses.iter().map(|u| u.to_string()).collect(), + manifest: scripts.map(|s| format!("{{\"scripts\":{s}}}")), + } + } + + /// The site is what CI builds; the studio has a build script and no CI + /// job; the shared package declares no build. + fn workspace_plan() -> ProofPlan { + let mut plan = discover( + "pnpm-lock.yaml", + &[ci("pnpm --filter web build", Some("apps/web"), true)], + &pkg(r#"{"dev":"turbo dev"}"#), + ); + add_projects( + &mut plan, + "pnpm-lock.yaml", + &[ + affected( + "apps/web", + &["path-match@3.1.2"], + Some(r#"{"build":"next build"}"#), + ), + affected( + "apps/studio", + &["glob-walk@2.3.1"], + Some(r#"{"build":"studio build"}"#), + ), + affected( + "packages/ui", + &["path-match@3.1.2"], + Some(r#"{"lint":"eslint ."}"#), + ), + ], + ); + plan + } + + #[test] + fn a_project_no_ci_job_builds_is_built_when_its_manifest_declares_a_build() { + let plan = workspace_plan(); + let cmds: Vec<(&str, &str)> = plan + .builds + .iter() + .map(|b| (b.cmd.as_str(), b.dir.as_str())) + .collect(); + assert_eq!( + cmds, + vec![ + ("pnpm --filter web build", "apps/web"), + ("pnpm run build", "apps/studio"), + ] + ); + assert_eq!( + plan.builds[1].source, + "the `build` script of `apps/studio/package.json`" + ); + // The site is covered by the build CI runs in its folder. + assert_eq!(plan.projects[0].builds, vec![0]); + assert_eq!(plan.projects[1].builds, vec![1]); + assert_eq!( + plan.projects[2].not_built, + "`packages/ui/package.json` declares no `build` script" + ); + let sh = script(&plan); + assert!(sh.contains("( cd 'apps/studio' && pnpm run build )")); + // The studio's build failing never keeps the site's start from + // running: only the main project's builds gate it. + let studio = sh.lines().find(|l| l.contains("apps/studio")).unwrap(); + assert!(!studio.contains("ch_built=1"), "{studio}"); + let web = sh.lines().find(|l| l.contains("--filter web")).unwrap(); + assert!(web.contains("ch_built=1"), "{web}"); + } + + #[test] + fn a_project_build_only_the_bumps_break_is_blamed_and_feeds_the_take_out() { + let plan = workspace_plan(); + let base = ProofResult { + ran: true, + builds: vec![Some(0), Some(0)], + start: "skipped".into(), + ..Default::default() + }; + let head = ProofResult { + builds: vec![Some(0), Some(1)], + ..base.clone() + }; + assert_eq!( + blamed(&plan, &base, &head), + vec!["the build `pnpm run build` fails (exit 1)".to_string()] + ); + // Blamed, so not listed as unproven: only the project with no build is. + let open = unproven_projects(&plan, Some(&base), Some(&head)); + assert_eq!(open.len(), 1); + assert_eq!(open[0].0, "packages/ui"); + } + + #[test] + fn a_project_that_cannot_be_built_in_the_sandbox_is_named_as_not_proven() { + let plan = workspace_plan(); + // The studio's build needs a token the sandbox does not have: it + // fails on the base branch too. + let base = ProofResult { + ran: true, + builds: vec![Some(0), Some(1)], + start: "skipped".into(), + ..Default::default() + }; + let head = base.clone(); + assert!( + blamed(&plan, &base, &head).is_empty(), + "never blamed on a bump" + ); + let open = unproven_projects(&plan, Some(&base), Some(&head)); + assert_eq!(open.len(), 2); + assert_eq!(open[0].0, "apps/studio"); + assert!( + open[0].1.contains("fails on the base branch too"), + "{}", + open[0].1 + ); + let r = report(&plan, Some(&base), Some(&head)); + assert!( + r.contains("- Project `apps/studio` takes `glob-walk@2.3.1`: **not proven here**: its build `pnpm run build` fails on the base branch too"), + "{r}" + ); + assert!( + r.contains("- Project `packages/ui` takes `path-match@3.1.2`: **not proven here**: `packages/ui/package.json` declares no `build` script"), + "{r}" + ); + assert!(r.contains("- Project `apps/web` takes `path-match@3.1.2`: built here (`pnpm --filter web build`)."), "{r}"); + // No result at all: every built project is unproven, and said so. + let none = unproven_projects(&plan, Some(&base), None); + assert!(none + .iter() + .any(|(d, w)| d == "apps/web" && w.contains("gave no result"))); + } + + #[test] + fn the_project_of_another_lockfile_is_built_after_its_own_install() { + let mut plan = discover("package-lock.json", &[], &pkg(r#"{"build":"vite build"}"#)); + let studio = discover( + "studio/package-lock.json", + &[], + &[( + "studio/package.json".to_string(), + r#"{"scripts":{"build":"studio build"}}"#.to_string(), + )], + ); + add_lockfile(&mut plan, "studio/package-lock.json", 3, &studio); + let tools = discover("tools/package-lock.json", &[], &[]); + add_lockfile(&mut plan, "tools/package-lock.json", 1, &tools); + assert_eq!(plan.builds.len(), 2); + assert_eq!(plan.builds[1].dir, "studio"); + assert!( + plan.builds[1] + .cmd + .ends_with("npm ci --no-audit --no-fund && npm run build"), + "{}", + plan.builds[1].cmd + ); + assert_eq!( + plan.projects[0].because, + "has its own lockfile `studio/package-lock.json` with 3 of the bumps" + ); + assert!( + plan.projects[1] + .not_built + .contains("`tools/package.json` has no `build` script"), + "{}", + plan.projects[1].not_built + ); + assert!(plan.not_covered.is_empty()); + // The cap is said, never silently dropped. + let mut many = discover("pnpm-lock.yaml", &[], &pkg(r#"{"build":"x"}"#)); + let all: Vec = (0..MAX_PROJECT_BUILDS + 2) + .map(|i| { + affected( + &format!("apps/a{i}"), + &["glob-walk@2.3.1"], + Some(r#"{"build":"x"}"#), + ) + }) + .collect(); + add_projects(&mut many, "pnpm-lock.yaml", &all); + assert_eq!(many.builds.len(), 1 + MAX_PROJECT_BUILDS); + assert_eq!( + many.projects + .iter() + .filter(|p| p.not_built.contains("at most")) + .count(), + 2 + ); + } + + #[test] + fn workspace_folders_are_read_from_the_root_manifest() { + let tree: Vec = [ + "package.json", + "apps/web/package.json", + "apps/studio/package.json", + "apps/web/node_modules/x/package.json", + "packages/ui/package.json", + "packages/deep/inner/package.json", + "tools/release/package.json", + ] + .iter() + .map(|p| p.to_string()) + .collect(); + assert_eq!( + workspace_dirs(r#"{"workspaces":["apps/*","packages/**"]}"#, &tree, ""), + vec![ + "apps/studio", + "apps/web", + "packages/deep/inner", + "packages/ui" + ] + ); + assert_eq!( + workspace_dirs( + r#"{"workspaces":{"packages":["tools/release"]}}"#, + &tree, + "" + ), + vec!["tools/release"] + ); + assert!(workspace_dirs(r#"{"name":"x"}"#, &tree, "").is_empty()); + } + #[test] fn the_build_is_the_one_ci_runs_on_a_pull_request() { let plan = discover( diff --git a/services/common/src/security_fixes.rs b/services/common/src/security_fixes.rs index 1bde75999..cb60237be 100644 --- a/services/common/src/security_fixes.rs +++ b/services/common/src/security_fixes.rs @@ -3041,11 +3041,21 @@ fn fmt_num(n: f64) -> String { /// A bundle's table: every package bump with its advisories, reachability /// and due date. pub fn bump_table(unit: &FixUnit, members: &[(&Finding, &FindingState)]) -> String { + bump_table_at(unit, members, None) +} + +/// [`bump_table`] with each Version cell as the head resolves it, when the +/// head was read ([`crate::dep_head`]). +pub fn bump_table_at( + unit: &FixUnit, + members: &[(&Finding, &FindingState)], + head: Option<&crate::dep_head::HeadFacts>, +) -> String { let cell = |s: &str| s.replace('|', "\\|").replace('\n', " "); let mut s = String::from( "| Package | Version | Advisories | Reachability | Due |\n| --- | --- | --- | --- | --- |\n", ); - for b in &unit.bumps { + for (i, b) in unit.bumps.iter().enumerate() { let mine: Vec<&Finding> = members .iter() .map(|(f, _)| *f) @@ -3073,11 +3083,9 @@ pub fn bump_table(unit: &FixUnit, members: &[(&Finding, &FindingState)]) -> Stri .unwrap_or_default(); let tier = mine.iter().filter_map(|f| f.tier).min(); s.push_str(&format!( - "| `{}` | {} to {}{} | {} | {} | {}{} |\n", + "| `{}` | {} | {} | {} | {}{} |\n", cell(&b.package), - cell(&b.from), - cell(&b.to), - if b.major { " (major)" } else { "" }, + cell(&version_cell(b, i, head)), cell(&ids.join(", ")), verdict, tier.map(|t| format!("{} ", t.as_str())).unwrap_or_default(), @@ -3152,10 +3160,66 @@ pub fn pr_body_linked( check: &crate::upgrade_notes::WhatToCheck, links: &BodyLinks, ) -> String { - let body = if uses_short_body(unit, members) { - short_body(unit, members, change, check, links) + body_linked(unit, members, change, check, links, None) +} + +/// [`pr_body_linked`] for a pull request that exists or is about to: its +/// table and its first sentences say what the lockfile on the head +/// resolves (`head`, from [`crate::dep_head::resolve`]), never what the run +/// planned. A line that could not be read is shown as a plan and said to be +/// one. +pub fn pr_body_at_head( + unit: &FixUnit, + members: &[(&Finding, &FindingState)], + change: &str, + check: &crate::upgrade_notes::WhatToCheck, + links: &BodyLinks, + head: &crate::dep_head::HeadFacts, +) -> String { + body_linked(unit, members, change, check, links, Some(head)) +} + +/// The table's Version cell of bump `i`: what the head resolves when it was +/// read, the plan's versions otherwise. +fn version_cell(b: &Bump, i: usize, head: Option<&crate::dep_head::HeadFacts>) -> String { + match head { + Some(h) => h.version_cell(i), + None => format!( + "{} to {}{}", + b.from, + b.to, + if b.major { " (major)" } else { "" } + ), + } +} + +fn body_linked( + unit: &FixUnit, + members: &[(&Finding, &FindingState)], + change: &str, + check: &crate::upgrade_notes::WhatToCheck, + links: &BodyLinks, + head: Option<&crate::dep_head::HeadFacts>, +) -> String { + // Which body is chosen by the plan's size, so it never flips between + // two heads; everything shown comes from the head when it was read. + let short = uses_short_body(unit, members); + let plan = unit; + let at_head = head.map(|h| h.unit_at_head(unit)); + let unit = at_head.as_ref().unwrap_or(unit); + let headline = head.map(|h| h.headline(plan, members)); + let body = if short { + short_body( + unit, + members, + change, + check, + links, + head, + headline.as_deref(), + ) } else { - full_body(unit, members, change, check) + full_body(unit, members, change, check, head, headline.as_deref()) }; let more = if !links.detail.is_empty() { links.detail.as_str() @@ -3173,7 +3237,7 @@ pub fn detail_doc( change: &str, check: &crate::upgrade_notes::WhatToCheck, ) -> String { - let full = full_body(unit, members, change, check); + let full = full_body(unit, members, change, check, None, None); // The description's marker stays in the description only. let full = full.replace(MARKER, ""); format!( @@ -3255,12 +3319,15 @@ fn package_cell(b: &Bump, members: &[(&Finding, &FindingState)], links: &BodyLin /// first, each linked to its finding page), the advisories and evidence /// that matter most, "What to check" for the packages to look at first, /// the rest by tier with counts, Proof and Closes as usual. +#[allow(clippy::too_many_arguments)] fn short_body( unit: &FixUnit, members: &[(&Finding, &FindingState)], change: &str, check: &crate::upgrade_notes::WhatToCheck, links: &BodyLinks, + head: Option<&crate::dep_head::HeadFacts>, + headline: Option<&str>, ) -> String { let mut s = String::new(); let tiers = package_tiers(unit, members); @@ -3290,14 +3357,20 @@ fn short_body( } else { String::new() }; - s.push_str(&format!( - "## Summary\n\nFixes {advisories} advisor{} in {} packages ({majors} major version{}). \ - {}{due}.\n\n{where_all}\n\n", - if advisories == 1 { "y" } else { "ies" }, - unit.bumps.len(), - if majors == 1 { "" } else { "s" }, - top.as_str(), - )); + match headline { + Some(h) => s.push_str(&format!( + "## Summary\n\n{h} {}{due}.\n\n{where_all}\n\n", + top.as_str() + )), + None => s.push_str(&format!( + "## Summary\n\nFixes {advisories} advisor{} in {} packages ({majors} major version{}). \ + {}{due}.\n\n{where_all}\n\n", + if advisories == 1 { "y" } else { "ies" }, + unit.bumps.len(), + if majors == 1 { "" } else { "s" }, + top.as_str(), + )), + } // The table: every bump, most urgent first, ids capped per row. let cell = |s: &str| s.replace('|', "\\|").replace('\n', " "); s.push_str("| Package | Version | Advisories | Reachability | Due |\n| --- | --- | --- | --- | --- |\n"); @@ -3329,11 +3402,9 @@ fn short_body( .map(|d| d.format("%b %-d").to_string()) .unwrap_or_default(); s.push_str(&format!( - "| {} | {} to {}{} | {} | {} | {}{} |\n", + "| {} | {} | {} | {} | {}{} |\n", package_cell(b, members, links), - cell(&b.from), - cell(&b.to), - if b.major { " (major)" } else { "" }, + cell(&version_cell(b, i, head)), cell(&shown_ids), verdict, tiers[i] @@ -3542,13 +3613,7 @@ fn short_body( .take(25) .map(|&i| { let b = &unit.bumps[i]; - format!( - "`{}` {} to {}{}", - b.package, - b.from, - b.to, - if b.major { " (major)" } else { "" } - ) + format!("`{}` {}", b.package, version_cell(b, i, head)) }) .collect(); rest.push_str(&format!( @@ -3676,6 +3741,8 @@ fn full_body( members: &[(&Finding, &FindingState)], change: &str, check: &crate::upgrade_notes::WhatToCheck, + head: Option<&crate::dep_head::HeadFacts>, + headline: Option<&str>, ) -> String { let mut s = String::new(); let top = members @@ -3709,18 +3776,34 @@ fn full_body( ); if unit.bundle { let advisories = primaries(members).len(); - s.push_str(&format!( - "## Summary\n\nFixes {advisories} advisor{} in {} package{}. {when}.\n\n", - if advisories == 1 { "y" } else { "ies" }, - unit.bumps.len(), - if unit.bumps.len() == 1 { "" } else { "s" }, - )); - s.push_str(&bump_table(unit, members)); + match headline { + Some(h) => s.push_str(&format!("## Summary\n\n{h} {when}.\n\n")), + None => s.push_str(&format!( + "## Summary\n\nFixes {advisories} advisor{} in {} package{}. {when}.\n\n", + if advisories == 1 { "y" } else { "ies" }, + unit.bumps.len(), + if unit.bumps.len() == 1 { "" } else { "s" }, + )), + } + s.push_str(&bump_table_at(unit, members, head)); } else { - s.push_str(&format!( - "## Summary\n\nFixes {}. {when}.\n\n", - what.join("; ") - )); + match headline { + // One fix: what it is for, then what the head resolves. + Some(h) => s.push_str(&format!( + "## Summary\n\nFor {}. {h} {when}.\n\n", + what.join("; ") + )), + None => s.push_str(&format!( + "## Summary\n\nFixes {}. {when}.\n\n", + what.join("; ") + )), + } + if let Some(h) = head { + for (i, b) in unit.bumps.iter().enumerate() { + s.push_str(&format!("- `{}` {}\n", b.package, h.version_cell(i))); + } + s.push('\n'); + } } s.push_str("## Advisory\n\n"); for (f, st) in members { @@ -9010,6 +9093,80 @@ mod tests { (unit, fs, check) } + /// The plan called 37 of the bundle's 55 packages major versions. A + /// review round kept each on its line; the description says what the + /// head's lockfile resolves, and where the head can't be read it says + /// so and marks the plan as a plan. + #[test] + fn a_bundles_table_and_headline_come_from_the_head_never_the_plan() { + use crate::dep_head::{resolve, unknown, LockAt}; + let (unit, fs, check) = big_bundle(); + let pairs: Vec<(&Finding, &FindingState)> = fs.iter().map(|(f, s)| (f, s)).collect(); + let links = BodyLinks::default(); + let planned = pr_body_linked(&unit, &pairs, "Bumped.", &check, &links); + assert!(planned.contains("(37 major versions)"), "the plan's count"); + let copies = |v: &str| -> Option> { + Some( + unit.bumps + .iter() + .map(|b| (b.package.clone(), v.to_string())) + .collect(), + ) + }; + let lock = LockAt { + path: "pnpm-lock.yaml".into(), + base: copies("1.4.2"), + head: copies("1.4.9"), + why: String::new(), + }; + let head = resolve(&unit, "0123abc4567", &[lock]); + let body = pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &head); + let summary = &body[..body.find("## Advisory").unwrap()]; + assert!( + summary.contains("in 55 package version lines (0 cross a major version), read from the lockfile on the head `0123abc`"), + "{summary}" + ); + assert!( + !body.contains("(major)"), + "no line crosses a major on the head" + ); + assert!( + !summary.contains("2.0.1"), + "the plan's target is not what the head installs" + ); + assert!(summary.contains("| 1.4.2 to 1.4.9 |"), "{summary}"); + // Advisories are counted against their patched versions. + let fixed = fs + .iter() + .filter(|(f, _)| head.fixed(&unit, f) == crate::dep_head::Fixed::Yes) + .count(); + assert!( + fixed < fs.len(), + "a finding patched only in 2.0.1 is not fixed at 1.4.9" + ); + assert!(summary.contains("Not fixed on the head:"), "{summary}"); + // Same head, same text. + assert_eq!( + body, + pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &head) + ); + // The head could not be read: nothing is counted, the plan is + // shown as a plan. + let blind = unknown(&unit, "`pnpm-lock.yaml` could not be read on the head"); + let body = pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &blind); + let summary = &body[..body.find("## Advisory").unwrap()]; + assert!( + summary.contains("What the head installs is not known"), + "{summary}" + ); + assert!(!summary.contains("Fixes "), "{summary}"); + assert!( + summary.contains("1.4.2 to 2.0.1 planned; not read from the head"), + "{summary}" + ); + assert!(body.chars().count() <= crate::pr_body_fit::GITHUB_BODY_MAX); + } + #[test] fn a_55_package_bundle_fits_and_lists_what_to_look_at_first() { let (unit, fs, check) = big_bundle(); @@ -9018,7 +9175,7 @@ mod tests { "Raised the direct ranges and added overrides for transitive copies. ".repeat(40); // The description before: every advisory, path, piece of evidence // and package note, over GitHub's limit. - let before = full_body(&unit, &pairs, &change, &check); + let before = full_body(&unit, &pairs, &change, &check, None, None); assert!( before.chars().count() > crate::pr_body_fit::GITHUB_BODY_MAX, "{}", diff --git a/services/worker/src/passes/covering.rs b/services/worker/src/passes/covering.rs index f9753e2e3..ef1517173 100644 --- a/services/worker/src/passes/covering.rs +++ b/services/worker/src/passes/covering.rs @@ -532,9 +532,7 @@ impl Cover for GhCover<'_> { } async fn raw_set_body(&self, number: u64, body: &str) -> Result<(), Error> { - self.github - .update_pr_body(self.owner, self.repo, number, body) - .await + crate::passes::description::save(self.github, self.owner, self.repo, number, body).await } } @@ -1235,7 +1233,7 @@ mod tests { assert_eq!(body.matches(".raw_fast_forward(").count(), 1); assert_eq!(body.matches(".raw_set_body(").count(), 1); assert_eq!(body.matches(".fast_forward(self.owner").count(), 1); - assert_eq!(body.matches(".update_pr_body(").count(), 1); + assert_eq!(body.matches("description::save(").count(), 1); let guarded = |name: &str| { let at = body.find(&format!("pub async fn {name}<")).unwrap(); let f = &body[at..]; diff --git a/services/worker/src/passes/dep_fix.rs b/services/worker/src/passes/dep_fix.rs index f3ea8aebe..dcc036bac 100644 --- a/services/worker/src/passes/dep_fix.rs +++ b/services/worker/src/passes/dep_fix.rs @@ -430,7 +430,11 @@ impl Probe<'_> { /// What the runtime proof of a run runs: the build and start commands of /// the project most of its applied bumps are in, read from the repository's -/// workflows and that project's manifest. +/// workflows and that project's manifest, then the build of every other +/// project the bumps can break: each workspace project whose dependencies +/// bring in a changed package line (read from the lockfile), and the +/// project of every other lockfile the run bumped. A project with no build +/// to run is named as not built, with why. async fn proof_plan(w: &Work<'_>, run: &DepRun) -> rp::ProofPlan { let (o, n, base) = (&w.msg.repo_owner, &w.msg.repo_name, &w.msg.base_branch); let mut by: HashMap<&str, usize> = HashMap::new(); @@ -444,15 +448,141 @@ async fn proof_plan(w: &Work<'_>, run: &DepRun) -> rp::ProofPlan { }; let workflows = checks::read_workflows(w.github, o, n, base).await; let ci = checks::build_commands(&workflows, base); + let mut plan = rp::discover(lockfile, &ci, &proof_files(w, lockfile).await); + if plan.install.is_empty() { + // Not a lockfile CoderHelm builds from: nothing more to add. + plan.not_covered = locks.iter().skip(1).map(|(l, _)| l.to_string()).collect(); + return plan; + } + // The workspace projects that take a changed package line. + let asked: Vec<(String, String)> = run + .applied_bumps() + .iter() + .filter(|b| b.manifest == lockfile) + .map(|b| (b.package.clone(), b.from.clone())) + .collect(); + match affected_projects(w, lockfile, &asked).await { + Ok(projects) => rp::add_projects(&mut plan, lockfile, &projects), + Err(why) => plan.projects_unknown = why, + } + // The projects of the other lockfiles with bumps. + for (other, bumps) in locks.iter().skip(1) { + let found = rp::discover(other, &ci, &proof_files(w, other).await); + rp::add_lockfile(&mut plan, other, *bumps, &found); + } + plan +} + +/// The files [`rp::discover`] reads for a lockfile that exist on the base +/// branch. +async fn proof_files(w: &Work<'_>, lockfile: &str) -> Vec<(String, String)> { + let (o, n, base) = (&w.msg.repo_owner, &w.msg.repo_name, &w.msg.base_branch); let mut files = vec![]; for path in rp::files_to_read(lockfile) { if let Ok(Some(text)) = w.github.read_file_if_exists(o, n, &path, base).await { files.push((path, text)); } } - let mut plan = rp::discover(lockfile, &ci, &files); - plan.not_covered = locks.iter().skip(1).map(|(l, _)| l.to_string()).collect(); - plan + files +} + +/// Workspace manifests one proof reads at most. +const MAX_WORKSPACE_MANIFESTS: usize = 60; + +/// The workspace projects of `lockfile` whose dependencies bring in one of +/// the changed package lines (`asked`: package and the version it had), +/// each with its scripts manifest. `Err` says why they could not be worked +/// out; a lockfile with one project gives none. +async fn affected_projects( + w: &Work<'_>, + lockfile: &str, + asked: &[(String, String)], +) -> Result, String> { + let (o, n, base) = (&w.msg.repo_owner, &w.msg.repo_name, &w.msg.base_branch); + if !common::reachability::is_lockfile(lockfile) { + // Not a JavaScript workspace lockfile: one project per lockfile. + return Ok(vec![]); + } + let root = lockfile.rsplit_once('/').map(|(d, _)| d).unwrap_or(""); + let at = |dir: &str| -> String { + match (root.is_empty(), dir.is_empty()) { + (_, true) => root.to_string(), + (true, false) => dir.to_string(), + (false, false) => format!("{root}/{dir}"), + } + }; + let manifest_path = |dir: &str| -> String { + let d = at(dir); + if d.is_empty() { + "package.json".to_string() + } else { + format!("{d}/package.json") + } + }; + let text = match w.github.read_file_if_exists(o, n, lockfile, base).await { + Ok(Some(t)) => t, + _ => return Err(format!("`{lockfile}` could not be read on the base branch")), + }; + // `yarn.lock` does not list its projects: the root manifest's + // workspaces and each project's manifest do. + let mut manifests: Vec<(String, String)> = vec![]; + if lockfile.ends_with("yarn.lock") { + let Ok(Some(root_manifest)) = w + .github + .read_file_if_exists(o, n, &manifest_path(""), base) + .await + else { + return Err(format!( + "`{}` could not be read to list the workspace", + manifest_path("") + )); + }; + let tree: Vec = match w.github.get_tree(o, n, base).await { + Ok(t) => t.into_iter().map(|e| e.path).collect(), + Err(_) => return Err("the repository's files could not be listed".to_string()), + }; + let dirs = rp::workspace_dirs(&root_manifest, &tree, root); + if dirs.len() > MAX_WORKSPACE_MANIFESTS { + return Err(format!( + "the workspace has {} projects, more than one proof reads", + dirs.len() + )); + } + manifests.push((String::new(), root_manifest)); + for d in dirs { + if let Ok(Some(t)) = w + .github + .read_file_if_exists(o, n, &manifest_path(&d), base) + .await + { + manifests.push((d, t)); + } + } + } + let Some(projects) = common::reachability::lock_projects(lockfile, &text, &manifests, asked) + else { + return Err(format!( + "`{lockfile}` could not be read as a workspace's lockfile" + )); + }; + let mut out = vec![]; + for p in projects.into_iter().filter(|p| !p.uses.is_empty()) { + let manifest = match manifests.iter().find(|(d, _)| *d == p.dir) { + Some((_, t)) => Some(t.clone()), + None => w + .github + .read_file_if_exists(o, n, &manifest_path(&p.dir), base) + .await + .ok() + .flatten(), + }; + out.push(rp::AffectedProject { + dir: at(&p.dir), + uses: p.uses, + manifest, + }); + } + Ok(out) } /// Everything the driver borrows from the run. diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs new file mode 100644 index 000000000..aa442a826 --- /dev/null +++ b/services/worker/src/passes/description.rs @@ -0,0 +1,317 @@ +//! The one place a pull request's description is written from. +//! +//! A dependency run's pull request had the right code after a review round +//! and the wrong description: its table still showed the plan (five packages +//! as major version jumps the final manifest no longer makes), its headline +//! counted advisories nobody had compared with the final lockfile, and the +//! round that fixed the code said it could not edit the description and left +//! the corrections to a person. +//! +//! A description is a function of the head. Three rules keep it one: +//! +//! - [`save`] is the only call of the GitHub client's body write in the +//! pipeline. Every writer (the first description, a section CoderHelm +//! owns, a rewrite) sends its text through it, so no path can write a +//! description this module does not see. A test reads the sources and +//! fails on a call anywhere else. +//! - [`head_moved`] is what every path that moves the head calls (a CI fix, +//! a review fix, feedback, a bump taken out): the description's prose is +//! rewritten from the whole diff, and a dependency pull request's table, +//! headline, "What to check" and Proof are rebuilt from what the lockfile +//! on the head resolves ([`dependency_sections`]). The model is never the +//! source of a version or a count. +//! - A round's account that hands an edit of the description to a person is +//! caught ([`round_account`]): the sentence goes, and the rebuild runs +//! even when the round pushed no code. + +use tracing::warn; + +use crate::agent::provider::ModelProvider; +use crate::clients::github::GitHubClient; +use crate::models::TokenUsage; +use crate::WorkerState; + +type Error = Box; + +/// Writes a pull request's description. The only caller of the client's +/// body write: a sentence that says the description can't be edited, or +/// leaves an edit of it to a person, never reaches a description. +pub async fn save( + github: &GitHubClient, + owner: &str, + repo: &str, + number: u64, + body: &str, +) -> Result<(), Error> { + let body = clean(body); + github.update_pr_body(owner, repo, number, &body).await +} + +/// `body` as [`save`] writes it. +pub fn clean(body: &str) -> std::borrow::Cow<'_, str> { + match common::description_handoff::scrub(body) { + Some(scrubbed) => { + warn!("A description said it could not be edited; that sentence was taken out"); + // The replacement sentence is for a round's account, not for + // the description itself. + std::borrow::Cow::Owned( + scrubbed + .lines() + .filter(|l| { + l.trim().trim_start_matches(['-', '*', '>']).trim() + != common::description_handoff::REBUILT + }) + .map(|l| { + l.replace(common::description_handoff::REBUILT, "") + .trim_end() + .to_string() + }) + .collect::>() + .join("\n"), + ) + } + None => std::borrow::Cow::Borrowed(body), + } +} + +/// The pull request whose head moved. +pub struct Moved<'a> { + pub state: &'a WorkerState, + pub github: &'a GitHubClient, + pub team_id: &'a str, + pub installation_id: u64, + pub owner: &'a str, + pub repo: &'a str, + pub number: u64, + /// The run's ticket: a security ticket's pull request has the sections + /// rebuilt from its lockfiles. + pub ticket_id: &'a str, + pub team_instructions: &'a str, + /// What a person with write access asked to change in the description + /// (empty when nobody asked). + pub requests: &'a [String], +} + +/// The head of an open pull request moved, or a person asked for a change to +/// its description: the description is rebuilt from the branch. Returns +/// what the rewrite changed (see `pr::refresh_description`). +pub async fn head_moved( + m: &Moved<'_>, + provider: &ModelProvider, + usage: &mut TokenUsage, +) -> Option> { + let changed = super::pr::refresh_description( + m.state, + m.github, + (m.team_id, m.installation_id), + m.owner, + m.repo, + m.number, + m.team_instructions, + m.requests, + provider, + usage, + ) + .await; + // After the rewrite, so what the lockfile resolves is the last word on + // every version and count. + dependency_sections( + m.state, + m.github, + m.team_id, + m.owner, + m.repo, + m.number, + m.ticket_id, + ) + .await; + changed +} + +/// A dependency pull request's table, headline, "What to check" and Proof, +/// rebuilt from what the lockfile on its head resolves. Costs no model +/// call. Nothing for any other pull request. +pub async fn dependency_sections( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + owner: &str, + repo: &str, + number: u64, + ticket_id: &str, +) { + if !common::security_fixes::is_ticket(ticket_id) { + return; + } + super::security_fixes::rebuild_at_head( + state, + github, + team_id, + &format!("{owner}/{repo}"), + number, + ticket_id, + ) + .await; +} + +/// A round's account, checked: `(the account without any sentence that +/// hands the description to a person, whether there was one)`. A `true` +/// means the description is rebuilt now, whatever the round pushed. +pub fn round_account(account: &str) -> (String, bool) { + match common::description_handoff::scrub(account) { + Some(clean) => (clean, true), + None => (account.to_string(), false), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every source file of the worker, with its path from `src/`. + fn sources() -> Vec<(String, String)> { + fn walk(dir: &std::path::Path, root: &std::path::Path, out: &mut Vec<(String, String)>) { + for e in std::fs::read_dir(dir).unwrap().flatten() { + let p = e.path(); + if p.is_dir() { + walk(&p, root, out); + } else if p.extension().is_some_and(|x| x == "rs") { + out.push(( + p.strip_prefix(root) + .unwrap() + .to_string_lossy() + .replace('\\', "/"), + std::fs::read_to_string(&p).unwrap(), + )); + } + } + } + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut out = vec![]; + walk(&root, &root, &mut out); + assert!(out.len() > 100, "the worker's sources were not found"); + out + } + + /// The code of a file: no comment lines, and nothing from its tests on. + fn code(text: &str) -> String { + let end = text.find("#[cfg(test)]").unwrap_or(text.len()); + text[..end] + .lines() + .filter(|l| !l.trim_start().starts_with("//")) + .collect::>() + .join("\n") + } + + /// The guard: a new call site that writes a description some other way + /// fails here. + #[test] + fn the_description_is_written_from_one_place() { + let call = [".update_pr", "_body("].concat(); + let mut calls: Vec = vec![]; + let mut through = 0; + for (path, text) in sources() { + let code = code(&text); + // The client defines the write; it never calls it. + if path != "clients/github.rs" { + for _ in code.matches(&call) { + calls.push(path.clone()); + } + } + // A description sent as a raw request would pass the client's + // method by. + if path != "clients/github.rs" { + for l in code.lines() { + assert!( + !(l.contains("/pulls/") && l.contains(".patch(")), + "{path} patches a pull request itself: {l}" + ); + } + } + through += code.matches("description::save(").count(); + } + assert_eq!( + calls, + vec!["passes/description.rs".to_string()], + "a description is written only through description::save" + ); + assert!(through >= 20, "the writers go through it: {through}"); + // And the client has one method that replaces a description. + let client = include_str!("../clients/github.rs"); + assert_eq!( + client.matches("\n pub async fn update_pr_body(").count(), + 1 + ); + } + + /// Every path that moves a pull request's head rebuilds its + /// description, through this module. + #[test] + fn every_path_that_moves_the_head_rebuilds_the_description() { + let resume = include_str!("resume.rs"); + let round = &resume[resume.find("\nasync fn run_fix_round(").unwrap()..]; + let round = &round[..round[1..].find("\nasync fn ").unwrap()]; + let pushed = round.find("Landed::Pushed { files }").unwrap(); + assert!(round[pushed..].contains("description::head_moved(")); + assert!( + round.contains("description::round_account("), + "a round's account is checked for a handed-off description" + ); + // A bump CI took out. + let revert = &resume[resume.find("\nasync fn revert_dep_commit(").unwrap()..]; + let revert = &revert[..revert[1..].find("\nasync fn ").unwrap_or(revert.len() - 1)]; + assert!(revert.contains("description::dependency_sections(")); + // Feedback from a person or a reviewer. + let feedback = include_str!("feedback.rs"); + assert!(feedback.contains("description::head_moved(")); + assert!(feedback.contains("description::round_account(")); + // Nothing calls the rewrite past this module. + for (path, text) in sources() { + // The incident cases quote the pipeline's source; they call nothing. + if path == "passes/description.rs" + || path == "passes/pr.rs" + || path.starts_with("passes/incidents/") + { + continue; + } + assert!( + !code(&text).contains("pr::refresh_description("), + "{path} rewrites the description past description::head_moved" + ); + } + // The dependency sections come from the head in every writer. + let sec = code(include_str!("security_fixes.rs")); + assert_eq!(sec.matches("sec::pr_body_linked(").count(), 0); + assert!(sec.matches("sec::pr_body_at_head(").count() >= 3); + } + + #[test] + fn a_description_never_says_it_cannot_be_edited() { + let body = "## Summary\n\nKept glob-walk on the 2 line.\n\n## Open items\n- I can't edit the PR description from here.\n- The studio build was not run.\n"; + let out = clean(body); + assert!(!out.contains("can't edit"), "{out}"); + assert!(out.contains("- The studio build was not run."), "{out}"); + assert!(!out.contains(common::description_handoff::REBUILT), "{out}"); + let fine = "## Summary\n\nKept glob-walk on the 2 line.\n"; + assert!(matches!(clean(fine), std::borrow::Cow::Borrowed(_))); + } + + #[test] + fn a_rounds_handoff_becomes_the_rebuild() { + let (account, rebuild) = round_account( + "Scoped the override to the 2 line. I can't edit the PR description from here, so the table still says 4.0.4.", + ); + assert!(rebuild); + assert_eq!( + account, + format!( + "Scoped the override to the 2 line. {}", + common::description_handoff::REBUILT + ) + ); + assert_eq!( + round_account("Scoped the override to the 2 line."), + ("Scoped the override to the 2 line.".to_string(), false) + ); + } +} diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 97e13b26e..0c633bb35 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -770,10 +770,15 @@ Rules: && github .has_write_access(&msg.repo_owner, &msg.repo_name, msg.trigger_author.trim()) .await; - if !msg.trigger_author.trim().is_empty() { - tools.push(update_description_tool()); - } + // The tool is there in every round: a round with no person behind it + // (CoderHelm's own review, a security follow-up) was told to call a tool + // it did not have, and answered that it could not edit the description. + // There the call asks for the rebuild from the branch. + let person_asked = !msg.trigger_author.trim().is_empty(); + tools.push(update_description_tool()); let mut full_system = system.clone(); + full_system.push_str("\n\n"); + full_system.push_str(common::description_handoff::ROUND_NOTE); // Live systems the team connected for this repo, if any: read-only lookups // so the fix rests on the system's real shape. let live = super::live_sources::LiveSources::load( @@ -968,7 +973,7 @@ Rules: branch: &feedback_round.wip_branch, base_branch: &base, files_modified: std::sync::Mutex::new(false), - description: DescriptionRequests::new(may_edit_description), + description: DescriptionRequests::for_round(may_edit_description, person_asked), scope_guard, history: Some(&history), graphs: Some(&graphs), @@ -1399,24 +1404,42 @@ Rules: // with no code change. What changed goes on the reply. // The round's changes landed above, as one commit in one push. let asked = executor.description.taken(); - let description_note = if fix_pushed || !asked.is_empty() { - let changed = super::pr::refresh_description( - state, - &github, - (&msg.team_id, msg.installation_id), - &msg.repo_owner, - &msg.repo_name, - msg.pr_number, - &team_instructions, - &asked, - &provider, - &mut usage, - ) - .await; - description_reply(&asked, changed.as_deref()) - } else { - String::new() - }; + // A reply that says the description can't be edited, or leaves an edit + // of it to a person, loses that sentence; the rebuild then runs whether + // or not code was pushed. + let (response, handed_off) = super::description::round_account(&response); + if handed_off { + warn!(run_id = %msg.run_id, "A feedback round handed the description to a person; rebuilding it from the branch"); + } + let description_note = + if fix_pushed || !asked.is_empty() || handed_off || executor.description.wants_rebuild() { + let changed = super::description::head_moved( + &super::description::Moved { + state, + github: &github, + team_id: &msg.team_id, + installation_id: msg.installation_id, + owner: &msg.repo_owner, + repo: &msg.repo_name, + number: msg.pr_number, + // A security follow-up names its ticket; any other round's + // ticket is the run's. + ticket_id: if msg.security_ticket.is_empty() { + &ticket.0 + } else { + &msg.security_ticket + }, + team_instructions: &team_instructions, + requests: &asked, + }, + &provider, + &mut usage, + ) + .await; + description_reply(&asked, changed.as_deref()) + } else { + String::new() + }; // Redirects and links the PR changes are checked again after a push // (or when the evidence is a day old) and the description's table @@ -2379,7 +2402,11 @@ fn update_description_tool() -> ToolDefinition { item). Pass the change in the person's words, with every value they gave. \ CoderHelm rewrites the description once you finish (after any code you \ commit), keeps its shape, and adds what changed to your reply. Only people \ - with write access to the repository can have it changed." + with write access to the repository can have it changed to order. When a \ + review finding (not a person) says the description is wrong or out of \ + date, call this too with what is wrong: CoderHelm then rebuilds the \ + description from the branch as it stands. You can always call it; never \ + answer that you cannot edit the description." .to_string(), input_schema: json!({ "type": "object", @@ -2395,23 +2422,53 @@ fn update_description_tool() -> ToolDefinition { /// whether the person who asked may have it changed. struct DescriptionRequests { allowed: bool, + /// A person triggered the round (false: CoderHelm's own review or a + /// follow-up it sent itself). + person: bool, asked: std::sync::Mutex>, + /// The round asked for the description to be rebuilt from the branch. + rebuild: std::sync::atomic::AtomicBool, } impl DescriptionRequests { + #[cfg(test)] fn new(allowed: bool) -> Self { + Self::for_round(allowed, true) + } + + fn for_round(allowed: bool, person: bool) -> Self { Self { allowed, + person, asked: std::sync::Mutex::new(Vec::new()), + rebuild: std::sync::atomic::AtomicBool::new(false), } } + /// The round asked for a rebuild from the branch (no person's words to + /// apply). + fn wants_rebuild(&self) -> bool { + self.rebuild.load(std::sync::atomic::Ordering::Relaxed) + } + /// Records one request and says what happens with it. fn ask(&self, change: &str) -> String { let change = change.split_whitespace().collect::>().join(" "); if change.is_empty() { return "Say what to change in the description.".to_string(); } + if !self.person { + // Nobody's wording to apply: the description is rebuilt from + // the branch, which is what makes it right. + self.rebuild + .store(true, std::sync::atomic::Ordering::Relaxed); + return "Recorded. CoderHelm rebuilds the description from the branch as it stands \ + when you finish (the versions the lockfile resolves, the counts, the changes, \ + the verification and the open items), so the statement you named is replaced \ + by what the branch shows. Fix the code if the code is what is wrong; never \ + write that you cannot edit the description." + .to_string(); + } if !self.allowed { return "Not changed: only people with write access to this repository can have the \ description changed. Tell the person so in your reply, politely; change \ @@ -4281,6 +4338,33 @@ mod description_request_tests { assert!(tool.description.contains("write access")); assert_eq!(tool.input_schema["required"][0], "change"); } + + /// A round with no person behind it (CoderHelm's own review) was told + /// to call a tool it did not have and said it could not edit the + /// description. It has the tool now, and the call asks for the rebuild. + #[test] + fn a_round_nobody_asked_can_still_have_the_description_rebuilt() { + let d = DescriptionRequests::for_round(false, false); + assert!(!d.wants_rebuild()); + let out = d + .ask("the table lists glob-walk as 2.3.1 to 4.0.4 (major); the manifest keeps it on 2"); + assert!( + out.starts_with("Recorded. CoderHelm rebuilds the description from the branch"), + "{out}" + ); + assert!(d.wants_rebuild()); + assert!(d.taken().is_empty(), "no person's wording is applied"); + assert!(common::description_handoff::handoffs(&out).is_empty()); + let tool = update_description_tool(); + assert!(tool + .description + .contains("never answer that you cannot edit the description")); + // The round's instructions and the tool are in every round. + let src = include_str!("feedback.rs"); + let run = &src[..src.find("\nfn update_description_tool()").unwrap()]; + assert!(run.contains("tools.push(update_description_tool());\n let mut full_system")); + assert!(run.contains("common::description_handoff::ROUND_NOTE")); + } } #[cfg(test)] diff --git a/services/worker/src/passes/file_claims.rs b/services/worker/src/passes/file_claims.rs new file mode 100644 index 000000000..a2f6eca64 --- /dev/null +++ b/services/worker/src/passes/file_claims.rs @@ -0,0 +1,221 @@ +//! A sentence the run writes into a repository file that says a check +//! passes stands only on a recorded result (`common::file_claims`). +//! +//! The records are the ones the pull request's own sections are written +//! from: the run's last sandbox check (`proof::SandboxRecord`), which says +//! which kinds of check ran and passed. A claim with a passing record +//! stays. One without is taken out of the file before the run finishes, as +//! one commit, and the run page says which sentence and why; the sentence +//! never ships on a guess. + +use common::file_claims::{self as fc, Claim, ClaimKind}; +use tracing::{info, warn}; + +use super::checks::CheckKind; +use super::proof::RunEvidence; +use crate::clients::github::{FileOp, GitHubClient}; +use crate::models::TicketMessage; +use crate::WorkerState; + +/// The kinds of check with a passing result recorded for the branch as the +/// run last checked it. +pub fn proven(evidence: &RunEvidence) -> Vec { + evidence + .sandbox + .passed + .iter() + .filter_map(|k| match k { + CheckKind::Build => Some(ClaimKind::Build), + CheckKind::Tests => Some(ClaimKind::Tests), + CheckKind::Lint => Some(ClaimKind::Lint), + CheckKind::Typecheck => Some(ClaimKind::Typecheck), + _ => None, + }) + .collect() +} + +/// The claims the branch's diff adds to prose files that no recorded +/// passing result covers. +pub fn unproven_in_diff(diff: &serde_json::Value, evidence: &RunEvidence) -> Vec { + let mut claims = vec![]; + for f in diff["files"].as_array().into_iter().flatten() { + if f["status"].as_str() == Some("removed") { + continue; + } + let (Some(path), Some(patch)) = (f["filename"].as_str(), f["patch"].as_str()) else { + continue; + }; + claims.extend(fc::claims_in_patch(path, patch)); + } + fc::unproven(&claims, &proven(evidence)) +} + +/// The run page's line for the claims taken out. +pub fn note(removed: &[Claim]) -> String { + let list: Vec = removed + .iter() + .map(|c| { + format!( + "`{}` line {}: \"{}\" (no passing result is recorded for {})", + c.path, + c.line, + common::truncate_str(&c.sentence, 160), + c.what() + ) + }) + .collect(); + format!( + "Took {} out of the files this run wrote: a sentence that says a check passes stays only \ + when that check has a recorded passing result on this branch. {}", + if removed.len() == 1 { + "one sentence".to_string() + } else { + format!("{} sentences", removed.len()) + }, + list.join("; ") + ) +} + +/// Reads what the branch adds to its prose files and takes out every claim +/// that a check passes with no recorded passing result. Returns the claims +/// taken out. Best effort: a diff that can't be read changes nothing. +pub async fn settle( + state: &WorkerState, + msg: &TicketMessage, + github: &GitHubClient, + branch: &str, + evidence: &RunEvidence, +) -> Vec { + let (owner, repo) = (&msg.repo_owner, &msg.repo_name); + let Ok(diff) = github.get_diff(owner, repo, &msg.base_branch, branch).await else { + return vec![]; + }; + let open = unproven_in_diff(&diff, evidence); + if open.is_empty() { + return vec![]; + } + let mut paths: Vec<&str> = open.iter().map(|c| c.path.as_str()).collect(); + paths.sort(); + paths.dedup(); + let mut ops = vec![]; + let mut removed: Vec = vec![]; + for path in paths { + let Ok(Some(text)) = github.read_file_if_exists(owner, repo, path, branch).await else { + continue; + }; + if let Some(next) = fc::without(path, &text, &open) { + removed.extend( + open.iter() + .filter(|c| c.path == path && text.contains(c.sentence.as_str())) + .cloned(), + ); + ops.push(FileOp::Write { + path: path.to_string(), + content: next, + }); + } + } + if ops.is_empty() { + return vec![]; + } + let conventions = super::load_git_conventions(state, &msg.team_id, &msg.ticket_id).await; + let message = conventions.commit_message( + &super::ticket_tokens(msg), + "Remove claims that a check passes where no result is recorded", + ); + if let Err(e) = github + .batch_write(owner, repo, branch, &message, &ops) + .await + { + warn!(branch, error = %e, "Could not take unproven claims out of the files the run wrote"); + return vec![]; + } + info!( + branch, + removed = removed.len(), + "Took unproven claims out of the run's files" + ); + removed +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::passes::proof::SandboxRecord; + use serde_json::json; + + fn diff() -> serde_json::Value { + json!({"files": [ + {"filename": "README.md", "status": "modified", + "patch": "@@ -4,2 +4,4 @@\n ## Upgrading\n+The build passes with these versions.\n+All tests pass.\n Node 20 or later.\n"}, + {"filename": "src/build.ts", "status": "modified", + "patch": "@@ -1 +1,2 @@\n+// The build passes with these versions.\n"}, + {"filename": "docs/old.md", "status": "removed", + "patch": "@@ -1 +0,0 @@\n-All tests pass.\n"} + ]}) + } + + fn evidence(passed: &[CheckKind]) -> RunEvidence { + RunEvidence { + sandbox: SandboxRecord { + ran: passed.to_vec(), + passed: passed.to_vec(), + ..Default::default() + }, + ..Default::default() + } + } + + #[test] + fn a_claim_needs_the_recorded_result_the_pull_request_is_written_from() { + // Nothing ran: both sentences are unproven. + let open = unproven_in_diff(&diff(), &evidence(&[])); + let got: Vec<(&str, u64, &str)> = open + .iter() + .map(|c| (c.path.as_str(), c.line, c.sentence.as_str())) + .collect(); + assert_eq!( + got, + vec![ + ("README.md", 5, "The build passes with these versions."), + ("README.md", 6, "All tests pass."), + ] + ); + // The tests passed in the sandbox; the build never ran. + let open = unproven_in_diff(&diff(), &evidence(&[CheckKind::Tests, CheckKind::Lint])); + assert_eq!(open.len(), 1); + assert_eq!(open[0].sentence, "The build passes with these versions."); + // Both recorded as passing: the sentences stay. + assert!( + unproven_in_diff(&diff(), &evidence(&[CheckKind::Tests, CheckKind::Build])).is_empty() + ); + let n = note(&open); + assert!( + n.starts_with("Took one sentence out of the files this run wrote"), + "{n}" + ); + assert!( + n.contains("`README.md` line 5") && n.contains("recorded for the build"), + "{n}" + ); + } + + /// Both paths that write files check them before the description is + /// built from the branch. + #[test] + fn the_run_and_its_fix_rounds_settle_their_claims() { + let run = include_str!("mod.rs"); + assert!( + run.matches("file_claims::settle(").count() >= 2, + "both ways a run opens its pull request" + ); + let resume = include_str!("resume.rs"); + let round = &resume[resume.find("\nasync fn run_fix_round(").unwrap()..]; + let claims = round.find("file_claims::settle(").unwrap(); + let rebuild = round.find("description::head_moved(").unwrap(); + assert!( + claims < rebuild, + "claims are settled before the description is rebuilt" + ); + } +} diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 3e5ffef7d..52a94c947 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -195,7 +195,8 @@ pub async fn run( let feedback_section = match review_feedback { Some(fb) => format!( - "\n\n## Review Feedback (from previous cycle)\nThe reviewer found issues with the previous implementation. Fix ALL of the following:\n{fb}" + "\n\n## Review Feedback (from previous cycle)\nThe reviewer found issues with the previous implementation. Fix ALL of the following:\n{fb}\n\n## The pull request's description\n{}", + common::description_handoff::ROUND_NOTE ), None => String::new(), }; diff --git a/services/worker/src/passes/incidents/ah_dep_run_choice_and_proof.rs b/services/worker/src/passes/incidents/ah_dep_run_choice_and_proof.rs index 174040774..9a70c9ca1 100644 --- a/services/worker/src/passes/incidents/ah_dep_run_choice_and_proof.rs +++ b/services/worker/src/passes/incidents/ah_dep_run_choice_and_proof.rs @@ -433,7 +433,7 @@ fn the_build_and_the_start_prove_the_bumps_and_what_breaks_them_is_taken_out() { assert!(out < written && written < moved); let plan_src = fn_src(dep, "async fn proof_plan("); assert!(plan_src.contains("checks::build_commands(&workflows, base)")); - assert!(plan_src.contains("rp::discover(lockfile, &ci, &files)")); + assert!(plan_src.contains("rp::discover(lockfile, &ci, &proof_files(w, lockfile).await)")); assert!(worker_dep_fix::proof_waits( Some(std::time::Duration::from_secs(240)), false diff --git a/services/worker/src/passes/incidents/aj_description_from_the_head.rs b/services/worker/src/passes/incidents/aj_description_from_the_head.rs new file mode 100644 index 000000000..e2b6e277e --- /dev/null +++ b/services/worker/src/passes/incidents/aj_description_from_the_head.rs @@ -0,0 +1,325 @@ +//! aj. A dependency security run's pull request had the right code after a +//! review round and the wrong description: +//! +//! - its table still showed the plan: five packages as major version jumps +//! ("2.3.1 to 4.0.4 (major)") when the final manifest keeps each inside +//! its current major through a scoped override, and a headline that +//! counted twenty major versions; +//! - its count of fixed advisories had never been compared with what the +//! final lockfile installs; +//! - the round that fixed the code wrote "I can't edit the PR description +//! from here" and left the corrections to a person; +//! - the repository's second app, a CMS studio no CI job builds, took a +//! package an override moved to a new major, and nothing built it. +//! +//! Guarantee: the description is a function of the head. A dependency pull +//! request's table and headline are what the lockfile on the head resolves +//! compared with the base branch, an advisory counts as fixed only at or +//! past its patched version, and what can't be read is said as not known. +//! Every write of a description goes through one place, every path that +//! moves the head rebuilds it there, and a round's sentence that hands the +//! description to a person becomes the rebuild. A sentence a run writes +//! into a file that says a check passes needs that check's recorded result. +//! Every workspace project that takes a changed package is built when its +//! manifest declares a build, CI job or not; one that can't be proven is +//! named with why. + +use super::fixture::*; +use crate::passes::{checks::CheckKind, description, file_claims, proof}; +use common::dep_head::{self, Fixed, LockAt}; +use common::runtime_proof as rp; +use common::security_fixes::{self as sec, Advisory, Bump, Finding, FindingState, FixUnit}; + +/// The fixture monorepo's lockfile: the site, the studio no CI job builds, +/// and the studio's tooling bringing in `glob-walk` on the 2 line. +fn lockfile(glob_walk: &str, path_match: &str) -> String { + format!( + "lockfileVersion: '9.0'\nimporters:\n .:\n devDependencies:\n turbo:\n specifier: ^2.0.0\n version: 2.0.1\n apps/web:\n dependencies:\n path-match:\n specifier: ^3.1.0\n version: {path_match}\n apps/studio:\n dependencies:\n studio-kit:\n specifier: ^3.0.0\n version: 3.2.0\npackages:\n glob-walk@{glob_walk}: {{}}\n path-match@{path_match}: {{}}\n studio-kit@3.2.0: {{}}\n turbo@2.0.1: {{}}\nsnapshots:\n glob-walk@{glob_walk}: {{}}\n path-match@{path_match}: {{}}\n studio-kit@3.2.0:\n dependencies:\n glob-walk: {glob_walk}\n turbo@2.0.1: {{}}\n" + ) +} + +fn unit() -> FixUnit { + let bump = |package: &str, from: &str, to: &str| Bump { + package: package.into(), + from: from.into(), + to: to.into(), + major: sec::is_major_bump(from, to), + manifest: "pnpm-lock.yaml".into(), + }; + FixUnit { + repo: format!("{OWNER}/{REPO}"), + ecosystem: "npm".into(), + bundle: true, + // The plan: both as major version jumps. + bumps: vec![ + bump("glob-walk", "2.3.1", "4.0.4"), + bump("path-match", "3.1.2", "11.0.1"), + ], + ..Default::default() + } +} + +fn findings() -> Vec<(Finding, FindingState)> { + let f = |id: &str, package: &str, version: &str, patched: &str| Finding { + id: format!("f-{id}"), + package: package.into(), + version: version.into(), + fixed_version: Some(patched.into()), + manifest: "pnpm-lock.yaml".into(), + advisory: Advisory { + primary: id.into(), + ids: vec![id.into()], + ..Default::default() + }, + ..Default::default() + }; + vec![ + ( + f("GHSA-aaaa-0001", "glob-walk", "2.3.1", "2.3.2"), + FindingState::default(), + ), + ( + f("GHSA-bbbb-0002", "path-match", "3.1.2", "3.1.5"), + FindingState::default(), + ), + ] +} + +fn lock_at(base: &str, head: &str) -> LockAt { + LockAt { + path: "pnpm-lock.yaml".into(), + base: common::reachability::lock_copies("pnpm-lock.yaml", base), + head: common::reachability::lock_copies("pnpm-lock.yaml", head), + why: String::new(), + } +} + +/// The description after the review round kept both packages on their +/// lines: the table and the headline are the head's, not the plan's. +#[test] +fn the_table_and_headline_are_what_the_head_resolves() { + let (unit, fs) = (unit(), findings()); + let pairs: Vec<(&Finding, &FindingState)> = fs.iter().map(|(f, s)| (f, s)).collect(); + let check = common::upgrade_notes::WhatToCheck::default(); + let links = sec::BodyLinks::default(); + // What the pull request said: the plan. + let planned = sec::pr_body_linked(&unit, &pairs, "Bumped.", &check, &links); + assert!(planned.contains("2.3.1 to 4.0.4 (major)")); + // The head: scoped overrides keep each on its line. + let head = dep_head::resolve( + &unit, + "5e1f00d7a9", + &[lock_at( + &lockfile("2.3.1", "3.1.2"), + &lockfile("2.3.2", "3.1.5"), + )], + ); + let body = sec::pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &head); + let mut end = Ending::default(); + end.said(body.clone()); + assert!(end.says("| `glob-walk` | 2.3.1 to 2.3.2 |"), "{body}"); + assert!(end.says("| `path-match` | 3.1.2 to 3.1.5 |"), "{body}"); + assert!( + end.says("Fixes 2 of 2 advisories in 2 package version lines (0 cross a major version), read from the lockfile on the head `5e1f00d`."), + "{body}" + ); + end.never_says("(major)"); + end.never_says("4.0.4"); + end.never_says("11.0.1"); + // A head that stops short of the patch is not counted as a fix. + let short = dep_head::resolve( + &unit, + "0ddba11", + &[lock_at( + &lockfile("2.3.1", "3.1.2"), + &lockfile("2.3.2", "3.1.4"), + )], + ); + assert_eq!(short.fixed(&unit, &fs[1].0), Fixed::No); + let body = sec::pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &short); + assert!(body.contains("Fixes 1 of 2 advisories"), "{body}"); + assert!( + body.contains("Not fixed on the head: GHSA-bbbb-0002"), + "{body}" + ); + // A head that can't be read: said, never the plan as a result. + let blind = dep_head::unknown(&unit, "`pnpm-lock.yaml` could not be read on the head"); + let body = sec::pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &blind); + assert!( + body.contains("What the head installs is not known"), + "{body}" + ); + assert!( + body.contains("2.3.1 to 4.0.4 planned; not read from the head"), + "{body}" + ); + assert!(!body.contains("Fixes "), "{body}"); +} + +/// The rebuild replaces the stale sections of the open pull request and +/// keeps the rest; a second rebuild on the same head changes nothing. +#[test] +fn a_rebuild_replaces_the_stale_sections_in_place() { + let (unit, fs) = (unit(), findings()); + let pairs: Vec<(&Finding, &FindingState)> = fs.iter().map(|(f, s)| (f, s)).collect(); + let check = common::upgrade_notes::WhatToCheck::default(); + let links = sec::BodyLinks::default(); + let open = format!( + "\nDraft: waiting on CI.\n\n\n{}", + sec::pr_body_linked(&unit, &pairs, "Bumped.", &check, &links) + ); + let head = dep_head::resolve( + &unit, + "5e1f00d7a9", + &[lock_at( + &lockfile("2.3.1", "3.1.2"), + &lockfile("2.3.2", "3.1.5"), + )], + ); + let fresh = sec::pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &head); + let sections = ["## Summary", "## What to check", "## Proof"]; + let rebuilt = common::upgrade_notes::replace_sections(&open, &fresh, §ions); + assert!(rebuilt.starts_with("\nDraft: waiting on CI.")); + assert!(!rebuilt.contains("(major)"), "{rebuilt}"); + assert!(rebuilt.contains("| `glob-walk` | 2.3.1 to 2.3.2 |")); + assert!(rebuilt.contains(sec::MARKER)); + assert_eq!( + common::upgrade_notes::replace_sections(&rebuilt, &fresh, §ions), + rebuilt + ); + // The pipeline rebuilds those sections from the head, in one place. + let src = include_str!("../security_fixes.rs"); + let rebuild = fn_src(src, "pub(crate) async fn rebuild_at_head("); + assert!(rebuild.contains("head_facts(")); + assert!(rebuild.contains("sec::pr_body_at_head(")); + assert!(rebuild.contains("\"## Summary\", \"## What to check\", \"## Proof\"")); + assert!(rebuild.contains("description::save(")); +} + +/// "I can't edit the PR description from here" never reaches a person: the +/// round is told the description is rebuilt, its account loses the +/// sentence, and the rebuild runs. +#[test] +fn a_round_never_hands_the_description_to_a_person() { + let account = "Scoped the overrides so glob-walk stays on 2 and path-match on 3.\n\ + I can't edit the PR description from here. Please update the table in the description: it still lists both as major."; + let (clean, rebuild) = description::round_account(account); + assert!(rebuild); + let mut end = Ending::default(); + end.said(clean); + assert!(end.says("Scoped the overrides so glob-walk stays on 2")); + assert!(end.says(common::description_handoff::REBUILT)); + end.never_says("can't edit the PR description"); + end.never_says("Please update the table"); + // Every fix round is told, and has no reason to say it. + let implement = include_str!("../implement.rs"); + assert!(implement.contains("common::description_handoff::ROUND_NOTE")); + assert!(common::description_handoff::ROUND_NOTE.contains("rebuilt from the branch")); + // The description itself never carries such a sentence either. + let body = "## Open items\n- I can't edit the PR description from here.\n"; + assert!(!description::clean(body).contains("can't edit")); +} + +/// The studio no CI job builds takes the changed `glob-walk` line through +/// its tooling: it is found from the lockfile and built from its manifest's +/// build script; when its build can't run in the sandbox, the pull request +/// names it as not proven. +#[test] +fn the_app_no_ci_job_builds_is_built_or_named_as_not_proven() { + let asked = vec![ + ("glob-walk".to_string(), "2.3.1".to_string()), + ("path-match".to_string(), "3.1.2".to_string()), + ]; + let projects = common::reachability::lock_projects( + "pnpm-lock.yaml", + &lockfile("2.3.1", "3.1.2"), + &[], + &asked, + ) + .unwrap(); + let affected: Vec = projects + .into_iter() + .filter(|p| !p.uses.is_empty()) + .map(|p| rp::AffectedProject { + manifest: Some(match p.dir.as_str() { + "apps/studio" => r#"{"scripts":{"build":"studio build"}}"#.to_string(), + _ => r#"{"scripts":{"build":"next build"}}"#.to_string(), + }), + dir: p.dir, + uses: p.uses, + }) + .collect(); + let dirs: Vec<&str> = affected.iter().map(|a| a.dir.as_str()).collect(); + assert_eq!(dirs, vec!["apps/studio", "apps/web"]); + // CI builds the site only. + let ci = [rp::CiBuild { + cmd: "pnpm --filter web build".into(), + dir: Some("apps/web".into()), + workflow: "ci.yml".into(), + job: "build".into(), + on_pull_request: true, + }]; + let mut plan = rp::discover("pnpm-lock.yaml", &ci, &[]); + rp::add_projects(&mut plan, "pnpm-lock.yaml", &affected); + let studio = plan + .builds + .iter() + .position(|b| b.dir == "apps/studio") + .unwrap(); + assert_eq!(plan.builds[studio].cmd, "pnpm run build"); + // The studio's build breaks only with the bumps: blamed, which is what + // the take-out acts on. + let base = rp::ProofResult { + ran: true, + builds: vec![Some(0), Some(0)], + start: "skipped".into(), + ..Default::default() + }; + let mut head = base.clone(); + head.builds[studio] = Some(1); + let blamed = rp::blamed(&plan, &base, &head); + assert_eq!( + blamed, + vec!["the build `pnpm run build` fails (exit 1)".to_string()] + ); + let drive = include_str!("../dep_fix.rs"); + assert!(fn_src(drive, "async fn proof_plan(").contains("affected_projects(")); + assert!(fn_src(drive, "async fn proof_plan(").contains("rp::add_lockfile(")); + // The studio's build needs a token the sandbox lacks: it fails on the + // base branch too, so it is not blamed and is named as not proven. + let mut base_red = base.clone(); + base_red.builds[studio] = Some(1); + assert!(rp::blamed(&plan, &base_red, &head).is_empty()); + let mut end = Ending::default(); + end.said(rp::report(&plan, Some(&base_red), Some(&head))); + assert!(end.says("Project `apps/studio` takes `glob-walk@2.3.1`: **not proven here**")); + assert!(end.says("fails on the base branch too")); + end.never_says("Covers the project of"); +} + +/// A sentence the run wrote into the README says the build passes; only +/// the tests have a recorded passing result. +#[test] +fn a_file_the_run_wrote_claims_only_what_a_check_recorded() { + let diff = serde_json::json!({"files": [{ + "filename": "README.md", "status": "modified", + "patch": "@@ -8,2 +8,4 @@\n ## Security updates\n+The build passes with the new versions.\n+All tests pass.\n Run `pnpm install` after pulling.\n" + }]}); + let evidence = proof::RunEvidence { + sandbox: proof::SandboxRecord { + ran: vec![CheckKind::Tests], + passed: vec![CheckKind::Tests], + ..Default::default() + }, + ..Default::default() + }; + let open = file_claims::unproven_in_diff(&diff, &evidence); + assert_eq!(open.len(), 1); + assert_eq!(open[0].sentence, "The build passes with the new versions."); + let file = "## Security updates\nThe build passes with the new versions.\nAll tests pass.\nRun `pnpm install` after pulling.\n"; + let mut end = Ending::default(); + end.said(common::file_claims::without("README.md", file, &open).unwrap()); + end.never_says("The build passes"); + assert!(end.says("All tests pass.")); + assert!(end.says("Run `pnpm install` after pulling.")); +} diff --git a/services/worker/src/passes/incidents/h_pr_updates.rs b/services/worker/src/passes/incidents/h_pr_updates.rs index d7193e579..e741368a6 100644 --- a/services/worker/src/passes/incidents/h_pr_updates.rs +++ b/services/worker/src/passes/incidents/h_pr_updates.rs @@ -42,7 +42,7 @@ fn the_description_drops_an_older_rounds_failure_when_a_newer_round_lands() { let resume = include_str!("../resume.rs"); let round = fn_src(resume, "\nasync fn run_fix_round("); let pushed = round.find("Landed::Pushed { files }").unwrap(); - assert!(round[pushed..].contains("pr::refresh_description(")); + assert!(round[pushed..].contains("description::head_moved(")); } #[test] diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 5013e7218..40eda292e 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -25,6 +25,7 @@ mod af_lockfiles_out_of_sync; mod ag_red_ci_ships_what_passes; mod ah_dep_run_choice_and_proof; mod ai_open_items_settled; +mod aj_description_from_the_head; mod b_open_pr_retry; mod c_codegen_egress; mod d_echoed_markers; diff --git a/services/worker/src/passes/link_checks.rs b/services/worker/src/passes/link_checks.rs index 26eef918d..30acd4aa8 100644 --- a/services/worker/src/passes/link_checks.rs +++ b/services/worker/src/passes/link_checks.rs @@ -1425,9 +1425,8 @@ pub async fn refresh_pr( super::completeness::Section::Links, String::new(), ); - if let Err(e) = github - .update_pr_body(owner, repo, pr_number, &without) - .await + if let Err(e) = + crate::passes::description::save(github, owner, repo, pr_number, &without).await { warn!(pr_number, error = %e, "Could not drop the link checks from the description"); } @@ -1453,9 +1452,8 @@ pub async fn refresh_pr( report.section(), ); if updated != body { - if let Err(e) = github - .update_pr_body(owner, repo, pr_number, &updated) - .await + if let Err(e) = + crate::passes::description::save(github, owner, repo, pr_number, &updated).await { warn!(pr_number, error = %e, "Could not save the link checks to the description"); return None; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 74fd0fbea..ae05252ea 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1203,6 +1203,7 @@ mod covering; mod cross_repo; pub mod dep_fix; pub mod deploy_stats; +pub mod description; pub mod dlq_cleanup; pub mod e2e; pub mod e2e_attribution; @@ -1210,6 +1211,7 @@ pub mod e2e_setup; pub mod email_events; pub mod feature; pub mod feedback; +pub mod file_claims; mod finish_planned; pub mod fix_location; pub mod formatter; @@ -6756,6 +6758,18 @@ async fn run_passes( "The proof check needs more time than this step has left" ); let mut gaps = proof::prove(&work, &mut evidence, usage, has_time).await; + // A sentence the run wrote into a file that says a check passes stays + // only on a recorded passing result. + let unproven_claims = file_claims::settle(state, msg, &github, work.branch, &evidence).await; + if !unproven_claims.is_empty() { + add_progress_note( + state, + &msg.team_id, + run_id, + &file_claims::note(&unproven_claims), + ) + .await; + } // Planned work the check found not done is never an Open item: it goes at // the top of the pull request, which stays a draft until it's done. if !proof::planned_work(&gaps).is_empty() { @@ -8076,6 +8090,16 @@ async fn run_repo_pipeline( has_time_for_remediation(start) }) .await; + let unproven_claims = file_claims::settle(state, msg, github, work.branch, &evidence).await; + if !unproven_claims.is_empty() { + add_progress_note( + state, + &msg.team_id, + run_id, + &file_claims::note(&unproven_claims), + ) + .await; + } // Planned work still not done after the fix rounds: this repository's // pull request stays a draft with it listed at the top. let unfinished = proof::unfinished_section(&gaps); diff --git a/services/worker/src/passes/outside_exec.rs b/services/worker/src/passes/outside_exec.rs index 51e9ad714..b9aed3713 100644 --- a/services/worker/src/passes/outside_exec.rs +++ b/services/worker/src/passes/outside_exec.rs @@ -862,7 +862,7 @@ pub async fn refresh_pr(github: &GitHubClient, owner: &str, repo: &str, pr: u64, ); let updated = outside_work::with_not_done_top(&super::completeness::assemble(&rest, &owned), c); if updated != body { - if let Err(e) = github.update_pr_body(owner, repo, pr, &updated).await { + if let Err(e) = crate::passes::description::save(github, owner, repo, pr, &updated).await { warn!(pr, error = %e, "Could not update the PR's outside steps"); } } diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 366fffdbd..432f1ca9f 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -642,9 +642,14 @@ Return ONLY the markdown body text."#, info!(pr_number = number, pr_url = %url, "Using existing PR"); // A re-run changed the code: the description is rewritten from this // diff, never left describing the earlier version. - if let Err(e) = github - .update_pr_body(&msg.repo_owner, &msg.repo_name, number, &full_body) - .await + if let Err(e) = crate::passes::description::save( + github, + &msg.repo_owner, + &msg.repo_name, + number, + &full_body, + ) + .await { warn!(pr_number = number, error = %e, "Could not update the existing PR's description"); } @@ -1592,7 +1597,7 @@ pub async fn put_open_items( } let out = super::completeness::assemble(&rest, &owned); if out != body { - if let Err(e) = github.update_pr_body(owner, repo, number, &out).await { + if let Err(e) = crate::passes::description::save(github, owner, repo, number, &out).await { warn!(pr_number = number, error = %e, "Could not list the open items on the PR"); } } @@ -1630,9 +1635,9 @@ pub async fn apply_checks( }; let out = with_checks(&body, plan, proof, &repo); if out != body { - if let Err(e) = github - .update_pr_body(&msg.repo_owner, &msg.repo_name, number, &out) - .await + if let Err(e) = + crate::passes::description::save(github, &msg.repo_owner, &msg.repo_name, number, &out) + .await { warn!(pr_number = number, error = %e, "Could not add the checks' results to the PR"); } @@ -1939,7 +1944,7 @@ Return ONLY the markdown body text, then a line `{CHANGES_MARK}` and one bullet if body == current { return None; } - if let Err(e) = github.update_pr_body(owner, repo, pr_number, &body).await { + if let Err(e) = crate::passes::description::save(github, owner, repo, pr_number, &body).await { warn!(pr_number, error = %e, "Could not save the rewritten PR description"); return None; } @@ -2020,7 +2025,7 @@ async fn fill_placeholders_once( if fixed == body.trim() { return; } - match github.update_pr_body(owner, repo, pr_number, &fixed).await { + match crate::passes::description::save(github, owner, repo, pr_number, &fixed).await { Ok(()) => { let left = super::completeness::placeholder_holes(&fixed); if left.is_empty() { @@ -2063,7 +2068,7 @@ pub async fn link_siblings(github: &GitHubClient, prs: &[(String, String, u64)]) if new == body { continue; } - match github.update_pr_body(owner, name, *number, &new).await { + match crate::passes::description::save(github, owner, name, *number, &new).await { Ok(()) => info!( pr_number = number, "Named the run's sibling PRs and merge order" @@ -2094,7 +2099,7 @@ pub async fn settle_unverified_by_ci( let Some(body) = super::proof::settle_by_ci(pr["body"].as_str().unwrap_or("")) else { return; }; - match github.update_pr_body(owner, repo, pr_number, &body).await { + match crate::passes::description::save(github, owner, repo, pr_number, &body).await { Ok(()) => info!( pr_number, "CI passed: removed the checks it settled from the PR's Open items" diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index f4e72053b..27f44352f 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -1147,9 +1147,7 @@ async fn fix_own_findings(ctx: &Ctx<'_>, run_id: &str, f: &mut Facts) { // are deferred on the pull request with the reason and hold // nothing, so the draft waits only on what else holds it. let body = super::own_review::defer_findings(&f.body, &items, &why); - match ctx - .github - .update_pr_body(ctx.owner, ctx.repo, ctx.pr, &body) + match crate::passes::description::save(ctx.github, ctx.owner, ctx.repo, ctx.pr, &body) .await { Ok(_) => { @@ -1407,10 +1405,8 @@ async fn write_body(ctx: &Ctx<'_>, body: &str, d: &Decision) { let Some(new) = body_for(body, d) else { return; }; - if let Err(e) = ctx - .github - .update_pr_body(ctx.owner, ctx.repo, ctx.pr, &new) - .await + if let Err(e) = + crate::passes::description::save(ctx.github, ctx.owner, ctx.repo, ctx.pr, &new).await { warn!(pr = ctx.pr, error = %e, "Could not write the draft status to the description"); } @@ -1472,9 +1468,7 @@ async fn retry_or_give_up(ctx: &Ctx<'_>, run_id: &str, pr_url: &str, r: Refused) failed_section(&what), ); if new != body { - let _ = ctx - .github - .update_pr_body(ctx.owner, ctx.repo, ctx.pr, &new) + let _ = crate::passes::description::save(ctx.github, ctx.owner, ctx.repo, ctx.pr, &new) .await; } } diff --git a/services/worker/src/passes/release_run.rs b/services/worker/src/passes/release_run.rs index 5dcf004a2..6fcb50835 100644 --- a/services/worker/src/passes/release_run.rs +++ b/services/worker/src/passes/release_run.rs @@ -564,7 +564,9 @@ pub async fn run(state: &WorkerState, msg: ReleaseStepsMessage) -> Result<(), Bo let body = p["body"].as_str().unwrap_or(""); let updated = release_plan::put_section(body, &release_plan::section(&after)); if updated != body { - if let Err(e) = github.update_pr_body(owner, repo, pr, &updated).await { + if let Err(e) = + crate::passes::description::save(&github, owner, repo, pr, &updated).await + { warn!(pr, error = %e, "release: could not update the PR's release section"); } } diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 496e04bb9..33c0ee463 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -3953,7 +3953,17 @@ async fn run_fix_round( Ok(RoundEnd::Incomplete) } } - Ok(r) => { + Ok(mut r) => { + // The description is CoderHelm's to rebuild: an account that + // says it can't be edited, or leaves an edit of it to a person, + // loses that sentence and the rebuild runs below, whether or not + // the round pushed code. + let (account, handed_off) = + super::description::round_account(r.evidence.latest_notes()); + if handed_off { + warn!(run_id = %msg.run_id, "A fix round handed the description to a person; rebuilding it from the branch"); + r.evidence.notes = account; + } // What this round was asked and looked up reaches the next one. if round.kind == run_round::Kind::ReviewFix { record_own_round_note( @@ -3976,15 +3986,31 @@ async fn run_fix_round( // from the whole diff now, never left on the earlier // version. if files > 0 { - let _ = super::pr::refresh_description( + // A sentence the round wrote into a file that says + // a check passes stands only on a recorded result. + super::file_claims::settle( state, + &ctx.ticket_msg, &ctx.github, - (&msg.team_id, ctx.ticket_msg.installation_id), - pr.owner, - pr.repo, - pr.number, - &ctx.ticket_msg.team_instructions, - &[], + pr.branch, + &r.evidence, + ) + .await; + } + if files > 0 || handed_off { + let _ = super::description::head_moved( + &super::description::Moved { + state, + github: &ctx.github, + team_id: &msg.team_id, + installation_id: ctx.ticket_msg.installation_id, + owner: pr.owner, + repo: pr.repo, + number: pr.number, + ticket_id: &ctx.ticket_msg.ticket_id, + team_instructions: &ctx.ticket_msg.team_instructions, + requests: &[], + }, &ctx.provider, &mut ctx.usage, ) @@ -3994,6 +4020,25 @@ async fn run_fix_round( } super::round::Landed::Nothing => { super::round::clear(state, &msg.team_id, &msg.run_id).await; + if handed_off { + let _ = super::description::head_moved( + &super::description::Moved { + state, + github: &ctx.github, + team_id: &msg.team_id, + installation_id: ctx.ticket_msg.installation_id, + owner: pr.owner, + repo: pr.repo, + number: pr.number, + ticket_id: &ctx.ticket_msg.ticket_id, + team_instructions: &ctx.ticket_msg.team_instructions, + requests: &[], + }, + &ctx.provider, + &mut ctx.usage, + ) + .await; + } Ok(RoundEnd::Done { files: 0 }) } super::round::Landed::Refused(why) => { @@ -4583,10 +4628,14 @@ async fn after_planned_round( section.clone(), ); if updated != body { - if let Err(e) = ctx - .github - .update_pr_body(pr.owner, pr.repo, pr.number, &updated) - .await + if let Err(e) = crate::passes::description::save( + &ctx.github, + pr.owner, + pr.repo, + pr.number, + &updated, + ) + .await { warn!(run_id = msg.run_id, error = %e, "Could not update the PR's Not finished section"); } @@ -4771,10 +4820,9 @@ async fn recheck_security( } }; if let Some(updated) = super::proof::with_security_items(&body, &items) { - if let Err(e) = ctx - .github - .update_pr_body(pr.owner, pr.repo, pr.number, &updated) - .await + if let Err(e) = + crate::passes::description::save(&ctx.github, pr.owner, pr.repo, pr.number, &updated) + .await { warn!(run_id = msg.run_id, error = %e, "Could not update the PR's security items"); } @@ -5875,9 +5923,14 @@ async fn finish_on_own_findings( let body = p["body"].as_str().unwrap_or(""); let now = super::own_review::defer_findings(body, open, why); if now != body { - if let Err(e) = github - .update_pr_body(&msg.repo_owner, &msg.repo_name, pr_number, &now) - .await + if let Err(e) = crate::passes::description::save( + github, + &msg.repo_owner, + &msg.repo_name, + pr_number, + &now, + ) + .await { warn!(run_id, error = %e, "Could not list the deferred findings on the pull request"); } @@ -5976,9 +6029,8 @@ async fn hand_off_red_ci( match github.get_pull_request(pr.owner, pr.repo, pr.number).await { Ok(p) => { let body = with_ci_failing(p["body"].as_str().unwrap_or(""), §ion); - if let Err(e) = github - .update_pr_body(pr.owner, pr.repo, pr.number, &body) - .await + if let Err(e) = + crate::passes::description::save(github, pr.owner, pr.repo, pr.number, &body).await { warn!(run_id = msg.run_id, error = %e, "Could not write what fails on the pull request"); } @@ -6071,9 +6123,8 @@ pub(crate) async fn end_red_ci_rounds( match github.get_pull_request(pr.owner, pr.repo, number).await { Ok(p) => { let body = with_ci_failing(p["body"].as_str().unwrap_or(""), §ion); - if let Err(e) = github - .update_pr_body(pr.owner, pr.repo, number, &body) - .await + if let Err(e) = + crate::passes::description::save(github, pr.owner, pr.repo, number, &body).await { warn!(run_id, error = %e, "Could not write what fails on the pull request"); } @@ -6313,6 +6364,18 @@ async fn revert_dep_commit( apply_revert(state, msg, github, pr, files, ¬e).await?; super::dep_fix::save(state, ticket_msg, &msg.run_id, &run).await; super::dep_fix::settle(state, ticket_msg, &run).await; + // The head lost a set of bumps: the table and the headline say what it + // resolves now. + super::description::dependency_sections( + state, + github, + &msg.team_id, + pr.owner, + pr.repo, + pr.number, + &ticket_msg.ticket_id, + ) + .await; Some(note) } @@ -6439,9 +6502,7 @@ async fn apply_revert( } else { format!("{}\n\n## Deferred\n{line}", body.trim_end()) }; - let _ = github - .update_pr_body(pr.owner, pr.repo, pr.number, &now) - .await; + let _ = crate::passes::description::save(github, pr.owner, pr.repo, pr.number, &now).await; } Some(()) } diff --git a/services/worker/src/passes/review_fix/mod.rs b/services/worker/src/passes/review_fix/mod.rs index 1def9c499..f3ab956b4 100644 --- a/services/worker/src/passes/review_fix/mod.rs +++ b/services/worker/src/passes/review_fix/mod.rs @@ -1391,9 +1391,8 @@ pub async fn record_round( section, ); if updated != body { - if let Err(e) = github - .update_pr_body(owner, repo, pr_number, &updated) - .await + if let Err(e) = + crate::passes::description::save(github, owner, repo, pr_number, &updated).await { warn!(pr_number, error = %e, "review fix: could not record the round in the description"); } diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 611a4e5fe..de49173c9 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -3536,9 +3536,14 @@ async fn run_once( section, ); if updated != pr_body { - if let Err(e) = github - .update_pr_body(&msg.repo_owner, &msg.repo_name, msg.pr_number, &updated) - .await + if let Err(e) = crate::passes::description::save( + &github, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + &updated, + ) + .await { warn!(pr = msg.pr_number, error = %e, "Could not update the own PR's open review findings"); } else { @@ -4525,9 +4530,14 @@ async fn end_self_review_rounds( let body = p["body"].as_str().unwrap_or(""); let now = super::own_review::defer_findings(body, open, why); if now != body { - if let Err(e) = github - .update_pr_body(&msg.repo_owner, &msg.repo_name, msg.pr_number, &now) - .await + if let Err(e) = crate::passes::description::save( + github, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + &now, + ) + .await { warn!(pr = msg.pr_number, error = %e, "Could not list the deferred findings on the pull request"); } diff --git a/services/worker/src/passes/security_fixes.rs b/services/worker/src/passes/security_fixes.rs index 9471a522f..93d26fc29 100644 --- a/services/worker/src/passes/security_fixes.rs +++ b/services/worker/src/passes/security_fixes.rs @@ -2997,8 +2997,11 @@ async fn refresh_pr( ) .await; let links = body_links(cx.state, item.as_ref()); - let body = sec::pr_body_linked(unit, &pairs, &change, &check, &links); - if let Err(e) = cx.gh.update_pr_body(o, n, pr, &body).await { + // What the branch resolves now, with the fixes that joined or left. + let base = cx.gh.get_default_branch(o, n).await.unwrap_or_default(); + let head = head_facts(&cx.gh, unit, &base, &unit.branch).await; + let body = sec::pr_body_at_head(unit, &pairs, &change, &check, &links, &head); + if let Err(e) = crate::passes::description::save(&cx.gh, o, n, pr, &body).await { warn!(repo = %unit.repo, pr, error = %e, "security: could not write the bundle's description"); } if let Err(e) = cx.gh.update_pr_title(o, n, pr, &unit.title).await { @@ -4176,7 +4179,104 @@ pub async fn pr_body(state: &WorkerState, msg: &TicketMessage, change: &str) -> } } } - Some(sec::pr_body_linked(&unit, &pairs, change, &check, &links)) + // The table and the headline say what the branch's lockfile resolves, + // never what the run planned. + let head = match &gh { + Some(gh) => head_facts(gh, &unit, &msg.base_branch, &unit.branch).await, + None => common::dep_head::unknown(&unit, "GitHub could not be reached to read the branch"), + }; + Some(sec::pr_body_at_head( + &unit, &pairs, change, &check, &links, &head, + )) +} + +/// The lockfiles whose resolved copies CoderHelm reads. +fn is_read_lockfile(path: &str) -> bool { + let name = path.rsplit('/').next().unwrap_or(path); + !path.contains("node_modules/") + && (common::reachability::is_lockfile(path) + || matches!( + name, + "Cargo.lock" | "poetry.lock" | "uv.lock" | "Gemfile.lock" + )) +} + +/// What the head of a unit's branch resolves for each of its bumps: the +/// lockfiles its bumps go through, read on the base branch and on the head +/// and compared (`common::dep_head`). Whatever can't be read is said as not +/// known, with why. +pub(crate) async fn head_facts( + gh: &GitHubClient, + unit: &FixUnit, + base: &str, + head: &str, +) -> common::dep_head::HeadFacts { + use common::dep_head::{self, LockAt}; + let Some((o, n)) = unit.repo.split_once('/') else { + return dep_head::unknown(unit, "the repository is not known"); + }; + if head.is_empty() { + return dep_head::unknown(unit, "the pull request's branch is not known"); + } + let tree = match gh.get_tree(o, n, head).await { + Ok(t) => t, + Err(e) => { + warn!(repo = %unit.repo, error = %e, "security: could not list the head's files"); + return dep_head::unknown(unit, "the files on the head could not be listed"); + } + }; + let lockfiles: Vec = tree + .into_iter() + .map(|t| t.path) + .filter(|p| is_read_lockfile(p)) + .collect(); + let mut wanted: Vec = vec![]; + for b in &unit.bumps { + let lock = + common::dep_fix::lockfile_for(&b.manifest, &lockfiles).or_else(|| { + match lockfiles.as_slice() { + [one] => Some(one.clone()), + _ => None, + } + }); + if let Some(l) = lock { + if !wanted.contains(&l) { + wanted.push(l); + } + } + } + let mut locks = vec![]; + for path in wanted { + let mut at = LockAt { + path: path.clone(), + ..Default::default() + }; + for (side, git_ref) in [("the base branch", base), ("the head", head)] { + let copies = match gh.read_file_if_exists(o, n, &path, git_ref).await { + // Not there: nothing is installed through it on that side. + Ok(None) => Some(vec![]), + Ok(Some(text)) => { + let c = common::reachability::lock_copies(&path, &text); + if c.is_none() { + at.why = format!("`{path}` on {side} could not be read as a lockfile"); + } + c + } + Err(e) => { + at.why = format!("`{path}` could not be read on {side} ({e})"); + None + } + }; + if side == "the head" { + at.head = copies; + } else { + at.base = copies; + } + } + locks.push(at); + } + let sha = gh.get_ref(o, n, head).await.unwrap_or_default(); + dep_head::resolve(unit, &sha, &locks) } /// Where a security description points for what it leaves out: each @@ -4363,37 +4463,73 @@ async fn what_to_check( } /// A security pull request whose CI just ended (passed or failed): its -/// "What to check" and Proof say so, in place; the rest of the description -/// (the draft status at its top) stays. +/// description is rebuilt from its head. async fn refresh_ci_sections(cx: &Ctx<'_>, repo: &str, number: u64, ticket: &str) { - let Some(unit) = load_unit(cx.state, cx.team_id, ticket).await else { + rebuild_at_head(cx.state, &cx.gh, cx.team_id, repo, number, ticket).await; +} + +/// The sections of a security pull request's description CoderHelm +/// computes, written again from the head: the first sentences and the +/// table (what the lockfile on the head resolves, compared with the base +/// branch), "What to check" and Proof (where CI stands on this head). The +/// rest of the description (the draft status at its top, the run's words) +/// stays. Running it twice on one head writes nothing the second time. +pub(crate) async fn rebuild_at_head( + state: &WorkerState, + gh: &GitHubClient, + team_id: &str, + repo: &str, + number: u64, + ticket: &str, +) { + let Some(unit) = load_unit(state, team_id, ticket).await else { return; }; + if unit.ecosystem == common::infra_vuln::records::UNIT_ECOSYSTEM { + return; + } let Some((o, n)) = repo.split_once('/') else { return; }; - let Ok(pr) = cx.gh.get_pull_request(o, n, number).await else { + let Ok(pr) = gh.get_pull_request(o, n, number).await else { return; }; let body = pr["body"].as_str().unwrap_or(""); if !body.contains(sec::MARKER) { return; } - let item = ticket_item(cx.state, cx.team_id, ticket).await; + let item = ticket_item(state, team_id, ticket).await; let change = item.as_ref().map(|i| s(i, "change")).unwrap_or_default(); let notes = item.as_ref().map(|i| s(i, "notes")).unwrap_or_default(); - let members = unit_findings(cx.state, cx.team_id, &unit).await; + let members = unit_findings(state, team_id, &unit).await; let pairs: Vec<(&Finding, &FindingState)> = members.iter().map(|(f, st)| (f, st)).collect(); - let check = what_to_check(&cx.gh, &unit, ¬es, Some(number)).await; + let mut check = what_to_check(gh, &unit, ¬es, Some(number)).await; + check.dep_report = item + .as_ref() + .map(|i| s(i, "dep_report")) + .unwrap_or_default(); // The same links as when it opened: the rewritten sections are the // short ones a bundle's description carries. - let links = body_links(cx.state, item.as_ref()); - let fresh = sec::pr_body_linked(&unit, &pairs, &change, &check, &links); - let next = - common::upgrade_notes::replace_sections(body, &fresh, &["## What to check", "## Proof"]); + let links = body_links(state, item.as_ref()); + let head = head_facts( + gh, + &unit, + pr["base"]["ref"].as_str().unwrap_or(""), + pr["head"]["sha"] + .as_str() + .filter(|s| !s.is_empty()) + .unwrap_or(&unit.branch), + ) + .await; + let fresh = sec::pr_body_at_head(&unit, &pairs, &change, &check, &links, &head); + let next = common::upgrade_notes::replace_sections( + body, + &fresh, + &["## Summary", "## What to check", "## Proof"], + ); if next != body { - if let Err(e) = cx.gh.update_pr_body(o, n, number, &next).await { - warn!(%repo, number, error = %e, "security: could not write the CI result into the description"); + if let Err(e) = crate::passes::description::save(gh, o, n, number, &next).await { + warn!(%repo, number, error = %e, "security: could not rebuild the description from the head"); } } } diff --git a/services/worker/src/passes/stack.rs b/services/worker/src/passes/stack.rs index 9b8e9799d..547d3a9e7 100644 --- a/services/worker/src/passes/stack.rs +++ b/services/worker/src/passes/stack.rs @@ -1063,7 +1063,7 @@ pub async fn note_pr(github: &GitHubClient, owner: &str, repo: &str, pr: u64, de let body = p["body"].as_str().unwrap_or(""); let updated = put_section(body, &dep.section()); if updated != body { - if let Err(e) = github.update_pr_body(owner, repo, pr, &updated).await { + if let Err(e) = crate::passes::description::save(github, owner, repo, pr, &updated).await { tracing::warn!(pr, error = %e, "Could not state the stacked pull request's dependency"); } } diff --git a/services/worker/src/passes/stop_pr.rs b/services/worker/src/passes/stop_pr.rs index b1dbd4cd4..bf1909a1c 100644 --- a/services/worker/src/passes/stop_pr.rs +++ b/services/worker/src/passes/stop_pr.rs @@ -430,9 +430,14 @@ pub async fn open_with( // The pull request already open says what is not finished too. if !unfinished.is_empty() { let now = with_unfinished(p["body"].as_str().unwrap_or(""), &unfinished); - if let Err(e) = github - .update_pr_body(&msg.repo_owner, &msg.repo_name, number, &now) - .await + if let Err(e) = crate::passes::description::save( + &github, + &msg.repo_owner, + &msg.repo_name, + number, + &now, + ) + .await { tracing::warn!(run_id, error = %e, "Could not say what is not finished on the open pull request"); } @@ -701,9 +706,14 @@ async fn ship( } else { format!("{}\n\n{deferred}", body.trim_end()) }; - if let Err(e) = github - .update_pr_body(&msg.repo_owner, &msg.repo_name, number, &now) - .await + if let Err(e) = crate::passes::description::save( + github, + &msg.repo_owner, + &msg.repo_name, + number, + &now, + ) + .await { tracing::warn!(run_id, error = %e, "Could not list what is deferred on the open pull request"); }