From 91005c57852cf8625cd728a7ce5e5ff9dc71d3b3 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 13 Nov 2026 10:49:29 -0500 Subject: [PATCH] Runs settle their own open items before finishing: checks and audits run, stale and duplicate items go, refused checks carry to a fresh step --- docs/incidents.md | 1 + services/common/src/dep_audit.rs | 711 +++++++ services/common/src/lib.rs | 1 + services/worker/src/passes/completeness.rs | 11 +- services/worker/src/passes/dep_fix.rs | 2 +- services/worker/src/passes/implement.rs | 53 +- .../passes/incidents/ah_open_items_settled.rs | 422 +++++ services/worker/src/passes/incidents/mod.rs | 1 + services/worker/src/passes/mod.rs | 93 +- services/worker/src/passes/pr.rs | 6 + services/worker/src/passes/proof.rs | 37 +- services/worker/src/passes/resume.rs | 179 ++ services/worker/src/passes/run_guard.rs | 4 + services/worker/src/passes/settle.rs | 1630 +++++++++++++++++ 14 files changed, 3142 insertions(+), 9 deletions(-) create mode 100644 services/common/src/dep_audit.rs create mode 100644 services/worker/src/passes/incidents/ah_open_items_settled.rs create mode 100644 services/worker/src/passes/settle.rs diff --git a/docs/incidents.md b/docs/incidents.md index fd64dcd99..005a16916 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -62,6 +62,7 @@ pipeline still calls it there. | ae. `ae_budget_rounds` | Two loops of fix rounds still stopped on their own budget after the supervisor took every other ending. At eight automatic pushes the CI-only rounds on a finished run's pull request marked it ready, completed the run with its checks red and said a comment naming a change would start the next round, even while each round turned another red check green; at two rounds the self-review on CoderHelm's own pull request said the same and left its findings holding the draft, even while each round closed one. | Both loops follow `supervisor::next_round`: rounds go on while they make progress (checks that were red turn green, findings close), past the cap up to twice it and below the spend ceiling; a round without progress changes approach (one item, a fresh context with small edits, a re-split, the strongest model). When the rounds end, the findings left move to "Deferred" with the reason and stop holding the draft, and the run finishes; red checks are reverted to the last green head and deferred, or, when nothing can come out, the run fails with what fails and why. No message asks for a comment to go on: the phrases are on the `ownership` hand-off list. | | af. `af_lockfiles_out_of_sync` | A security update's pull request changed three `package.json` files (a pnpm workspace root and two npm packages with their own lockfiles) and none of the lockfiles, so every CI job failed at its frozen install. A retry planned its bumps by rule, then handed the red pull request to a model instead of building the plan. The model changed nothing; landing "nothing" removed the round's work branch, so the next attempt wrote to a branch that was gone (every write a 404, a hand edit of a lockfile among them). The round was called unfinished and the run ended failed after one attempt of three, with the same vague sentence twice. | A lockfile out of sync with its manifest is repaired by code before any model round, for any ticket and every package manager CoderHelm writes lockfiles for: each manager writes its own lockfile in the sandbox (with another mode and the LTS Node as fallbacks), one commit, and one that can't be written never hides the others. Any run that changes a manifest gets its lockfile written before the pull request opens. A retry of a dependency fix rebuilds its change from its plan on the same branch. A model's write to a lockfile is refused and pointed to the regenerate tool. Every attempt of a CI fix round opens its work branch first; a fault inside the round (no work branch, a compare or push GitHub refuses, a sandbox failure, anything else) is classified and has a way around it, and the catch-all runs the round again from a clean state, then once in a fresh step, before the supervisor's ending is asked. An attempt that changed nothing is followed by the repairs by code, then fresh evidence, then the strongest model. A run about to complete with red checks goes back to its CI fix round first, and an ending for red checks names the recorded cause, once. | | 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_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. | ## Adding a case diff --git a/services/common/src/dep_audit.rs b/services/common/src/dep_audit.rs new file mode 100644 index 000000000..26244e068 --- /dev/null +++ b/services/common/src/dep_audit.rs @@ -0,0 +1,711 @@ +//! The package manager's own audit, run by code after a change to the +//! dependencies, so the pull request quotes what is left. +//! +//! A dependency update finished with "the remaining critical and high +//! advisory counts are unknown because the audit never ran" listed on its +//! pull request for a person, twice. Nothing a person has was missing: the +//! audit is one command of the package manager the repository already uses. +//! +//! The rules here: +//! +//! - [`audits`] names the audit of every lockfile in a tree, by its package +//! manager, the way `upgrade_notes::lock_tools` names the command that +//! writes it. +//! - [`command`] is the one sandbox command that runs them. An audit prints +//! far more than a build's output keeps, so the command reduces each +//! report to a few marked lines where it ran: the tool's own summary, a +//! tally by severity, or the number of distinct advisories. It always +//! exits 0: an audit that finds advisories is a result, not a failure. +//! - [`read`] turns those lines into counts per lockfile, or why an audit +//! gave none, and [`Audited::line`] is the sentence the pull request +//! quotes. +//! +//! Everything here is pure; the sandbox run is the worker's +//! (`worker::passes::settle`). + +use crate::upgrade_notes::{lock_tools, LockTool}; + +/// How a tool's report is reduced to counts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Reads { + /// The report carries its own totals by severity + /// (`"vulnerabilities":{"critical":0,"high":2,...}`). + Summary, + /// Each advisory carries a severity: they are tallied. + Severities, + /// The tool rates nothing: distinct advisory ids are counted. The + /// pattern is an extended regular expression over the report with its + /// whitespace removed. + Ids(&'static str), +} + +/// One lockfile's audit. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Audit { + pub manager: &'static str, + pub lockfile: String, + /// The audit as people read it (`pnpm audit --json`). + pub shown: &'static str, + /// The full command, run in the lockfile's folder. + pub command: String, + pub reads: Reads, +} + +/// A manager's audit: what people read, what runs (after making the tool +/// available), and how its report is read. +struct Tool { + shown: &'static str, + run: String, + reads: Reads, +} + +/// Writes a Python lockfile out as pinned requirements and audits those: +/// `pip-audit` reads no lockfile format of its own. +fn pip_audit(export: &str) -> String { + format!( + "(command -v pip-audit >/dev/null 2>&1 || pip install -q pip-audit) && {export} && \ + pip-audit -r /tmp/coderhelm_audit_reqs.txt --no-deps --disable-pip -f json" + ) +} + +const PIP_IDS: Reads = Reads::Ids(r#""id":"[A-Z]+-[A-Za-z0-9-]+""#); + +/// The audit of `manager`'s lockfile. `berry` is a yarn project with a +/// `.yarnrc.yml` (yarn 2 and later audit through `yarn npm audit`). +fn tool(manager: &str, berry: bool) -> Option { + use crate::e2e::test_package::{ensure_manager, Manager}; + Some(match manager { + "npm" => Tool { + shown: "npm audit --json", + run: "npm audit --json".into(), + reads: Reads::Summary, + }, + "pnpm" => Tool { + shown: "pnpm audit --json", + run: format!("{}pnpm audit --json", ensure_manager(Manager::Pnpm)), + reads: Reads::Summary, + }, + "yarn" if berry => Tool { + shown: "yarn npm audit --all --recursive --json", + run: format!( + "{}yarn npm audit --all --recursive --json", + ensure_manager(Manager::Yarn) + ), + reads: Reads::Severities, + }, + "yarn" => Tool { + shown: "yarn audit --json", + run: format!("{}yarn audit --json", ensure_manager(Manager::Yarn)), + reads: Reads::Summary, + }, + "bun" => Tool { + shown: "bun audit --json", + run: format!("{}bun audit --json", ensure_manager(Manager::Bun)), + reads: Reads::Severities, + }, + "cargo" => Tool { + shown: "cargo audit --json", + run: "(command -v cargo-audit >/dev/null 2>&1 || cargo install -q cargo-audit --locked) \ + && cargo audit --json" + .into(), + reads: Reads::Ids(r#""id":"RUSTSEC-[0-9-]+""#), + }, + "poetry" => Tool { + shown: "pip-audit (on `poetry export`)", + run: pip_audit( + "(command -v poetry >/dev/null 2>&1 || pip install -q poetry) && \ + (poetry export --without-hashes -f requirements.txt -o /tmp/coderhelm_audit_reqs.txt 2>/dev/null \ + || (pip install -q poetry-plugin-export && poetry export --without-hashes -f requirements.txt -o /tmp/coderhelm_audit_reqs.txt))", + ), + reads: PIP_IDS, + }, + "uv" => Tool { + shown: "pip-audit (on `uv export`)", + run: pip_audit( + "(command -v uv >/dev/null 2>&1 || pip install -q uv) && \ + uv export --frozen --no-hashes --no-emit-project -o /tmp/coderhelm_audit_reqs.txt >/dev/null", + ), + reads: PIP_IDS, + }, + "pipenv" => Tool { + shown: "pip-audit (on `pipenv requirements`)", + run: pip_audit( + "(command -v pipenv >/dev/null 2>&1 || pip install -q pipenv) && \ + pipenv requirements > /tmp/coderhelm_audit_reqs.txt", + ), + reads: PIP_IDS, + }, + "pip-tools" => Tool { + shown: "pip-audit -r requirements.txt", + run: pip_audit("cp requirements.txt /tmp/coderhelm_audit_reqs.txt"), + reads: PIP_IDS, + }, + "bundler" => Tool { + shown: "bundle-audit check --update --format json", + run: "(command -v bundle-audit >/dev/null 2>&1 || gem install -q bundler-audit) && \ + bundle-audit check --update --format json" + .into(), + reads: Reads::Severities, + }, + "go" => Tool { + shown: "govulncheck -json ./...", + run: "(command -v govulncheck >/dev/null 2>&1 || go install golang.org/x/vuln/cmd/govulncheck@latest) \ + && PATH=\"$PATH:$(go env GOPATH)/bin\" govulncheck -json ./..." + .into(), + reads: Reads::Ids(r#""finding":\{"osv":"GO-[0-9-]+""#), + }, + _ => return None, + }) +} + +fn dir_of(path: &str) -> &str { + path.rsplit_once('/').map(|(d, _)| d).unwrap_or("") +} + +/// The audit of every lockfile in `tree`, one per lockfile, in path order. +pub fn audits(tree: &[String]) -> Vec { + lock_tools(tree) + .into_iter() + .filter_map(|t: LockTool| { + let dir = dir_of(&t.lockfile); + let rc = if dir.is_empty() { + ".yarnrc.yml".to_string() + } else { + format!("{dir}/.yarnrc.yml") + }; + let berry = tree.contains(&rc); + let tool = tool(t.manager, berry)?; + Some(Audit { + manager: t.manager, + shown: tool.shown, + command: if dir.is_empty() { + tool.run + } else { + format!("cd '{dir}' && {}", tool.run) + }, + reads: tool.reads, + lockfile: t.lockfile, + }) + }) + .collect() +} + +/// The audits of the lockfiles a change touches: `changed` holds the +/// branch's changed paths, and a lockfile is touched when it changed or a +/// file its manager reads did. Empty for a change to no dependency. +pub fn audits_for(tree: &[String], changed: &[String]) -> Vec { + let touched: Vec = lock_tools(tree) + .into_iter() + .filter(|t| { + changed.iter().any(|c| { + *c == t.lockfile || { + let mut hit = false; + for g in &t.inputs { + match g.strip_prefix('!') { + Some(not) if glob(not, c) => return false, + Some(_) => {} + None => hit |= glob(g, c), + } + } + hit + } + }) + }) + .map(|t| t.lockfile) + .collect(); + audits(tree) + .into_iter() + .filter(|a| touched.contains(&a.lockfile)) + .collect() +} + +/// A lock tool's input glob against a path: `**/` spans folders, a trailing +/// `/**` takes everything under one, anything else is the path itself. +fn glob(pattern: &str, path: &str) -> bool { + if let Some(dir) = pattern.strip_suffix("/**") { + return path.starts_with(&format!("{dir}/")); + } + match pattern.split_once("**/") { + Some((dir, name)) => { + path.starts_with(dir) && path[dir.len()..].rsplit('/').next() == Some(name) + } + None => pattern == path, + } +} + +/// The hosts a manager's audit reads, beyond its registry. +pub fn hosts(manager: &str) -> &'static [&'static str] { + match manager { + "npm" | "pnpm" | "yarn" | "bun" => &["registry.npmjs.org", "registry.yarnpkg.com"], + "cargo" => &[ + "github.com", + "crates.io", + "index.crates.io", + "static.crates.io", + ], + "poetry" | "uv" | "pipenv" | "pip-tools" => { + &["pypi.org", "files.pythonhosted.org", "api.osv.dev"] + } + "bundler" => &["rubygems.org", "github.com"], + "go" => &["vuln.go.dev", "proxy.golang.org", "sum.golang.org"], + _ => &[], + } +} + +// ── The command and its output ────────────────────────────────────────── + +/// What each audit's lines in the output start with. +pub const MARK: &str = "CODERHELM_AUDIT"; +const SUMMARY: &str = "CODERHELM_AUDIT_SUMMARY"; +const SEVERITY: &str = "CODERHELM_AUDIT_SEVERITY"; +const IDS: &str = "CODERHELM_AUDIT_IDS"; +const TAIL: &str = "CODERHELM_AUDIT_TAIL"; + +/// The one sandbox command that runs every audit in `audits`. Each reports +/// `CODERHELM_AUDIT `, then its report reduced to marked +/// lines, then the end of what it printed (for an audit that gave no +/// report). Always exits 0. +pub fn command(audits: &[Audit]) -> String { + let mut parts = Vec::new(); + for (i, a) in audits.iter().enumerate() { + let f = format!("/tmp/coderhelm_audit_{i}"); + let mut p = format!( + "({}) > {f}.out 2> {f}.err; c=$?; echo \"{MARK} {i} $c\"; \ + tr -d ' \\n\\r\\t' < {f}.out > {f}.flat; \ + grep -oE '\"vulnerabilities\":\\{{[^{{}}]*\\}}' {f}.flat | tail -n 1 | sed 's/^/{SUMMARY} {i} /'; \ + grep -oiE '\"(severity|criticality)\":\"[a-z]+\"' {f}.flat | tr 'A-Z' 'a-z' | sort | uniq -c | sed 's/^ */{SEVERITY} {i} /'", + a.command + ); + if let Reads::Ids(pattern) = a.reads { + p.push_str(&format!( + "; grep -oE '{pattern}' {f}.flat | sort -u | wc -l | sed 's/^ */{IDS} {i} /'" + )); + } + p.push_str(&format!( + "; cat {f}.err {f}.out | tail -c 300 | tr '\\n' ' ' | sed 's/^/{TAIL} {i} /'; echo" + )); + parts.push(p); + } + parts.push("true".to_string()); + parts.join("; ") +} + +/// Advisories left, by severity. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Counts { + pub critical: u32, + pub high: u32, + /// Moderate, low and informational. + pub other: u32, + /// Advisories the tool gives no severity for. + pub unrated: u32, +} + +impl Counts { + pub fn total(&self) -> u32 { + self.critical + self.high + self.other + self.unrated + } +} + +/// What one audit came to. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + Counts(Counts), + /// It gave no report, with the end of what it printed. + Failed(String), +} + +/// One lockfile's audit with its result. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Audited { + pub manager: String, + pub lockfile: String, + pub shown: String, + pub outcome: Outcome, +} + +impl Audited { + /// The sentence the pull request quotes. + pub fn line(&self) -> String { + let at = format!("`{}` on `{}`", self.shown, self.lockfile); + match &self.outcome { + Outcome::Counts(c) if c.total() == 0 => format!("{at}: no advisories left"), + Outcome::Counts(c) if c.unrated > 0 && c.unrated == c.total() => format!( + "{at}: {} advisor{} left (the tool gives no severity)", + c.unrated, + if c.unrated == 1 { "y" } else { "ies" } + ), + Outcome::Counts(c) => format!( + "{at}: {} critical, {} high and {} lower advisor{} left", + c.critical, + c.high, + c.other + c.unrated, + if c.other + c.unrated == 1 { "y" } else { "ies" } + ), + Outcome::Failed(why) => format!("{at} gave no report: {why}"), + } + } + + pub fn ran(&self) -> bool { + matches!(self.outcome, Outcome::Counts(_)) + } +} + +/// The lines of `output` marked `mark `, each without that prefix. +fn marked<'a>(output: &'a str, mark: &str, index: usize) -> Vec<&'a str> { + let head = format!("{mark} {index} "); + output + .lines() + .filter_map(|l| l.trim().strip_prefix(head.as_str())) + .collect() +} + +/// The number after `"key":` in a flat JSON object. +fn number(object: &str, key: &str) -> Option { + let at = object.find(&format!("\"{key}\":"))? + key.len() + 3; + let digits: String = object[at..] + .chars() + .take_while(char::is_ascii_digit) + .collect(); + digits.parse().ok() +} + +fn by_severity(c: &mut Counts, severity: &str, n: u32) { + match severity { + "critical" => c.critical += n, + "high" => c.high += n, + "none" | "unknown" | "" => c.unrated += n, + _ => c.other += n, + } +} + +/// Each audit's result from a [`command`] run's output, in order. An audit +/// with no line of its own (the build was cut short) gave no report. +pub fn read(audits: &[Audit], output: &str) -> Vec { + audits + .iter() + .enumerate() + .map(|(i, a)| { + let exit: Option = marked(output, MARK, i) + .first() + .and_then(|c| c.trim().parse().ok()); + let tail = marked(output, TAIL, i) + .first() + .map(|t| crate::truncate_str(t.trim(), 240).to_string()) + .unwrap_or_default(); + let failed = |what: &str| { + Outcome::Failed(if tail.is_empty() { + what.to_string() + } else { + format!("{what} ({tail})") + }) + }; + let outcome = match (exit, a.reads) { + (None, _) => failed("the sandbox build ended before it reported"), + (Some(code), Reads::Summary) => { + match marked(output, SUMMARY, i) + .into_iter() + .find(|s| s.contains("\"critical\":")) + { + Some(s) => { + let n = |k: &str| number(s, k).unwrap_or(0); + Outcome::Counts(Counts { + critical: n("critical"), + high: n("high"), + other: n("moderate") + n("low") + n("info"), + unrated: 0, + }) + } + None => failed(&format!("{} exited {code} with no summary", a.manager)), + } + } + (Some(code), Reads::Severities) => { + let mut c = Counts::default(); + for l in marked(output, SEVERITY, i) { + let mut it = l.split_whitespace(); + let (Some(n), Some(kv)) = + (it.next().and_then(|n| n.parse().ok()), it.next()) + else { + continue; + }; + let sev = kv.rsplit(':').next().unwrap_or("").trim_matches('"'); + by_severity(&mut c, sev, n); + } + if code != 0 && c.total() == 0 { + failed(&format!( + "{} exited {code} and listed no advisory", + a.manager + )) + } else { + Outcome::Counts(c) + } + } + (Some(code), Reads::Ids(_)) => { + let n: u32 = marked(output, IDS, i) + .first() + .and_then(|n| n.trim().parse().ok()) + .unwrap_or(0); + if code != 0 && n == 0 { + failed(&format!( + "{} exited {code} and listed no advisory", + a.manager + )) + } else { + Outcome::Counts(Counts { + unrated: n, + ..Default::default() + }) + } + } + }; + Audited { + manager: a.manager.to_string(), + lockfile: a.lockfile.clone(), + shown: a.shown.to_string(), + outcome, + } + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tree(paths: &[&str]) -> Vec { + paths.iter().map(|p| p.to_string()).collect() + } + + /// Every manager CoderHelm writes a lockfile for has its audit. + #[test] + fn every_lockfile_manager_has_its_audit() { + let all = tree(&[ + "package-lock.json", + "web/pnpm-lock.yaml", + "classic/yarn.lock", + "berry/yarn.lock", + "berry/.yarnrc.yml", + "edge/bun.lock", + "svc/Cargo.lock", + "py/poetry.lock", + "ml/uv.lock", + "old/Pipfile.lock", + "tools/requirements.txt", + "tools/requirements.in", + "api/Gemfile.lock", + "cli/go.sum", + ]); + let found = audits(&all); + let of = |lock: &str| { + found + .iter() + .find(|a| a.lockfile == lock) + .unwrap_or_else(|| panic!("no audit for {lock}")) + }; + assert_eq!(of("package-lock.json").command, "npm audit --json"); + assert_eq!(of("package-lock.json").reads, Reads::Summary); + let pnpm = of("web/pnpm-lock.yaml"); + assert!(pnpm.command.starts_with("cd 'web' && "), "{}", pnpm.command); + assert!(pnpm.command.ends_with("pnpm audit --json")); + assert_eq!(of("classic/yarn.lock").shown, "yarn audit --json"); + assert_eq!(of("classic/yarn.lock").reads, Reads::Summary); + assert_eq!( + of("berry/yarn.lock").shown, + "yarn npm audit --all --recursive --json" + ); + assert_eq!(of("berry/yarn.lock").reads, Reads::Severities); + assert!(of("edge/bun.lock").command.ends_with("bun audit --json")); + assert!(of("svc/Cargo.lock").command.ends_with("cargo audit --json")); + for lock in [ + "py/poetry.lock", + "ml/uv.lock", + "old/Pipfile.lock", + "tools/requirements.txt", + ] { + assert!(of(lock).command.contains("pip-audit -r "), "{lock}"); + } + assert!(of("api/Gemfile.lock") + .command + .contains("bundle-audit check")); + assert!(of("cli/go.sum").command.contains("govulncheck -json ./...")); + // Every manager the lockfile table names is here, and each names + // the hosts its audit reads. + for t in lock_tools(&all) { + assert!( + found.iter().any(|a| a.lockfile == t.lockfile), + "{} has no audit", + t.manager + ); + assert!(!hosts(t.manager).is_empty(), "{} has no hosts", t.manager); + } + assert_eq!(found.len(), lock_tools(&all).len()); + } + + #[test] + fn only_the_lockfiles_a_change_touches_are_audited() { + let t = tree(&[ + "package.json", + "pnpm-lock.yaml", + "apps/web/package.json", + "svc/Cargo.toml", + "svc/Cargo.lock", + "docs/readme.md", + ]); + let names = |changed: &[&str]| -> Vec { + audits_for(&t, &tree(changed)) + .into_iter() + .map(|a| a.lockfile) + .collect() + }; + assert_eq!(names(&["apps/web/package.json"]), vec!["pnpm-lock.yaml"]); + assert_eq!(names(&["svc/Cargo.lock"]), vec!["svc/Cargo.lock"]); + assert_eq!(names(&["svc/Cargo.toml"]), vec!["svc/Cargo.lock"]); + assert!(names(&["docs/readme.md", "apps/web/src/a.ts"]).is_empty()); + } + + fn two() -> Vec { + audits(&tree(&["pnpm-lock.yaml", "svc/Cargo.lock"])) + } + + #[test] + fn one_command_runs_every_audit_and_never_fails_the_build() { + let cmd = command(&two()); + assert!(cmd.contains("echo \"CODERHELM_AUDIT 0 $c\"")); + assert!(cmd.contains("echo \"CODERHELM_AUDIT 1 $c\"")); + assert!(cmd.contains("pnpm audit --json")); + assert!(cmd.contains("cd 'svc' && ")); + // Only a tool that rates nothing has its ids counted. + assert_eq!(cmd.matches("CODERHELM_AUDIT_IDS").count(), 1); + assert!(cmd.ends_with("; true")); + } + + #[test] + fn counts_are_read_from_each_tools_report() { + let out = "CODERHELM_AUDIT 0 1\n\ + CODERHELM_AUDIT_SUMMARY 0 \"vulnerabilities\":{\"info\":0,\"low\":1,\"moderate\":4,\"high\":2,\"critical\":0}\n\ + CODERHELM_AUDIT_SEVERITY 0 9 \"severity\":\"high\"\n\ + CODERHELM_AUDIT_TAIL 0 }\n\ + CODERHELM_AUDIT 1 1\n\ + CODERHELM_AUDIT_IDS 1 3\n\ + CODERHELM_AUDIT_TAIL 1 }\n"; + let read = read(&two(), out); + // The summary stands, never the per-advisory tally beside it (npm + // and pnpm repeat a severity on every path to a package). + assert_eq!( + read[0].outcome, + Outcome::Counts(Counts { + critical: 0, + high: 2, + other: 5, + unrated: 0 + }) + ); + assert_eq!( + read[0].line(), + "`pnpm audit --json` on `pnpm-lock.yaml`: 0 critical, 2 high and 5 lower advisories left" + ); + assert_eq!( + read[1].line(), + "`cargo audit --json` on `svc/Cargo.lock`: 3 advisories left (the tool gives no severity)" + ); + assert!(read.iter().all(Audited::ran)); + } + + #[test] + fn severities_are_tallied_for_tools_without_a_summary() { + let a = audits(&tree(&["yarn.lock", ".yarnrc.yml", "api/Gemfile.lock"])); + // In path order: the Gemfile's audit is 0, the root yarn.lock's is 1. + let out = "CODERHELM_AUDIT 1 1\n\ + CODERHELM_AUDIT_SEVERITY 1 2 \"severity\":\"critical\"\n\ + CODERHELM_AUDIT_SEVERITY 1 1 \"severity\":\"moderate\"\n\ + CODERHELM_AUDIT 0 0\n"; + let read = read(&a, out); + let api = read.iter().find(|r| r.manager == "bundler").unwrap(); + assert_eq!(api.outcome, Outcome::Counts(Counts::default())); + assert!(api.line().ends_with("no advisories left"), "{}", api.line()); + let yarn = read.iter().find(|r| r.manager == "yarn").unwrap(); + assert_eq!( + yarn.outcome, + Outcome::Counts(Counts { + critical: 2, + high: 0, + other: 1, + unrated: 0 + }) + ); + } + + #[test] + fn an_audit_that_gave_no_report_says_why_and_is_never_read_as_clean() { + let out = "CODERHELM_AUDIT 0 1\n\ + CODERHELM_AUDIT_TAIL 0 ERR_PNPM_AUDIT_BAD_RESPONSE The audit endpoint responded with 503\n"; + let read = read(&two(), out); + assert!(!read[0].ran()); + assert!( + read[0].line().contains("gave no report") && read[0].line().contains("503"), + "{}", + read[0].line() + ); + // The build was cut before the second audit printed anything. + assert_eq!( + read[1].outcome, + Outcome::Failed("the sandbox build ended before it reported".into()) + ); + // A tool that rates nothing and exits clean found nothing. + let clean = super::read( + &two()[1..], + "CODERHELM_AUDIT 0 0\nCODERHELM_AUDIT_IDS 0 0\n", + ); + assert_eq!(clean[0].outcome, Outcome::Counts(Counts::default())); + } + + /// The reduction itself, run by a real shell on reports shaped like each + /// tool's: what the sandbox prints is what [`read`] reads. + #[test] + fn the_shell_reduces_real_shaped_reports_to_the_marked_lines() { + let dir = std::env::temp_dir().join(format!("coderhelm-audit-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let npm = dir.join("npm.json"); + std::fs::write( + &npm, + "{\n \"vulnerabilities\": {\n \"left-pad\": {\n \"severity\": \"high\",\n \"via\": [{ \"severity\": \"high\" }]\n }\n },\n \"metadata\": {\n \"vulnerabilities\": {\n \"info\": 0,\n \"low\": 0,\n \"moderate\": 1,\n \"high\": 1,\n \"critical\": 0,\n \"total\": 2\n }\n }\n}\n", + ) + .unwrap(); + let rust = dir.join("rust.json"); + std::fs::write( + &rust, + "{\"vulnerabilities\":{\"found\":true,\"count\":2,\"list\":[{\"advisory\":{\"id\":\"RUSTSEC-2024-0001\"}},{\"advisory\":{\"id\":\"RUSTSEC-2024-0002\"}},{\"advisory\":{\"id\":\"RUSTSEC-2024-0001\"}}]}}", + ) + .unwrap(); + let mut audits = two(); + audits[0].command = format!("cat '{}'; exit 1", npm.display()); + audits[1].command = format!("cat '{}'; exit 1", rust.display()); + let out = std::process::Command::new("sh") + .arg("-c") + .arg(command(&audits)) + .output() + .unwrap(); + assert!(out.status.success(), "the command must exit 0"); + let text = String::from_utf8_lossy(&out.stdout).to_string(); + let read = read(&audits, &text); + assert_eq!( + read[0].outcome, + Outcome::Counts(Counts { + critical: 0, + high: 1, + other: 1, + unrated: 0 + }), + "{text}" + ); + assert_eq!( + read[1].outcome, + Outcome::Counts(Counts { + unrated: 2, + ..Default::default() + }), + "{text}" + ); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 4b3e47c00..4df935c8b 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -41,6 +41,7 @@ pub mod deliveries; pub mod deliveries_rollup; /// Dependency fix runs: the risk-aware plan, sandbox verification and /// bisect, resumable state. +pub mod dep_audit; pub mod dep_fix; /// The shared dead-letter queue: whose each failed message is, whether the /// worker can read it, and when the cleanup archives it. diff --git a/services/worker/src/passes/completeness.rs b/services/worker/src/passes/completeness.rs index 2b0130f0c..c3f1f15ae 100644 --- a/services/worker/src/passes/completeness.rs +++ b/services/worker/src/passes/completeness.rs @@ -118,6 +118,9 @@ pub enum Section { /// What each review fix round checked before its push (see /// `review_fix`). ReviewFixes, + /// What CoderHelm ran in its sandbox to settle its own open items, with + /// each result (see `settle`). + Settled, /// What is still open, at the bottom (#238's "Not yet verified"). OpenItems, /// Planned work the check before the PR still found not done after its @@ -139,12 +142,13 @@ pub enum Section { } impl Section { - const ALL: [Section; 10] = [ + const ALL: [Section; 11] = [ Section::Links, Section::Mirrors, Section::MergeOrder, Section::NotInPr, Section::ReviewFixes, + Section::Settled, Section::OpenItems, Section::Unfinished, Section::OpenFindings, @@ -169,6 +173,7 @@ impl Section { super::review_fix::evidence::START, super::review_fix::evidence::END, ), + Section::Settled => (super::settle::SETTLED_START, super::settle::SETTLED_END), Section::OpenItems => (super::proof::UNVERIFIED_START, super::proof::UNVERIFIED_END), Section::Unfinished => (super::proof::UNFINISHED_START, super::proof::UNFINISHED_END), Section::OpenFindings => (super::own_review::START, super::own_review::END), @@ -206,6 +211,7 @@ pub struct Owned { pub merge_order: String, pub not_in_pr: String, pub review_fixes: String, + pub settled: String, pub open_items: String, pub unfinished: String, pub open_findings: String, @@ -221,6 +227,7 @@ impl Owned { Section::MergeOrder => &mut self.merge_order, Section::NotInPr => &mut self.not_in_pr, Section::ReviewFixes => &mut self.review_fixes, + Section::Settled => &mut self.settled, Section::OpenItems => &mut self.open_items, Section::Unfinished => &mut self.unfinished, Section::OpenFindings => &mut self.open_findings, @@ -347,6 +354,7 @@ pub fn assemble(rest: &str, owned: &Owned) -> String { &owned.merge_order, &owned.not_in_pr, &owned.review_fixes, + &owned.settled, ] .into_iter() .map(|s| s.trim()) @@ -1197,6 +1205,7 @@ mod tests { fn the_description_is_put_together_in_its_order() { let writer = "Closes #9\n\n**Summary** The report needs a reader.\n\n**Changes**\n* **Users** add `analytics_reader`\n\n**Risk** **Low**: one new user.\n\n**Verification**\n1. Run the plan."; let owned = Owned { + settled: String::new(), unfinished: String::new(), open_findings: String::new(), objections: String::new(), diff --git a/services/worker/src/passes/dep_fix.rs b/services/worker/src/passes/dep_fix.rs index 8adf3580b..86de04baf 100644 --- a/services/worker/src/passes/dep_fix.rs +++ b/services/worker/src/passes/dep_fix.rs @@ -388,7 +388,7 @@ pub struct Work<'a> { /// The steps a probe runs: the repository's install and type-check/build, /// its CI's lint and format commands, and its unit tests (all of them: a /// dependency touches every caller). -async fn probe_steps(github: &GitHubClient, msg: &TicketMessage) -> Vec { +pub(crate) async fn probe_steps(github: &GitHubClient, msg: &TicketMessage) -> Vec { let (o, n, base) = (&msg.repo_owner, &msg.repo_name, &msg.base_branch); let ci = checks::detect_ci(github, o, n, base).await; let mut steps = vec![]; diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 9c4e50025..3e5ffef7d 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -750,6 +750,7 @@ pub async fn run( node_version, terraform_version, check_budget: std::sync::atomic::AtomicUsize::new(0), + locks_written_at: std::sync::Mutex::new(None), gen_edit_rejects: std::sync::Mutex::new(std::collections::HashMap::new()), deadline, policy: Some(crate::agent::policy::gate( @@ -1186,6 +1187,8 @@ pub async fn run( // Read from the diff when the change is judged. environments: Vec::new(), data_change: false, + // Run by the settle stage, after the coder. + audits: Vec::new(), }, }) } @@ -1402,6 +1405,14 @@ fn run_checks_tool() -> ToolDefinition { } } +/// Whether the lockfiles already match the branch at `head`: they were +/// regenerated for exactly this head in this pass. A regeneration is a +/// sandbox build of minutes, and two of them in one step once left no time +/// for the checks. +pub(crate) fn lockfiles_current(written_at: Option<&str>, head: &str) -> bool { + !head.is_empty() && written_at == Some(head) +} + /// Regenerates the repo's generated files (Sanity types, GraphQL types, etc.) by /// running its codegen in the sandbox and committing the changed files back — /// the capability that lets the agent finish tickets whose fix depends on @@ -1419,7 +1430,9 @@ fn run_codegen_tool() -> ToolDefinition { (package.json, pyproject.toml, Cargo.toml, Gemfile, go.mod), every lockfile that \ reads it (package-lock.json, pnpm-lock.yaml, yarn.lock, ...) is written again by \ its own package manager and committed. Never write a lockfile yourself: such a \ - write is refused. Takes no arguments. After it runs, call run_checks to confirm." + write is refused. Each call is a sandbox build of several minutes: make EVERY manifest \ + change the task needs first, then call this ONCE. Takes no arguments. After it runs, \ + call run_checks to confirm." .to_string(), input_schema: json!({"type": "object", "properties": {}}), } @@ -1738,6 +1751,9 @@ struct WriteToolExecutor<'a> { run_id: Option, /// Bounds sandbox runs per pass; also the S3 key nonce per attempt. check_budget: std::sync::atomic::AtomicUsize, + /// The branch head the lockfiles were last regenerated for in this pass + /// (see [`lockfiles_current`]). + locks_written_at: std::sync::Mutex>, /// Per-path count of generated-file edit rejections. After MAX_GEN_REJECTS /// on the same path the guard opens (escape hatch) so a banner-carrying file /// that run_codegen cannot regenerate — or a false-positive banner match — @@ -2618,8 +2634,14 @@ impl<'a> WriteToolExecutor<'a> { } if !sandbox.has_time(self.deadline) { note(LogOutcome::soft_fail("not run: not enough time left")); + // The check is owed, not dropped: the settle stage runs it in a + // step with a full window before the run finishes (`settle`). + self.sandbox_record.lock().unwrap().refused_for_time = true; return Ok(json!( - "Not enough time remains to run a sandbox build safely; finalize your changes now." + "This step has too little time left for a sandbox build. Finish your changes \ + now; CoderHelm runs the repository's checks on the branch in a fresh step \ + before the run finishes, and fixes what they find. Do not write that a check \ + passed: none has run on these changes." )); } @@ -2833,6 +2855,20 @@ impl<'a> WriteToolExecutor<'a> { } } } + // One regeneration per state of the branch: a lockfile written for + // this head is not written again until a manifest changes. + let head = self + .github + .get_ref(&self.owner, &self.repo, &self.branch) + .await + .unwrap_or_default(); + if lockfiles_current(self.locks_written_at.lock().unwrap().as_deref(), &head) { + return Ok(Some( + "Lockfiles: already regenerated for the manifests as they are now; nothing \ + changed since. Call run_checks." + .to_string(), + )); + } let attempt = self.check_budget.fetch_add(1, Ordering::SeqCst); if attempt >= MAX_CHECKS_PER_RUN { return Ok(Some(format!( @@ -2860,6 +2896,19 @@ impl<'a> WriteToolExecutor<'a> { &cmd, ) .await; + if repair.not_run.is_none() && repair.failed.is_empty() { + // The head the lockfiles now match: the commit that wrote them, + // or the one they already matched. + let now = if repair.written.is_empty() { + head.clone() + } else { + self.github + .get_ref(&self.owner, &self.repo, &self.branch) + .await + .unwrap_or_default() + }; + *self.locks_written_at.lock().unwrap() = Some(now).filter(|h| !h.is_empty()); + } for p in &repair.written { self.files_modified.lock().unwrap().insert(p.clone()); self.file_cache diff --git a/services/worker/src/passes/incidents/ah_open_items_settled.rs b/services/worker/src/passes/incidents/ah_open_items_settled.rs new file mode 100644 index 000000000..dba50fbdd --- /dev/null +++ b/services/worker/src/passes/incidents/ah_open_items_settled.rs @@ -0,0 +1,422 @@ +//! ah. A dependency update finished "completed" with its checks passed, and +//! its pull request still listed five Open items for a person: +//! +//! 1. the remaining critical and high advisory counts were unknown, because +//! the package manager's audit never ran and no CI command runs it; +//! 2. nothing showed that the packages an override moved to a new major +//! still worked ("confirm with the build results and the tests"); +//! 3. a README line said build, type check, lint and tests pass while no +//! check had run (by the end of the run the line had been rewritten and +//! the checks had run, and the item was still there); +//! 4. the audit's counts were unknown, again, in other words; +//! 5. the plan had no end-to-end checklist, on a change with nothing to +//! take to production. +//! +//! The coder had asked for the full checks twice and was refused both times +//! ("not run: not enough time left") after two lockfile regenerations of +//! about three minutes each in the same step. Nothing carried the check +//! anywhere. +//! +//! Guarantee: a run settles its own open items before it finishes. What +//! CoderHelm can run (a check of the repository's own, the package +//! manager's audit after a change to the dependencies) runs in its sandbox +//! in a step with a full window, a fresh one when needed, and the result is +//! quoted on the pull request; a failing result is acted on. An item that +//! does not apply to the run is never raised, the same missing fact is one +//! item, and items are derived again when the head moves. What stays on +//! the pull request names why it stays. + +use super::fixture::fn_src; +use crate::passes::checks::{CheckKind, Step}; +use crate::passes::proof::{self, Finding}; +use crate::passes::settle::{self, Action, Class, Facts, Next, Plan, Record, Room}; +use crate::passes::triage::TicketIntent; +use common::dep_audit::{self, Audited, Counts, Outcome}; + +fn item(point: &str, check: &str, detail: &str, settle: &str) -> Finding { + Finding { + point: point.into(), + check: check.into(), + detail: detail.into(), + settle: settle.into(), + ..Default::default() + } +} + +/// The five items, as the run wrote them (package names removed). +fn five() -> Vec { + vec![ + item( + "unrun_check", + "security", + "The remaining critical and high advisory counts are unknown because the audit never ran and no CI command runs it.", + "Run it and quote the counts in the PR.", + ), + item( + "assumption", + "", + "The root overrides force parents onto a new major they never declared, and nothing shows those parents work.", + "Confirm with the web and Studio build results and the tests, and pin back within the current major any override whose parent breaks.", + ), + item( + "assumption", + "", + "The README says build, type check, lint and tests pass, but no check has run on this branch.", + "Rewrite that line from the actual results.", + ), + item( + "external_fact", + "", + "The critical and high counts from the audit are unknown.", + "", + ), + item( + "end_to_end", + "", + "The plan has no end-to-end checklist.", + "List every step the ticket needs in production and who does it.", + ), + ] +} + +/// The run: a chore that changes a workspace's manifests and its lockfile. +fn run_facts() -> Facts { + let tree: Vec = [ + "package.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + "apps/web/package.json", + "apps/studio/package.json", + "README.md", + ] + .iter() + .map(|p| p.to_string()) + .collect(); + let changed: Vec = ["package.json", "pnpm-lock.yaml", "README.md"] + .iter() + .map(|p| p.to_string()) + .collect(); + let audits = dep_audit::audits_for(&tree, &changed); + assert_eq!(audits.len(), 1); + assert_eq!(audits[0].shown, "pnpm audit --json"); + Facts { + intent: TicketIntent::Chore, + planned_by_rules: false, + dep_change: !audits.is_empty(), + // The coder's two refused checks. + checks_owed: true, + } +} + +fn steps() -> Vec { + let step = |kinds: &[CheckKind], cmd: &str| Step { + kinds: kinds.to_vec(), + cmd: cmd.into(), + scope: None, + }; + vec![ + step( + &[CheckKind::Typecheck, CheckKind::Build], + "pnpm install --frozen-lockfile && pnpm -r typecheck && pnpm -r build", + ), + step(&[CheckKind::Lint], "pnpm lint"), + step(&[CheckKind::Tests], "pnpm test"), + ] +} + +fn audit(outcome: Outcome) -> Audited { + Audited { + manager: "pnpm".into(), + lockfile: "pnpm-lock.yaml".into(), + shown: "pnpm audit --json".into(), + outcome, + } +} + +fn room() -> Room { + Room { + build: true, + round: true, + sandbox: true, + dep_sets: 0, + } +} + +#[test] +fn each_of_the_five_items_is_run_or_dropped_never_listed_for_a_person() { + let facts = run_facts(); + let items = five(); + let classes: Vec = items.iter().map(|f| settle::classify(f, &facts)).collect(); + assert_eq!(classes[0], Class::Run(vec![Action::Audit])); + assert_eq!( + classes[1], + Class::Run(vec![ + Action::Check(CheckKind::Build), + Action::Check(CheckKind::Tests) + ]) + ); + assert_eq!( + classes[2], + Class::Run(vec![ + Action::Check(CheckKind::Typecheck), + Action::Check(CheckKind::Build), + Action::Check(CheckKind::Lint), + Action::Check(CheckKind::Tests), + ]) + ); + assert_eq!(classes[3], Class::Run(vec![Action::Audit])); + assert!(matches!(classes[4], Class::NotApplicable(_))); + assert!( + !classes.iter().any(|c| matches!(c, Class::Human(_))), + "none of the five needs anything only a person has" + ); + + // One build of the repository's checks and one audit answer all of them. + let plan = settle::plan(&items, &facts); + assert!(plan.checks && plan.audit); + + // The step the coder left had no window: a fresh step, not a guess. + let mut rec = Record::default(); + rec.for_head("h1"); + let short = Room { + build: false, + ..room() + }; + assert!(matches!( + settle::next(&plan, &rec, &short), + Next::FreshStep(_) + )); + assert_eq!(settle::next(&plan, &rec, &room()), Next::Build); + + // The fresh step ran both. Everything passes; the audit leaves one high. + rec.record_checks(&steps(), &[Some(0), Some(0), Some(0)], "ok"); + rec.record_audits(&[audit(Outcome::Counts(Counts { + critical: 0, + high: 1, + other: 3, + unrated: 0, + }))]); + assert_eq!(settle::next(&plan, &rec, &room()), Next::Done); + + let settled = settle::apply(items, &facts, &rec); + assert!( + settled.open.is_empty(), + "still listed: {:?}", + settled.open.iter().map(|f| &f.detail).collect::>() + ); + // Items 1 and 4 were one item; 2 and 3 closed on the checks; 5 never + // applied. + assert_eq!(settled.closed.len(), 3); + assert_eq!(settled.dropped.len(), 1); + assert!(settled.closed[0] + .1 + .contains("0 critical, 1 high and 3 lower advisories left")); + assert!(settled.closed[1].1.contains("PASS")); + + // The pull request: no Open items, and the real results quoted. + assert!(proof::gaps_section(&settled.open).is_empty()); + let section = settle::settled_section(&settled, &rec); + assert!(section.contains( + "`pnpm audit --json` on `pnpm-lock.yaml`: 0 critical, 1 high and 3 lower advisories left" + )); + assert!(section.contains("tests: PASS, `pnpm test`")); + assert!(section.contains("on commit `h1`")); + for old in [ + "counts are unknown", + "no check has run", + "end-to-end checklist", + ] { + assert!(!section.contains(old), "{old}"); + } +} + +#[test] +fn a_failing_build_takes_out_what_breaks_it_and_ships_what_passes() { + let facts = run_facts(); + let plan = settle::plan(&five(), &facts); + let mut rec = Record::default(); + rec.for_head("h3"); + rec.record_checks( + &steps(), + &[Some(2), Some(0), Some(0)], + "apps/studio build: error TS2305: Module '\"schema-kit\"' has no exported member 'defineKind'", + ); + // The same build ran the audit. + rec.record_audits(&[audit(Outcome::Counts(Counts { + critical: 0, + high: 0, + other: 2, + unrated: 0, + }))]); + // A dependency fix with verified sets on the branch: the newest set + // comes out and the checks run again on what is left. + let dep = Room { + dep_sets: 3, + ..room() + }; + assert_eq!(settle::next(&plan, &rec, &dep), Next::TakeOutSet); + let note = crate::passes::resume::settle_revert_note( + &["`schema-kit` 3.4.0 to 4.0.1 deferred: the checks CoderHelm ran in its sandbox failed with it applied".to_string()], + 2, + ); + assert!(note.contains("took out that set of 1 bump and kept the 2 sets before it")); + assert!(note.contains("`schema-kit` 3.4.0 to 4.0.1 deferred")); + // Any other run: the coder gets the real output, in a round of its own. + assert_eq!(settle::next(&plan, &rec, &room()), Next::FixRound); + let feedback = settle::fix_feedback(&rec, &five()[1..2]); + assert!(feedback.contains("error TS2305")); + assert!(feedback.contains("typecheck + build: FAIL (exit 2)")); + assert!(feedback.contains("nothing shows those parents work")); + // The head moved: the old results say nothing about the new one. + rec.for_head("h4"); + assert_eq!(settle::next(&plan, &rec, &room()), Next::Build); + assert_eq!(rec.rounds, 0, "counted where the round starts"); + + // The pipeline: the same revert the red-CI path uses, written before + // the run's saved state moves. + let src = include_str!("../resume.rs"); + let take = fn_src(src, "pub(crate) async fn take_out_dep_set("); + let write = take.find("apply_revert(").unwrap(); + assert!(take.find("take_out_last_commit(").unwrap() < write); + assert!(write < take.find("dep_fix::save(").unwrap()); + assert!(write < take.find("dep_fix::settle(").unwrap()); +} + +#[test] +fn an_item_a_later_round_fixed_is_gone_when_the_head_moves() { + let facts = run_facts(); + let readme = five().remove(2); + // Written on the first head, where no check had run. + let mut rec = Record::default(); + rec.for_head("h1"); + let open = settle::apply(vec![readme.clone()], &facts, &rec).open; + assert_eq!(open.len(), 1); + let body = format!( + "## Summary\nx\n\n{}", + settle::stamp(&proof::gaps_section(&open), "h1") + ); + // A later round rewrote the line: the head is another one, the items + // are of the old one, and the run goes back to its checks before it + // finishes. Once per head. + assert!(settle::redrive_due(&body, "h2", 0, "")); + assert!(!settle::redrive_due(&body, "h2", 1, "h2")); + assert!(!settle::redrive_due(&body, "h1", 0, "")); + // There the checks run on the head, and the item is gone. + rec.for_head("h2"); + rec.record_checks(&steps(), &[Some(0), Some(0), Some(0)], "ok"); + assert!(settle::apply(vec![readme], &facts, &rec).open.is_empty()); + + // The pipeline: a run about to complete asks first, and the checks' + // step writes every item with its head. + let resume = include_str!("../resume.rs"); + let complete = fn_src(resume, "async fn complete_run_with_status("); + assert!( + complete.find("redrive_stale_items(").unwrap() < complete.find("end_run(").unwrap(), + "the run ends before its open items are derived again" + ); + let redrive = fn_src(resume, "async fn redrive_stale_items("); + assert!(redrive.contains("settle::redrive_due(")); + assert!(redrive.contains("recheck_at_checks(")); + let passes = include_str!("../mod.rs"); + assert_eq!( + passes + .matches("settle::stamp(&proof::gaps_section(&gaps), &items_head)") + .count(), + 2, + "single and multi repository" + ); +} + +#[test] +fn a_check_refused_for_lack_of_time_is_owed_and_run_in_a_fresh_step() { + // The coder's tool records the refusal and never tells the coder to + // finalise unverified. + let implement = include_str!("../implement.rs"); + let checks = fn_src(implement, "async fn run_checks_impl("); + let refused = &checks[checks + .find("if !sandbox.has_time(self.deadline) {") + .unwrap()..]; + let refused = &refused[..refused.find("let changed: Vec").unwrap()]; + assert!(refused.contains("refused_for_time = true")); + assert!(refused.contains("in a fresh step")); + assert!(!refused.contains("finalize your changes now")); + + // Owed with no item at all, and carried until a step has the window. + let facts = Facts { + checks_owed: true, + ..Default::default() + }; + let plan = settle::plan(&[], &facts); + assert_eq!( + plan, + Plan { + checks: true, + kinds: vec![], + audit: false + } + ); + let rec = Record::default(); + let short = Room { + build: false, + ..room() + }; + assert!(matches!( + settle::next(&plan, &rec, &short), + Next::FreshStep(_) + )); + + // The pipeline: the stage runs after every check and before the + // description is written, and a fresh step resumes at the checks. + let passes = include_str!("../mod.rs"); + let stage = passes + .find("let (gaps, settled) = match settle::run(") + .unwrap(); + assert!(passes.find("let mut gaps = proof::prove(&work").unwrap() < stage); + let after = &passes[stage..]; + assert!( + after.find("settle_in_fresh_step(").unwrap() < after.find("pr::apply_checks(").unwrap() + ); + let fresh = fn_src(passes, "async fn settle_in_fresh_step("); + assert!(fresh.contains("steps::Gate::Checks")); + assert!(fresh.contains("try_auto_continue(")); + + // One lockfile regeneration per state of the branch. + assert!(implement::lockfiles_current(Some("h1"), "h1")); + assert!(!implement::lockfiles_current(Some("h1"), "h2")); + assert!(!implement::lockfiles_current(None, "h1")); + let locks = fn_src(implement, "async fn regenerate_lockfiles("); + assert!( + locks.find("lockfiles_current(").unwrap() < locks.find("run_lock_repair(").unwrap(), + "a second regeneration of the same head starts a build" + ); +} + +#[test] +fn what_stays_on_the_pull_request_names_why() { + let facts = Facts { + intent: TicketIntent::Feature, + ..Default::default() + }; + let items = vec![ + item( + "external_fact", + "", + "The partner's webhook secret format is unconfirmed: no connection reaches their sandbox.", + "", + ), + item("end_to_end", "", "No owner is named for: rotate the signing key", ""), + item("unrun_check", "plan", "The plan never ran before the PR.", ""), + ]; + let settled = settle::apply(items, &facts, &Record::default()); + assert_eq!(settled.open.len(), 3); + let section = proof::gaps_section(&settled.open); + for why in [ + "Only a person can settle this: access CoderHelm doesn't have.", + "Only a person can settle this: a product decision.", + "Only a person can settle this: a credential only a person can provide.", + ] { + assert!(section.contains(why), "{why}\n{section}"); + } +} + +use crate::passes::implement; diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 518a27d05..36b8edce2 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -23,6 +23,7 @@ mod ad_hand_back_reply; mod ae_budget_rounds; mod af_lockfiles_out_of_sync; mod ag_red_ci_ships_what_passes; +mod ah_open_items_settled; mod b_open_pr_retry; mod c_codegen_egress; mod d_echoed_markers; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 164257557..74fd0fbea 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1315,6 +1315,7 @@ pub mod security_fixes; #[cfg(test)] mod selfhost_links; mod series; +pub(crate) mod settle; pub mod setup; pub mod skill_compat; pub mod skill_suggest; @@ -6591,6 +6592,7 @@ async fn run_passes( &pr::Proof { evidence: &opening_evidence.for_pr(), gaps: &proof::gaps_section(&known_open), + settled: "", unfinished: "", manual: "", ci: &opening_evidence.ci_commands, @@ -6824,6 +6826,40 @@ async fn run_passes( // What the stop judge assumed instead of asking: an Open item a person // corrects if it's wrong. gaps.extend(stop_judge::assumptions(state, &msg.team_id, run_id).await); + // --- Settle: what CoderHelm can run itself is run, never listed --- + // A check an item waits on, the package manager's audit after a change + // to the dependencies, a check the coder's step had no time for: each + // runs in the sandbox with a full window, in a fresh step when this one + // has too little left. Only what a result didn't settle is written. + let (gaps, settled) = match settle::run( + &work, + &gaps, + triage_result.intent, + pr_result.pr_number, + &mut evidence, + usage, + has_time, + ) + .await + { + settle::Ran::Settled(s, rec) => (s.open.clone(), settle::settled_section(&s, &rec)), + settle::Ran::Again(why) => { + match settle_in_fresh_step(state, msg, run_id, &branch_name, &carry, &why, usage).await + { + Handoff::Continued => { + close_memory(state, agent_memory.take()).await; + return Ok(()); + } + Handoff::Stopped(reason) => { + warn!(run_id, reason = %reason, "Settle: the run couldn't go on in a fresh step; what is open is written as it stands"); + let (s, rec) = + settle::finish(&work, &gaps, triage_result.intent, &mut evidence).await; + (s.open.clone(), settle::settled_section(&s, &rec)) + } + } + } + }; + let items_head = work.head().await; pr::apply_checks( state, msg, @@ -6833,7 +6869,8 @@ async fn run_passes( pr_result.pr_number, &pr::Proof { evidence: &evidence.for_pr(), - gaps: &proof::gaps_section(&gaps), + gaps: &settle::stamp(&proof::gaps_section(&gaps), &items_head), + settled: &settled, unfinished: &unfinished, manual: &proof::manual_steps(&gaps), ci: &evidence.ci_commands, @@ -7076,6 +7113,33 @@ async fn hand_off_at( } } +/// The settle stage goes on in a fresh step at the checks: the checkpoint +/// names the gate, and the step's mark starts over (a step that waited for +/// a sandbox window is not one that made no progress). Never an error: a +/// run that can't continue writes its open items as they stand. +async fn settle_in_fresh_step( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + branch: &str, + carry: &steps::Carry, + why: &str, + usage: &TokenUsage, +) -> Handoff { + save_checkpoint(state, &msg.team_id, run_id, "implement", branch, 0, usage).await; + steps::save_gate( + state, + &msg.team_id, + run_id, + steps::Gate::Checks, + Some(carry), + ) + .await; + steps::save_mark(state, &msg.team_id, run_id, "", 0, 0).await; + let from = Some(("implement".to_string(), branch.to_string(), 0u8)); + try_auto_continue(state, msg, run_id, &from, &["implement"], false, why).await +} + /// A finished run's checks, again, in a fresh step of the run that resumes /// at [`steps::Gate::Checks`] on its open pull request (see `recheck`): /// the checks run on the head and the Open items are written from what they @@ -7930,6 +7994,7 @@ async fn run_repo_pipeline( &pr::Proof { evidence: &opening_evidence.for_pr(), gaps: &proof::gaps_section(&known_open), + settled: "", unfinished: "", manual: "", ci: &opening_evidence.ci_commands, @@ -8040,6 +8105,29 @@ async fn run_repo_pipeline( } }; gaps.extend(stop_judge::assumptions(state, &msg.team_id, run_id).await); + // Settle, as the single-repository path does. A run across repositories + // has no step that resumes one repository at its checks, so what needs + // a fresh step is written as it stands. + let triage_intent = repo_plan.fix.as_ref().map(|d| d.intent).unwrap_or_default(); + let (s, rec) = match settle::run( + &work, + &gaps, + triage_intent, + pr_result.pr_number, + &mut evidence, + usage, + || has_time_for_remediation(start), + ) + .await + { + settle::Ran::Settled(s, rec) => (*s, rec), + settle::Ran::Again(_) => { + let (s, rec) = settle::finish(&work, &gaps, triage_intent, &mut evidence).await; + (*s, rec) + } + }; + let (gaps, settled) = (s.open.clone(), settle::settled_section(&s, &rec)); + let items_head = work.head().await; pr::apply_checks( state, msg, @@ -8049,7 +8137,8 @@ async fn run_repo_pipeline( pr_result.pr_number, &pr::Proof { evidence: &evidence.for_pr(), - gaps: &proof::gaps_section(&gaps), + gaps: &settle::stamp(&proof::gaps_section(&gaps), &items_head), + settled: &settled, unfinished: &unfinished, manual: &proof::manual_steps(&gaps), ci: &evidence.ci_commands, diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index e7d20c639..366fffdbd 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -34,6 +34,9 @@ pub struct Proof<'a> { /// the description (`proof::unfinished_section`); empty when none. pub unfinished: &'a str, pub manual: &'a str, + /// What the settle stage ran in the sandbox, with each result + /// (`settle::settled_section`); empty when it ran nothing. + pub settled: &'a str, pub ci: &'a [CiCommand], pub mirrors: &'a [super::completeness::Mirror], /// For a run started from a log finding: what its evidence step found. @@ -1686,6 +1689,7 @@ fn owned_sections(plan: &PlanResult, proof: &Proof<'_>, repo: &str) -> super::co }, ), review_fixes: String::new(), + settled: proof.settled.to_string(), open_findings: String::new(), objections: String::new(), draft_status: String::new(), @@ -2171,6 +2175,7 @@ mod check_results_tests { Proof { evidence: "", gaps, + settled: "", unfinished: "", manual, ci: &[], @@ -2392,6 +2397,7 @@ mod refresh_tests { let proof = super::Proof { evidence: "", gaps: &gaps, + settled: "", unfinished: "", manual: "", ci: &[], diff --git a/services/worker/src/passes/proof.rs b/services/worker/src/passes/proof.rs index 3e14b2adb..4d8024cf2 100644 --- a/services/worker/src/passes/proof.rs +++ b/services/worker/src/passes/proof.rs @@ -151,6 +151,10 @@ pub struct RunEvidence { /// The diff changes stored data (see `feature::data_rules::touches_data`), /// read from it when the change is judged. pub data_change: bool, + /// What the package manager's audit came to on this head, one line per + /// lockfile, as the settle stage recorded it (`settle::Record`). Empty + /// when none ran. + pub audits: Vec, } /// What the sandbox came to on the run's last check: the kinds of check it @@ -161,6 +165,10 @@ pub struct SandboxRecord { pub passed: Vec, /// Why the last attempt gave no result (the build's status and phases). pub failure: Option, + /// The coder asked for a check and none started, because its step had + /// too little time left for a sandbox build. The check is owed: the + /// settle stage runs it in a step with a full window (`settle`). + pub refused_for_time: bool, } impl SandboxRecord { @@ -249,6 +257,9 @@ impl RunEvidence { self.environments = later.environments; } self.data_change |= later.data_change; + if !later.audits.is_empty() { + self.audits = later.audits; + } let notes = later.notes.trim(); if !notes.is_empty() { if self.notes.trim().is_empty() { @@ -302,16 +313,20 @@ impl RunEvidence { let sources: Vec<&str> = self.sources.iter().map(String::as_str).collect(); let lookups: Vec<&str> = self.lookups.iter().map(|l| l.line.as_str()).collect(); let checks: Vec<&str> = self.checks.iter().map(String::as_str).collect(); + let audits: Vec = self.audits.iter().map(|a| format!("- {a}")).collect(); + let audits: Vec<&str> = audits.iter().map(String::as_str).collect(); format!( "## Data sources this team connected for this repository\n{}\n\ ## Lookups the run made, and what came back\n{}\n\ ## Checks run in the sandbox before the PR opened (recorded by CoderHelm, not the coder)\n{}\n\ + ## Dependency audit run in the sandbox on this head (recorded by CoderHelm, not the coder)\n{}\n\ ## Checks the repository's CI runs on this pull request\n{}\n\n\ ## Environments the diff changes (read from its file paths)\n{}\n\n\ ## The coder's evidence notes (they become the PR description's evidence)\n{}\n", list(&sources, "(none connected)"), list(&lookups, "(no lookups were made)"), list(&checks, "(no sandbox checks ran)"), + list(&audits, "(no audit ran)"), self.ci_for_judge(), match self.environments.as_slice() { [] => "(none)".to_string(), @@ -374,6 +389,11 @@ pub struct Finding { /// [`classify`]; never read from the judge. #[serde(skip)] pub ci_cmd: String, + /// Why the item is still open after the settle stage, set only by it + /// (`settle::apply`): the reason only a person can settle it, or what + /// CoderHelm ran and what came back. Never read from the judge. + #[serde(skip)] + pub needs: String, } /// What settles a finding. @@ -467,7 +487,11 @@ impl Finding { (Settler::Ci, _) => " Settles when this PR's CI passes.".to_string(), _ => String::new(), }; - format!("- **{}:** {what}{settle}", self.label()) + let needs = match self.needs.trim() { + "" => String::new(), + n => format!(" {}.", n.trim_end_matches('.')), + }; + format!("- **{}:** {what}{settle}{needs}", self.label()) } } @@ -659,7 +683,10 @@ pub const JUDGE_SYSTEM: &str = "You check a code change before its pull request at DEBUG.\n\ 4. assumption: a miss when the change rests on an assumption (what another system sends, \ what values a field takes, uniqueness, ordering) that nothing in the lookups or the code \ - proves.\n\ + proves. That the repository's own code still builds, type-checks or passes its tests (after \ + a version bump, an override, a refactor), or that a document's claim about those checks is \ + true, is never this point: a sandbox check listed as PASS proves it, and when none ran it \ + is ci_pending (point 11) with the check's kind.\n\ 5. structured_field: a miss when the change reads another system's data by parsing a name, \ title or description (a regex, a pattern, a substring) while the payload has a structured \ field or flag (a boolean, a type, a quantity, an id) that says the same thing, or when it \ @@ -691,7 +718,10 @@ pub const JUDGE_SYSTEM: &str = "You check a code change before its pull request command it runs, with an id like C1), its result settles it, so it is not a proof gap. Set \ `check` to the kind, `command` to the command the check needs (e.g. `terraform fmt -check`), \ and `ci` to the id of the CI command that runs it, or empty when CI runs none. A check the \ - sandbox list shows as PASS is not a finding.\n\ + sandbox list shows as PASS is not a finding. The package manager's audit of the \ + dependencies is the `security` kind: advisory counts the dependency audit section gives \ + are proven, and counts nobody ran an audit for are ci_pending with `check` \"security\", \ + never an external_fact.\n\ 12. manual_check: something only a person can verify (in a real browser, on a device, a \ manual click-through). Never a gap; it becomes a numbered step in the PR's Verification \ section. Never a command the CI list shows: running that is CI's job, so it is ci_pending \ @@ -2956,6 +2986,7 @@ mod tests { ran: vec![CheckKind::Typecheck, CheckKind::Tests], passed: vec![CheckKind::Typecheck, CheckKind::Tests], failure: None, + refused_for_time: false, }; let kinds: Vec = recorded_gaps(&passed) .into_iter() diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 6fb208aad..496e04bb9 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -6316,6 +6316,73 @@ async fn revert_dep_commit( Some(note) } +/// The same revert for a check CoderHelm ran itself in its sandbox before +/// the run finished (`settle`): the newest verified set of bumps comes out +/// with `why`, the sets before it stay, and the pull request names each +/// bump under "Deferred". `None` when the run isn't a dependency fix, or +/// one set or none is left. +pub(crate) async fn take_out_dep_set( + state: &WorkerState, + ticket_msg: &TicketMessage, + run_id: &str, + github: &GitHubClient, + branch: &str, + pr_number: u64, + why: &str, +) -> Option { + if !common::security_fixes::is_ticket(&ticket_msg.ticket_id) { + return None; + } + let mut run = super::dep_fix::load(state, ticket_msg, run_id).await?; + let out = run.take_out_last_commit(why)?; + let (owner, repo) = (&ticket_msg.repo_owner, &ticket_msg.repo_name); + let changed = github + .compare_changed_files(owner, repo, &out.restore_to, branch) + .await + .ok()?; + let mut files = Vec::new(); + for path in &changed { + let was = github + .read_file_if_exists(owner, repo, path, &out.restore_to) + .await + .ok()?; + files.push((path.clone(), was)); + } + let note = settle_revert_note(&out.lines, run.commits.len()); + let msg = ResumeMessage { + team_id: ticket_msg.team_id.clone(), + run_id: run_id.to_string(), + installation_id: ticket_msg.installation_id, + ..Default::default() + }; + let pr = PrRef { + owner, + repo, + branch, + number: pr_number, + url: "", + }; + apply_revert(state, &msg, github, &pr, files, ¬e).await?; + super::dep_fix::save(state, ticket_msg, run_id, &run).await; + super::dep_fix::settle(state, ticket_msg, &run).await; + Some(note) +} + +/// The pull request's "Deferred" line for a set of bumps a sandbox check +/// took out. +pub(crate) fn settle_revert_note(lines: &[String], commits_left: usize) -> String { + format!( + "The repository's checks failed in CoderHelm's sandbox with the newest verified set \ + applied: took out that set of {} bump{} and kept the {} set{} before it. {}. The checks \ + run again on what is left.", + lines.len(), + if lines.len() == 1 { "" } else { "s" }, + commits_left, + if commits_left == 1 { "" } else { "s" }, + lines.join("; ") + ) +} + /// The pull request's "Deferred" line for a commit of bumps CI took out. pub(crate) fn dep_revert_note(lines: &[String], commits_left: usize) -> String { format!( @@ -6648,6 +6715,109 @@ async fn redrive_red_ci( Ok(true) } +/// A run about to be completed whose pull request lists Open items written +/// on an earlier head goes back to its checks in a fresh step +/// (`settle::redrive_due`): the items are derived again from the head as it +/// is, what CoderHelm can run is run, and the run finishes from there. +/// Once per head and at most `settle::MAX_REDRIVES` times a run. False when +/// there is nothing stale, or the step couldn't be queued (the run then +/// finishes as it stands). +async fn redrive_stale_items( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + pr_number: u64, + branch: &str, +) -> bool { + let Ok(github) = GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + msg.installation_id, + &state.http, + ) else { + return false; + }; + let Ok(pr) = github + .get_pull_request(&msg.repo_owner, &msg.repo_name, pr_number) + .await + else { + return false; + }; + let body = pr["body"].as_str().unwrap_or(""); + let head = pr["head"]["sha"].as_str().unwrap_or(""); + let redrives = run_number(state, &msg.team_id, run_id, "items_redrives").await; + let last = run_text(state, &msg.team_id, run_id, "items_redrive_head").await; + if !super::settle::redrive_due(body, head, redrives, &last) { + return false; + } + add_run_number(state, &msg.team_id, run_id, "items_redrives").await; + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET items_redrive_head = :h") + .expression_attribute_values(":h", attr_s(head)) + .send() + .await; + // The step after the run's last one, from its record (the message in + // hand may be a resume's, which carries no step number). + let item = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("run_id", attr_s(run_id)) + .consistent_read(true) + .send() + .await + .ok() + .and_then(|o| o.item) + .unwrap_or_default(); + let Some((ticket, _)) = super::recheck::message_of(&item) else { + return false; + }; + let why = "The pull request's open items were written before its last changes"; + match super::recheck_at_checks( + state, + &ticket, + run_id, + branch, + super::recheck::carry_of(body).as_ref(), + why, + ) + .await + { + super::Handoff::Continued => { + info!(run_id, pr_number, %head, "Open items are of an earlier head: deriving them again before the run finishes"); + true + } + super::Handoff::Stopped(reason) => { + warn!(run_id, pr_number, reason = %reason, "Could not derive the open items again: the run finishes as it stands"); + false + } + } +} + +/// A text kept on the run record (empty when absent). +async fn run_text(state: &WorkerState, team_id: &str, run_id: &str, field: &str) -> String { + state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("#f") + .expression_attribute_names("#f", field) + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| i.get(field).and_then(|v| v.as_s().ok()).cloned()) + .unwrap_or_default() +} + /// Whether a run with red checks goes back to its CI fix round instead of /// ending: once per run, while fix cycles are left. pub(crate) fn may_redrive_red_ci(redrives: u32, cycle: usize) -> bool { @@ -6669,6 +6839,15 @@ async fn complete_run_with_status( duration: u64, ) -> Result<(), Box> { debug_assert_ne!(status, "needs_input", "use wait_for_review"); + // Open items written on an earlier head are not this run's last word: a + // later round may have settled one. The run goes back to its checks on + // the head first, and finishes from there. + if status == common::run_status::COMPLETED + && pr_number > 0 + && redrive_stale_items(state, msg, run_id, pr_number, branch).await + { + return Ok(()); + } // The one outcome rule (`outcome::decide`): a run whose pull request's CI // is red, by its own record, is never completed. It waits on a person, // with why, on every path that would have said "completed". diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index df23c2193..9d1d1d502 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -1052,6 +1052,10 @@ pub struct Ledger { /// kept. #[serde(default)] pub checks_version: String, + /// What the settle stage ran for the run's open items, and what it came + /// to (`settle::Record`). + #[serde(default)] + pub settle: super::settle::Record, } /// A record larger than this drops its longest text: DynamoDB's item limit is diff --git a/services/worker/src/passes/settle.rs b/services/worker/src/passes/settle.rs new file mode 100644 index 000000000..1c23eccc5 --- /dev/null +++ b/services/worker/src/passes/settle.rs @@ -0,0 +1,1630 @@ +//! A run settles its own open items before it finishes. +//! +//! A dependency update finished "completed" with five Open items on its pull +//! request. Two said the same thing: the package manager's audit never ran, +//! so the advisory counts were unknown. One asked for the build and test +//! results of the packages an override touched. One quoted a README line +//! that a later round had already rewritten. One asked for an end-to-end +//! checklist on a change with nothing to deploy. Every one of them was +//! CoderHelm's to run or to drop; none needed anything only a person has. +//! The full build had been refused twice in the coder's step for lack of +//! time, and nothing carried it anywhere. +//! +//! The rules: +//! +//! - Every open item is classified ([`classify`]): CoderHelm runs it in its +//! sandbox (a check of the repository's own, the package manager's audit), +//! the repository's CI settles it, it does not apply to this run, only a +//! person has what it needs (a reason on `common::handback`), or it is +//! CoderHelm's own work left (a fix round's, a deferral's). +//! - What CoderHelm can run, it runs, in a step with a full sandbox window: +//! when this step has too little time left, the run goes on in a fresh +//! step at the checks and takes it from there ([`next`]). The real output +//! is the proof. A passing result closes the item and is quoted on the +//! pull request; a failing one is acted on: a dependency fix takes out its +//! newest verified set of bumps and defers them with the cause, any other +//! run gets a fix round with the failing output. +//! - A change to the dependencies is always audited by its package manager +//! after the bumps (`common::dep_audit`), whether an item asked or not, +//! and the counts left are quoted on the pull request. +//! - A check the coder's step was refused for lack of time is owed: it runs +//! here whether or not anything listed it. +//! - An item that does not apply to the run is never raised, and items that +//! name the same missing fact are one item ([`dedup`]). +//! - Open items are derived again whenever the head moves. Each line names +//! the head it was written on ([`stamp`]); a run about to finish with +//! lines written on an earlier head checks again first ([`stale`]). +//! - What stays on the pull request says why: an item only a person can +//! settle names the reason, and an item CoderHelm ran and could not +//! settle names what it ran and what came back. + +use serde::{Deserialize, Serialize}; +use tracing::{info, warn}; + +use common::dep_audit; +use common::handback::{human_only_in, HumanOnly}; + +use super::checks::{CheckKind, Step}; +use super::proof::{self, Finding, RunEvidence, SandboxRecord}; +use super::triage::TicketIntent; +use crate::models::TokenUsage; + +/// Fix rounds a failing settle check gets in one run. +pub const MAX_FIX_ROUNDS: u32 = 2; +/// Fresh steps one run takes to find a full sandbox window. +pub const MAX_STEPS: u32 = 4; +/// Times a run about to finish goes back to derive its open items again. +pub const MAX_REDRIVES: u32 = 3; + +// ── Classifying ───────────────────────────────────────────────────────── + +/// Something CoderHelm runs in its sandbox. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Action { + /// A check of the repository's own, by kind. + Check(CheckKind), + /// The package manager's audit of the lockfiles the change touches. + Audit, +} + +/// What settles an open item. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Class { + /// CoderHelm runs these and reads the result. + Run(Vec), + /// The repository's CI runs it on the pull request. + Ci, + /// It does not apply to this run: never raised. + NotApplicable(&'static str), + /// Only a person has what it needs. + Human(HumanOnly), + /// CoderHelm's own work left: a fix round's gap, a check the change did + /// not pass, a security item, a deferral with its reason. + Own, +} + +/// What a run is, for classifying its items. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Facts { + pub intent: TicketIntent, + /// The plan was written by rules (a dependency fix run): no planner + /// chose where the fix goes or what else production needs. + pub planned_by_rules: bool, + /// The change touches a lockfile or a manifest one reads. + pub dep_change: bool, + /// The coder's step was refused a check for lack of time. + pub checks_owed: bool, +} + +impl Facts { + /// Upkeep with no new behaviour: nothing to take to production beyond + /// the pull request itself. + fn upkeep(&self) -> bool { + self.intent == TicketIntent::Chore || self.planned_by_rules + } +} + +/// Words that say a check has no result yet. +const NOT_RUN: &[&str] = &[ + "no check", + "never ran", + "not run", + "did not run", + "didn't run", + "hasn't run", + "has not run", + "have not run", + "haven't run", + "nothing shows", + "no result", +]; + +/// The repository's own checks a sentence names, by word. Format, plan and +/// security are left out: as words they mean other things. +fn check_words(text: &str) -> Vec { + let mut kinds = Vec::new(); + let words: Vec = text + .split(|c: char| !c.is_alphanumeric() && c != '-') + .filter(|w| !w.is_empty()) + .map(str::to_lowercase) + .collect(); + for (i, w) in words.iter().enumerate() { + let kind = match w.as_str() { + "build" | "builds" | "compile" | "compiles" => Some(CheckKind::Build), + "tests" | "test" => Some(CheckKind::Tests), + "lint" | "linter" => Some(CheckKind::Lint), + "typecheck" | "type-check" | "typechecks" => Some(CheckKind::Typecheck), + "type" if words.get(i + 1).is_some_and(|n| n.starts_with("check")) => { + Some(CheckKind::Typecheck) + } + _ => None, + }; + if let Some(k) = kind { + if !kinds.contains(&k) { + kinds.push(k); + } + } + } + kinds +} + +/// Whether a sentence asks for the package manager's audit result: it names +/// an audit or advisories, and a count or a severity of them. +pub fn names_audit(text: &str) -> bool { + let t = text.to_lowercase(); + if t.contains("audit log") || t.contains("audit trail") { + return false; + } + let any = |marks: &[&str]| marks.iter().any(|m| t.contains(m)); + any(&["audit", "advisor", "vulnerabilit"]) + && any(&[ + "count", + "critical", + "high", + "severity", + "remaining", + "how many", + "never ran", + "not run", + ]) +} + +fn text_of(f: &Finding) -> String { + format!("{} {}", f.detail, f.settle) +} + +/// What settles `f` in a run with these facts. +pub fn classify(f: &Finding, facts: &Facts) -> Class { + let point = f.point.trim(); + let text = text_of(f); + match point { + "ci_pending" => return Class::Ci, + "manual_check" => return Class::Human(HumanOnly::PersonAction), + "check_blocked" | "rule_failing" | "security" | "security_unchecked" | "optional_task" + | "planned_work" => return Class::Own, + // A step outside the pull request the plan names without an owner + // is the team's to assign. A checklist nobody wrote, or a step the + // judge thinks is missing, says nothing for upkeep. + "end_to_end" => { + return if facts.upkeep() && !f.detail.starts_with("No owner is named for:") { + Class::NotApplicable( + "upkeep with no new behaviour has nothing to take to production beyond its \ + pull request", + ) + } else { + Class::Human(HumanOnly::ProductDecision) + }; + } + p if p == proof::JUDGE_ASSUMPTION => { + return Class::Human(human_only_in(&text).unwrap_or(HumanOnly::ProductDecision)); + } + _ => {} + } + let kind = CheckKind::parse(&f.check); + if kind == Some(CheckKind::Security) || names_audit(&text) { + return if facts.dep_change { + Class::Run(vec![Action::Audit]) + } else { + Class::Own + }; + } + if point == "unrun_check" { + return match kind { + // A plan or preview needs credentials the sandbox never has. + Some(CheckKind::Plan) => Class::Human(HumanOnly::Credential), + Some(k) => Class::Run(vec![Action::Check(k)]), + None => Class::Own, + }; + } + if let Some(why) = human_only_in(&text) { + return Class::Human(why); + } + // A gap whose own words say the repository's checks settle it. + if matches!(point, "assumption" | "external_fact" | "team_rule") { + let mut kinds = check_words(&f.settle); + let lower = f.detail.to_lowercase(); + if NOT_RUN.iter().any(|m| lower.contains(m)) { + for k in check_words(&f.detail) { + if !kinds.contains(&k) { + kinds.push(k); + } + } + } + if !kinds.is_empty() { + kinds.sort(); + return Class::Run(kinds.into_iter().map(Action::Check).collect()); + } + } + Class::Own +} + +/// The words of a sentence worth comparing: lowercase, longer than three +/// letters, without the ones every item shares. +fn content_words(text: &str) -> Vec { + const COMMON: &[&str] = &[ + "that", "this", "with", "from", "because", "there", "their", "which", "never", "nothing", + "unknown", "have", "been", "were", "what", "when", "into", "them", "they", "does", + ]; + let mut out: Vec = text + .split(|c: char| !c.is_alphanumeric()) + .map(str::to_lowercase) + .filter(|w| w.len() > 3 && !COMMON.contains(&w.as_str())) + .collect(); + out.sort(); + out.dedup(); + out +} + +/// Whether two items name the same missing fact: the same finding, the +/// audit, the same check that did not run, or sentences that share most of +/// their words. +fn same_fact(a: &(Finding, Class), b: &(Finding, Class)) -> bool { + if a.0 == b.0 { + return true; + } + let audit = |c: &Class| matches!(c, Class::Run(r) if r.as_slice() == [Action::Audit]); + if audit(&a.1) && audit(&b.1) { + return true; + } + let unrun = |x: &(Finding, Class)| { + matches!(x.0.point.trim(), "unrun_check" | "ci_pending") + .then(|| CheckKind::parse(&x.0.check)) + .flatten() + }; + if let (Some(x), Some(y)) = (unrun(a), unrun(b)) { + return x == y; + } + if a.0.point.trim() != b.0.point.trim() { + return false; + } + let (x, y) = (content_words(&a.0.detail), content_words(&b.0.detail)); + if x.len() < 3 || y.len() < 3 { + return false; + } + let shared = x.iter().filter(|w| y.contains(w)).count(); + shared * 10 >= x.len().min(y.len()) * 8 +} + +/// The items with each missing fact named once: the first one that names +/// it stays. +pub fn dedup(items: Vec<(Finding, Class)>) -> Vec<(Finding, Class)> { + let mut out: Vec<(Finding, Class)> = Vec::new(); + for item in items { + if !out.iter().any(|kept| same_fact(kept, &item)) { + out.push(item); + } + } + out +} + +// ── What ran, kept across steps ───────────────────────────────────────── + +/// What the settle stage ran and came to, for the whole run. The results +/// are of one head; the counts are the run's. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Record { + /// The head the results below are of. + pub head: String, + /// Each check step's result line (`checks::result_line`). + pub checks: Vec, + /// The kinds of check that reported, and those that passed, by name. + pub ran: Vec, + pub passed: Vec, + /// The end of the output of a run with a failing check. + pub failing: String, + /// The checks ran on this head (whatever they came to). + pub checked: bool, + /// Why the sandbox gave no result for the checks, when it gave none. + pub no_result: String, + /// Each lockfile's audit line, as the pull request quotes it. + pub audits: Vec, + /// The audit ran on this head and every lockfile reported. + pub audited: bool, + /// Why the audit gave no counts, when it gave none. + pub audit_failed: String, + /// Fix rounds taken on a failing check. + pub rounds: u32, + /// Sets of bumps taken out on a failing check. + pub reverts: u32, + /// Fresh steps taken for a sandbox window. + pub steps: u32, +} + +impl Record { + /// The results are of `head`: another head's are set aside. The run's + /// counts stay. + pub fn for_head(&mut self, head: &str) { + if self.head == head { + return; + } + *self = Record { + head: head.to_string(), + rounds: self.rounds, + reverts: self.reverts, + steps: self.steps, + ..Default::default() + }; + } + + fn passed(&self, k: CheckKind) -> bool { + self.passed.iter().any(|p| p == k.name()) + } + + fn ran(&self, k: CheckKind) -> bool { + self.ran.iter().any(|p| p == k.name()) + } + + /// The kinds that ran and failed, lint and format aside: those are + /// reported, and never hold a run (`checks::Step::advisory`). + fn failed(&self) -> Vec { + [CheckKind::Build, CheckKind::Typecheck, CheckKind::Tests] + .into_iter() + .filter(|k| self.ran(*k) && !self.passed(*k)) + .collect() + } + + /// A check run's steps and exit codes, recorded. + pub fn record_checks(&mut self, steps: &[Step], codes: &[Option], output: &str) { + let rec = SandboxRecord::from_steps(steps, codes); + self.checks = steps + .iter() + .zip(codes) + .map(|(s, c)| super::checks::result_line(s, *c)) + .collect(); + self.ran = rec.ran.iter().map(|k| k.name().to_string()).collect(); + self.passed = rec.passed.iter().map(|k| k.name().to_string()).collect(); + self.checked = true; + self.no_result.clear(); + self.failing = if self.failed().is_empty() { + String::new() + } else { + common::tail_str(output.trim(), 3000).to_string() + }; + } + + /// An audit run's results, recorded. + pub fn record_audits(&mut self, read: &[dep_audit::Audited]) { + self.audits = read.iter().map(dep_audit::Audited::line).collect(); + self.audited = !read.is_empty() && read.iter().all(dep_audit::Audited::ran); + self.audit_failed = if self.audited { + String::new() + } else { + read.iter() + .filter(|a| !a.ran()) + .map(dep_audit::Audited::line) + .collect::>() + .join("; ") + }; + } + + /// The record as the sandbox's own for the proof check and the pull + /// request: the latest check run is what the branch stands on. + pub fn write_evidence(&self, evidence: &mut RunEvidence) { + if self.checked { + evidence.checks = self.checks.clone(); + let kinds = |names: &[String]| -> Vec { + names.iter().filter_map(|n| CheckKind::parse(n)).collect() + }; + evidence.sandbox = SandboxRecord { + ran: kinds(&self.ran), + passed: kinds(&self.passed), + failure: None, + refused_for_time: false, + }; + } + evidence.audits = self.audits.clone(); + } +} + +// ── Deciding ──────────────────────────────────────────────────────────── + +/// What the settle stage runs for a run's items. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Plan { + /// The repository's checks run (all of its steps: one build). + pub checks: bool, + /// The kinds the items ask for. + pub kinds: Vec, + pub audit: bool, +} + +/// What to run for `items`: the checks when an item names one or the coder +/// was refused one, the audit when an item names it or the change touches +/// the dependencies. +pub fn plan(items: &[Finding], facts: &Facts) -> Plan { + let mut p = Plan { + checks: facts.checks_owed, + audit: facts.dep_change, + ..Default::default() + }; + for f in items { + if let Class::Run(actions) = classify(f, facts) { + for a in actions { + match a { + Action::Audit => p.audit = true, + Action::Check(k) => { + p.checks = true; + if !p.kinds.contains(&k) { + p.kinds.push(k); + } + } + } + } + } + } + p +} + +/// What the stage does next. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Next { + /// Run what is planned and has no result on this head. + Build, + /// A check fails and the run is a dependency fix with a set to spare: + /// take out its newest verified set of bumps. + TakeOutSet, + /// A check fails: one fix round with the failing output. + FixRound, + /// This step has too little time left: go on in a fresh one. + FreshStep(&'static str), + /// Nothing more to run: write what is left. + Done, +} + +/// What the step can still do. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Room { + /// A sandbox build fits before the step's deadline. + pub build: bool, + /// A fix round fits. + pub round: bool, + /// A sandbox exists, and has not given up on this run. + pub sandbox: bool, + /// Verified sets of bumps on the branch (a dependency fix run's). + pub dep_sets: usize, +} + +/// Decides the next move from what is planned, what ran and what the step +/// has room for. A check that needs a sandbox build this step has no time +/// for is carried into a fresh step, never left unverified; only a run that +/// has spent its steps writes it down as not run. +pub fn next(plan: &Plan, rec: &Record, room: &Room) -> Next { + let wants_checks = plan.checks && !rec.checked && rec.no_result.is_empty(); + let wants_audit = plan.audit && !rec.audited && rec.audit_failed.is_empty(); + if (wants_checks || wants_audit) && room.sandbox { + return if room.build { + Next::Build + } else if rec.steps < MAX_STEPS { + Next::FreshStep("Settling the open items needs a sandbox build with a full time window") + } else { + Next::Done + }; + } + if plan.checks && rec.checked && !rec.failed().is_empty() { + if room.dep_sets >= 2 { + return Next::TakeOutSet; + } + if rec.rounds < MAX_FIX_ROUNDS { + return if room.round { + Next::FixRound + } else if rec.steps < MAX_STEPS { + Next::FreshStep("Fixing the failing check needs more time than this step has left") + } else { + Next::Done + }; + } + } + Next::Done +} + +/// What the stage came to for the pull request. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Settled { + /// What stays under Open items, each saying why. + pub open: Vec, + /// Items a result closed, each with the result that closed it. + pub closed: Vec<(Finding, String)>, + /// Items that do not apply to this run, each with why. + pub dropped: Vec<(Finding, &'static str)>, +} + +/// The result that closes an item CoderHelm ran, when every action it +/// needs has one; else why it stays open. +fn result_of(actions: &[Action], rec: &Record) -> Result { + let mut proof = Vec::new(); + for a in actions { + match a { + Action::Audit if rec.audited => proof.push(rec.audits.join("; ")), + Action::Audit if !rec.audit_failed.is_empty() => { + return Err(format!("CoderHelm ran the audit: {}", rec.audit_failed)) + } + Action::Audit => { + return Err( + "CoderHelm had no step with a full sandbox window left to run the audit".into(), + ) + } + Action::Check(k) if rec.passed(*k) => { + let line = rec + .checks + .iter() + .find(|l| l.contains(k.name())) + .cloned() + .unwrap_or_else(|| format!("- {}: PASS", k.name())); + proof.push(line.trim_start_matches("- ").to_string()); + } + Action::Check(k) if rec.ran(*k) => { + return Err(format!( + "CoderHelm ran {} in its sandbox and it fails; its fix rounds did not turn it \ + green", + k.name() + )) + } + Action::Check(k) if rec.checked => { + return Err(format!( + "CoderHelm ran the repository's checks in its sandbox and they have no {} step", + k.name() + )) + } + Action::Check(_) if !rec.no_result.is_empty() => { + return Err(format!( + "CoderHelm's sandbox gave no result: {}", + rec.no_result + )) + } + Action::Check(k) => { + return Err(format!( + "CoderHelm had no step with a full sandbox window left to run {}", + k.name() + )) + } + } + } + proof.dedup(); + Ok(proof.join("; ")) +} + +/// The items as they go on the pull request: what does not apply is +/// dropped, what a result settled is closed with that result, the same +/// missing fact is named once, and what stays says why. +pub fn apply(items: Vec, facts: &Facts, rec: &Record) -> Settled { + let mut out = Settled::default(); + let classed: Vec<(Finding, Class)> = items + .into_iter() + .map(|f| { + let c = classify(&f, facts); + (f, c) + }) + .collect(); + for (mut f, class) in dedup(classed) { + match class { + Class::NotApplicable(why) => out.dropped.push((f, why)), + Class::Run(actions) => match result_of(&actions, rec) { + Ok(proof) => out.closed.push((f, proof)), + Err(why) => { + f.needs = why; + out.open.push(f); + } + }, + Class::Human(why) => { + f.needs = format!("Only a person can settle this: {}", why.label()); + out.open.push(f); + } + // A check a passing sandbox run already answers needs no CI. + Class::Ci + if CheckKind::parse(&f.check).is_some_and(|k| { + rec.passed(k) || (k == CheckKind::Security && rec.audited) + }) => + { + let k = CheckKind::parse(&f.check).unwrap_or(CheckKind::Build); + let action = if k == CheckKind::Security { + Action::Audit + } else { + Action::Check(k) + }; + let proof = result_of(&[action], rec).unwrap_or_default(); + out.closed.push((f, proof)); + } + Class::Ci | Class::Own => out.open.push(f), + } + } + out +} + +/// What the stage settled, for the pull request: each result quoted once. +/// Empty when it ran nothing. +pub fn settled_section(settled: &Settled, rec: &Record) -> String { + let mut lines: Vec = Vec::new(); + if rec.checked { + lines.extend(rec.checks.iter().cloned()); + } + lines.extend(rec.audits.iter().map(|a| format!("- {a}"))); + if lines.is_empty() { + return String::new(); + } + let closed = settled.closed.len(); + let commit: String = rec.head.chars().take(7).collect(); + let lead = if closed == 0 { + format!("CoderHelm ran these in its sandbox on commit `{commit}`:") + } else { + format!( + "CoderHelm ran these in its sandbox on commit `{commit}`; they settle {closed} \ + item{} that would have been open:", + if closed == 1 { "" } else { "s" } + ) + }; + format!( + "{SETTLED_START}\n## Checked by CoderHelm\n{lead}\n{}\n{SETTLED_END}", + lines.join("\n") + ) +} + +pub const SETTLED_START: &str = ""; +pub const SETTLED_END: &str = ""; + +// ── Derived again when the head moves ─────────────────────────────────── + +const ON_HEAD_START: &str = ""; + +fn is_item(line: &str) -> bool { + let l = line.trim_start_matches('>').trim_start(); + l.starts_with("- ") || l.starts_with("* ") +} + +/// The Open items section with each item naming the head it was written on. +pub fn stamp(section: &str, head: &str) -> String { + if head.is_empty() { + return section.to_string(); + } + section + .lines() + .map(|l| { + if is_item(l) && !l.contains(ON_HEAD_START) { + format!("{l} {ON_HEAD_START}{head}{ON_HEAD_END}") + } else { + l.to_string() + } + }) + .collect::>() + .join("\n") +} + +/// The head an item line was written on. +fn head_of(line: &str) -> Option<&str> { + let at = line.find(ON_HEAD_START)? + ON_HEAD_START.len(); + let rest = &line[at..]; + Some(rest[..rest.find(ON_HEAD_END)?].trim()).filter(|h| !h.is_empty()) +} + +/// Whether the description's Open items were written on a head other than +/// `head`: a later round may have settled one, so they are derived again. +/// Items written before lines carried a head are left as they are. +pub fn stale(body: &str, head: &str) -> bool { + if head.is_empty() { + return false; + } + let (owned, _) = super::completeness::take_owned(body); + owned + .open_items + .lines() + .filter(|l| is_item(l)) + .filter_map(head_of) + .any(|h| h != head) +} + +/// Whether a run about to finish goes back to its checks first: its open +/// items are of another head, and it has gone back fewer than +/// [`MAX_REDRIVES`] times and not for this head. +pub fn redrive_due(body: &str, head: &str, redrives: u32, last_head: &str) -> bool { + redrives < MAX_REDRIVES && last_head != head && stale(body, head) +} + +// ── Running ───────────────────────────────────────────────────────────── + +/// How the stage ended in this step. +pub enum Ran { + /// Settled: what goes on the pull request. + Settled(Box, Record), + /// The run goes on in a fresh step at the checks, with why. + Again(String), +} + +/// The feedback of a fix round on a failing settle check. +pub fn fix_feedback(rec: &Record, asked: &[Finding]) -> String { + let failed: Vec<&str> = rec.failed().iter().map(|k| k.name()).collect(); + let items: Vec = asked + .iter() + .map(|f| format!("- {}", f.detail.trim())) + .collect(); + format!( + "Before the run finishes, CoderHelm ran the repository's checks in its sandbox on this \ + branch and {} failed. Fix the cause in the code or the manifests (never by weakening a \ + check), then call run_checks. The results:\n{}\n\nThe end of the output:\n```\n{}\n```{}", + failed.join(", "), + rec.checks.join("\n"), + rec.failing.trim(), + if items.is_empty() { + String::new() + } else { + format!( + "\n\nThese open items wait on that result; make what they say true, or correct \ + the text they quote from the real results:\n{}", + items.join("\n") + ) + } + ) +} + +/// The facts of the run on `w`'s branch: what its change touches, read from +/// the tree and the diff's paths. +pub async fn facts( + w: &proof::Work<'_>, + intent: TicketIntent, + evidence: &RunEvidence, +) -> (Facts, Vec) { + // A dependency fix run's plan is written by rules. + let planned_by_rules = common::security_fixes::is_ticket(&w.msg.ticket_id) + && super::dep_fix::load(w.state, w.msg, w.run_id) + .await + .is_some(); + let (owner, name) = (&w.msg.repo_owner, &w.msg.repo_name); + let tree: Vec = match w.github.get_tree(owner, name, w.branch).await { + Ok(t) => t + .into_iter() + .filter(|e| e.entry_type == "blob") + .map(|e| e.path) + .collect(), + Err(_) => Vec::new(), + }; + let changed = + super::plan_coverage::changed_files(w.github, owner, name, &w.msg.base_branch, w.branch) + .await + .unwrap_or_default(); + let audits = dep_audit::audits_for(&tree, &changed); + ( + Facts { + intent, + planned_by_rules, + dep_change: !audits.is_empty(), + checks_owed: evidence.sandbox.refused_for_time, + }, + audits, + ) +} + +fn sandbox<'a>(w: &proof::Work<'a>) -> crate::clients::sandbox::SandboxClient<'a> { + crate::clients::sandbox::SandboxClient::new( + &w.state.codebuild, + &w.state.s3, + &w.state.logs, + &w.state.config.sandbox_bucket_name, + &w.state.config.sandbox_project_name, + ) +} + +/// The steps the agent permissions let run, in order. +async fn permitted(w: &proof::Work<'_>, steps: Vec) -> Vec { + let gate = crate::agent::policy::gate( + w.state, + w.provider.scope.ctx(common::agent_policy::Agent::Coder), + w.deadline, + ); + let mut kept = Vec::new(); + for s in steps { + if let common::agent_policy::Outcome::Run { .. } = gate + .check_command(&s.cmd, "Run the repository's checks") + .await + { + kept.push(s); + } + } + kept +} + +/// Runs what the plan still lacks on `head`, in the sandbox, and records +/// it. Every path records something, so the stage never asks for the same +/// build twice. +async fn build( + w: &proof::Work<'_>, + plan: &Plan, + audits: &[dep_audit::Audit], + head: &str, + rec: &mut Record, +) { + let (owner, name) = (&w.msg.repo_owner, &w.msg.repo_name); + let egress = crate::agent::policy::sandbox_egress(w.state, &w.msg.team_id).await; + let node = super::detect_node_version(w.github, owner, name, w.branch).await; + if plan.checks && !rec.checked && rec.no_result.is_empty() { + let sb = sandbox(w).with_egress(egress.clone()); + let steps = permitted(w, super::dep_fix::probe_steps(w.github, w.msg).await).await; + if steps.is_empty() { + rec.no_result = + "the repository has no check command CoderHelm may run in its sandbox".into(); + } else if !sb.has_time(w.deadline) { + // Decided again by `next`: a fresh step, never a guess. + return; + } else { + let source = sb + .ensure_source(w.run_id, head, || { + w.github.download_tarball(owner, name, head) + }) + .await; + match source { + Err(e) => rec.no_result = format!("the branch couldn't be snapshotted: {e}"), + Ok(source) => match sb + .run_checks( + &source, + &super::checks::script(&steps), + node.as_deref(), + None, + w.deadline, + ) + .await + { + Ok(o) if o.ran => { + crate::clients::sandbox::NoResults::clear(w.run_id); + let codes = super::checks::step_results(&o.output, steps.len()); + if codes.iter().all(Option::is_none) { + rec.no_result = "the build ended before a step reported".into(); + } else { + rec.record_checks(&steps, &codes, &o.output); + } + } + Ok(o) => { + if o.broken { + crate::clients::sandbox::NoResults::record(w.run_id, &o.reason); + rec.no_result = o.reason; + } + // Not started for lack of time: `next` decides. + } + Err(e) => rec.no_result = format!("the sandbox could not be driven ({e})"), + }, + } + } + info!( + run_id = w.run_id, + checked = rec.checked, + passed = ?rec.passed, + no_result = %rec.no_result, + "Settle: the repository's checks" + ); + } + if plan.audit && !rec.audited && rec.audit_failed.is_empty() { + if audits.is_empty() { + rec.audit_failed = "the change touches no lockfile CoderHelm has an audit for".into(); + return; + } + let cmd = dep_audit::command(audits); + let gate = crate::agent::policy::gate( + w.state, + w.provider.scope.ctx(common::agent_policy::Agent::Coder), + w.deadline, + ); + if !matches!( + gate.check_command(&cmd, "Audit the dependencies with their package manager") + .await, + common::agent_policy::Outcome::Run { .. } + ) { + rec.audit_failed = "the team's agent permissions hold the audit command".into(); + return; + } + let mut hosts: Vec = super::generators::lockfile_hosts(); + for a in audits { + for h in dep_audit::hosts(a.manager) { + if !hosts.iter().any(|x| x == h) { + hosts.push(h.to_string()); + } + } + } + let sb = sandbox(w) + .with_egress(egress) + .with_generator_hosts(hosts, vec![cmd.clone()]); + if !sb.has_time(w.deadline) { + return; + } + let source = sb + .ensure_source(w.run_id, head, || { + w.github.download_tarball(owner, name, head) + }) + .await; + match source { + Err(e) => rec.audit_failed = format!("the branch couldn't be snapshotted: {e}"), + Ok(source) => match sb + .run_checks(&source, &cmd, node.as_deref(), None, w.deadline) + .await + { + Ok(o) if o.ran => rec.record_audits(&dep_audit::read(audits, &o.output)), + Ok(o) if o.broken => rec.audit_failed = o.reason, + Ok(_) => {} + Err(e) => rec.audit_failed = format!("the sandbox could not be driven ({e})"), + }, + } + info!( + run_id = w.run_id, + audited = rec.audited, + audits = ?rec.audits, + "Settle: the dependency audit" + ); + } +} + +/// The settle stage: classifies `items`, runs what CoderHelm can run, acts +/// on what comes back, and returns what goes on the pull request, or says +/// the run goes on in a fresh step. `evidence` gains what ran. +#[allow(clippy::too_many_arguments)] +pub async fn run( + w: &proof::Work<'_>, + items: &[Finding], + intent: TicketIntent, + pr_number: u64, + evidence: &mut RunEvidence, + usage: &mut TokenUsage, + has_time: impl Fn() -> bool, +) -> Ran { + let head = w.head().await; + let (facts, audits) = facts(w, intent, evidence).await; + let plan = plan(items, &facts); + let mut rec = w.ledger.update(|l| { + l.settle.for_head(&head); + l.settle.clone() + }); + let sandbox_on = + sandbox(w).is_enabled() && crate::clients::sandbox::NoResults::given_up(w.run_id).is_none(); + let save = |rec: &Record| { + w.ledger.update(|l| l.settle = rec.clone()); + }; + loop { + let dep_sets = match common::security_fixes::is_ticket(&w.msg.ticket_id) { + true => super::dep_fix::load(w.state, w.msg, w.run_id) + .await + .map_or(0, |r| r.commits.len()), + false => 0, + }; + let room = Room { + build: sandbox(w).has_time(w.deadline), + round: has_time(), + sandbox: sandbox_on, + dep_sets, + }; + match next(&plan, &rec, &room) { + Next::Build => { + let before = rec.clone(); + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + "Settling the open items: running the checks they wait on in the sandbox", + ) + .await; + build(w, &plan, &audits, &head, &mut rec).await; + save(&rec); + w.save_ledger().await; + if rec == before { + // The window closed between the decision and the build. + rec.steps += 1; + save(&rec); + w.save_ledger().await; + if rec.steps <= MAX_STEPS { + return Ran::Again( + "Settling the open items needs a sandbox build with a full time window" + .into(), + ); + } + break; + } + } + Next::TakeOutSet => { + let why = format!( + "the checks CoderHelm ran in its sandbox failed with it applied ({}); taken \ + out so the bumps before it ship", + common::truncate_str( + &rec.checks + .iter() + .filter(|l| l.contains("FAIL")) + .cloned() + .collect::>() + .join("; "), + 300 + ) + ); + match super::resume::take_out_dep_set( + w.state, w.msg, w.run_id, w.github, w.branch, pr_number, &why, + ) + .await + { + Some(note) => { + rec.reverts += 1; + save(&rec); + w.save_ledger().await; + super::add_progress_note(w.state, &w.msg.team_id, w.run_id, ¬e).await; + return Ran::Again( + "A set of bumps came out after a failing check: the checks run again \ + on what is left" + .into(), + ); + } + None => { + warn!( + run_id = w.run_id, + "Settle: the newest set of bumps couldn't be taken out" + ); + break; + } + } + } + Next::FixRound => { + rec.rounds += 1; + save(&rec); + w.save_ledger().await; + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + "A check the open items wait on fails in the sandbox: fixing it with the real output", + ) + .await; + let asked: Vec = items + .iter() + .filter(|f| matches!(classify(f, &facts), Class::Run(_))) + .cloned() + .collect(); + let fixed = super::implement::run( + w.state, + w.msg, + w.github, + w.plan, + w.branch, + w.rules, + w.repo_instructions, + Some(&fix_feedback(&rec, &asked)), + "medium", + w.provider, + usage, + w.file_cache, + Some(w.run_id), + w.deadline, + true, + ) + .await; + match fixed { + Ok(r) => evidence.merge(r.evidence), + Err(e) => { + warn!(run_id = w.run_id, error = %e, "Settle: the fix round failed"); + break; + } + } + if w.head().await == head { + // The round changed nothing: what failed still fails. + break; + } + return Ran::Again( + "A fix round changed the branch: the checks run again on the new head".into(), + ); + } + Next::FreshStep(why) => { + rec.steps += 1; + save(&rec); + w.save_ledger().await; + return Ran::Again(why.to_string()); + } + Next::Done => break, + } + } + Ran::Settled( + Box::new(write_down(w, items, &facts, &rec, evidence).await), + rec, + ) +} + +/// What goes on the pull request from what has run so far, with nothing +/// more run: for a run that can't go on in a fresh step. +pub async fn finish( + w: &proof::Work<'_>, + items: &[Finding], + intent: TicketIntent, + evidence: &mut RunEvidence, +) -> (Box, Record) { + let head = w.head().await; + let (facts, _) = facts(w, intent, evidence).await; + let rec = w.ledger.update(|l| { + l.settle.for_head(&head); + l.settle.clone() + }); + let settled = write_down(w, items, &facts, &rec, evidence).await; + (Box::new(settled), rec) +} + +async fn write_down( + w: &proof::Work<'_>, + items: &[Finding], + facts: &Facts, + rec: &Record, + evidence: &mut RunEvidence, +) -> Settled { + rec.write_evidence(evidence); + let settled = apply(items.to_vec(), facts, rec); + info!( + run_id = w.run_id, + open = settled.open.len(), + closed = settled.closed.len(), + dropped = settled.dropped.len(), + "Settle: the open items" + ); + if !settled.closed.is_empty() || !settled.dropped.is_empty() { + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + &format!( + "Open items: {} settled by a check CoderHelm ran, {} left out as not applying to this run, {} left", + settled.closed.len(), + settled.dropped.len(), + settled.open.len() + ), + ) + .await; + } + settled +} + +#[cfg(test)] +mod tests { + use super::*; + + fn f(point: &str, detail: &str, settle: &str) -> Finding { + Finding { + point: point.into(), + detail: detail.into(), + settle: settle.into(), + ..Default::default() + } + } + + fn chore() -> Facts { + Facts { + intent: TicketIntent::Chore, + dep_change: true, + ..Default::default() + } + } + + #[test] + fn an_item_is_run_dropped_or_named_as_a_persons() { + let facts = chore(); + // A check that did not run is run. + let mut unrun = f("unrun_check", "Tests never ran before the PR.", ""); + unrun.check = "tests".into(); + assert_eq!( + classify(&unrun, &facts), + Class::Run(vec![Action::Check(CheckKind::Tests)]) + ); + // A plan needs credentials the sandbox never has. + unrun.check = "plan".into(); + assert_eq!( + classify(&unrun, &facts), + Class::Human(HumanOnly::Credential) + ); + // A gap whose own words say the checks settle it. + let asks = f( + "assumption", + "The override moves two parents to a major they never declared.", + "Confirm with the web build and the tests.", + ); + assert_eq!( + classify(&asks, &facts), + Class::Run(vec![ + Action::Check(CheckKind::Build), + Action::Check(CheckKind::Tests) + ]) + ); + // A gap about another system is a fix round's, never a build's. + let vendor = f( + "external_fact", + "The vendor's build id field is assumed to be a string.", + "Read one payload and quote it.", + ); + assert_eq!(classify(&vendor, &facts), Class::Own); + // A source no connection reaches is a person's to grant. + let access = f( + "external_fact", + "The billing table's column is unconfirmed: no connection reaches the warehouse.", + "", + ); + assert_eq!( + classify(&access, &facts), + Class::Human(HumanOnly::MissingAccess) + ); + // CI's are CI's. + assert_eq!(classify(&f("ci_pending", "Lint.", ""), &facts), Class::Ci); + } + + #[test] + fn the_audit_is_run_only_for_a_change_to_the_dependencies() { + let item = f( + "external_fact", + "The remaining critical and high advisory counts are unknown.", + "", + ); + assert_eq!(classify(&item, &chore()), Class::Run(vec![Action::Audit])); + let other = Facts::default(); + assert_eq!(classify(&item, &other), Class::Own); + assert!(!names_audit( + "The vendor's audit log count is not confirmed." + )); + // And it runs after the bumps whether or not an item asks. + assert!(plan(&[], &chore()).audit); + assert!(!plan(&[], &other).audit && !plan(&[], &other).checks); + } + + #[test] + fn an_end_to_end_checklist_is_not_raised_for_upkeep() { + let none = f( + "end_to_end", + "The plan has no end-to-end checklist.", + "List every step.", + ); + assert!(matches!(classify(&none, &chore()), Class::NotApplicable(_))); + let by_rules = Facts { + planned_by_rules: true, + ..Default::default() + }; + assert!(matches!( + classify(&none, &by_rules), + Class::NotApplicable(_) + )); + // A feature's missing checklist is the team's to answer. + let feature = Facts { + intent: TicketIntent::Feature, + ..Default::default() + }; + assert_eq!( + classify(&none, &feature), + Class::Human(HumanOnly::ProductDecision) + ); + // A step the plan itself names without an owner stays, even for upkeep. + let unowned = f("end_to_end", "No owner is named for: rotate the key", ""); + assert_eq!( + classify(&unowned, &chore()), + Class::Human(HumanOnly::ProductDecision) + ); + } + + #[test] + fn the_same_missing_fact_is_one_item() { + let facts = chore(); + let mut a = f( + "unrun_check", + "The remaining critical and high advisory counts are unknown because the audit never ran.", + "Run it and quote the counts.", + ); + a.check = "security".into(); + let b = f( + "external_fact", + "The critical and high counts from the audit are unknown.", + "", + ); + let c = f( + "assumption", + "The override moves two parents to a major they never declared.", + "Confirm with the build and the tests.", + ); + let d = f( + "assumption", + "The README says build and tests pass, but no check has run.", + "Rewrite that line.", + ); + let classed = |v: Vec| -> Vec<(Finding, Class)> { + v.into_iter() + .map(|x| { + let cl = classify(&x, &facts); + (x, cl) + }) + .collect() + }; + let out = dedup(classed(vec![a.clone(), b, c.clone(), d.clone()])); + let kept: Vec<&Finding> = out.iter().map(|(x, _)| x).collect(); + // The two audit items are one; two different facts that both wait + // on the build stay two. + assert_eq!(kept, vec![&a, &c, &d]); + // The same check listed twice is one. + let mut t1 = f("unrun_check", "Tests never ran.", ""); + t1.check = "tests".into(); + let mut t2 = f( + "ci_pending", + "The test suite did not run before the PR.", + "", + ); + t2.check = "tests".into(); + assert_eq!(dedup(classed(vec![t1, t2])).len(), 1); + // Near-identical sentences of one point are one. + let e1 = f( + "external_fact", + "The vendor sends the amount in cents on every order payload.", + "", + ); + let e2 = f( + "external_fact", + "Unconfirmed: the vendor sends the amount in cents on every order payload", + "", + ); + assert_eq!(dedup(classed(vec![e1, e2])).len(), 1); + } + + fn step(kind: CheckKind, cmd: &str) -> Step { + Step { + kinds: vec![kind], + cmd: cmd.into(), + scope: None, + } + } + + fn green() -> Record { + let mut r = Record { + head: "h1".into(), + ..Default::default() + }; + r.record_checks( + &[ + step(CheckKind::Build, "pnpm -r build"), + step(CheckKind::Tests, "pnpm test"), + ], + &[Some(0), Some(0)], + "ok", + ); + r + } + + #[test] + fn a_passing_result_closes_the_item_with_the_result_as_proof() { + let asks = f( + "assumption", + "The override moves two parents to a major they never declared.", + "Confirm with the build and the tests.", + ); + let out = apply(vec![asks.clone()], &chore(), &green()); + assert!(out.open.is_empty()); + assert_eq!(out.closed.len(), 1); + assert!(out.closed[0].1.contains("build: PASS, `pnpm -r build`")); + assert!(out.closed[0].1.contains("tests: PASS, `pnpm test`")); + // Without the result it stays, and says what CoderHelm did. + let none = Record { + head: "h1".into(), + no_result: "the sandbox build ended FAILED and printed no result".into(), + ..Default::default() + }; + let out = apply(vec![asks], &chore(), &none); + assert!(out.closed.is_empty()); + assert!( + out.open[0].needs.contains("gave no result"), + "{}", + out.open[0].needs + ); + } + + #[test] + fn items_are_derived_again_from_the_results_of_the_head() { + let readme = f( + "assumption", + "The README says build and tests pass, but no check has run on this branch.", + "Rewrite that line from the actual results.", + ); + // On the head the item was raised on, nothing had run. + let mut rec = Record::default(); + rec.for_head("h1"); + assert_eq!(apply(vec![readme.clone()], &chore(), &rec).open.len(), 1); + // A later round moved the head and the checks ran there: gone. + let mut rec = green(); + rec.rounds = 1; + assert!(apply(vec![readme.clone()], &chore(), &rec).open.is_empty()); + // The head moves again: the old results are set aside, the counts stay. + rec.for_head("h2"); + assert!(!rec.checked && rec.passed.is_empty()); + assert_eq!(rec.rounds, 1); + assert_eq!(apply(vec![readme], &chore(), &rec).open.len(), 1); + } + + #[test] + fn what_stays_names_why() { + let facts = Facts { + intent: TicketIntent::Feature, + ..Default::default() + }; + let out = apply( + vec![ + f("end_to_end", "No owner is named for: rotate the key", ""), + f("logging", "An INFO log fires per record.", "Lower it."), + ], + &facts, + &Record::default(), + ); + assert_eq!(out.open.len(), 2); + assert_eq!( + out.open[0].needs, + "Only a person can settle this: a product decision" + ); + // CoderHelm's own work left is not dressed up as a person's. + assert!(out.open[1].needs.is_empty()); + let section = proof::gaps_section(&out.open); + assert!(section.contains("Only a person can settle this: a product decision")); + } + + fn room() -> Room { + Room { + build: true, + round: true, + sandbox: true, + dep_sets: 0, + } + } + + #[test] + fn a_check_without_a_window_goes_to_a_fresh_step_never_unverified() { + let plan = Plan { + checks: true, + kinds: vec![CheckKind::Build], + audit: true, + }; + let mut rec = Record::default(); + assert_eq!(next(&plan, &rec, &room()), Next::Build); + let short = Room { + build: false, + ..room() + }; + assert!(matches!(next(&plan, &rec, &short), Next::FreshStep(_))); + // Bounded: a run that never finds a window writes it down. + rec.steps = MAX_STEPS; + assert_eq!(next(&plan, &rec, &short), Next::Done); + let out = apply( + vec![{ + let mut x = f("unrun_check", "Build never ran.", ""); + x.check = "build".into(); + x + }], + &chore(), + &rec, + ); + assert!(out.open[0] + .needs + .contains("no step with a full sandbox window")); + // No sandbox at all: nothing to wait for. + let none = Room { + sandbox: false, + ..room() + }; + assert_eq!(next(&plan, &Record::default(), &none), Next::Done); + // The coder's refused check is owed with no item at all. + let owed = super::plan( + &[], + &Facts { + checks_owed: true, + ..Default::default() + }, + ); + assert!(owed.checks); + assert_eq!(next(&owed, &Record::default(), &room()), Next::Build); + } + + #[test] + fn a_failing_check_is_acted_on() { + let plan = Plan { + checks: true, + kinds: vec![CheckKind::Build], + audit: false, + }; + let mut rec = Record::default(); + rec.record_checks( + &[ + step(CheckKind::Build, "pnpm -r build"), + step(CheckKind::Lint, "pnpm lint"), + ], + &[Some(2), Some(1)], + "error TS2305: Module has no exported member", + ); + assert_eq!( + rec.failed(), + vec![CheckKind::Build], + "lint never holds a run" + ); + // A dependency fix with a set to spare takes its newest set out. + let dep = Room { + dep_sets: 3, + ..room() + }; + assert_eq!(next(&plan, &rec, &dep), Next::TakeOutSet); + // Its last set is never taken out: a fix round instead. + let last = Room { + dep_sets: 1, + ..room() + }; + assert_eq!(next(&plan, &rec, &last), Next::FixRound); + // Any other run: a fix round with the real output. + assert_eq!(next(&plan, &rec, &room()), Next::FixRound); + let feedback = fix_feedback(&rec, &[]); + assert!(feedback.contains("build: FAIL (exit 2), `pnpm -r build`")); + assert!(feedback.contains("error TS2305")); + // No time for the round: a fresh step. Rounds spent: written down. + let short = Room { + round: false, + ..room() + }; + assert!(matches!(next(&plan, &rec, &short), Next::FreshStep(_))); + rec.rounds = MAX_FIX_ROUNDS; + assert_eq!(next(&plan, &rec, &room()), Next::Done); + let mut item = f("unrun_check", "Build never ran.", ""); + item.check = "build".into(); + let out = apply(vec![item], &Facts::default(), &rec); + assert!( + out.open[0].needs.contains("it fails"), + "{}", + out.open[0].needs + ); + // A lint failure alone starts nothing. + let mut lint = Record::default(); + lint.record_checks(&[step(CheckKind::Lint, "pnpm lint")], &[Some(1)], "x"); + assert_eq!(next(&plan, &lint, &room()), Next::Done); + } + + #[test] + fn items_name_their_head_and_another_head_makes_them_stale() { + let section = proof::gaps_section(&[f("logging", "An INFO log fires per record.", "")]); + let on = stamp(§ion, "abc123"); + assert!(on.contains("")); + assert_eq!(stamp(&on, "def456"), on, "a line is stamped once"); + let body = format!("## Summary\nx\n\n{on}"); + assert!(!stale(&body, "abc123")); + assert!(stale(&body, "def456")); + // Items written before lines carried a head are left alone. + assert!(!stale(&format!("## Summary\nx\n\n{section}"), "def456")); + assert!(!stale("## Summary\nx", "def456")); + // Once per head, and bounded. + assert!(redrive_due(&body, "def456", 0, "")); + assert!(!redrive_due(&body, "def456", 1, "def456")); + assert!(!redrive_due(&body, "def456", MAX_REDRIVES, "")); + assert!(!redrive_due(&body, "abc123", 0, "")); + // The marks survive the description being put together again. + let (owned, rest) = crate::passes::completeness::take_owned(&body); + let again = crate::passes::completeness::assemble(&rest, &owned); + assert!(stale(&again, "def456")); + } + + #[test] + fn the_results_are_quoted_on_the_pull_request() { + let mut rec = green(); + rec.record_audits(&[dep_audit::Audited { + manager: "pnpm".into(), + lockfile: "pnpm-lock.yaml".into(), + shown: "pnpm audit --json".into(), + outcome: dep_audit::Outcome::Counts(dep_audit::Counts { + high: 1, + other: 2, + ..Default::default() + }), + }]); + let mut audit = f("unrun_check", "The audit never ran.", ""); + audit.check = "security".into(); + let settled = apply(vec![audit], &chore(), &rec); + assert!(settled.open.is_empty()); + let section = settled_section(&settled, &rec); + assert!(section.contains("## Checked by CoderHelm")); + assert!(section.contains("- build: PASS, `pnpm -r build`")); + assert!(section.contains( + "- `pnpm audit --json` on `pnpm-lock.yaml`: 0 critical, 1 high and 2 lower advisories left" + )); + assert!(section.contains("they settle 1 item that")); + assert!(settled_section(&Settled::default(), &Record::default()).is_empty()); + // An audit that gave no report is never read as clean. + let mut bad = Record::default(); + bad.record_audits(&[dep_audit::Audited { + manager: "pnpm".into(), + lockfile: "pnpm-lock.yaml".into(), + shown: "pnpm audit --json".into(), + outcome: dep_audit::Outcome::Failed("pnpm exited 1 with no summary".into()), + }]); + assert!(!bad.audited); + let mut audit = f("unrun_check", "The audit never ran.", ""); + audit.check = "security".into(); + let out = apply(vec![audit], &chore(), &bad); + assert!(out.open[0].needs.contains("gave no report")); + } +}