diff --git a/docs/api/openapi.json b/docs/api/openapi.json index b78ed2bd4..c6cfac554 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -3838,6 +3838,17 @@ "null" ] }, + "merge_standing": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunMergeStanding", + "description": "Where the run's pull request stands on its way to merge, in the one\nreason that is true now (`common::merge_standing`): what holds it,\nwhat happens next, whether a person has to act and, when a setting\ndecides it, where that setting is. Null until the worker has looked\nat the pull request." + } + ] + }, "outside_change_report": { "description": "The report written when (part of) the fix is a change outside the code.", "examples": [ @@ -4641,6 +4652,56 @@ ], "type": "object" }, + "RunMergeStanding": { + "description": "Where a run's pull request stands on its way to merge.", + "properties": { + "code": { + "description": "Stable code: `merged`, `closed`, `reviewing`, `fixing_review`,\n`review_changes_requested`, `checks_running`, `checks_failing`,\n`conflict`, `draft`, `auto_merge_off`, `needs_person_approval`,\n`repo_requires_person_review` or `merging`.", + "examples": [ + "auto_merge_off" + ], + "type": "string" + }, + "link": { + "description": "Where the rule is set, when a setting decides it: a dashboard path\nor a GitHub URL. Null otherwise.", + "examples": [ + "/reviewer/config" + ], + "type": [ + "string", + "null" + ] + }, + "needs_person": { + "description": "A person has to act for the merge to happen.", + "examples": [ + true + ], + "type": "boolean" + }, + "next": { + "description": "What happens next, one sentence.", + "examples": [ + "Merge it, or turn auto-merge on and CoderHelm merges approved pull requests itself." + ], + "type": "string" + }, + "text": { + "description": "What is true now, one sentence.", + "examples": [ + "Auto-merge is off for this repo, so CoderHelm leaves the merge to your team." + ], + "type": "string" + } + }, + "required": [ + "code", + "text", + "next", + "needs_person" + ], + "type": "object" + }, "RunNote": { "description": "A note the run wrote while it worked.", "properties": { diff --git a/docs/incidents.md b/docs/incidents.md index 3db737cd7..f57786b7d 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -64,6 +64,11 @@ pipeline still calls it there. | ag. `ag_red_ci_ships_what_passes` | Three ways were left for a run to end badly over red checks or a refused landing. A dependency fix whose CI stayed red was taken apart by planned task (one task per lockfile, so a lockfile went back without its manifest), and after three reverts the run ended failed with bumps left in that passed on their own. A run stopped after its work opened its pull request with manifests changed and lockfiles unwritten, and waited for CI to fail first. A review fix or feedback round whose finished work GitHub refused to land was recorded as unfinished at once. | Red checks after every fix take out only what breaks them. A dependency fix takes out its newest commit of verified bumps, defers those bumps with what CI printed, holds their findings out of later bundles and keeps the commits before it, again while CI stays red, never emptying the pull request. Any other run is taken apart task by task (up to eight reverts) down to the part that passes; what ships is green with the rest under "Deferred". A stopped run's lockfiles are written by their package managers before its pull request opens, and one that can't be written is named without stopping it. Every kind of fix round takes one classified decision about a fault (`round::plan_for_fault`): while it may continue it runs again in a fresh step, keeping its work when only the landing failed and starting from the pull request's head otherwise. | | ah. `ah_dep_run_choice_and_proof` | A dependency security run of 64 packages finished with its checks passed. Two packages had been forced onto a new major version through an override although a patched release existed on the installed line (a unit listed one bump per package, to the highest target of all of the package's copies); CoderHelm's reviewer caught it and a fix round pinned them back. Four overrides did have to cross a major version and nothing showed their parents work on it: the sandbox ran the install, the type check, the linter and the unit tests, never the application's build or its start. One pull request carried all 64 bumps, and it did not say how many advisories stayed open or why. | A bump stays on its installed version line with that line's lowest patched release, one bump per package and line; it crosses a major version only when the advisory data lists no patched release on the line, and says which advisory. A fix that crosses a major version is a pull request of its own from the start (a person who asks for one pull request still gets one), its release notes read before any patch bump's, with the parent of a transitive package named and the range it declares. After the batches, the repository's real build (the command its CI runs, else its build script) and its declared start command run in a sandbox build of their own with a full time window, on the base branch and on the branch; what passes on the base and fails with the bumps takes out the newest commit of bumps and defers it with the cause, and only the set whose removal made it pass is held as breaking. What did not run is said, never claimed. The description ends with the advisories that stay open, counted by reason. | | ai. `ai_open_items_settled` | A dependency update finished completed with five Open items on its pull request for a person: the package manager's audit never ran so the advisory counts were unknown (listed twice, in different words), nothing showed that the packages an override moved still built and passed their tests, a README line claimed checks no run had made (and was still listed after a later round rewrote it), and the plan had no end-to-end checklist for a change with nothing to deploy. The coder's full checks had been refused twice for lack of time after two lockfile regenerations in one step, and nothing carried them anywhere. | A run settles its own open items before it finishes (`settle`). Each item is classified: CoderHelm runs it in its sandbox, the repository's CI settles it, it does not apply to the run, or only a person has what it needs (a reason on the human-only list). What CoderHelm can run it runs in a step with a full sandbox window, a fresh step when this one has too little time, and a check the coder was refused for lack of time is owed whether or not an item names it. A change to the dependencies is always audited by its package manager after the bumps (`common::dep_audit`, one row per manager) and the counts left are quoted. A passing result closes the item and is quoted under "Checked by CoderHelm"; a failing one takes out a dependency fix's newest verified set of bumps, or gives any other run a fix round with the real output. An end-to-end checklist is not raised for upkeep, the same missing fact is one item, every item names the head it was written on, and a run about to finish with items of an earlier head derives them again first. What stays says why. Lockfiles are regenerated once per state of the branch. | +| aj. `aj_coder_habits` | A bug fix was right on its face and wrong four ways. Its plan named two files and nothing about them. The fix was written first and its test after, and the test passed with or without the fix. It rounded per line, an approach one pull request had shipped and another had reverted two months earlier, with the reason one commit list away. It changed a response field another of the team's repositories read and never named that repository. Its one real doubt (half up or half even) was listed at the bottom of the finished pull request, and a helper file no task named was reformatted along the way. | Before code, a bug's plan names the test that fails on the code as it is (or why none can and the next best proof), and that test is the first task. The worker itself reads the commits of the files the plan modifies and what depends on them (the code graph, a search of the team's other repositories for each changed name); a revert must be answered by name, and every dependent is updated by a task or called safe with the reason. A doubt that changes what is built is asked at planning time with the default the run builds. After the build each new or changed test runs with and without the change: one that passes either way, a bug's test that can't build on the base, a changed file outside the plan with no reason and a planned dependent left untouched all go back to the coder. The pull request carries the failing and the passing result, the history, and who the change affects. | +| al. `al_learning_loop` | A person pushed the same fix on top of two of CoderHelm's pull requests two weeks apart, and the same reviewer asked for the same test both times. All that was kept from the first was "PR #101 was rewritten by people before merging", and nobody could say how often its pull requests were edited, closed or reverted without reading the runs. | What becomes of every pull request CoderHelm opens is counted from the webhooks, each pull request once however often an event is delivered: merged, closed, reverted, review rounds, a person's commit on top, open items. A person's edit, a close with a comment and a revert with a reason each become a lesson that names the code and says how to check a change against it, with the evidence attached. The same lesson from another pull request is counted on the kept one, and a lesson people go against loses weight until it is no longer given. What a reviewer asked for on several pull requests is given to the next build when that reviewer is likely to review it, and nothing personal is kept. A lesson seen on enough pull requests is proposed for the repository's guide file as one pull request at a time, never as a push to the default branch. | +| ba. `ba_verdict_on_old_commit` | A run finished as Done with its pull request ready while its own reviewer stood at "Changes requested" on a commit older than the head, and the run page said a person was needed and that merging was the team's call. The last fix was pushed, and the wake-up that found CI green with no event to read completed the run through an ending that skips the review step, so the new head was never reviewed. | Every completion and the sweep look at the finished run's pull request (`pr_watch`): no reviewer verdict on the head asks for the review of that commit, once per head; changes requested on the head get their fix round, and when the run's rounds are over the findings are deferred on the pull request with the reason. The run page names the one true reason the pull request is where it is (`common::merge_standing`) and names a person only for the team's own rule, with where it is set. | +| bb. `bb_flaky_not_broken` | An end-to-end workflow failed on a timeout in a spec the change never touched, as it had on unrelated pull requests that week. The run spent fix rounds editing the spec's timeout and a retry helper. Where the GitHub App may not write Actions, the re-run tried first was refused and the same fix round followed. | Before a CI fix round the failure is judged (`common::flaky_checks`): a failure naming a changed file is the change's; a check with a record of failing and then passing on one commit of other pull requests, naming no changed file, is re-run once and no code changes for it, and the pull request says which check, the evidence and what was done. A refused re-run is said with the permission by name and still changes no code. The record is per repository and learns only from a commit that failed and then passed unchanged. | +| bc. `bc_stays_through_merge_and_deploy` | Pull requests were left as they were after their runs finished: one conflicted after its base moved, one went red a day later on a commit status no event carries, and one merged by a person had its production deploy fail with nothing watching. | A finished run's pull request is looked at on completion and by the sweep: a conflict starts the conflict round once per base commit, red checks not red on the base go to the fix loop once per head, and a merge by anyone gets its merge commit's deploy watched once. A deploy of CoderHelm's own change that fails on checks passing before the merge gets a revert pull request with the failing jobs as evidence, ready for the team's approval and never merged by CoderHelm; files changed again since are never overwritten. | ## Adding a case diff --git a/services/common/src/flaky_checks.rs b/services/common/src/flaky_checks.rs new file mode 100644 index 000000000..a3886b693 --- /dev/null +++ b/services/common/src/flaky_checks.rs @@ -0,0 +1,642 @@ +//! Flaky or broken: whose failure a red check is. +//! +//! A red check on CoderHelm's pull request is not always the pull request's +//! doing. Before a fix round changes code for it, three things are read: +//! +//! - whether the check also fails on the base branch's head (red before the +//! change, see `resume::split_base_failures`); +//! - whether the repository has a record of the check failing and then +//! passing on the same commit of OTHER pull requests ([`Record`]); +//! - whether the failure names a file the pull request changed ([`touch`]). +//! +//! A failure that names a changed file is the change's, whatever the record +//! says. A failure of a check with a record of intermittent failures on +//! unrelated pull requests, which names no changed file, is re-run, not +//! "fixed": changing code that is not wrong makes the pull request worse and +//! the next reader's trust in it lower. The pull request says which check +//! was judged flaky and on what evidence ([`section`]). +//! +//! The record is one item per repository. It learns from what really +//! happened: a commit whose check failed and then passed on a re-run with +//! no change in between is the only observation that counts as flaky. + +use std::collections::BTreeMap; + +use chrono::{DateTime, Duration, Utc}; +use serde::{Deserialize, Serialize}; + +/// Sort key prefix of a repository's record (`FLAKY#owner/repo`), under the +/// team's partition of the settings table. +pub const PREFIX: &str = "FLAKY#"; + +/// Observations older than this say nothing about the check today. +pub const WINDOW_DAYS: i64 = 30; +/// Other pull requests that must have seen the check fail and then pass on +/// one commit before it counts as flaky for this one. +pub const MIN_OTHER_PRS: usize = 2; +/// Observations kept per check, newest last. +pub const MAX_OBSERVATIONS: usize = 20; +/// Checks kept per repository; the ones seen longest ago go first. +pub const MAX_CHECKS: usize = 200; + +/// The record's sort key for `owner/repo`. +pub fn sk(repo: &str) -> String { + format!("{PREFIX}{repo}") +} + +/// What was seen of one check on one commit. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + /// It failed, was re-run with no change, and passed. + PassedOnRerun, + /// It failed for the runner's or a service's reason (a DNS miss, a + /// runner that went away), read from its log. + Infra, +} + +/// One observation, with what a person needs to check it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Observation { + pub kind: Kind, + /// RFC 3339. + pub at: String, + pub pr: u64, + pub sha: String, + /// The line that says so (an infrastructure line), empty when none. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub line: String, +} + +/// A repository's flaky checks: observations by check name. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Record { + #[serde(default)] + pub checks: BTreeMap>, +} + +impl Record { + pub fn from_json(s: &str) -> Record { + serde_json::from_str(s).unwrap_or_default() + } + + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string()) + } + + /// Adds an observation. The same commit of the same pull request is one + /// observation however often it is reported (a webhook and a sweep). True + /// when the record changed. + pub fn observe(&mut self, check: &str, o: Observation) -> bool { + let check = check.trim(); + if check.is_empty() { + return false; + } + let list = self.checks.entry(check.to_string()).or_default(); + if list + .iter() + .any(|x| x.kind == o.kind && x.pr == o.pr && x.sha == o.sha) + { + return false; + } + list.push(o); + if list.len() > MAX_OBSERVATIONS { + let drop = list.len() - MAX_OBSERVATIONS; + list.drain(..drop); + } + while self.checks.len() > MAX_CHECKS { + let oldest = self + .checks + .iter() + .min_by_key(|(_, v)| v.last().map(|o| o.at.clone()).unwrap_or_default()) + .map(|(k, _)| k.clone()); + match oldest { + Some(k) => { + self.checks.remove(&k); + } + None => break, + } + } + true + } + + /// The check's observations inside the window on pull requests other + /// than `pr`, newest last. + pub fn elsewhere(&self, check: &str, pr: u64, now: DateTime) -> Vec<&Observation> { + let cut = now - Duration::days(WINDOW_DAYS); + self.checks + .get(check.trim()) + .map(|l| { + l.iter() + .filter(|o| o.pr != pr && o.kind == Kind::PassedOnRerun) + .filter(|o| { + DateTime::parse_from_rfc3339(&o.at) + .map(|t| t.with_timezone(&Utc) >= cut) + .unwrap_or(false) + }) + .collect() + }) + .unwrap_or_default() + } + + /// Whether the check has a record of intermittent failure on unrelated + /// pull requests: it failed and then passed on one commit of at least + /// [`MIN_OTHER_PRS`] other pull requests inside the window. + pub fn known_flaky(&self, check: &str, pr: u64, now: DateTime) -> bool { + let mut prs: Vec = self + .elsewhere(check, pr, now) + .iter() + .map(|o| o.pr) + .collect(); + prs.sort_unstable(); + prs.dedup(); + prs.len() >= MIN_OTHER_PRS + } +} + +/// What a failure's output says about the files the pull request changed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Touch { + /// It names these changed files: the change's own failure. + Changed(Vec), + /// It names files, none of them changed by the pull request. + Elsewhere(Vec), + /// It names no file. + Unknown, +} + +/// File extensions a failure's output names source files with. +const SOURCE_EXTS: &[&str] = &[ + "rs", "ts", "tsx", "js", "jsx", "mjs", "cjs", "py", "go", "rb", "java", "kt", "swift", "cs", + "php", "c", "cc", "cpp", "h", "hpp", "vue", "svelte", "scala", "ex", "exs", "tf", "sql", + "yaml", "yml", "json", "toml", "css", "scss", "html", "sh", +]; + +/// A token of a log line as a repository path, when it reads as one: +/// `src/a/b.test.ts:12:3`, `./src/a.py`, `/home/runner/work/app/app/src/a.go`. +fn path_in(token: &str) -> Option { + let t = token.trim_matches(|c: char| { + !(c.is_alphanumeric() || matches!(c, '/' | '.' | '_' | '-' | '@' | '[' | ']')) + }); + // `file.rs:12:3` and `file.py(12)`: the position goes. + let t = t.split([':', '(']).next().unwrap_or(t); + let t = t.trim_end_matches(['.', ',', ')', ']']); + let (stem, ext) = t.rsplit_once('.')?; + if stem.is_empty() || !SOURCE_EXTS.contains(&ext.to_ascii_lowercase().as_str()) { + return None; + } + if t.contains("://") || t.len() > 300 { + return None; + } + // A bare file name names nothing in particular; a path does. + if !t.contains('/') { + return None; + } + let t = t.trim_start_matches("./"); + // A runner's checkout prefix (`/home/runner/work/{repo}/{repo}/`). + let t = match t.split_once("/work/") { + Some((_, rest)) if t.starts_with('/') => { + let mut parts = rest.splitn(3, '/'); + match (parts.next(), parts.next(), parts.next()) { + (Some(a), Some(b), Some(path)) if a == b => path, + _ => rest, + } + } + _ => t, + }; + let t = t.trim_start_matches('/'); + (!t.is_empty() && !t.contains("node_modules/")).then(|| t.to_string()) +} + +/// The repository paths a failure's output names, in order, each once. +pub fn named_paths(logs: &str) -> Vec { + let mut out: Vec = Vec::new(); + for token in logs.split(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | '`' | '=')) { + if let Some(p) = path_in(token) { + if !out.contains(&p) { + out.push(p); + } + } + if out.len() >= 200 { + break; + } + } + out +} + +/// Whether a path a log names is the changed file `changed`: equal, or one +/// ends with the other at a directory boundary (a log printed relative to a +/// package directory, or with a build prefix). +fn same_file(named: &str, changed: &str) -> bool { + let ends = |long: &str, short: &str| { + long.ends_with(short) + && long[..long.len() - short.len()] + .chars() + .last() + .is_none_or(|c| c == '/') + }; + named == changed || ends(named, changed) || ends(changed, named) +} + +/// What the failure's output says about the pull request's changed files. +pub fn touch(logs: &str, changed: &[String]) -> Touch { + let named = named_paths(logs); + if named.is_empty() { + return Touch::Unknown; + } + let hit: Vec = changed + .iter() + .filter(|c| named.iter().any(|n| same_file(n, c))) + .cloned() + .collect(); + if hit.is_empty() { + Touch::Elsewhere(named.into_iter().take(5).collect()) + } else { + Touch::Changed(hit) + } +} + +/// Why a failing check is not the pull request's. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum NotOurs { + /// It fails on the base branch's head too. + RedOnBase, + /// The runner or a service failed, with the line that says so. + Infra(String), + /// It failed and then passed on one commit of these other pull requests + /// (`#pr at sha`), newest last. + Flaky(Vec), +} + +/// Whose failure each failing check is. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Judgement { + /// Checks the pull request has to fix. + pub ours: Vec, + /// Checks it did not cause, with why. + pub not_ours: Vec<(String, NotOurs)>, +} + +impl Judgement { + /// Nothing here is the pull request's to fix: re-run, don't change code. + pub fn none_ours(&self) -> bool { + self.ours.is_empty() && !self.not_ours.is_empty() + } +} + +/// Judges the failing checks of a pull request's head. `failing` is every +/// failing check, `on_base` those failing on the base branch's head too, +/// `touch` what the failure output says about the changed files, `infra` +/// the infrastructure line the output shows. +/// +/// A check failing on the base is the base's. For the rest: output that +/// names a changed file makes every one of them the pull request's. An +/// infrastructure line makes them the runner's. Otherwise a check is flaky +/// only with a record on unrelated pull requests; with none it is the pull +/// request's, since a failure that names no changed file can still be +/// caused by one. +pub fn judge( + failing: &[String], + on_base: &[String], + touch: &Touch, + infra: Option<&str>, + record: &Record, + pr: u64, + now: DateTime, +) -> Judgement { + let mut j = Judgement::default(); + for check in failing { + if on_base.contains(check) { + j.not_ours.push((check.clone(), NotOurs::RedOnBase)); + continue; + } + if matches!(touch, Touch::Changed(_)) { + j.ours.push(check.clone()); + continue; + } + if let Some(line) = infra { + j.not_ours + .push((check.clone(), NotOurs::Infra(line.to_string()))); + continue; + } + if record.known_flaky(check, pr, now) { + let seen = record + .elsewhere(check, pr, now) + .iter() + .map(|o| format!("#{} at `{}`", o.pr, short(&o.sha))) + .collect(); + j.not_ours.push((check.clone(), NotOurs::Flaky(seen))); + continue; + } + j.ours.push(check.clone()); + } + j +} + +fn short(sha: &str) -> &str { + sha.get(..7).unwrap_or(sha) +} + +/// What happened to the re-run of the checks judged not the pull request's. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Rerun { + /// The failed jobs were started again. + Started, + /// GitHub refused: the installation may not write Actions. + NoPermission, + /// Nothing to start again (a check outside GitHub Actions). + NotActions, +} + +/// Whether GitHub's refusal of a re-run is a missing permission (the App +/// has no Actions write on the repository), not a failure worth a retry. +pub fn rerun_refused_for_permission(error: &str) -> bool { + let e = error.to_ascii_lowercase(); + e.contains("resource not accessible by integration") + || (e.contains("403") && (e.contains("actions") || e.contains("must have admin rights"))) +} + +pub const START: &str = ""; +pub const END: &str = ""; + +/// The pull request's section saying which red checks CoderHelm judged not +/// caused by the change, the evidence for each, and what it did about it. +/// Empty when every failing check is the pull request's. +pub fn section(j: &Judgement, base: &str, rerun: &Rerun, touch: &Touch) -> String { + if j.not_ours.is_empty() { + return String::new(); + } + let mut lines: Vec = Vec::new(); + for (check, why) in &j.not_ours { + lines.push(match why { + NotOurs::RedOnBase => { + format!("* `{check}` also fails on the head of `{base}`: red before this change.") + } + NotOurs::Infra(line) => format!( + "* `{check}` failed on the runner or a service, not on the code: `{}`.", + line.replace('`', "'") + ), + NotOurs::Flaky(seen) => format!( + "* `{check}` has failed and then passed on the same commit of other pull \ + requests ({}).", + seen.join(", ") + ), + }); + } + if let Touch::Elsewhere(files) = touch { + lines.push(format!( + "* The failure names {}, which this pull request does not change.", + files + .iter() + .map(|f| format!("`{f}`")) + .collect::>() + .join(", ") + )); + } + let did = match rerun { + Rerun::Started if j.ours.is_empty() => { + "CoderHelm re-ran the failed jobs and changed no code for them." + } + Rerun::Started => { + "CoderHelm re-ran the failed jobs for these and fixes the others in code." + } + Rerun::NoPermission => { + "CoderHelm changed no code for them. It could not re-run them: its GitHub App has no \ + Actions write permission on this repository (Settings, GitHub App, Repository \ + permissions, Actions: Read and write)." + } + Rerun::NotActions => { + "CoderHelm changed no code for them. They run outside GitHub Actions, so it has no \ + way to start them again." + } + }; + format!( + "{START}\n**Red checks not caused by this change**\n{}\n\n{did}\n{END}", + lines.join("\n") + ) +} + +/// What the fix round is told when a check with a flaky record failed again +/// after its re-run: the record is evidence, the second failure is too. +pub fn fixer_note(j: &Judgement) -> String { + let flaky: Vec<&str> = j + .not_ours + .iter() + .filter(|(_, w)| matches!(w, NotOurs::Flaky(_))) + .map(|(c, _)| c.as_str()) + .collect(); + if flaky.is_empty() { + return String::new(); + } + format!( + "Note on {}: the repository's record shows it failing and then passing on one commit of \ + unrelated pull requests, and it failed here again after a re-run. Find what in THIS \ + change it depends on before changing anything; change only code the failure output \ + ties to this change, and never weaken, skip or delete the test.", + flaky.join(", ") + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn now() -> DateTime { + DateTime::parse_from_rfc3339("2026-03-10T12:00:00Z") + .unwrap() + .with_timezone(&Utc) + } + + fn seen(pr: u64, sha: &str, days_ago: i64) -> Observation { + Observation { + kind: Kind::PassedOnRerun, + at: (now() - Duration::days(days_ago)).to_rfc3339(), + pr, + sha: sha.to_string(), + line: String::new(), + } + } + + fn strings(v: &[&str]) -> Vec { + v.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn one_commit_is_one_observation() { + let mut r = Record::default(); + assert!(r.observe("e2e", seen(11, "aaaaaaa1", 1))); + assert!(!r.observe("e2e", seen(11, "aaaaaaa1", 0))); + assert_eq!(r.checks["e2e"].len(), 1); + assert!(!r.observe(" ", seen(11, "aaaaaaa1", 0))); + } + + #[test] + fn flaky_needs_other_pull_requests_inside_the_window() { + let mut r = Record::default(); + // This pull request's own history is not evidence about itself. + r.observe("e2e", seen(40, "s1", 1)); + r.observe("e2e", seen(40, "s2", 1)); + assert!(!r.known_flaky("e2e", 40, now())); + // One other pull request is not a record. + r.observe("e2e", seen(31, "s3", 2)); + assert!(!r.known_flaky("e2e", 40, now())); + // Old observations say nothing about today. + r.observe("e2e", seen(12, "s4", WINDOW_DAYS + 3)); + assert!(!r.known_flaky("e2e", 40, now())); + r.observe("e2e", seen(33, "s5", 5)); + assert!(r.known_flaky("e2e", 40, now())); + // An infrastructure failure is not a flaky test. + let mut infra = Record::default(); + for pr in [1, 2, 3] { + infra.observe( + "build", + Observation { + kind: Kind::Infra, + ..seen(pr, "s", 1) + }, + ); + } + assert!(!infra.known_flaky("build", 40, now())); + } + + #[test] + fn the_record_stays_bounded_and_round_trips() { + let mut r = Record::default(); + for i in 0..(MAX_OBSERVATIONS as u64 + 5) { + r.observe("e2e", seen(i, "s", 1)); + } + assert_eq!(r.checks["e2e"].len(), MAX_OBSERVATIONS); + assert_eq!(r.checks["e2e"][0].pr, 5); + assert_eq!(Record::from_json(&r.to_json()), r); + assert_eq!(Record::from_json("not json"), Record::default()); + } + + #[test] + fn paths_are_read_from_failure_output() { + let logs = "FAIL apps/web/src/cart/total.test.ts:41:7\n\ + at /home/runner/work/shop/shop/apps/web/src/cart/total.ts:12:3\n\ + error[E0308]: mismatched types --> services/api/src/price.rs:88:9\n\ + see https://example.com/docs/a.html and node_modules/x/y.js and total.ts"; + assert_eq!( + named_paths(logs), + strings(&[ + "apps/web/src/cart/total.test.ts", + "apps/web/src/cart/total.ts", + "services/api/src/price.rs" + ]) + ); + } + + #[test] + fn touch_matches_changed_files_at_directory_boundaries() { + let changed = strings(&["apps/web/src/cart/total.ts"]); + // A log printed relative to the package directory. + assert_eq!( + touch("FAIL src/cart/total.ts:3:1", &changed), + Touch::Changed(changed.clone()) + ); + // A file whose name merely ends alike is another file. + assert_eq!( + touch("FAIL src/cart/subtotal.ts:3:1", &changed), + Touch::Elsewhere(strings(&["src/cart/subtotal.ts"])) + ); + assert_eq!( + touch("Timeout of 30000ms exceeded", &changed), + Touch::Unknown + ); + } + + fn flaky_record() -> Record { + let mut r = Record::default(); + r.observe("e2e", seen(31, "abcdef1234", 2)); + r.observe("e2e", seen(33, "1234abcdef", 5)); + r + } + + #[test] + fn a_failure_naming_a_changed_file_is_the_changes_whatever_the_record_says() { + let j = judge( + &strings(&["e2e"]), + &[], + &Touch::Changed(strings(&["src/a.ts"])), + Some("ECONNRESET"), + &flaky_record(), + 40, + now(), + ); + assert_eq!(j.ours, strings(&["e2e"])); + assert!(!j.none_ours()); + } + + #[test] + fn a_known_flaky_check_that_names_no_changed_file_is_not_fixed_in_code() { + let j = judge( + &strings(&["e2e", "unit"]), + &strings(&["lint"]), + &Touch::Elsewhere(strings(&["tests/checkout.spec.ts"])), + None, + &flaky_record(), + 40, + now(), + ); + // `unit` has no record: a failure that names no changed file can + // still be caused by one. + assert_eq!(j.ours, strings(&["unit"])); + assert_eq!( + j.not_ours, + vec![( + "e2e".to_string(), + NotOurs::Flaky(strings(&["#31 at `abcdef1`", "#33 at `1234abc`"])) + )] + ); + let only = judge( + &strings(&["e2e", "lint"]), + &strings(&["lint"]), + &Touch::Unknown, + None, + &flaky_record(), + 40, + now(), + ); + assert!(only.none_ours()); + assert_eq!(only.not_ours[1], ("lint".to_string(), NotOurs::RedOnBase)); + } + + #[test] + fn the_section_names_each_check_its_evidence_and_what_was_done() { + let j = judge( + &strings(&["e2e", "lint"]), + &strings(&["lint"]), + &Touch::Elsewhere(strings(&["tests/checkout.spec.ts"])), + None, + &flaky_record(), + 40, + now(), + ); + let touch = Touch::Elsewhere(strings(&["tests/checkout.spec.ts"])); + let s = section(&j, "main", &Rerun::Started, &touch); + assert!(s.starts_with(START) && s.ends_with(END)); + assert!(s.contains("`e2e` has failed and then passed on the same commit of other pull requests (#31 at `abcdef1`, #33 at `1234abc`)")); + assert!(s.contains("`lint` also fails on the head of `main`")); + assert!(s.contains("`tests/checkout.spec.ts`, which this pull request does not change")); + assert!(s.contains("re-ran the failed jobs and changed no code")); + let refused = section(&j, "main", &Rerun::NoPermission, &touch); + assert!(refused.contains("no Actions write permission")); + assert!(refused.contains("changed no code")); + assert_eq!( + section(&Judgement::default(), "main", &Rerun::Started, &touch), + "" + ); + } + + #[test] + fn a_refused_rerun_is_told_from_a_failed_one() { + assert!(rerun_refused_for_permission( + "GitHub API 403: {\"message\":\"Resource not accessible by integration\"}" + )); + assert!(!rerun_refused_for_permission("GitHub API 502: bad gateway")); + assert!(!rerun_refused_for_permission( + "GitHub API 409: workflow run is already running" + )); + } +} diff --git a/services/common/src/guide.rs b/services/common/src/guide.rs new file mode 100644 index 000000000..147512e8f --- /dev/null +++ b/services/common/src/guide.rs @@ -0,0 +1,877 @@ +//! The repository's guide file, kept up by CoderHelm through pull requests. +//! +//! Every run reads the repository's guide (`AGENTS.md`, `CLAUDE.md` and the +//! others the worker's `INSTRUCTION_FILES` lists). When lessons CoderHelm +//! learned in a repository reach the confidence for it +//! (`rewards::lessons::guide_ready`), CoderHelm proposes them for that file +//! as a small pull request of its own ([`with_lessons`], [`pr_body`]), so +//! the team reviews what it learned like any other change. It never writes +//! to the default branch: the change is one commit on a new branch +//! ([`branch`]) and a pull request from it. +//! +//! It is rate limited by one record per repository ([`Record`], +//! `GUIDEPR#`): at most one guide pull request open at a time, +//! [`MIN_DAYS_BETWEEN`] after one merged, [`DECLINED_PAUSE_DAYS`] after one +//! the team closed without merging ([`may_propose`]). The record is claimed +//! before anything is written to GitHub, so two workers never open two. +//! +//! A team can turn guide pull requests off, for every repository or for one +//! ([`Switch`], `SETTINGS#GUIDE_PRS`; on unless turned off). Off, nothing is +//! written to the repository: no branch, no commit, no pull request. Lessons +//! still reach the prompt as before. The switch is read before anything is +//! claimed or created, and a switch that cannot be read counts as off. +//! +//! When the pull request closes ([`settle`]): lessons still in the merged +//! file are marked as in the guide (the run reads them there from then on +//! and they leave the prompt); lessons people took out before merging, and +//! every lesson of a pull request closed without merging, are declined: +//! never proposed again, and counted as contradicted once. + +use crate::rewards::lessons::{self, Lesson}; +use aws_sdk_dynamodb::types::AttributeValue; +use std::collections::HashMap; + +/// The guide files a lessons section may go in, first existing wins; with +/// none, [`DEFAULT_FILE`] is created. +pub const GUIDE_FILES: &[&str] = &[ + "AGENTS.md", + ".github/AGENTS.md", + "CLAUDE.md", + ".claude/CLAUDE.md", +]; +pub const DEFAULT_FILE: &str = "AGENTS.md"; + +pub const SECTION_HEADING: &str = "## Lessons from earlier pull requests"; +pub const SECTION_START: &str = ""; +pub const SECTION_END: &str = ""; +/// The head branch of every guide pull request starts with this. +pub const BRANCH_PREFIX: &str = "coderhelm/guide-lessons-"; +pub const RECORD_PREFIX: &str = "GUIDEPR#"; +/// The team's switch for guide pull requests. +pub const SETTINGS_SK: &str = "SETTINGS#GUIDE_PRS"; +/// The label every guide pull request carries. +pub const LABEL: &str = "coderhelm-lessons"; +/// Most per-repository overrides one team keeps. +pub const MAX_REPO_OVERRIDES: usize = 500; + +/// Most lessons proposed in one pull request: small enough to review. +pub const MAX_LESSONS_PER_PR: usize = 6; +/// Days after a merged guide pull request before the next one. +pub const MIN_DAYS_BETWEEN: i64 = 14; +/// Days after one the team closed without merging. +pub const DECLINED_PAUSE_DAYS: i64 = 60; +/// A claim whose pull request was never recorded (the worker stopped) is +/// free again after this. +pub const CLAIM_MINUTES: i64 = 60; +/// A proposal that failed at GitHub is tried again after this. +pub const RETRY_HOURS: i64 = 24; +/// Word overlap at which a guide line already says a lesson. +pub const SAID_AT: f64 = 0.6; +/// The guide file is never grown past this by a proposal. +pub const MAX_GUIDE_BYTES: usize = 64_000; + +pub const STATE_OPENING: &str = "opening"; +pub const STATE_OPEN: &str = "open"; +pub const STATE_MERGED: &str = "merged"; +pub const STATE_DECLINED: &str = "declined"; +pub const STATE_FAILED: &str = "failed"; + +pub fn record_sk(repo: &str) -> String { + format!("{RECORD_PREFIX}{repo}") +} + +/// Whether `head` is a guide pull request's branch. This only keeps guide +/// pull requests out of what is counted and scored as code work; which pull +/// request is the repository's guide pull request is the record's say. +pub fn is_guide_branch(head: &str) -> bool { + head.starts_with(BRANCH_PREFIX) +} + +/// The branch of a proposal made at `now`. +pub fn branch(now: chrono::DateTime) -> String { + format!("{BRANCH_PREFIX}{}", now.format("%Y%m%d-%H%M")) +} + +/// The repository's guide pull request, as last recorded. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Record { + pub repo: String, + pub state: String, + pub pr: u64, + pub branch: String, + /// The guide file the lessons went in. + pub path: String, + pub lesson_ids: Vec, + /// When the state was last set. + pub at: String, + /// Guide pull requests the team closed without merging, in a row. + pub declined_in_a_row: u64, +} + +/// Why no guide pull request is proposed now. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Hold { + /// One is open (or being opened): at most one per repository. + Open(u64), + /// The last one merged or was declined too recently; free again at + /// this time. + Until(String), +} + +/// Pure: may a guide pull request be proposed for the repository now? +pub fn may_propose(r: Option<&Record>, now: chrono::DateTime) -> Result<(), Hold> { + let Some(r) = r else { + return Ok(()); + }; + let at = chrono::DateTime::parse_from_rfc3339(&r.at) + .map(|t| t.with_timezone(&chrono::Utc)) + .unwrap_or(now); + let wait = match r.state.as_str() { + STATE_OPEN => return Err(Hold::Open(r.pr)), + STATE_OPENING => chrono::Duration::minutes(CLAIM_MINUTES), + STATE_MERGED => chrono::Duration::days(MIN_DAYS_BETWEEN), + // Each decline in a row doubles the pause: a team that keeps + // closing them is asked less and less. + STATE_DECLINED => chrono::Duration::days( + DECLINED_PAUSE_DAYS * (1i64 << r.declined_in_a_row.clamp(1, 4).saturating_sub(1)), + ), + STATE_FAILED => chrono::Duration::hours(RETRY_HOURS), + _ => return Ok(()), + }; + let free = at + wait; + if now >= free { + Ok(()) + } else if r.state == STATE_OPENING { + Err(Hold::Open(0)) + } else { + Err(Hold::Until(free.to_rfc3339())) + } +} + +/// A lesson as one line of the guide's section. +pub fn lesson_line(l: &Lesson) -> String { + let one_line = |s: &str| s.split_whitespace().collect::>().join(" "); + let scope = if l.applies_to.trim().is_empty() { + String::new() + } else { + format!("In `{}`: ", l.applies_to.trim().trim_matches('`')) + }; + let check = if l.check.trim().is_empty() { + String::new() + } else { + format!(" Check: {}", one_line(&l.check)) + }; + format!("- {scope}{}{check}", one_line(&l.text)) +} + +/// The lines of the guide's lessons section (without the leading `- `). +pub fn section_lines(content: &str) -> Vec { + let Some(start) = content.find(SECTION_START) else { + return vec![]; + }; + let rest = &content[start + SECTION_START.len()..]; + let section = &rest[..rest.find(SECTION_END).unwrap_or(rest.len())]; + section + .lines() + .map(str::trim) + .filter_map(|l| l.strip_prefix("- ").or_else(|| l.strip_prefix("* "))) + .map(|l| l.trim().to_string()) + .filter(|l| !l.is_empty()) + .collect() +} + +/// Whether the guide already says the lesson: in its lessons section, or +/// in any other line of the file people wrote themselves. +pub fn already_said(content: &str, l: &Lesson) -> bool { + content + .lines() + .map(|line| line.trim().trim_start_matches(['-', '*', ' '])) + .filter(|line| line.len() >= 20) + .any(|line| lessons::similarity(line, &l.text) >= SAID_AT) +} + +/// Pure: the lessons to propose now: ready for the guide, not said in it +/// already, heaviest first, at most [`MAX_LESSONS_PER_PR`]. +pub fn pick(kept: &[Lesson], guide: &str, now: chrono::DateTime) -> Vec { + let mut ready: Vec<(f64, &Lesson)> = kept + .iter() + .filter(|l| lessons::guide_ready(l, now) && !already_said(guide, l)) + .map(|l| (lessons::weight_of(l, now), l)) + .collect(); + ready.sort_by(|a, b| { + b.0.partial_cmp(&a.0) + .unwrap_or(std::cmp::Ordering::Equal) + .then(a.1.id.cmp(&b.1.id)) + }); + ready + .into_iter() + .take(MAX_LESSONS_PER_PR) + .map(|(_, l)| l.clone()) + .collect() +} + +/// Pure: the guide file with the lessons added to its section (made at the +/// end of the file when there is none). Everything people wrote stays as it +/// is. None when the result would pass [`MAX_GUIDE_BYTES`]. +pub fn with_lessons(content: &str, add: &[Lesson]) -> Option { + let lines: Vec = add.iter().map(lesson_line).collect(); + if lines.is_empty() { + return None; + } + let block = lines.join("\n"); + let out = match (content.find(SECTION_START), content.find(SECTION_END)) { + (Some(a), Some(b)) if a < b => { + let head = content[..b].trim_end(); + format!("{head}\n{block}\n{}", &content[b..]) + } + _ => { + let head = content.trim_end(); + let gap = if head.is_empty() { "" } else { "\n\n" }; + let title = if head.is_empty() { + "# Working on this repository\n\n" + } else { + "" + }; + format!( + "{head}{gap}{title}{SECTION_HEADING}\n\nWhat CoderHelm learned from what happened to its pull requests here. Edit or remove any line; CoderHelm follows the file as it is.\n\n{SECTION_START}\n{block}\n{SECTION_END}\n" + ) + } + }; + (out.len() <= MAX_GUIDE_BYTES).then_some(out) +} + +/// The title says where the pull request comes from before anything else. +pub fn pr_title(n: usize) -> String { + if n == 1 { + "CoderHelm lessons: one for the guide file".to_string() + } else { + format!("CoderHelm lessons: {n} for the guide file") + } +} + +/// Whether guide pull requests are on: for the team, and per repository +/// where the team set one apart. On unless turned off. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Switch { + pub enabled: bool, + /// `owner/name` to on or off, for repositories set apart from the team. + pub repos: std::collections::BTreeMap, +} + +impl Default for Switch { + fn default() -> Self { + Switch { + enabled: true, + repos: Default::default(), + } + } +} + +impl Switch { + /// Whether a guide pull request may be opened in `repo`: the + /// repository's own setting when it has one, else the team's. + pub fn allows(&self, repo: &str) -> bool { + self.repos.get(repo).copied().unwrap_or(self.enabled) + } + + /// From the body of a save: `{"enabled": bool, "repos": {"owner/name": + /// bool}}`. An error says what to change. + pub fn parse(body: &serde_json::Value) -> Result { + let enabled = body["enabled"] + .as_bool() + .ok_or("`enabled` must be true or false.")?; + let mut repos = std::collections::BTreeMap::new(); + match &body["repos"] { + serde_json::Value::Null => {} + serde_json::Value::Object(m) => { + if m.len() > MAX_REPO_OVERRIDES { + return Err(format!( + "At most {MAX_REPO_OVERRIDES} repositories can be set apart." + )); + } + for (repo, on) in m { + let valid = crate::review_lessons::valid_scope(repo) + && repo != crate::review_lessons::TEAM_SCOPE; + match (valid, on.as_bool()) { + (true, Some(on)) => { + repos.insert(repo.clone(), on); + } + (false, _) => return Err(format!("`{repo}` is not `owner/name`.")), + (_, None) => return Err(format!("`{repo}` must be set to true or false.")), + } + } + } + _ => return Err("`repos` must map `owner/name` to true or false.".into()), + } + Ok(Switch { enabled, repos }) + } + + pub fn view(&self) -> serde_json::Value { + serde_json::json!({ "enabled": self.enabled, "repos": self.repos }) + } + + pub fn to_item(&self, team: &str, now: &str, by: &str) -> Item { + Item::from([ + ("pk".to_string(), s(team)), + ("sk".to_string(), s(SETTINGS_SK)), + ("record_type".to_string(), s("guide_pr_switch")), + ("enabled".to_string(), AttributeValue::Bool(self.enabled)), + ( + "repos".to_string(), + AttributeValue::M( + self.repos + .iter() + .map(|(r, on)| (r.clone(), AttributeValue::Bool(*on))) + .collect(), + ), + ), + ("updated_at".to_string(), s(now)), + ("updated_by".to_string(), s(by)), + ]) + } + + /// From the stored item; no item, or one without a field, is the + /// default (on). + pub fn from_item(i: Option<&Item>) -> Switch { + let Some(i) = i else { + return Switch::default(); + }; + Switch { + enabled: i + .get("enabled") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(true), + repos: i + .get("repos") + .and_then(|v| v.as_m().ok()) + .map(|m| { + m.iter() + .filter_map(|(r, on)| Some((r.clone(), *on.as_bool().ok()?))) + .collect() + }) + .unwrap_or_default(), + } + } +} + +/// The team's switch. An error is the caller's to treat as off. +pub async fn load_switch( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team: &str, +) -> Result { + dynamo + .get_item() + .table_name(table) + .key("pk", s(team)) + .key("sk", s(SETTINGS_SK)) + .consistent_read(true) + .send() + .await + .map(|r| Switch::from_item(r.item.as_ref())) + .map_err(|e| aws_sdk_dynamodb::error::DisplayErrorContext(e).to_string()) +} + +pub async fn save_switch( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team: &str, + switch: &Switch, + by: &str, +) -> Result<(), String> { + dynamo + .put_item() + .table_name(table) + .set_item(Some(switch.to_item( + team, + &chrono::Utc::now().to_rfc3339(), + by, + ))) + .send() + .await + .map(|_| ()) + .map_err(|e| aws_sdk_dynamodb::error::DisplayErrorContext(e).to_string()) +} + +/// The pull request's description: each lesson with the pull requests and +/// the evidence behind it. +pub fn pr_body(path: &str, repo: &str, add: &[Lesson]) -> String { + let mut out = format!( + "**This pull request comes from CoderHelm's lessons, not from a ticket.** It changes \ + only `{path}`, the guide file I read at the start of every run, and adds what I learned \ + from earlier pull requests in this repository. Each lesson is below with what it came \ + from. Edit the wording, remove a line you disagree with, or close this without merging: \ + I follow the file as merged, drop what you take out, and do not propose a declined \ + lesson again. An admin can turn these pull requests off, for this repository or for \ + every one, on the Learning page in CoderHelm.\n" + ); + for l in add { + out.push_str(&format!( + "\n### {}\n", + crate::truncate_str(l.text.trim(), 200) + )); + if !l.check.trim().is_empty() { + out.push_str(&format!("Check: {}\n", l.check.trim())); + } + let prs: Vec = l + .prs + .iter() + .filter_map(|p| p.strip_prefix(&format!("{repo}#"))) + .map(|n| format!("#{n}")) + .collect(); + if !prs.is_empty() { + out.push_str(&format!("\nFrom {}.\n", prs.join(", "))); + } + for e in l.evidence.iter().take(4) { + out.push_str(&format!("- {}\n", crate::truncate_str(e.trim(), 300))); + } + } + out +} + +/// What became of the lessons a guide pull request proposed. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Settled { + /// Still in the merged file. + pub kept: Vec, + /// Taken out before merging, or the pull request was closed. + pub declined: Vec, +} + +/// Pure: sorts a closed guide pull request's lessons. `merged_guide` is the +/// guide file on the default branch after the merge; None when the pull +/// request was closed without merging. +pub fn settle(proposed: &[Lesson], merged_guide: Option<&str>) -> Settled { + let mut out = Settled::default(); + let lines = merged_guide.map(section_lines).unwrap_or_default(); + for l in proposed { + let line = lesson_line(l); + let line = line.trim_start_matches("- "); + // People may reword a line: it is still the lesson while most of + // its words are there. + let still = lines + .iter() + .any(|kept| kept == line || lessons::similarity(kept, line) >= SAID_AT); + if merged_guide.is_some() && still { + out.kept.push(l.id.clone()); + } else { + out.declined.push(l.id.clone()); + } + } + out +} + +// ── The record ─────────────────────────────────────────────────────── + +type Item = HashMap; + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +fn gs(i: &Item, k: &str) -> String { + i.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() +} + +fn gu(i: &Item, k: &str) -> u64 { + i.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse().ok()) + .unwrap_or(0) +} + +impl Record { + pub fn to_item(&self, team: &str) -> Item { + Item::from([ + ("pk".to_string(), s(team)), + ("sk".to_string(), s(&record_sk(&self.repo))), + ("record_type".to_string(), s("guide_pr")), + ("repo".to_string(), s(&self.repo)), + ("state".to_string(), s(&self.state)), + ("pr".to_string(), AttributeValue::N(self.pr.to_string())), + ("branch".to_string(), s(&self.branch)), + ("path".to_string(), s(&self.path)), + ( + "lesson_ids".to_string(), + AttributeValue::L(self.lesson_ids.iter().map(|l| s(l)).collect()), + ), + ("at".to_string(), s(&self.at)), + ( + "declined_in_a_row".to_string(), + AttributeValue::N(self.declined_in_a_row.to_string()), + ), + ]) + } + + pub fn from_item(i: &Item) -> Option { + if !gs(i, "sk").starts_with(RECORD_PREFIX) { + return None; + } + Some(Record { + repo: gs(i, "repo"), + state: gs(i, "state"), + pr: gu(i, "pr"), + branch: gs(i, "branch"), + path: gs(i, "path"), + lesson_ids: i + .get("lesson_ids") + .and_then(|v| v.as_l().ok()) + .map(|l| l.iter().filter_map(|v| v.as_s().ok().cloned()).collect()) + .unwrap_or_default(), + at: gs(i, "at"), + declined_in_a_row: gu(i, "declined_in_a_row"), + }) + } +} + +pub async fn load( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team: &str, + repo: &str, +) -> Result, String> { + dynamo + .get_item() + .table_name(table) + .key("pk", s(team)) + .key("sk", s(&record_sk(repo))) + .consistent_read(true) + .send() + .await + .map(|r| r.item.as_ref().and_then(Record::from_item)) + .map_err(|e| aws_sdk_dynamodb::error::DisplayErrorContext(e).to_string()) +} + +/// Writes `next` only when the stored record is still `prev` (by its state +/// and time; None: there is none). False when another worker changed it +/// first: then this one does nothing. +pub async fn swap( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team: &str, + prev: Option<&Record>, + next: &Record, +) -> Result { + let mut put = dynamo + .put_item() + .table_name(table) + .set_item(Some(next.to_item(team))); + put = match prev { + None => put.condition_expression("attribute_not_exists(sk)"), + Some(p) => put + .condition_expression("#st = :st AND #at = :at") + .expression_attribute_names("#st", "state") + .expression_attribute_names("#at", "at") + .expression_attribute_values(":st", s(&p.state)) + .expression_attribute_values(":at", s(&p.at)), + }; + match put.send().await { + Ok(_) => Ok(true), + Err(e) => { + let msg = aws_sdk_dynamodb::error::DisplayErrorContext(&e).to_string(); + if msg.contains("ConditionalCheckFailed") { + Ok(false) + } else { + Err(msg) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::TimeZone; + + fn now() -> chrono::DateTime { + chrono::Utc + .with_ymd_and_hms(2026, 10, 20, 9, 30, 0) + .unwrap() + } + + fn lesson(id: &str, text: &str, check: &str, prs: &[&str]) -> Lesson { + Lesson { + id: id.into(), + repo: "acme/web".into(), + agent: "coder".into(), + text: text.into(), + check: check.into(), + seen: prs.len() as u64, + prs: prs.iter().map(|p| p.to_string()).collect(), + created_at: "2026-10-01T00:00:00Z".into(), + last_seen_at: "2026-10-19T00:00:00Z".into(), + evidence: vec![ + "PR #12: people changed `apps/web/src/api.ts` (\"Use the shared client\")".into(), + ], + ..Default::default() + } + } + + fn hook() -> Lesson { + lesson( + "L1", + "Fetch through the shared `useApi` hook, never with a bare `fetch` call.", + "No `fetch(` in the diff under `apps/web/src`.", + &["acme/web#12", "acme/web#15"], + ) + } + + fn migrations() -> Lesson { + let mut l = lesson( + "L2", + "Name migration files `NNNN_what.sql`.", + "The new file starts with four digits.", + &["acme/web#3", "acme/web#5", "acme/web#8"], + ); + l.applies_to = "db/migrations".into(); + l + } + + fn record(state: &str, at: &str) -> Record { + Record { + repo: "acme/web".into(), + state: state.into(), + pr: 40, + at: at.into(), + ..Default::default() + } + } + + #[test] + fn at_most_one_guide_pull_request_is_open_per_repository() { + assert_eq!(may_propose(None, now()), Ok(())); + assert_eq!( + may_propose(Some(&record(STATE_OPEN, "2026-01-01T00:00:00Z")), now()), + Err(Hold::Open(40)), + "an open one holds however old it is" + ); + // Being opened by another worker right now. + assert_eq!( + may_propose(Some(&record(STATE_OPENING, "2026-10-20T09:00:00Z")), now()), + Err(Hold::Open(0)) + ); + // A claim nobody finished is free again after an hour. + assert_eq!( + may_propose(Some(&record(STATE_OPENING, "2026-10-20T08:00:00Z")), now()), + Ok(()) + ); + } + + #[test] + fn a_merged_or_declined_one_is_followed_by_a_pause() { + assert!(matches!( + may_propose(Some(&record(STATE_MERGED, "2026-10-10T00:00:00Z")), now()), + Err(Hold::Until(_)) + )); + assert_eq!( + may_propose(Some(&record(STATE_MERGED, "2026-10-01T00:00:00Z")), now()), + Ok(()) + ); + let mut declined = record(STATE_DECLINED, "2026-09-01T00:00:00Z"); + declined.declined_in_a_row = 1; + assert!(matches!( + may_propose(Some(&declined), now()), + Err(Hold::Until(_)) + )); + declined.at = "2026-08-01T00:00:00Z".into(); + assert_eq!(may_propose(Some(&declined), now()), Ok(())); + // Declined twice in a row: twice the pause. + declined.declined_in_a_row = 2; + assert!(matches!( + may_propose(Some(&declined), now()), + Err(Hold::Until(_)) + )); + // A failure at GitHub is retried the next day. + assert!(may_propose(Some(&record(STATE_FAILED, "2026-10-20T00:00:00Z")), now()).is_err()); + assert_eq!( + may_propose(Some(&record(STATE_FAILED, "2026-10-19T00:00:00Z")), now()), + Ok(()) + ); + } + + #[test] + fn the_section_is_added_once_and_peoples_text_is_left_alone() { + let before = "# Working on shop\n\nRun `make test` before a commit.\n"; + let after = with_lessons(before, &[hook()]).unwrap(); + assert!(after.starts_with(before.trim_end())); + assert!(after.contains(SECTION_HEADING)); + assert_eq!( + section_lines(&after), + vec!["Fetch through the shared `useApi` hook, never with a bare `fetch` call. Check: No `fetch(` in the diff under `apps/web/src`."] + ); + // A second proposal goes in the same section, after the first. + let again = with_lessons(&after, &[migrations()]).unwrap(); + assert_eq!(again.matches(SECTION_START).count(), 1); + assert_eq!(again.matches(SECTION_HEADING).count(), 1); + let lines = section_lines(&again); + assert_eq!(lines.len(), 2); + assert!(lines[1].starts_with("In `db/migrations`: Name migration files")); + assert!(again.trim_end().ends_with(SECTION_END)); + // No guide file yet: one is started. + let fresh = with_lessons("", &[hook()]).unwrap(); + assert!(fresh.starts_with("# Working on this repository")); + assert_eq!(with_lessons(before, &[]), None); + // Never grown without bound. + assert_eq!(with_lessons(&"x".repeat(MAX_GUIDE_BYTES), &[hook()]), None); + } + + #[test] + fn only_confident_lessons_the_guide_does_not_say_are_proposed() { + let once = lesson( + "L3", + "Use `zod` for request bodies.", + "Each handler parses with `zod`.", + &["acme/web#9"], + ); + let mut contradicted = migrations(); + contradicted.id = "L4".into(); + contradicted.text = "Keep feature flags in `flags.ts`.".into(); + contradicted.contradicted = 1; + let kept = vec![hook(), once, contradicted, migrations()]; + let picked: Vec = pick(&kept, "", now()).into_iter().map(|l| l.id).collect(); + assert_eq!( + picked, + vec!["L2", "L1"], + "heaviest first, only the ready ones" + ); + // People already wrote it in the guide themselves: not proposed. + let guide = "## Conventions\n- Always fetch through the shared `useApi` hook; never a bare `fetch` call.\n"; + let picked: Vec = pick(&kept, guide, now()) + .into_iter() + .map(|l| l.id) + .collect(); + assert_eq!(picked, vec!["L2"]); + // At most a reviewable handful. + let many: Vec = (0..10) + .map(|i| { + lesson( + &format!("M{i}"), + &format!("Rule number{i} about `thing{i}` in module{i}."), + "A check to run here.", + &["acme/web#1", "acme/web#2"], + ) + }) + .collect(); + assert_eq!(pick(&many, "", now()).len(), MAX_LESSONS_PER_PR); + } + + #[test] + fn the_description_names_the_evidence_behind_each_lesson() { + let body = pr_body("AGENTS.md", "acme/web", &[hook()]); + assert!(body.contains("`AGENTS.md`")); + assert!(body.contains("### Fetch through the shared `useApi` hook")); + assert!(body.contains("From #12, #15.")); + assert!(body.contains("Use the shared client")); + assert!(body.contains("close this without merging")); + assert!(body.starts_with("**This pull request comes from CoderHelm's lessons")); + assert!(body.contains("An admin can turn these pull requests off")); + assert_eq!(pr_title(1), "CoderHelm lessons: one for the guide file"); + assert_eq!(pr_title(3), "CoderHelm lessons: 3 for the guide file"); + assert!(is_guide_branch(&branch(now()))); + assert_eq!(branch(now()), "coderhelm/guide-lessons-20261020-0930"); + assert!(!is_guide_branch("coderhelm/abc-1")); + } + + #[test] + fn a_closed_guide_pull_request_settles_each_lesson() { + let proposed = vec![hook(), migrations()]; + // Closed without merging: the team declined them all. + let s = settle(&proposed, None); + assert_eq!(s.declined, vec!["L1", "L2"]); + assert!(s.kept.is_empty()); + // Merged as proposed. + let merged = with_lessons("# Guide\n", &proposed).unwrap(); + let s = settle(&proposed, Some(&merged)); + assert_eq!(s.kept, vec!["L1", "L2"]); + // Merged after people reworded one line and removed the other. + let edited = merged + .replace( + "never with a bare `fetch` call.", + "not a bare `fetch` call.", + ) + .lines() + .filter(|l| !l.contains("migration")) + .collect::>() + .join("\n"); + let s = settle(&proposed, Some(&edited)); + assert_eq!(s.kept, vec!["L1"]); + assert_eq!(s.declined, vec!["L2"]); + // Merged, but the section was removed from the file altogether. + let s = settle(&proposed, Some("# Guide\n")); + assert_eq!(s.declined, vec!["L1", "L2"]); + } + + #[test] + fn guide_pull_requests_are_on_unless_turned_off_and_a_repository_can_differ() { + // Nothing saved: on everywhere. + let none = Switch::from_item(None); + assert_eq!(none, Switch::default()); + assert!(none.allows("acme/web")); + // Off for the team, on for one repository. + let off = Switch::parse(&serde_json::json!({ + "enabled": false, + "repos": {"acme/web": true} + })) + .unwrap(); + assert!(!off.allows("acme/api")); + assert!(off.allows("acme/web")); + // On for the team, off for one repository. + let on = Switch::parse(&serde_json::json!({ + "enabled": true, + "repos": {"acme/api": false} + })) + .unwrap(); + assert!(on.allows("acme/web")); + assert!(!on.allows("acme/api")); + // It round trips through its item, under the team's key. + let item = off.to_item("TEAM#a", "2026-10-20T00:00:00Z", "an admin"); + assert_eq!(item["sk"], s(SETTINGS_SK)); + assert_eq!(item["pk"], s("TEAM#a")); + assert_eq!(Switch::from_item(Some(&item)), off); + assert_eq!(off.view()["repos"]["acme/web"], true); + // An item from before a field existed reads as on. + assert!(Switch::from_item(Some(&Item::new())).allows("acme/web")); + // A save names what is wrong. + let bad = |v: serde_json::Value| Switch::parse(&v).unwrap_err(); + assert!(bad(serde_json::json!({})).contains("`enabled`")); + assert!( + bad(serde_json::json!({"enabled": true, "repos": {"acme": true}})) + .contains("not `owner/name`") + ); + assert!( + bad(serde_json::json!({"enabled": true, "repos": {"*": true}})) + .contains("not `owner/name`") + ); + assert!( + bad(serde_json::json!({"enabled": true, "repos": {"acme/web": "no"}})) + .contains("true or false") + ); + assert!(bad(serde_json::json!({"enabled": true, "repos": []})).contains("`repos`")); + assert!(Switch::parse(&serde_json::json!({"enabled": true})) + .unwrap() + .repos + .is_empty()); + } + + #[test] + fn the_record_round_trips() { + let r = Record { + repo: "acme/web".into(), + state: STATE_OPEN.into(), + pr: 40, + branch: branch(now()), + path: "AGENTS.md".into(), + lesson_ids: vec!["L1".into(), "L2".into()], + at: now().to_rfc3339(), + declined_in_a_row: 1, + }; + let item = r.to_item("TEAM#a"); + assert_eq!(item["sk"], s("GUIDEPR#acme/web")); + assert_eq!(Record::from_item(&item), Some(r)); + assert_eq!(Record::from_item(&Item::new()), None); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 77e2dad8a..7a8f53f26 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -119,6 +119,9 @@ pub mod memory_meta; /// The auto-merge gate's per-PR record: keys and states (the worker runs the /// gate, the gateway re-arms it on GitHub events). pub mod merge_gate; +/// Where a finished run's pull request stands on its way to merge, in the +/// one reason that is true. +pub mod merge_standing; /// Every message on the worker queues: one enum the gateway and worker share. pub mod messages; /// Retrying model API calls on transient failures, classified by status. @@ -153,6 +156,11 @@ pub mod run_prs; // review_stats: time-ordered review records for analytics pub mod decision_log; pub mod deploy_stats; +/// Flaky or broken: whose failure a red check is, and the repository's +/// record of checks that failed and then passed on one commit. +pub mod flaky_checks; +/// Lessons the reviewer learns from people's pushback on its findings. +pub mod guide; /// Run statuses; which ones a person set; closing and reopening a run. pub mod handback; /// Work CoderHelm started on its own pull request and hasn't landed, and @@ -177,7 +185,6 @@ pub mod requester; pub mod review_activity; /// The PR's "CoderHelm review" check run, from scheduled to finished. pub mod review_check; -/// Lessons the reviewer learns from people's pushback on its findings. pub mod review_lessons; /// Where the reviewer is with each PR right now (queued, reviewing, retrying, /// done), and the one status a PR shows on the dashboard. @@ -186,6 +193,7 @@ pub mod review_live; pub mod review_overview; pub mod review_session; pub mod review_stats; +pub mod reviewer_prefs; /// Learning from outcomes: reward events, scores, calibration, variants, /// examples and evidence-backed lessons, per team. pub mod rewards; @@ -204,6 +212,7 @@ pub mod run_wait; /// what to run (found in its CI and manifests), the sandbox script, and what /// the bumps are blamed for. pub mod runtime_proof; +pub mod scorecard; #[cfg(test)] mod selfhost_links; pub mod skill_apply; diff --git a/services/common/src/merge_standing.rs b/services/common/src/merge_standing.rs new file mode 100644 index 000000000..e72a2efa8 --- /dev/null +++ b/services/common/src/merge_standing.rs @@ -0,0 +1,395 @@ +//! Where a finished run's pull request stands on its way to merge, in the +//! one reason that is true. +//! +//! A run page once said "Needs a person" and "merging is your team's call" +//! for every finished run with an open pull request, whatever held the +//! merge: auto-merge being off, the repository asking for a person's +//! approval, CoderHelm's own review still asking for changes, or nothing at +//! all. A person is needed only for what only a person can give, and then +//! the page says exactly which thing that is and where it is set. +//! +//! [`decide`] reads the facts in the order they hold the merge and returns +//! one [`Standing`]: its code (stable, for the dashboard and analytics), the +//! sentence shown, whether a person has to act, and the setting it comes +//! from when it comes from a setting. The worker writes it on the run +//! record ([`FIELD`]) whenever it looks at the pull request. + +use serde::{Deserialize, Serialize}; + +/// The run record's field holding the standing, as JSON. +pub const FIELD: &str = "merge_standing"; + +/// What the worker knows about the pull request and the repository's rules. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Facts { + pub merged: bool, + pub closed: bool, + pub draft: bool, + /// The pull request's head commit. + pub head: String, + /// CoderHelm's reviewer is on for the repository. + pub reviewer_on: bool, + /// CoderHelm's latest review verdict and the commit it is on. + pub own_verdict: Option<(String, String)>, + /// A fix round or a review of the head is queued or running. + pub working: bool, + /// Checks failing on the head (names), and whether any still runs. + pub failing: Vec, + pub checks_running: bool, + /// The pull request conflicts with its base. + pub conflict: bool, + /// The repository's auto-merge setting, and whether it asks for a + /// person's approval before CoderHelm merges. + pub auto_merge: bool, + pub require_human_approval: bool, + /// A person approved the head. + pub human_approved: bool, + /// GitHub reports the merge blocked by the branch's rules although the + /// checks are green (`mergeable_state` = `blocked`). + pub blocked_by_rules: bool, +} + +/// One standing, as shown. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Standing { + /// Stable code: `merged`, `closed`, `reviewing`, `fixing_review`, + /// `review_changes_requested`, `checks_running`, `checks_failing`, + /// `conflict`, `draft`, `auto_merge_off`, `needs_person_approval`, + /// `repo_requires_person_review`, `merging`. + pub code: String, + /// What is true now, one sentence. + pub text: String, + /// What happens next, one sentence. + pub next: String, + /// A person has to act for the merge to happen. + pub needs_person: bool, + /// Where the rule is set, when it is a setting (a dashboard path, or a + /// GitHub URL); empty otherwise. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub link: String, +} + +impl Standing { + fn new(code: &str, text: String, next: &str, needs_person: bool, link: String) -> Standing { + Standing { + code: code.to_string(), + text, + next: next.to_string(), + needs_person, + link, + } + } + + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_default() + } + + pub fn from_json(s: &str) -> Option { + serde_json::from_str(s).ok() + } +} + +fn short(sha: &str) -> &str { + sha.get(..7).unwrap_or(sha) +} + +/// The dashboard page where a repository's reviewer and auto-merge are set. +pub fn settings_path(_repo: &str) -> String { + "/reviewer/config".to_string() +} + +/// GitHub's page for a repository's branch rules. +pub fn branch_rules_url(repo: &str) -> String { + format!("https://github.com/{repo}/settings/branches") +} + +/// The standing of `repo`'s pull request, from the facts, first holder +/// first. CoderHelm's own work (a review of the head, a fix round, checks) +/// never asks for a person; only the team's own rules do. +pub fn decide(repo: &str, f: &Facts) -> Standing { + let none = String::new; + if f.merged { + return Standing::new( + "merged", + "The pull request is merged.".into(), + "CoderHelm watches the deploy of the merge commit.", + false, + none(), + ); + } + if f.closed { + return Standing::new( + "closed", + "The pull request was closed without merging.".into(), + "Nothing further runs on it.", + false, + none(), + ); + } + if f.conflict { + return Standing::new( + "conflict", + "The pull request conflicts with its base branch.".into(), + "CoderHelm merges the base branch in and resolves the conflict.", + false, + none(), + ); + } + if !f.failing.is_empty() && !f.checks_running { + return Standing::new( + "checks_failing", + format!( + "Checks fail on `{}`: {}.", + short(&f.head), + f.failing + .iter() + .take(4) + .cloned() + .collect::>() + .join(", ") + ), + "CoderHelm fixes them, or says on the pull request why they are not this change's.", + false, + none(), + ); + } + if f.reviewer_on { + match &f.own_verdict { + Some((verdict, sha)) if sha == &f.head && verdict == "APPROVE" => {} + Some((verdict, sha)) if sha == &f.head && verdict == "REQUEST_CHANGES" => { + return if f.working { + Standing::new( + "fixing_review", + format!( + "CoderHelm's review asked for changes on `{}` and a fix round is \ + taking them.", + short(sha) + ), + "The fix is pushed and the new head is reviewed.", + false, + none(), + ) + } else { + Standing::new( + "review_changes_requested", + format!( + "CoderHelm's review asks for changes on `{}`; what it could not fix \ + is listed as deferred on the pull request.", + short(sha) + ), + "CoderHelm does not merge over its own review; the deferred findings \ + say what each needs.", + false, + none(), + ) + }; + } + // No verdict, or one on an older commit: never shown as the + // verdict on this head. + other => { + let was = other + .as_ref() + .map(|(_, sha)| format!(" (its last review was of `{}`)", short(sha))) + .unwrap_or_default(); + return Standing::new( + "reviewing", + format!("CoderHelm is reviewing the head `{}`{was}.", short(&f.head)), + "Its verdict on this commit decides what follows: a fix round, or the merge.", + false, + none(), + ); + } + } + } + if f.checks_running { + return Standing::new( + "checks_running", + format!("Checks are still running on `{}`.", short(&f.head)), + "CoderHelm reads their result when they finish.", + false, + none(), + ); + } + if f.draft { + return Standing::new( + "draft", + "The pull request is still a draft; its description says why at the top.".into(), + "CoderHelm marks it ready once what holds it is settled.", + false, + none(), + ); + } + if !f.auto_merge { + return Standing::new( + "auto_merge_off", + "Auto-merge is off for this repo, so CoderHelm leaves the merge to your team.".into(), + "Merge it, or turn auto-merge on and CoderHelm merges approved pull requests itself.", + true, + settings_path(repo), + ); + } + if f.require_human_approval && !f.human_approved { + return Standing::new( + "needs_person_approval", + "This repo's auto-merge setting requires an approving review from a person before \ + CoderHelm merges." + .into(), + "Once a person approves this commit, CoderHelm merges it and follows the deploy.", + true, + settings_path(repo), + ); + } + if f.blocked_by_rules { + return Standing::new( + "repo_requires_person_review", + "Your repo's branch rules block the merge: they require an approving review from a \ + person (or another rule GitHub enforces on this branch)." + .into(), + "Once the branch's rules are met, CoderHelm merges it and follows the deploy.", + true, + branch_rules_url(repo), + ); + } + Standing::new( + "merging", + "Approved, checks green, and the repo's rules allow it: CoderHelm merges it.".into(), + "After the merge CoderHelm watches the deploy of the merge commit.", + false, + none(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + const HEAD: &str = "9f8e7d6c5b4a39281706f5e4d3c2b1a098765432"; + const OLD: &str = "1111111aaaaaaa2222222bbbbbbb3333333ccccc"; + + /// Everything in place for CoderHelm to merge on its own. + fn clear() -> Facts { + Facts { + head: HEAD.into(), + reviewer_on: true, + own_verdict: Some(("APPROVE".into(), HEAD.into())), + auto_merge: true, + require_human_approval: false, + ..Default::default() + } + } + + #[test] + fn approved_green_and_allowed_merges_with_nobody_asked() { + let s = decide("acme/shop", &clear()); + assert_eq!(s.code, "merging"); + assert!(!s.needs_person); + assert!(s.next.contains("watches the deploy")); + } + + #[test] + fn a_verdict_on_an_older_commit_is_never_the_standing_verdict() { + let mut f = clear(); + f.own_verdict = Some(("REQUEST_CHANGES".into(), OLD.into())); + let s = decide("acme/shop", &f); + assert_eq!(s.code, "reviewing"); + assert!(!s.needs_person, "a review of the head is CoderHelm's work"); + assert!( + s.text.contains("`9f8e7d6`") && s.text.contains("its last review was of `1111111`") + ); + assert!(!s.text.to_lowercase().contains("changes requested")); + f.own_verdict = None; + assert_eq!(decide("acme/shop", &f).code, "reviewing"); + } + + #[test] + fn changes_requested_on_the_head_is_coderhelms_to_fix() { + let mut f = clear(); + f.own_verdict = Some(("REQUEST_CHANGES".into(), HEAD.into())); + f.working = true; + let s = decide("acme/shop", &f); + assert_eq!(s.code, "fixing_review"); + assert!(!s.needs_person); + f.working = false; + let s = decide("acme/shop", &f); + assert_eq!(s.code, "review_changes_requested"); + assert!(!s.needs_person); + assert!(s.text.contains("deferred")); + } + + #[test] + fn a_person_is_asked_only_for_the_teams_own_rule_and_the_rule_is_named() { + let mut off = clear(); + off.auto_merge = false; + let s = decide("acme/shop", &off); + assert_eq!(s.code, "auto_merge_off"); + assert!(s.needs_person); + assert!(s.text.starts_with("Auto-merge is off for this repo")); + assert_eq!(s.link, "/reviewer/config"); + + let mut key = clear(); + key.require_human_approval = true; + let s = decide("acme/shop", &key); + assert_eq!(s.code, "needs_person_approval"); + assert!(s.needs_person); + assert!(s + .text + .contains("requires an approving review from a person")); + key.human_approved = true; + assert_eq!(decide("acme/shop", &key).code, "merging"); + + let mut rules = clear(); + rules.blocked_by_rules = true; + let s = decide("acme/shop", &rules); + assert_eq!(s.code, "repo_requires_person_review"); + assert!(s + .text + .starts_with("Your repo's branch rules block the merge")); + assert_eq!(s.link, "https://github.com/acme/shop/settings/branches"); + } + + #[test] + fn coderhelms_own_work_comes_before_any_ask_of_a_person() { + // Auto-merge off AND red checks: the checks are said, not the setting. + let mut f = clear(); + f.auto_merge = false; + f.failing = vec!["unit".into()]; + let s = decide("acme/shop", &f); + assert_eq!(s.code, "checks_failing"); + assert!(!s.needs_person); + f.failing.clear(); + f.conflict = true; + assert_eq!(decide("acme/shop", &f).code, "conflict"); + f.conflict = false; + f.checks_running = true; + assert_eq!(decide("acme/shop", &f).code, "checks_running"); + } + + #[test] + fn no_standing_says_a_person_is_needed_without_naming_why() { + let mut all = vec![clear()]; + for i in 0..7 { + let mut f = clear(); + match i { + 0 => f.auto_merge = false, + 1 => f.require_human_approval = true, + 2 => f.blocked_by_rules = true, + 3 => f.draft = true, + 4 => f.merged = true, + 5 => f.closed = true, + _ => f.reviewer_on = false, + } + all.push(f); + } + for f in all { + let s = decide("acme/shop", &f); + assert!(!s.text.is_empty() && !s.next.is_empty(), "{s:?}"); + if s.needs_person { + assert!( + !s.link.is_empty(), + "a person's turn names its setting: {s:?}" + ); + } + assert_eq!(Standing::from_json(&s.to_json()), Some(s)); + } + } +} diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index e02e896b4..ad8dd9ce2 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -848,6 +848,12 @@ pub struct HealthCheckMessage { /// merge), so an approval wait never runs into it. #[serde(default)] pub approval_seen_at: Option, + /// The watch of a merge nobody asked a report for (CoderHelm's own pull + /// request merged by anyone, see `worker::passes::pr_watch`): it speaks + /// only when the deploy fails. A team's own health check setting is + /// never quiet. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub quiet: bool, } /// A deploy run of the merge commit that was superseded, and the later run on diff --git a/services/common/src/reviewer_prefs.rs b/services/common/src/reviewer_prefs.rs new file mode 100644 index 000000000..0f23a68f7 --- /dev/null +++ b/services/common/src/reviewer_prefs.rs @@ -0,0 +1,1119 @@ +//! What each of a team's reviewers repeatedly asks for on CoderHelm's pull +//! requests, so the next change arrives the way its likely reviewer wants +//! it. +//! +//! When one of CoderHelm's pull requests closes, the worker reads what +//! people wrote in their reviews of it and distils each reviewer's asks +//! into general ones ("add a test for the error path of a new function"). +//! An ask is kept per reviewer login within the team ([`Pref`], +//! `REVIEWERPREF##`), counted once per pull request, and given +//! to the coder and to CoderHelm's review of its own pull request only when +//! it was seen on at least [`MIN_SEEN`] pull requests and that reviewer is +//! a likely reviewer of the change ([`likely_reviewers`]): a code owner of +//! the touched files, or someone who recently reviewed that part of the +//! repository (`REVIEWERSEEN##`). +//! +//! Only review-relevant preferences are stored, nothing personal: an ask +//! must be about the code in one of a fixed list of categories +//! ([`CATEGORIES`]), carries no mention, address or link, and is dropped +//! when it is about a person ([`clean`]). What is kept is the ask, its +//! category, and the pull requests it was seen on; never the reviewer's +//! comments themselves. A team can list what is kept and forget a reviewer. +//! Asks fade like lessons do ([`HALF_LIFE_DAYS`]). + +use aws_sdk_dynamodb::types::AttributeValue; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +pub const PREF_PREFIX: &str = "REVIEWERPREF#"; +pub const SEEN_PREFIX: &str = "REVIEWERSEEN#"; + +/// What an ask may be about. +pub const CATEGORIES: &[&str] = &[ + "tests", + "error_handling", + "naming", + "structure", + "style", + "types", + "docs", + "performance", + "security", + "scope", + "api", + "logging", + "accessibility", + "description", +]; + +/// Pull requests an ask must be seen on before it is given to an agent. +pub const MIN_SEEN: u64 = 2; +/// Days for an ask's weight to halve without being seen again. +pub const HALF_LIFE_DAYS: f64 = 90.0; +/// Weight under which an ask is no longer given. +pub const MIN_WEIGHT: f64 = 0.5; +/// Most asks kept per reviewer. +pub const MAX_PER_REVIEWER: usize = 20; +/// Most asks of one reviewer put in a prompt, and most reviewers. +pub const MAX_PROMPT_ASKS: usize = 5; +pub const MAX_PROMPT_REVIEWERS: usize = 3; +/// Longest ask. +pub const MAX_ASK_CHARS: usize = 240; +const MIN_ASK_CHARS: usize = 12; +/// Word overlap at which two asks of one reviewer are the same ask. +pub const SAME_AT: f64 = 0.6; +/// A reviewer who has not reviewed here for this long is not a likely one. +pub const RECENT_DAYS: i64 = 120; +/// Most pull requests named on one ask. +pub const MAX_PRS: usize = 10; + +/// A GitHub login as stored: lower case. None when it is not a plain +/// person's login (a bot, a team, anything with other characters). +pub fn login_key(login: &str) -> Option { + let l = login.trim().trim_start_matches('@').to_ascii_lowercase(); + let plain = !l.is_empty() + && l.len() <= 39 + && l.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') + && !l.starts_with('-'); + (plain && !l.contains("coderhelm")).then_some(l) +} + +pub fn pref_sk(login: &str, id: &str) -> String { + format!("{PREF_PREFIX}{login}#{id}") +} + +pub fn seen_sk(repo: &str, login: &str) -> String { + format!("{SEEN_PREFIX}{repo}#{login}") +} + +/// One thing a reviewer repeatedly asks for. +#[derive(Debug, Clone, Default, PartialEq, Serialize)] +pub struct Pref { + pub id: String, + pub login: String, + pub text: String, + pub category: String, + /// Pull requests it was seen on. + pub seen: u64, + /// Those pull requests (`owner/name#12`), newest last. + pub prs: Vec, + pub created_at: String, + pub last_seen_at: String, +} + +/// An ask as the model distilled it from one pull request's reviews. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)] +pub struct Ask { + #[serde(default)] + pub reviewer: String, + #[serde(default)] + pub ask: String, + #[serde(default)] + pub category: String, + /// The id of a kept ask of this reviewer that says the same. + #[serde(default)] + pub same_as: Option, +} + +/// Words that make an ask about a person or their circumstances, not about +/// the code. An ask with one (as a whole word or phrase) is dropped whole. +const PERSONAL: &[&str] = &[ + "vacation", + "holiday", + "holidays", + "sick", + "illness", + "health", + "family", + "salary", + "mood", + "angry", + "annoyed", + "rude", + "tired", + "lazy", + "personality", + "attitude", + "timezone", + "time zone", + "working hours", + "weekend", + "weekends", + "lives in", + "he", + "she", + "him", + "his", + "her", +]; + +/// Lower case, every run of other characters one space, padded: a word or +/// phrase is in it when ` word ` is. +fn spaced(text: &str) -> String { + let words: Vec = text + .to_ascii_lowercase() + .split(|c: char| !c.is_ascii_alphanumeric()) + .filter(|w| !w.is_empty()) + .map(str::to_string) + .collect(); + format!(" {} ", words.join(" ")) +} + +fn strip_refs(text: &str) -> String { + text.split_whitespace() + .filter(|w| { + let w = w.trim_matches(|c: char| ",.;:()".contains(c)); + !(w.starts_with('@') + || w.contains("://") + || (w.contains('@') && w.contains('.')) + || w.starts_with("www.")) + }) + .collect::>() + .join(" ") +} + +/// The ask as it may be stored, or None: a plain person's login, a known +/// category, a text about the code with mentions, addresses and links +/// taken out, and nothing personal. +pub fn clean(a: &Ask) -> Option { + let reviewer = login_key(&a.reviewer)?; + let category = a + .category + .trim() + .to_ascii_lowercase() + .replace([' ', '-'], "_"); + if !CATEGORIES.contains(&category.as_str()) { + return None; + } + let text = strip_refs(a.ask.trim()); + let low = spaced(&text); + if text.len() < MIN_ASK_CHARS || PERSONAL.iter().any(|p| low.contains(&format!(" {p} "))) { + return None; + } + // The reviewer's own name is not part of what they ask for. + if low.contains(&spaced(&reviewer)) { + return None; + } + Some(Ask { + reviewer, + ask: crate::truncate_str(&text, MAX_ASK_CHARS).to_string(), + category, + same_as: a.same_as.clone().filter(|s| !s.trim().is_empty()), + }) +} + +/// The ask's weight at `now`: pull requests seen, halved every half-life +/// since the last one. +pub fn weight(p: &Pref, now: chrono::DateTime) -> f64 { + let age_days = chrono::DateTime::parse_from_rfc3339(&p.last_seen_at) + .map(|t| (now - t.with_timezone(&chrono::Utc)).num_seconds() as f64 / 86_400.0) + .unwrap_or(f64::INFINITY) + .max(0.0); + p.seen as f64 * 0.5f64.powf(age_days / HALF_LIFE_DAYS) +} + +/// What to do with one cleaned ask. +#[derive(Debug, Clone, PartialEq)] +pub enum Plan { + /// The reviewer already has it. `counts`: this pull request is new for + /// it. + Reinforce { id: String, counts: bool }, + /// A new ask; `drop` is the reviewer's lightest one when they are at + /// the cap. + Write { pref: Pref, drop: Option }, +} + +/// Pure: how a cleaned ask lands among the reviewer's kept ones (`kept`: +/// that reviewer's only). +pub fn plan( + kept: &[Pref], + a: &Ask, + pr_key: &str, + id: &str, + now: chrono::DateTime, +) -> Plan { + let mine: Vec<&Pref> = kept.iter().filter(|p| p.login == a.reviewer).collect(); + let named = a + .same_as + .as_deref() + .and_then(|id| mine.iter().find(|p| p.id == id).copied()); + let similar = || { + mine.iter() + .map(|p| (crate::rewards::lessons::similarity(&a.ask, &p.text), *p)) + .filter(|(s, _)| *s >= SAME_AT) + .max_by(|x, y| x.0.partial_cmp(&y.0).unwrap_or(std::cmp::Ordering::Equal)) + .map(|(_, p)| p) + }; + if let Some(p) = named.or_else(similar) { + return Plan::Reinforce { + id: p.id.clone(), + counts: !p.prs.iter().any(|x| x == pr_key), + }; + } + let drop = if mine.len() >= MAX_PER_REVIEWER { + mine.iter() + .min_by(|x, y| { + weight(x, now) + .partial_cmp(&weight(y, now)) + .unwrap_or(std::cmp::Ordering::Equal) + }) + .map(|p| p.id.clone()) + } else { + None + }; + let at = now.to_rfc3339(); + Plan::Write { + pref: Pref { + id: id.to_string(), + login: a.reviewer.clone(), + text: a.ask.clone(), + category: a.category.clone(), + seen: 1, + prs: vec![pr_key.to_string()], + created_at: at.clone(), + last_seen_at: at, + }, + drop, + } +} + +/// Pure: the kept asks after one plan, as the store writes it. +pub fn apply_plan(kept: &mut Vec, plan: &Plan, pr_key: &str, now: &str) { + match plan { + Plan::Reinforce { counts: false, .. } => {} + Plan::Reinforce { id, counts: true } => { + if let Some(p) = kept.iter_mut().find(|p| &p.id == id) { + p.seen += 1; + p.last_seen_at = now.to_string(); + p.prs.push(pr_key.to_string()); + } + } + Plan::Write { pref, drop } => { + if let Some(id) = drop { + kept.retain(|p| &p.id != id); + } + kept.push(pref.clone()); + } + } +} + +/// The asks given to an agent for `login`: seen on enough pull requests and +/// still heavy enough, heaviest first. +pub fn active(prefs: &[Pref], login: &str, now: chrono::DateTime) -> Vec { + let mut live: Vec<(f64, &Pref)> = prefs + .iter() + .filter(|p| p.login == login && p.seen >= MIN_SEEN) + .map(|p| (weight(p, now), p)) + .filter(|(w, _)| *w >= MIN_WEIGHT) + .collect(); + live.sort_by(|a, b| { + b.0.partial_cmp(&a.0) + .unwrap_or(std::cmp::Ordering::Equal) + .then(a.1.id.cmp(&b.1.id)) + }); + live.into_iter() + .take(MAX_PROMPT_ASKS) + .map(|(_, p)| p.clone()) + .collect() +} + +/// A reviewer's record on one repository: the parts of it they reviewed +/// CoderHelm's pull requests in, and when last. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct SeenReviewer { + pub repo: String, + pub login: String, + pub areas: BTreeSet, + pub reviews: u64, + pub last_at: String, +} + +/// The people (not teams) a CODEOWNERS file names for `paths`; with no +/// paths, the owners of the catch-all line. +pub fn code_owners(codeowners: &str, paths: &[String]) -> Vec { + let mut out: Vec = Vec::new(); + let mut add = |owners: Option| { + for o in owners.unwrap_or_default().split_whitespace() { + // `@org/team` is a team: no single person's asks apply. + if o.contains('/') { + continue; + } + if let Some(l) = login_key(o) { + if !out.contains(&l) { + out.push(l); + } + } + } + }; + if paths.is_empty() { + add(crate::e2e::owners::owners_of(codeowners, ".")); + } + for p in paths { + add(crate::e2e::owners::owners_of(codeowners, p)); + } + out +} + +/// Pure: who is likely to review a change to `paths` in a repository, most +/// likely first: the code owners of those files, then the people who +/// recently reviewed that part of it (with no paths yet: anyone who +/// recently reviewed the repository, most recent first). +pub fn likely_reviewers( + codeowners: Option<&str>, + paths: &[String], + seen: &[SeenReviewer], + now: chrono::DateTime, +) -> Vec { + let mut out = codeowners + .map(|c| code_owners(c, paths)) + .unwrap_or_default(); + let areas: BTreeSet = paths + .iter() + .map(|p| crate::rewards::event::file_area(p)) + .collect(); + let since = (now - chrono::Duration::days(RECENT_DAYS)).to_rfc3339(); + let mut recent: Vec<&SeenReviewer> = seen + .iter() + .filter(|s| s.last_at.as_str() >= since.as_str()) + .filter(|s| paths.is_empty() || s.areas.iter().any(|a| areas.contains(a))) + .collect(); + recent.sort_by(|a, b| { + b.last_at + .cmp(&a.last_at) + .then(b.reviews.cmp(&a.reviews)) + .then(a.login.cmp(&b.login)) + }); + for s in recent { + if !out.contains(&s.login) { + out.push(s.login.clone()); + } + } + out.truncate(MAX_PROMPT_REVIEWERS); + out +} + +/// The prompt block for the likely reviewers' asks; empty when none of +/// them has an ask that is given. +pub fn prompt_block( + reviewers: &[String], + prefs: &[Pref], + now: chrono::DateTime, +) -> String { + let mut lines = Vec::new(); + for r in reviewers.iter().take(MAX_PROMPT_REVIEWERS) { + for p in active(prefs, r, now) { + lines.push(format!( + "- {r}: {} ({}, on {} pull requests)", + p.text.trim(), + p.category, + p.seen + )); + } + } + if lines.is_empty() { + return String::new(); + } + format!( + "\n\n## What the likely reviewers of this change ask for\nEach line is something that reviewer asked for on several earlier pull requests here. Where it applies to this change, do it before they have to ask again; where it does not apply, leave it.\n{}", + lines.join("\n") + ) +} + +/// Pure: what the dashboard lists, grouped by reviewer, heaviest first. +pub fn view(prefs: &[Pref], now: chrono::DateTime) -> serde_json::Value { + let mut by: BTreeMap> = BTreeMap::new(); + for p in prefs { + by.entry(p.login.clone()).or_default().push(p); + } + let reviewers: Vec = by + .into_iter() + .map(|(login, mut list)| { + list.sort_by(|a, b| { + weight(b, now) + .partial_cmp(&weight(a, now)) + .unwrap_or(std::cmp::Ordering::Equal) + }); + let asks: Vec = list + .iter() + .map(|p| { + serde_json::json!({ + "id": p.id, + "text": p.text, + "category": p.category, + "seen": p.seen, + "prs": p.prs, + "last_seen_at": p.last_seen_at, + "given": p.seen >= MIN_SEEN && weight(p, now) >= MIN_WEIGHT, + }) + }) + .collect(); + serde_json::json!({"login": login, "asks": asks}) + }) + .collect(); + serde_json::json!({"min_seen": MIN_SEEN, "reviewers": reviewers}) +} + +// ── DynamoDB ───────────────────────────────────────────────────────── + +type Item = HashMap; + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +fn gs(i: &Item, k: &str) -> String { + i.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() +} + +fn gu(i: &Item, k: &str) -> u64 { + i.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse().ok()) + .unwrap_or(0) +} + +impl Pref { + pub fn to_item(&self, team: &str) -> Item { + Item::from([ + ("pk".to_string(), s(team)), + ("sk".to_string(), s(&pref_sk(&self.login, &self.id))), + ("record_type".to_string(), s("reviewer_pref")), + ("id".to_string(), s(&self.id)), + ("login".to_string(), s(&self.login)), + ("text".to_string(), s(&self.text)), + ("category".to_string(), s(&self.category)), + ("seen".to_string(), AttributeValue::N(self.seen.to_string())), + ( + "prs".to_string(), + AttributeValue::L(self.prs.iter().map(|p| s(p)).collect()), + ), + ("created_at".to_string(), s(&self.created_at)), + ("last_seen_at".to_string(), s(&self.last_seen_at)), + ]) + } + + pub fn from_item(i: &Item) -> Option { + if !gs(i, "sk").starts_with(PREF_PREFIX) || gs(i, "text").is_empty() { + return None; + } + Some(Pref { + id: gs(i, "id"), + login: gs(i, "login"), + text: gs(i, "text"), + category: gs(i, "category"), + seen: gu(i, "seen").max(1), + prs: i + .get("prs") + .and_then(|v| v.as_l().ok()) + .map(|l| l.iter().filter_map(|v| v.as_s().ok().cloned()).collect()) + .unwrap_or_default(), + created_at: gs(i, "created_at"), + last_seen_at: gs(i, "last_seen_at"), + }) + } +} + +fn seen_of(i: &Item) -> Option { + if !gs(i, "sk").starts_with(SEEN_PREFIX) { + return None; + } + Some(SeenReviewer { + repo: gs(i, "repo"), + login: gs(i, "login"), + areas: i + .get("areas") + .and_then(|v| v.as_ss().ok()) + .map(|v| v.iter().cloned().collect()) + .unwrap_or_default(), + reviews: gu(i, "reviews"), + last_at: gs(i, "last_at"), + }) +} + +/// The settings table, one team at a time. +pub struct Store { + pub dynamo: aws_sdk_dynamodb::Client, + pub table: String, +} + +impl Store { + pub fn new(dynamo: &aws_sdk_dynamodb::Client, table: &str) -> Self { + Self { + dynamo: dynamo.clone(), + table: table.to_string(), + } + } + + async fn query(&self, team: &str, prefix: &str) -> Result, String> { + let mut out = vec![]; + let mut start: Option = None; + for _ in 0..10 { + let page = self + .dynamo + .query() + .table_name(&self.table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", s(team)) + .expression_attribute_values(":p", s(prefix)) + .set_exclusive_start_key(start.take()) + .send() + .await + .map_err(|e| aws_sdk_dynamodb::error::DisplayErrorContext(e).to_string())?; + out.extend(page.items.unwrap_or_default()); + match page.last_evaluated_key { + Some(k) if !k.is_empty() => start = Some(k), + _ => break, + } + } + Ok(out) + } + + /// Every kept ask of the team, or one reviewer's. + pub async fn prefs(&self, team: &str, login: Option<&str>) -> Result, String> { + let prefix = match login { + Some(l) => format!("{PREF_PREFIX}{l}#"), + None => PREF_PREFIX.to_string(), + }; + Ok(self + .query(team, &prefix) + .await? + .iter() + .filter_map(Pref::from_item) + .collect()) + } + + /// The reviewers seen on one repository. + pub async fn seen(&self, team: &str, repo: &str) -> Result, String> { + Ok(self + .query(team, &format!("{SEEN_PREFIX}{repo}#")) + .await? + .iter() + .filter_map(seen_of) + .collect()) + } + + /// Notes that `login` reviewed a pull request touching `areas` of + /// `repo` (counted by the caller once per pull request). + pub async fn note_seen( + &self, + team: &str, + repo: &str, + login: &str, + areas: &BTreeSet, + at: &str, + ) -> Result<(), String> { + let mut u = self + .dynamo + .update_item() + .table_name(&self.table) + .key("pk", s(team)) + .key("sk", s(&seen_sk(repo, login))) + .expression_attribute_names("#rt", "record_type") + .expression_attribute_names("#repo", "repo") + .expression_attribute_names("#login", "login") + .expression_attribute_names("#last", "last_at") + .expression_attribute_names("#reviews", "reviews") + .expression_attribute_values(":rt", s("reviewer_seen")) + .expression_attribute_values(":r", s(repo)) + .expression_attribute_values(":l", s(login)) + .expression_attribute_values(":t", s(at)) + .expression_attribute_values(":one", AttributeValue::N("1".into())); + let areas: Vec = areas.iter().filter(|a| !a.is_empty()).cloned().collect(); + let add_areas = if areas.is_empty() { + "" + } else { + u = u + .expression_attribute_names("#areas", "areas") + .expression_attribute_values(":a", AttributeValue::Ss(areas)); + ", #areas :a" + }; + u.update_expression(format!( + "SET #rt = :rt, #repo = :r, #login = :l, #last = :t ADD #reviews :one{add_areas}" + )) + .send() + .await + .map(|_| ()) + .map_err(|e| aws_sdk_dynamodb::error::DisplayErrorContext(e).to_string()) + } + + /// Applies one plan. + pub async fn apply( + &self, + team: &str, + login: &str, + plan: &Plan, + pr_key: &str, + now: &str, + ) -> Result<(), String> { + match plan { + Plan::Reinforce { counts: false, .. } => Ok(()), + Plan::Reinforce { id, counts: true } => self + .dynamo + .update_item() + .table_name(&self.table) + .key("pk", s(team)) + .key("sk", s(&pref_sk(login, id))) + .condition_expression("attribute_exists(sk)") + .update_expression( + "ADD #seen :one SET #last = :t, \ + #prs = list_append(if_not_exists(#prs, :empty), :pr)", + ) + .expression_attribute_names("#seen", "seen") + .expression_attribute_names("#last", "last_seen_at") + .expression_attribute_names("#prs", "prs") + .expression_attribute_values(":one", AttributeValue::N("1".into())) + .expression_attribute_values(":t", s(now)) + .expression_attribute_values(":empty", AttributeValue::L(vec![])) + .expression_attribute_values(":pr", AttributeValue::L(vec![s(pr_key)])) + .send() + .await + .map(|_| ()) + .map_err(|e| aws_sdk_dynamodb::error::DisplayErrorContext(e).to_string()), + Plan::Write { pref, drop } => { + if let Some(id) = drop { + let _ = self + .dynamo + .delete_item() + .table_name(&self.table) + .key("pk", s(team)) + .key("sk", s(&pref_sk(login, id))) + .send() + .await; + } + self.dynamo + .put_item() + .table_name(&self.table) + .set_item(Some(pref.to_item(team))) + .send() + .await + .map(|_| ()) + .map_err(|e| aws_sdk_dynamodb::error::DisplayErrorContext(e).to_string()) + } + } + } + + /// Forgets everything kept about one reviewer: their asks, and where + /// they were seen. Returns how many records went. + pub async fn forget(&self, team: &str, login: &str) -> Result { + let mut keys: Vec = self + .query(team, &format!("{PREF_PREFIX}{login}#")) + .await? + .iter() + .map(|i| gs(i, "sk")) + .collect(); + keys.extend( + self.query(team, SEEN_PREFIX) + .await? + .iter() + .filter(|i| gs(i, "login") == login) + .map(|i| gs(i, "sk")), + ); + for sk in &keys { + self.dynamo + .delete_item() + .table_name(&self.table) + .key("pk", s(team)) + .key("sk", s(sk)) + .send() + .await + .map_err(|e| aws_sdk_dynamodb::error::DisplayErrorContext(e).to_string())?; + } + Ok(keys.len()) + } + + /// Forgets one ask. + pub async fn forget_ask(&self, team: &str, login: &str, id: &str) -> Result<(), String> { + self.dynamo + .delete_item() + .table_name(&self.table) + .key("pk", s(team)) + .key("sk", s(&pref_sk(login, id))) + .send() + .await + .map(|_| ()) + .map_err(|e| aws_sdk_dynamodb::error::DisplayErrorContext(e).to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::TimeZone; + + fn now() -> chrono::DateTime { + chrono::Utc.with_ymd_and_hms(2026, 10, 20, 0, 0, 0).unwrap() + } + + fn ask(reviewer: &str, text: &str, category: &str) -> Ask { + Ask { + reviewer: reviewer.into(), + ask: text.into(), + category: category.into(), + same_as: None, + } + } + + fn pref(id: &str, login: &str, text: &str, prs: &[&str], last: &str) -> Pref { + Pref { + id: id.into(), + login: login.into(), + text: text.into(), + category: "tests".into(), + seen: prs.len() as u64, + prs: prs.iter().map(|p| p.to_string()).collect(), + created_at: last.into(), + last_seen_at: last.into(), + } + } + + #[test] + fn only_review_relevant_asks_are_kept_and_nothing_personal() { + let ok = clean(&ask( + "@Pat-Lee", + "Add a test for the error path of every new function, see https://wiki.example/x and ask @sam", + "Tests", + )) + .unwrap(); + assert_eq!(ok.reviewer, "pat-lee"); + assert_eq!(ok.category, "tests"); + assert_eq!( + ok.ask, + "Add a test for the error path of every new function, see and ask" + ); + // Not about the code. + assert_eq!( + clean(&ask( + "pat", + "Is usually on vacation in August, wait for her", + "scope" + )), + None + ); + assert_eq!( + clean(&ask("pat", "Gets annoyed by long pull requests", "scope")), + None + ); + assert_eq!( + clean(&ask( + "pat", + "Works late; reviews arrive on the weekend", + "scope" + )), + None + ); + // Not a known category, not a person's login, too short to be an ask. + assert_eq!( + clean(&ask( + "pat", + "Prefers small functions over long ones", + "preferences" + )), + None + ); + assert_eq!( + clean(&ask("acme/backend", "Add tests for new functions", "tests")), + None + ); + assert_eq!( + clean(&ask( + "coderhelm[bot]", + "Add tests for new functions", + "tests" + )), + None + ); + assert_eq!( + clean(&ask( + "dependabot[bot]", + "Add tests for new functions", + "tests" + )), + None + ); + assert_eq!(clean(&ask("pat", "More tests", "tests")), None); + // "another" and "other" are not "her". + assert!(clean(&ask( + "pat", + "Move shared helpers to another module, not the handler", + "structure" + )) + .is_some()); + // An address is taken out, never stored. + let c = clean(&ask( + "pat", + "Send schema changes to pat@example.com before merging them", + "api", + )) + .unwrap(); + assert!(!c.ask.contains('@'), "{}", c.ask); + // The reviewer's name is not part of the ask. + assert_eq!( + clean(&ask( + "pat", + "Whatever pat says about naming goes here", + "naming" + )), + None + ); + } + + #[test] + fn an_ask_counts_each_pull_request_once_and_is_never_stored_twice() { + let a = clean(&ask( + "pat", + "Add a test for the error path of every new function", + "tests", + )) + .unwrap(); + let Plan::Write { pref: first, drop } = plan(&[], &a, "acme/web#12", "P1", now()) else { + panic!("a first ask is written"); + }; + assert_eq!((first.seen, drop), (1, None)); + assert_eq!(first.prs, vec!["acme/web#12"]); + // The same ask in other words on another pull request. + let again = clean(&ask( + "pat", + "Every new function needs a test for its error path", + "tests", + )) + .unwrap(); + assert_eq!( + plan( + std::slice::from_ref(&first), + &again, + "acme/web#15", + "P2", + now() + ), + Plan::Reinforce { + id: "P1".into(), + counts: true + } + ); + // The same pull request again adds nothing. + assert_eq!( + plan( + std::slice::from_ref(&first), + &again, + "acme/web#12", + "P2", + now() + ), + Plan::Reinforce { + id: "P1".into(), + counts: false + } + ); + // Applied: one ask, seen on two pull requests, then given. + let mut kept = vec![first.clone()]; + assert!( + active(&kept, "pat", now()).is_empty(), + "once is not repeatedly" + ); + let p = plan(&kept, &again, "acme/web#15", "P2", now()); + apply_plan(&mut kept, &p, "acme/web#15", &now().to_rfc3339()); + let p = plan(&kept, &again, "acme/web#15", "P3", now()); + apply_plan(&mut kept, &p, "acme/web#15", &now().to_rfc3339()); + assert_eq!((kept.len(), kept[0].seen), (1, 2)); + assert_eq!(kept[0].prs, vec!["acme/web#12", "acme/web#15"]); + assert_eq!(active(&kept, "pat", now()).len(), 1); + // Another reviewer's same words are their own ask. + let sams = clean(&ask( + "sam", + "Every new function needs a test for its error path", + "tests", + )) + .unwrap(); + assert!(matches!( + plan( + std::slice::from_ref(&first), + &sams, + "acme/web#15", + "P2", + now() + ), + Plan::Write { .. } + )); + // The model named the kept ask: that wins over wording. + let mut named = clean(&ask( + "pat", + "Cover failures of the payment client in unit tests", + "tests", + )) + .unwrap(); + named.same_as = Some("P1".into()); + assert_eq!( + plan( + std::slice::from_ref(&first), + &named, + "acme/web#16", + "P2", + now() + ), + Plan::Reinforce { + id: "P1".into(), + counts: true + } + ); + // An id of another reviewer's ask is not this reviewer's. + let mut wrong = sams.clone(); + wrong.same_as = Some("P1".into()); + wrong.ask = "Keep handlers under fifty lines each please".into(); + assert!(matches!( + plan(&[first], &wrong, "acme/web#16", "P2", now()), + Plan::Write { .. } + )); + } + + #[test] + fn an_ask_is_given_only_when_repeated_and_recent() { + let prefs = vec![ + pref( + "once", + "pat", + "Seen on one pull request only", + &["a/b#1"], + "2026-10-19T00:00:00Z", + ), + pref( + "twice", + "pat", + "Add a test for the error path", + &["a/b#1", "a/b#2"], + "2026-10-19T00:00:00Z", + ), + pref( + "old", + "pat", + "Seen twice long ago", + &["a/b#1", "a/b#2"], + "2025-10-01T00:00:00Z", + ), + pref( + "sams", + "sam", + "Name handlers after the route", + &["a/b#1", "a/b#2", "a/b#3"], + "2026-10-19T00:00:00Z", + ), + ]; + let ids: Vec = active(&prefs, "pat", now()) + .into_iter() + .map(|p| p.id) + .collect(); + assert_eq!(ids, vec!["twice"]); + let block = prompt_block(&["pat".into(), "nobody".into()], &prefs, now()); + assert!( + block.contains("- pat: Add a test for the error path (tests, on 2 pull requests)"), + "{block}" + ); + assert!(!block.contains("sam") && !block.contains("one pull request only")); + assert_eq!(prompt_block(&["nobody".into()], &prefs, now()), ""); + assert_eq!(prompt_block(&[], &prefs, now()), ""); + } + + #[test] + fn the_cap_drops_the_reviewers_lightest_ask() { + let mut kept: Vec = (0..MAX_PER_REVIEWER) + .map(|i| { + pref( + &format!("P{i}"), + "pat", + &format!("ask number{i} about thing{i}"), + &["a/b#1", "a/b#2"], + "2026-10-19T00:00:00Z", + ) + }) + .collect(); + kept[4].last_seen_at = "2026-01-01T00:00:00Z".into(); + let a = clean(&ask( + "pat", + "Document every exported function with a comment", + "docs", + )) + .unwrap(); + let Plan::Write { drop, .. } = plan(&kept, &a, "a/b#9", "NEW", now()) else { + panic!("written"); + }; + assert_eq!(drop.as_deref(), Some("P4")); + } + + #[test] + fn likely_reviewers_are_code_owners_then_recent_reviewers_of_those_files() { + let codeowners = "* @acme/everyone @lee\n/apps/web/ @pat @acme/web\n/apps/api/ @sam\n"; + let seen = vec![ + SeenReviewer { + repo: "acme/shop".into(), + login: "kim".into(), + areas: ["apps/web".to_string()].into(), + reviews: 4, + last_at: "2026-10-10T00:00:00Z".into(), + }, + SeenReviewer { + repo: "acme/shop".into(), + login: "ravi".into(), + areas: ["apps/api".to_string()].into(), + reviews: 9, + last_at: "2026-10-18T00:00:00Z".into(), + }, + SeenReviewer { + repo: "acme/shop".into(), + login: "gone".into(), + areas: ["apps/web".to_string()].into(), + reviews: 30, + last_at: "2026-01-01T00:00:00Z".into(), + }, + ]; + let web = vec!["apps/web/src/cart.ts".to_string()]; + assert_eq!( + likely_reviewers(Some(codeowners), &web, &seen, now()), + vec!["pat", "kim"] + ); + // No paths yet (the build has not chosen files): the catch-all's + // people, then whoever reviewed here recently. + assert_eq!( + likely_reviewers(Some(codeowners), &[], &seen, now()), + vec!["lee", "ravi", "kim"] + ); + // No CODEOWNERS file. + assert_eq!(likely_reviewers(None, &web, &seen, now()), vec!["kim"]); + assert!(likely_reviewers(None, &["docs/a.md".to_string()], &seen, now()).is_empty()); + assert_eq!( + code_owners(codeowners, &["apps/api/x.rs".to_string()]), + vec!["sam"] + ); + } + + #[test] + fn records_round_trip_and_the_view_says_what_is_given() { + let p = pref( + "P1", + "pat", + "Add a test for the error path", + &["a/b#1", "a/b#2"], + "2026-10-19T00:00:00Z", + ); + let item = p.to_item("TEAM#a"); + assert_eq!(item["sk"], s("REVIEWERPREF#pat#P1")); + assert_eq!(Pref::from_item(&item), Some(p.clone())); + assert_eq!(Pref::from_item(&Item::new()), None); + let once = pref( + "P2", + "pat", + "Seen on one pull request only", + &["a/b#1"], + "2026-10-19T00:00:00Z", + ); + let v = view(&[once, p], now()); + assert_eq!(v["reviewers"][0]["login"], "pat"); + assert_eq!(v["reviewers"][0]["asks"][0]["id"], "P1"); + assert_eq!(v["reviewers"][0]["asks"][0]["given"], true); + assert_eq!(v["reviewers"][0]["asks"][1]["given"], false); + assert_eq!(login_key("Pat-Lee"), Some("pat-lee".into())); + assert_eq!(login_key("acme/web"), None); + assert_eq!(login_key(""), None); + } +} diff --git a/services/common/src/rewards/event.rs b/services/common/src/rewards/event.rs index 64ac2fb4e..6ffc882f8 100644 --- a/services/common/src/rewards/event.rs +++ b/services/common/src/rewards/event.rs @@ -188,6 +188,9 @@ pub struct RewardEvent { /// People's own words about it: their commit subjects, the reason a PR /// was closed. pub notes: Vec, + /// Short excerpts of what people changed (their commits' own patches), + /// so a lesson can be distilled from the code and not only its name. + pub diff: Vec, } impl RewardEvent { @@ -331,7 +334,11 @@ impl RewardEvent { AttributeValue::Ss(self.skills.clone()), ); } - for (k, v) in [("files", &self.files), ("notes", &self.notes)] { + for (k, v) in [ + ("files", &self.files), + ("notes", &self.notes), + ("diff", &self.diff), + ] { if !v.is_empty() { i.insert( k.to_string(), @@ -374,6 +381,7 @@ impl RewardEvent { dedup: get_s(item, "dedup"), files: get_l(item, "files"), notes: get_l(item, "notes"), + diff: get_l(item, "diff"), }) } } @@ -427,6 +435,7 @@ mod tests { e.variant = "standard".into(); e.files = vec!["src/a.ts".into()]; e.notes = vec!["Use the shared client".into()]; + e.diff = vec!["src/a.ts\n-fetch(url)\n+client.get(url)".into()]; let item = e.to_item(); assert_eq!(item["pk"], AttributeValue::S("TEAM#a".into())); let back = RewardEvent::from_item(&item).unwrap(); diff --git a/services/common/src/rewards/lessons.rs b/services/common/src/rewards/lessons.rs index eb2edf962..50aa29a5d 100644 --- a/services/common/src/rewards/lessons.rs +++ b/services/common/src/rewards/lessons.rs @@ -7,6 +7,16 @@ //! kept one instead. Lessons fade: each counts `seen × ½^(age / half-life)` //! ([`weight`]), and ones that fall under [`MIN_WEIGHT`] are no longer given //! to agents. +//! +//! A lesson can also come from one outcome people explained themselves: +//! their own commits on top of CoderHelm's pull request, the comment they +//! closed it with, the reason they reverted it ([`Distilled`]). Such a +//! lesson must be specific and checkable ([`checkable`]): a rule that names +//! code, and a way to check the work against it. It is deduplicated against +//! the kept ones, counts each pull request once, and loses weight when a +//! later outcome contradicts it ([`plan_outcome`], [`CONTRADICTION_COST`]): +//! a lesson people contradicted as often as they confirmed it is no longer +//! recalled. use super::event::{RewardEvent, RewardKind}; use serde::Serialize; @@ -94,6 +104,59 @@ pub struct Lesson { pub evidence: Vec, /// An admin turned it off. pub reverted: bool, + /// How to check the work against it. Only lessons distilled from an + /// outcome people explained have one. + pub check: String, + /// Where it holds: a path or a path prefix, empty for the repository. + pub applies_to: String, + /// What it was learned from first: `edited`, `closed` or `reverted`; + /// empty for a pattern lesson. + pub source: String, + /// The pull requests behind it (`owner/name#12`), each once. + pub prs: Vec, + /// Later outcomes that went against it. + pub contradicted: u64, + /// People merged it into the repository's guide file: the guide carries + /// it from then on. + pub in_guide: bool, + /// People declined it for the guide: never proposed again. + pub guide_declined: bool, +} + +/// What one contradicting outcome takes off a lesson's `seen`. +pub const CONTRADICTION_COST: f64 = 1.5; +/// Independent pull requests a lesson needs before it is proposed for the +/// repository's guide file. +pub const GUIDE_MIN_SEEN: u64 = 2; +/// The weight it needs for that. +pub const GUIDE_MIN_WEIGHT: f64 = 1.5; +/// Most evidence lines kept on one lesson. +pub const MAX_EVIDENCE: usize = 12; +/// Most pull requests named on one lesson. +pub const MAX_PRS: usize = 12; + +/// The lesson's weight at `now`: what it was seen, less what contradicted +/// it, halved every half-life since it was last seen. +pub fn weight_of(l: &Lesson, now: chrono::DateTime) -> f64 { + let net = l.seen as f64 - CONTRADICTION_COST * l.contradicted as f64; + if net <= 0.0 { + return 0.0; + } + weight(1, &l.last_seen_at, now) * net +} + +/// Whether a lesson has reached the confidence to be proposed for the +/// repository's guide file: a checkable coder lesson seen on enough pull +/// requests, never contradicted, not turned off, and not already proposed. +pub fn guide_ready(l: &Lesson, now: chrono::DateTime) -> bool { + l.agent == super::event::AGENT_CODER + && !l.check.trim().is_empty() + && !l.reverted + && !l.in_guide + && !l.guide_declined + && l.contradicted == 0 + && l.seen >= GUIDE_MIN_SEEN + && weight_of(l, now) >= GUIDE_MIN_WEIGHT } /// The lesson's weight at `now`: `seen` halved every half-life since it was @@ -106,13 +169,14 @@ pub fn weight(seen: u64, last_seen_at: &str, now: chrono::DateTime) seen as f64 * 0.5f64.powf(age_days / HALF_LIFE_DAYS) } -/// The lessons to give an agent: not reverted, still heavy enough, heaviest -/// first, at most [`MAX_RECALLED`]. +/// The lessons to give an agent: not reverted, not already in the guide +/// file (the run reads that), still heavy enough after what contradicted +/// them, heaviest first, at most [`MAX_RECALLED`]. pub fn recall(kept: &[Lesson], agent: &str, now: chrono::DateTime) -> Vec { let mut live: Vec<(f64, Lesson)> = kept .iter() - .filter(|l| !l.reverted && l.agent == agent) - .map(|l| (weight(l.seen, &l.last_seen_at, now), l.clone())) + .filter(|l| !l.reverted && !l.in_guide && l.agent == agent) + .map(|l| (weight_of(l, now), l.clone())) .filter(|(w, _)| *w >= MIN_WEIGHT) .collect(); live.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)); @@ -130,15 +194,23 @@ pub fn prompt_block(lessons: &[Lesson]) -> String { let lines: Vec = lessons .iter() .map(|l| { + let check = if l.check.trim().is_empty() { + String::new() + } else { + format!( + " Check: {}", + crate::truncate_str(l.check.trim(), MAX_CHECK_CHARS) + ) + }; format!( - "- {} (seen {}×)", + "- {}{check} (seen {}×)", crate::truncate_str(l.text.trim(), MAX_PROMPT_LESSON_CHARS), l.seen ) }) .collect(); format!( - "\n\n## Lessons from what happened to earlier work in this repository\nEach is backed by at least two outcomes.\n{}", + "\n\n## Lessons from what happened to earlier work in this repository\nEach comes from what people did with earlier pull requests here (their own edits, why they closed or reverted one). Where a lesson gives a check, run it on your change before you finish.\n{}", lines.join("\n") ) } @@ -352,6 +424,324 @@ pub fn coder_lesson_text(area: &str, negatives: &[RewardEvent]) -> Option, + /// Ids of kept lessons this outcome goes against. + #[serde(default)] + pub contradicts: Vec, +} + +/// Why a distilled lesson is not kept. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NotCheckable { + /// No rule, or one too short or too long to be a rule. + NoRule, + /// Nothing says how to check a change against it. + NoCheck, + /// It names no code: no path, no identifier, no command. + NamesNothing, + /// Advice that fits any change ("be careful", "test thoroughly"). + Vague, + /// It is about a person, not about the code. + AboutAPerson, +} + +const VAGUE: &[&str] = &[ + "be careful", + "be more careful", + "pay attention", + "pay more attention", + "double check", + "double-check", + "best practice", + "test thoroughly", + "test more", + "write better", + "higher quality", + "read the surrounding code", + "understand the code", + "think carefully", + "avoid mistakes", + "avoid bugs", +]; + +fn names_code(text: &str) -> bool { + let mut ticks = text.match_indices('`'); + while let (Some((a, _)), Some((b, _))) = (ticks.next(), ticks.next()) { + if b > a + 1 { + return true; + } + } + false +} + +/// Is the lesson specific and checkable? A rule of a usable length, a way +/// to check it, at least one named piece of code (in backticks, or the path +/// it applies to), no advice that fits any change, nothing about a person. +pub fn checkable(d: &Distilled) -> Result<(), NotCheckable> { + let (rule, check) = (d.rule.trim(), d.check.trim()); + if rule.len() < MIN_RULE_CHARS || rule.len() > MAX_RULE_CHARS { + return Err(NotCheckable::NoRule); + } + if check.len() < MIN_CHECK_CHARS || check.len() > MAX_CHECK_CHARS { + return Err(NotCheckable::NoCheck); + } + if rule.contains('@') || check.contains('@') { + return Err(NotCheckable::AboutAPerson); + } + if !names_code(rule) && !names_code(check) && d.applies_to.trim().is_empty() { + return Err(NotCheckable::NamesNothing); + } + let low = rule.to_ascii_lowercase(); + if VAGUE.iter().any(|v| low.contains(v)) && !names_code(rule) { + return Err(NotCheckable::Vague); + } + Ok(()) +} + +/// What to do with a distilled lesson. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum OutcomeAction { + /// Not kept, and why. + Skip(NotCheckable), + /// A kept lesson says it already. `counts`: this pull request is new + /// evidence for it (false when it was already counted). + Reinforce { id: String, counts: bool }, + /// A new lesson. + Write, +} + +/// How one outcome's lesson lands among the kept ones. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OutcomePlan { + pub action: OutcomeAction, + /// Kept lessons this outcome contradicts (each counted against once per + /// pull request). + pub contradict: Vec, + /// The lightest kept lesson, dropped to make room for a new one. + pub drop: Option, +} + +/// Pure: how the lesson distilled from the outcome of `pr_key` +/// (`owner/name#12`) lands among the repository's kept lessons. `d` is None +/// when the outcome taught no rule; it may still contradict kept ones. +pub fn plan_outcome( + kept: &[Lesson], + d: Option<&Distilled>, + contradicts: &[String], + pr_key: &str, + now: chrono::DateTime, +) -> OutcomePlan { + let coder: Vec<&Lesson> = kept + .iter() + .filter(|l| l.agent == super::event::AGENT_CODER) + .collect(); + let known = |id: &str| coder.iter().find(|l| l.id == id).copied(); + let action = match d { + None => OutcomeAction::Skip(NotCheckable::NoRule), + Some(d) => match checkable(d) { + Err(why) => OutcomeAction::Skip(why), + Ok(()) => { + let named = d.duplicate_of.as_deref().and_then(known); + let similar = || { + coder + .iter() + .filter(|l| !l.check.is_empty()) + .map(|l| (similarity(&d.rule, &l.text), *l)) + .filter(|(s, _)| *s >= DUPLICATE_AT) + .max_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)) + .map(|(_, l)| l) + }; + match named.or_else(similar) { + Some(l) => OutcomeAction::Reinforce { + id: l.id.clone(), + counts: !l.prs.iter().any(|p| p == pr_key), + }, + None => OutcomeAction::Write, + } + } + }, + }; + let same = match &action { + OutcomeAction::Reinforce { id, .. } => Some(id.as_str()), + _ => None, + }; + let mut contradict: Vec = Vec::new(); + for id in contradicts { + // A lesson is never both confirmed and contradicted by one outcome, + // and an outcome counts against a lesson once. + if Some(id.as_str()) == same || contradict.contains(id) { + continue; + } + if let Some(l) = known(id) { + let mark = contradiction_mark(pr_key); + if !l.evidence.iter().any(|e| e.starts_with(&mark)) { + contradict.push(id.clone()); + } + } + } + let drop = if action == OutcomeAction::Write && kept.len() >= MAX_KEPT { + kept.iter() + .filter(|l| !l.in_guide) + .min_by(|a, b| { + weight_of(a, now) + .partial_cmp(&weight_of(b, now)) + .unwrap_or(std::cmp::Ordering::Equal) + }) + .map(|l| l.id.clone()) + } else { + None + }; + OutcomePlan { + action, + contradict, + drop, + } +} + +/// The last `max` of `list` with `more` added: lists on a lesson stay +/// bounded however many pull requests confirm it. +pub fn bounded(list: &[String], more: &[String], max: usize) -> Vec { + let all: Vec = list.iter().chain(more.iter()).cloned().collect(); + all[all.len().saturating_sub(max)..].to_vec() +} + +/// The evidence line that says a pull request went against a lesson. +pub fn contradiction_line(pr_key: &str, evidence: &[String]) -> String { + format!( + "{}: {}", + contradiction_mark(pr_key), + crate::truncate_str(evidence.first().map(String::as_str).unwrap_or(""), 300) + ) +} + +/// The evidence lines one more confirming pull request adds. +pub fn reinforcing_lines(evidence: &[String]) -> Vec { + evidence + .iter() + .take(3) + .map(|l| crate::truncate_str(l, 500).to_string()) + .collect() +} + +/// Pure: the new lesson an outcome writes. +pub fn new_outcome_lesson( + repo: &str, + id: &str, + d: &Distilled, + source: &str, + pr: u64, + evidence: &[String], + now: &str, +) -> Lesson { + Lesson { + id: id.to_string(), + repo: repo.to_string(), + agent: super::event::AGENT_CODER.to_string(), + text: d.rule.trim().to_string(), + check: d.check.trim().to_string(), + applies_to: d.applies_to.trim().to_string(), + source: source.to_string(), + seen: 1, + prs: vec![pr_key(repo, pr)], + created_at: now.to_string(), + last_seen_at: now.to_string(), + evidence: evidence + .iter() + .take(MAX_EVIDENCE) + .map(|l| crate::truncate_str(l, 500).to_string()) + .collect(), + ..Default::default() + } +} + +/// Pure: the kept lessons after an outcome's plan, as the store writes it +/// (`Store::learn_outcome` makes the same changes with atomic updates). +/// Returns the id of the lesson written or reinforced. +#[allow(clippy::too_many_arguments)] +pub fn apply_outcome( + kept: &mut Vec, + plan: &OutcomePlan, + d: Option<&Distilled>, + repo: &str, + source: &str, + pr: u64, + evidence: &[String], + new_id: &str, + now: &str, +) -> Option { + let key = pr_key(repo, pr); + for id in &plan.contradict { + if let Some(l) = kept.iter_mut().find(|l| &l.id == id) { + l.contradicted += 1; + l.evidence = bounded( + &l.evidence, + &[contradiction_line(&key, evidence)], + MAX_EVIDENCE, + ); + } + } + match (&plan.action, d) { + (OutcomeAction::Reinforce { id, counts }, _) => { + if let Some(l) = kept.iter_mut().find(|l| &l.id == id).filter(|_| *counts) { + l.seen += 1; + l.last_seen_at = now.to_string(); + l.prs = bounded(&l.prs, &[key], MAX_PRS); + l.evidence = bounded(&l.evidence, &reinforcing_lines(evidence), MAX_EVIDENCE); + } + Some(id.clone()) + } + (OutcomeAction::Write, Some(d)) => { + if let Some(drop) = &plan.drop { + kept.retain(|l| &l.id != drop); + } + kept.push(new_outcome_lesson( + repo, new_id, d, source, pr, evidence, now, + )); + Some(new_id.to_string()) + } + _ => None, + } +} + +/// How an evidence line that contradicts a lesson starts, so one pull +/// request counts against it once. +pub fn contradiction_mark(pr_key: &str) -> String { + format!("Contradicted by {pr_key}") +} + +/// The pull request key lessons name their evidence by. +pub fn pr_key(repo: &str, pr: u64) -> String { + format!("{repo}#{pr}") +} + #[cfg(test)] mod tests { use super::*; @@ -510,4 +900,368 @@ mod tests { ) > 0.99 ); } + + fn distilled(rule: &str, check: &str) -> Distilled { + Distilled { + rule: rule.into(), + check: check.into(), + ..Default::default() + } + } + + #[test] + fn a_lesson_must_be_specific_and_checkable() { + let good = distilled( + "Fetch through the shared `useApi` hook in `apps/web`, never with a bare `fetch` call.", + "Search the diff for `fetch(` under `apps/web/src`: there should be none.", + ); + assert_eq!(checkable(&good), Ok(())); + assert_eq!( + checkable(&distilled( + "Be more careful with changes to the API layer.", + &good.check + )), + Err(NotCheckable::Vague) + ); + assert_eq!( + checkable(&distilled( + "Changes to the billing code need a migration file.", + "Look at the migrations folder." + )), + Err(NotCheckable::NamesNothing) + ); + // The path it applies to is enough of a name. + let mut scoped = distilled( + "Changes to the billing code need a migration file.", + "A new file exists under migrations for the change.", + ); + scoped.applies_to = "services/billing".into(); + assert_eq!(checkable(&scoped), Ok(())); + assert_eq!( + checkable(&distilled(&good.rule, "")), + Err(NotCheckable::NoCheck) + ); + assert_eq!( + checkable(&distilled("Use `x`.", &good.check)), + Err(NotCheckable::NoRule) + ); + assert_eq!( + checkable(&distilled(&"a".repeat(MAX_RULE_CHARS + 1), &good.check)), + Err(NotCheckable::NoRule) + ); + assert_eq!( + checkable(&distilled( + "Ask @pat before touching `apps/web/src/api.ts` again.", + &good.check + )), + Err(NotCheckable::AboutAPerson) + ); + } + + fn kept_rule(id: &str, text: &str, prs: &[&str]) -> Lesson { + Lesson { + check: "Search the diff for `fetch(`.".into(), + prs: prs.iter().map(|p| p.to_string()).collect(), + seen: prs.len().max(1) as u64, + ..lesson(id, text, 1, "2026-10-01T00:00:00Z") + } + } + + #[test] + fn an_outcome_lesson_is_written_once_and_counts_each_pull_request_once() { + let now = chrono::Utc.with_ymd_and_hms(2026, 10, 2, 0, 0, 0).unwrap(); + let d = distilled( + "Fetch through the shared `useApi` hook in `apps/web`, never with a bare `fetch` call.", + "Search the diff for `fetch(` under `apps/web/src`: there should be none.", + ); + let p = plan_outcome(&[], Some(&d), &[], "acme/web#12", now); + assert_eq!(p.action, OutcomeAction::Write); + assert!(p.contradict.is_empty() && p.drop.is_none()); + + // The same rule in other words, from another pull request. + let kept = vec![kept_rule( + "L1", + "In `apps/web` fetch through the shared `useApi` hook, never a bare `fetch` call.", + &["acme/web#12"], + )]; + let p = plan_outcome(&kept, Some(&d), &[], "acme/web#15", now); + assert_eq!( + p.action, + OutcomeAction::Reinforce { + id: "L1".into(), + counts: true + } + ); + // The same pull request again (a redelivery) adds nothing. + let p = plan_outcome(&kept, Some(&d), &[], "acme/web#12", now); + assert_eq!( + p.action, + OutcomeAction::Reinforce { + id: "L1".into(), + counts: false + } + ); + // The model named the kept lesson it repeats: that wins over wording. + let mut named = distilled( + "Requests from the site go through `useApi`, which adds the session header.", + "No `fetch(` call in the diff under `apps/web/src`.", + ); + named.duplicate_of = Some("L1".into()); + let p = plan_outcome(&kept, Some(&named), &[], "acme/web#16", now); + assert!( + matches!(p.action, OutcomeAction::Reinforce { ref id, counts: true } if id == "L1") + ); + // An id the model made up is not a duplicate. + named.duplicate_of = Some("nope".into()); + let p = plan_outcome(&kept, Some(&named), &[], "acme/web#16", now); + assert_eq!(p.action, OutcomeAction::Write); + // A vague one is never kept. + let p = plan_outcome( + &kept, + Some(&distilled("Be careful.", "x")), + &[], + "acme/web#17", + now, + ); + assert!(matches!(p.action, OutcomeAction::Skip(_))); + } + + #[test] + fn a_contradicted_lesson_is_demoted_then_no_longer_recalled() { + let now = chrono::Utc.with_ymd_and_hms(2026, 10, 2, 0, 0, 0).unwrap(); + let mut once = kept_rule("L1", "Use `useApi` in `apps/web`.", &["acme/web#12"]); + let mut thrice = kept_rule( + "L2", + "Name migrations `NNNN_what.sql` in `db/migrations`.", + &["acme/web#3", "acme/web#5", "acme/web#8"], + ); + let kept = vec![once.clone(), thrice.clone()]; + // The outcome contradicts both, names one twice and one that is not + // kept; it teaches no rule of its own. + let ids = vec!["L1".to_string(), "L2".into(), "L1".into(), "ghost".into()]; + let p = plan_outcome(&kept, None, &ids, "acme/web#20", now); + assert_eq!(p.contradict, vec!["L1".to_string(), "L2".to_string()]); + assert!(matches!(p.action, OutcomeAction::Skip(_))); + + // Seen once, contradicted once: out. Seen three times: demoted. + once.contradicted = 1; + thrice.contradicted = 1; + assert_eq!(weight_of(&once, now), 0.0); + assert!(weight_of(&thrice, now) > 1.0 && weight_of(&thrice, now) < 2.0); + let recalled: Vec = recall(&[once.clone(), thrice.clone()], "coder", now) + .into_iter() + .map(|l| l.id) + .collect(); + assert_eq!(recalled, vec!["L2"]); + // A contradicted lesson is not proposed for the guide either. + assert!(!guide_ready(&thrice, now)); + + // The same pull request never counts against a lesson twice. + once.evidence = vec![format!( + "{}: people removed the hook", + contradiction_mark("acme/web#20") + )]; + let p = plan_outcome(&[once], None, &["L1".to_string()], "acme/web#20", now); + assert!(p.contradict.is_empty()); + + // An outcome never both confirms and contradicts the same lesson. + let d = Distilled { + duplicate_of: Some("L2".into()), + ..distilled( + "Name migrations `NNNN_what.sql` in `db/migrations`.", + "The new file under `db/migrations` starts with four digits.", + ) + }; + let p = plan_outcome(&[thrice], Some(&d), &["L2".to_string()], "acme/web#21", now); + assert!(p.contradict.is_empty()); + } + + #[test] + fn applying_the_plans_takes_a_lesson_from_one_outcome_to_the_guide() { + let now_t = chrono::Utc.with_ymd_and_hms(2026, 10, 2, 0, 0, 0).unwrap(); + let now = "2026-10-02T00:00:00Z"; + let d = distilled( + "Fetch through the shared `useApi` hook in `apps/web`, never with a bare `fetch` call.", + "Search the diff for `fetch(` under `apps/web/src`: there should be none.", + ); + let mut kept: Vec = Vec::new(); + let ev = vec!["PR #12: people edited it before merging".to_string()]; + let p = plan_outcome(&kept, Some(&d), &[], "acme/web#12", now_t); + let id = apply_outcome( + &mut kept, + &p, + Some(&d), + "acme/web", + SOURCE_EDITED, + 12, + &ev, + "L1", + now, + ); + assert_eq!(id.as_deref(), Some("L1")); + assert_eq!((kept[0].seen, kept[0].source.as_str()), (1, "edited")); + assert_eq!(kept[0].evidence, ev); + assert!( + !guide_ready(&kept[0], now_t), + "one pull request is not enough" + ); + // Delivered again: nothing changes. + let p = plan_outcome(&kept, Some(&d), &[], "acme/web#12", now_t); + apply_outcome( + &mut kept, + &p, + Some(&d), + "acme/web", + SOURCE_EDITED, + 12, + &ev, + "L2", + now, + ); + assert_eq!((kept.len(), kept[0].seen), (1, 1)); + // The same thing on another pull request. + let p = plan_outcome(&kept, Some(&d), &[], "acme/web#15", now_t); + apply_outcome( + &mut kept, + &p, + Some(&d), + "acme/web", + SOURCE_CLOSED, + 15, + &ev, + "L2", + now, + ); + assert_eq!((kept.len(), kept[0].seen), (1, 2)); + assert_eq!(kept[0].prs, vec!["acme/web#12", "acme/web#15"]); + assert_eq!(kept[0].source, "edited", "where it was first learned stays"); + assert!(guide_ready(&kept[0], now_t)); + // People then undo exactly that: it is demoted, and out of the guide's reach. + let p = plan_outcome(&kept, None, &["L1".to_string()], "acme/web#20", now_t); + let ev20 = + vec!["PR #20 in people's words: \"the hook is gone, call the client\"".to_string()]; + assert_eq!( + apply_outcome( + &mut kept, + &p, + None, + "acme/web", + SOURCE_EDITED, + 20, + &ev20, + "L3", + now + ), + None + ); + assert_eq!(kept[0].contradicted, 1); + assert!(kept[0] + .evidence + .last() + .unwrap() + .starts_with("Contradicted by acme/web#20: PR #20")); + assert!(!guide_ready(&kept[0], now_t)); + assert_eq!( + recall(&kept, "coder", now_t).len(), + 1, + "still recalled, lighter" + ); + let p = plan_outcome(&kept, None, &["L1".to_string()], "acme/web#21", now_t); + apply_outcome( + &mut kept, + &p, + None, + "acme/web", + SOURCE_REVERTED, + 21, + &ev20, + "L3", + now, + ); + assert!( + recall(&kept, "coder", now_t).is_empty(), + "contradicted as often as confirmed: gone" + ); + } + + #[test] + fn a_lessons_lists_stay_bounded() { + let many: Vec = (0..30).map(|i| format!("line {i}")).collect(); + let kept = bounded(&many, &["newest".to_string()], MAX_EVIDENCE); + assert_eq!(kept.len(), MAX_EVIDENCE); + assert_eq!(kept.last().map(String::as_str), Some("newest")); + assert_eq!(kept[0], "line 19"); + assert_eq!(bounded(&[], &["a".to_string()], 3), vec!["a"]); + assert_eq!(reinforcing_lines(&many).len(), 3); + assert!(contradiction_line("acme/web#20", &many) + .starts_with("Contradicted by acme/web#20: line 0")); + } + + #[test] + fn a_lesson_reaches_the_guide_only_with_confidence() { + let now = chrono::Utc.with_ymd_and_hms(2026, 10, 2, 0, 0, 0).unwrap(); + let ready = kept_rule("L1", "Use `useApi`.", &["acme/web#1", "acme/web#2"]); + assert!(guide_ready(&ready, now)); + // One pull request is not enough. + assert!(!guide_ready( + &kept_rule("L", "Use `useApi`.", &["acme/web#1"]), + now + )); + // A pattern lesson (no check) is a record of what happened, not a rule. + assert!(!guide_ready( + &lesson( + "A", + "In `x`: PR #3 was reverted.", + 4, + "2026-10-01T00:00:00Z" + ), + now + )); + let changes: [fn(&mut Lesson); 6] = [ + |l: &mut Lesson| l.reverted = true, + |l: &mut Lesson| l.in_guide = true, + |l: &mut Lesson| l.guide_declined = true, + |l: &mut Lesson| l.contradicted = 1, + |l: &mut Lesson| l.agent = "reviewer".into(), + // Faded: last seen long ago. + |l: &mut Lesson| l.last_seen_at = "2026-01-01T00:00:00Z".into(), + ]; + for change in changes { + let mut l = ready.clone(); + change(&mut l); + assert!(!guide_ready(&l, now), "{l:?}"); + } + // A lesson the guide carries is not repeated in the prompt. + let mut in_guide = ready.clone(); + in_guide.in_guide = true; + assert!(recall(&[in_guide], "coder", now).is_empty()); + // The prompt gives the check with the rule. + let block = prompt_block(&[ready]); + assert!( + block.contains("- Use `useApi`. Check: Search the diff for `fetch(`. (seen 2×)"), + "{block}" + ); + } + + #[test] + fn the_lightest_lesson_makes_room_for_a_new_one() { + let now = chrono::Utc.with_ymd_and_hms(2026, 10, 2, 0, 0, 0).unwrap(); + let mut kept: Vec = (0..MAX_KEPT) + .map(|i| { + kept_rule( + &format!("L{i}"), + &format!("Rule number{i} about `thing{i}` here."), + &["a/b#1", "a/b#2"], + ) + }) + .collect(); + kept[7].last_seen_at = "2026-03-01T00:00:00Z".into(); + let d = distilled( + "Fetch through the shared `useApi` hook in `apps/web`, never with a bare `fetch` call.", + "Search the diff for `fetch(` under `apps/web/src`: there should be none.", + ); + let p = plan_outcome(&kept, Some(&d), &[], "acme/web#12", now); + assert_eq!(p.action, OutcomeAction::Write); + assert_eq!(p.drop.as_deref(), Some("L7")); + } } diff --git a/services/common/src/rewards/mapping.rs b/services/common/src/rewards/mapping.rs index 2f0a492b0..3008d362b 100644 --- a/services/common/src/rewards/mapping.rs +++ b/services/common/src/rewards/mapping.rs @@ -38,11 +38,62 @@ pub struct PeopleEdits { pub files: Vec, /// Their commit subjects, oldest first. pub subjects: Vec, + /// Excerpts of their commits' own patches ([`diff_excerpts`]): what + /// they changed in CoderHelm's code, not only where. + pub diff: Vec, } /// Most paths and commit subjects kept on one event. pub const MAX_EDIT_FILES: usize = 6; pub const MAX_EDIT_NOTES: usize = 4; +/// Most patch excerpts kept on one event, and the longest one. +pub const MAX_DIFF_EXCERPTS: usize = 4; +pub const MAX_DIFF_CHARS: usize = 700; + +/// Generated and vendored files: what people changed there teaches nothing +/// about how to write the code. +fn is_generated(path: &str) -> bool { + let name = path.rsplit('/').next().unwrap_or(path); + name.ends_with(".lock") + || name.ends_with("-lock.json") + || name.ends_with("-lock.yaml") + || name.ends_with(".min.js") + || name.ends_with(".snap") + || name.ends_with(".map") + || path.contains("/vendor/") + || path.contains("/node_modules/") + || path.contains("/dist/") +} + +/// Short excerpts of people's patches, one per file, the files they changed +/// most first: the path, then the changed lines (context lines are left out +/// so the excerpt is what they removed and added). +pub fn diff_excerpts(patches: &[(String, String)]) -> Vec { + let mut by_size: Vec<(usize, &str, String)> = patches + .iter() + .filter(|(path, patch)| !is_generated(path) && !patch.trim().is_empty()) + .map(|(path, patch)| { + let changed: Vec<&str> = patch + .lines() + .filter(|l| { + (l.starts_with('+') || l.starts_with('-')) + && !l.starts_with("+++") + && !l.starts_with("---") + }) + .collect(); + (changed.len(), path.as_str(), changed.join("\n")) + }) + .filter(|(n, _, _)| *n > 0) + .collect(); + by_size.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(b.1))); + by_size + .into_iter() + .take(MAX_DIFF_EXCERPTS) + .map(|(_, path, changed)| { + crate::truncate_str(&format!("{path}\n{changed}"), MAX_DIFF_CHARS).to_string() + }) + .collect() +} impl PeopleEdits { /// The share of the PR's diff they changed, 0..1. @@ -154,6 +205,7 @@ pub fn pr_closed_events( .take(MAX_EDIT_NOTES) .map(|t| crate::truncate_str(t.trim(), 160).to_string()) .collect(); + e.diff = ed.diff.iter().take(MAX_DIFF_EXCERPTS).cloned().collect(); out.push(e); } } @@ -491,6 +543,14 @@ mod tests { lines: 40, files: vec!["src/api/a.ts".into()], subjects: vec!["Use the shared client".into(), " ".into()], + diff: diff_excerpts(&[ + ( + "src/api/a.ts".into(), + "@@ -1,4 +1,4 @@\n import x\n-const r = await fetch(url)\n+const r = await client.get(url)\n done".into(), + ), + ("package-lock.json".into(), "@@\n-a\n+b".into()), + ("src/empty.ts".into(), String::new()), + ]), }; let mut pr = merged(); pr["additions"] = json!(80); @@ -509,6 +569,15 @@ mod tests { // What people changed and said travels on the event. assert_eq!(v[0].files, vec!["src/api/a.ts".to_string()]); assert_eq!(v[0].notes, vec!["Use the shared client".to_string()]); + // And so does what they changed in the code: their lines only, never + // a lockfile's. + assert_eq!( + v[0].diff, + vec![ + "src/api/a.ts\n-const r = await fetch(url)\n+const r = await client.get(url)" + .to_string() + ] + ); assert_eq!(v[2].value, 2.0); // Unmeasured edits are not guessed. let v = pr_closed_events(&ctx(), &merged(), Some(3), None, CiSummary::default()); diff --git a/services/common/src/rewards/mod.rs b/services/common/src/rewards/mod.rs index 33711681a..1a2ad22de 100644 --- a/services/common/src/rewards/mod.rs +++ b/services/common/src/rewards/mod.rs @@ -49,4 +49,16 @@ pub struct RewardOutcomeMessage { /// A PR CoderHelm reviewed but didn't write: no coder outcome. #[serde(default)] pub review_only: bool, + /// What happened, when it is not the pull request closing: empty for a + /// close, [`TRIGGER_REVERTED`] when a merged CoderHelm change was + /// reverted (`pr_number` is the reverted one), [`TRIGGER_GUIDE_CLOSED`] + /// when the repository's guide pull request closed. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub trigger: String, + /// People's words that came with it: why they reverted. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub note: String, } + +pub const TRIGGER_REVERTED: &str = "reverted"; +pub const TRIGGER_GUIDE_CLOSED: &str = "guide_closed"; diff --git a/services/common/src/rewards/store.rs b/services/common/src/rewards/store.rs index 968e81be9..3dd9fc777 100644 --- a/services/common/src/rewards/store.rs +++ b/services/common/src/rewards/store.rs @@ -1127,6 +1127,221 @@ impl Store { } } } + + /// Keeps what one outcome taught: the lesson distilled from it (`d`, + /// None when it taught no rule) is written, or counted on the kept + /// lesson that says the same, once per pull request; the kept lessons + /// the outcome contradicts lose weight, each once per pull request. The + /// evidence lines go on the lesson (a contradiction as a line of its + /// own), and a new lesson is logged as a change an admin can turn off. + pub async fn learn_outcome( + &self, + team_id: &str, + repo: &str, + d: Option<&super::lessons::Distilled>, + contradicts: &[String], + ev: &OutcomeEvidence, + ) -> Result { + use super::lessons::{self, OutcomeAction}; + let kept = self.lessons(team_id, Some(repo)).await?; + let now_t = chrono::Utc::now(); + let now = now_t.to_rfc3339(); + let pr_key = lessons::pr_key(repo, ev.pr); + let plan = lessons::plan_outcome(&kept, d, contradicts, &pr_key, now_t); + let mut out = OutcomeLearned::default(); + let change_evidence = |why: &str| { + vec![serde_json::json!({ + "kind": ev.source, "at": now, "pr": ev.pr, "run_id": ev.run_id, "detail": why, + })] + }; + for id in &plan.contradict { + let Some(l) = kept.iter().find(|l| &l.id == id) else { + continue; + }; + let line = lessons::contradiction_line(&pr_key, &ev.lines); + let evidence = lessons::bounded( + &l.evidence, + std::slice::from_ref(&line), + lessons::MAX_EVIDENCE, + ); + self.dynamo + .update_item() + .table_name(&self.table) + .key("pk", s(team_id)) + .key("sk", s(&lesson_sk(repo, id))) + .condition_expression("attribute_exists(sk)") + .update_expression("ADD #c :one SET #ev = :ev, #ca = :t") + .expression_attribute_names("#c", "contradicted") + .expression_attribute_names("#ev", "evidence") + .expression_attribute_names("#ca", "last_contradicted_at") + .expression_attribute_values(":one", n(1)) + .expression_attribute_values( + ":ev", + AttributeValue::L(evidence.iter().map(|x| s(x)).collect()), + ) + .expression_attribute_values(":t", s(&now)) + .send() + .await + .map_err(|e| DisplayErrorContext(e).to_string())?; + out.contradicted.push(id.clone()); + } + match (&plan.action, d) { + (OutcomeAction::Reinforce { id, counts }, _) => { + if let Some(l) = kept.iter().find(|l| &l.id == id).filter(|_| *counts) { + let list = |v: Vec| AttributeValue::L(v.iter().map(|x| s(x)).collect()); + self.dynamo + .update_item() + .table_name(&self.table) + .key("pk", s(team_id)) + .key("sk", s(&lesson_sk(repo, id))) + .condition_expression("attribute_exists(sk)") + .update_expression("ADD #seen :one SET #ls = :t, #prs = :prs, #ev = :ev") + .expression_attribute_names("#seen", "seen") + .expression_attribute_names("#ls", "last_seen_at") + .expression_attribute_names("#prs", "prs") + .expression_attribute_names("#ev", "evidence") + .expression_attribute_values(":one", n(1)) + .expression_attribute_values(":t", s(&now)) + .expression_attribute_values( + ":prs", + list(lessons::bounded( + &l.prs, + std::slice::from_ref(&pr_key), + lessons::MAX_PRS, + )), + ) + .expression_attribute_values( + ":ev", + list(lessons::bounded( + &l.evidence, + &lessons::reinforcing_lines(&ev.lines), + lessons::MAX_EVIDENCE, + )), + ) + .send() + .await + .map_err(|e| DisplayErrorContext(e).to_string())?; + } + out.lesson = Some(id.clone()); + } + (OutcomeAction::Write, Some(d)) => { + if let Some(drop) = &plan.drop { + let _ = self + .dynamo + .delete_item() + .table_name(&self.table) + .key("pk", s(team_id)) + .key("sk", s(&lesson_sk(repo, drop))) + .send() + .await; + } + let id = ulid::Ulid::new().to_string(); + let lesson = + lessons::new_outcome_lesson(repo, &id, d, &ev.source, ev.pr, &ev.lines, &now); + self.dynamo + .put_item() + .table_name(&self.table) + .set_item(Some(outcome_lesson_item(team_id, &lesson))) + .send() + .await + .map_err(|e| DisplayErrorContext(e).to_string())?; + let change = Change { + id: ulid::Ulid::new().to_string(), + repo: repo.to_string(), + kind: changes::KIND_LESSON.into(), + key: id.clone(), + from: String::new(), + to: crate::truncate_str(d.rule.trim(), 300).to_string(), + reason: format!( + "New coder lesson from PR #{} ({})", + ev.pr, + match ev.source.as_str() { + lessons::SOURCE_EDITED => "people edited it before merging", + lessons::SOURCE_CLOSED => "closed without merging", + lessons::SOURCE_REVERTED => "reverted after merging", + _ => "its outcome", + } + ), + evidence: change_evidence(ev.lines.first().map(String::as_str).unwrap_or("")), + at: now.clone(), + ..Default::default() + }; + self.apply_change(team_id, &change).await?; + out.lesson = Some(id); + out.written = true; + } + _ => {} + } + Ok(out) + } + + /// Marks what became of lessons proposed for the guide file: merged + /// into it (`kept`), or taken out or declined by people (`declined`, + /// which also counts against the lesson once). + pub async fn settle_guide_lessons( + &self, + team_id: &str, + repo: &str, + kept: &[String], + declined: &[String], + pr: u64, + ) -> Result<(), String> { + let now = chrono::Utc::now().to_rfc3339(); + for id in kept { + self.dynamo + .update_item() + .table_name(&self.table) + .key("pk", s(team_id)) + .key("sk", s(&lesson_sk(repo, id))) + .condition_expression("attribute_exists(sk)") + .update_expression("SET #g = :y, #gp = :pr, #ga = :t") + .expression_attribute_names("#g", "in_guide") + .expression_attribute_names("#gp", "guide_pr") + .expression_attribute_names("#ga", "guide_at") + .expression_attribute_values(":y", AttributeValue::Bool(true)) + .expression_attribute_values(":pr", n(pr)) + .expression_attribute_values(":t", s(&now)) + .send() + .await + .map_err(|e| DisplayErrorContext(e).to_string())?; + } + for id in declined { + let line = format!("Declined for the guide file in PR #{pr}"); + self.dynamo + .update_item() + .table_name(&self.table) + .key("pk", s(team_id)) + .key("sk", s(&lesson_sk(repo, id))) + .condition_expression("attribute_exists(sk) AND attribute_not_exists(#gd)") + .update_expression( + "ADD #c :one SET #gd = :y, #gp = :pr, #ga = :t, \ + #ev = list_append(if_not_exists(#ev, :empty), :line)", + ) + .expression_attribute_names("#gd", "guide_declined") + .expression_attribute_names("#gp", "guide_pr") + .expression_attribute_names("#ga", "guide_at") + .expression_attribute_names("#c", "contradicted") + .expression_attribute_names("#ev", "evidence") + .expression_attribute_values(":one", n(1)) + .expression_attribute_values(":y", AttributeValue::Bool(true)) + .expression_attribute_values(":pr", n(pr)) + .expression_attribute_values(":t", s(&now)) + .expression_attribute_values(":empty", AttributeValue::L(vec![])) + .expression_attribute_values(":line", AttributeValue::L(vec![s(&line)])) + .send() + .await + .map(|_| ()) + .or_else(|e| { + let msg = DisplayErrorContext(&e).to_string(); + if msg.contains("ConditionalCheckFailed") { + Ok(()) // already settled, or the lesson is gone + } else { + Err(msg) + } + })?; + } + Ok(()) + } } /// Counts on a category record. @@ -1254,14 +1469,78 @@ pub fn lesson_of(i: &Item) -> Lesson { .and_then(|v| v.as_l().ok()) .map(|l| l.iter().filter_map(|v| v.as_s().ok().cloned()).collect()) .unwrap_or_default(), - reverted: i - .get("reverted") - .and_then(|v| v.as_bool().ok()) - .copied() - .unwrap_or(false), + reverted: gb(i, "reverted"), + check: gs(i, "check"), + applies_to: gs(i, "applies_to"), + source: gs(i, "source"), + prs: gl(i, "prs"), + contradicted: gu(i, "contradicted"), + in_guide: gb(i, "in_guide"), + guide_declined: gb(i, "guide_declined"), } } +fn gb(i: &Item, k: &str) -> bool { + i.get(k) + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false) +} + +fn gl(i: &Item, k: &str) -> Vec { + i.get(k) + .and_then(|v| v.as_l().ok()) + .map(|l| l.iter().filter_map(|v| v.as_s().ok().cloned()).collect()) + .unwrap_or_default() +} + +/// One outcome a lesson is distilled from: the pull request, what happened +/// to it, and the evidence lines kept with the lesson (what people changed +/// or said, in their words). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct OutcomeEvidence { + pub pr: u64, + /// `edited`, `closed` or `reverted` (`lessons::SOURCE_*`). + pub source: String, + pub run_id: String, + pub lines: Vec, +} + +/// What [`Store::learn_outcome`] did. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct OutcomeLearned { + /// The lesson written or reinforced. + pub lesson: Option, + pub written: bool, + /// Kept lessons the outcome counted against. + pub contradicted: Vec, +} + +/// Pure: the item of a lesson distilled from an outcome +/// (`lessons::new_outcome_lesson`); [`lesson_of`] reads it back. +pub fn outcome_lesson_item(team_id: &str, l: &Lesson) -> Item { + let list = |v: &[String]| AttributeValue::L(v.iter().map(|x| s(x)).collect()); + Item::from([ + ("pk".to_string(), s(team_id)), + ("sk".to_string(), s(&lesson_sk(&l.repo, &l.id))), + ("record_type".to_string(), s("reward_lesson")), + ("id".to_string(), s(&l.id)), + ("repo".to_string(), s(&l.repo)), + ("agent".to_string(), s(&l.agent)), + ("text".to_string(), s(&l.text)), + ("check".to_string(), s(&l.check)), + ("applies_to".to_string(), s(&l.applies_to)), + ("source".to_string(), s(&l.source)), + ("seen".to_string(), n(l.seen)), + ("contradicted".to_string(), n(l.contradicted)), + ("prs".to_string(), list(&l.prs)), + ("created_at".to_string(), s(&l.created_at)), + ("last_seen_at".to_string(), s(&l.last_seen_at)), + ("evidence".to_string(), list(&l.evidence)), + ("reverted".to_string(), AttributeValue::Bool(l.reverted)), + ]) +} + #[cfg(test)] mod tests { use super::*; @@ -1273,6 +1552,37 @@ mod tests { .collect() } + #[test] + fn an_outcome_lesson_reads_back_as_it_was_written() { + let d = super::super::lessons::Distilled { + rule: " Fetch through `useApi` in `apps/web`. ".into(), + check: "No `fetch(` in the diff.".into(), + applies_to: "apps/web".into(), + ..Default::default() + }; + let l = super::super::lessons::new_outcome_lesson( + "acme/web", + "L1", + &d, + "edited", + 12, + &["PR #12: people edited it before merging".to_string()], + "2026-10-02T00:00:00Z", + ); + let written = outcome_lesson_item("TEAM#a", &l); + assert_eq!(written["sk"], s("REWARDLESSON#acme/web#L1")); + assert_eq!(written["pk"], s("TEAM#a")); + let back = lesson_of(&written); + assert_eq!(back, l); + assert_eq!(back.text, "Fetch through `useApi` in `apps/web`."); + assert_eq!(back.prs, vec!["acme/web#12"]); + // A lesson written before these fields existed reads with none. + let old = item(&[("id", s("A")), ("text", s("x")), ("seen", n(3))]); + let l = lesson_of(&old); + assert_eq!((l.seen, l.contradicted, l.in_guide), (3, 0, false)); + assert!(l.check.is_empty() && l.prs.is_empty()); + } + #[test] fn keys_carry_repo_and_kind() { assert_eq!(cat_sk("acme/web", "style"), "REWARDCAT#acme/web#style"); diff --git a/services/common/src/scorecard.rs b/services/common/src/scorecard.rs new file mode 100644 index 000000000..4c773fd00 --- /dev/null +++ b/services/common/src/scorecard.rs @@ -0,0 +1,1819 @@ +//! The scorecard: what became of the pull requests CoderHelm opened, per +//! repository and per team, kept as counters that webhook events update. +//! +//! Of the pull requests CoderHelm opened: how many merged, closed without +//! merging or were reverted; how many review rounds they took before +//! approval; how long from opening to merging; how many needed a person's +//! commit on top before merging; how many finished with open items. +//! +//! Nothing here is counted by reading runs or pull requests back. Each pull +//! request has one small record ([`PrRecord`], `SCOREPR##`) +//! that the events change ([`Event`]): opened, a person's review, a person's +//! push to its branch, closed or merged, reopened, reverted. Every change of +//! the record adds the difference between what the record counted for before +//! and what it counts for now ([`contribution`]) to the counters, in the +//! same transaction that writes the record and only when the record is still +//! the one that was read ([`Store::commit`]). The differences telescope: a +//! redelivered webhook changes nothing, events may arrive in any order, and +//! two writers racing end with each pull request counted once in its last +//! state. +//! +//! Counters live on the settings table under the team's own key: +//! `SCORE##T` for the team and `SCORE##R#` for a +//! repository, where the period is the month the pull request was opened in +//! (`2026-11`) or [`ALL`]. A pull request always counts in the month it was +//! opened, so a month's numbers are about one fixed set of pull requests. +//! +//! Two pointers let events that carry no pull request number find it: +//! `SCOREBR##` (a push to the branch) and +//! `SCORESHA##` (a commit that reverts the merge commit). + +use aws_sdk_dynamodb::types::{AttributeValue, Put, TransactWriteItem, Update}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +pub const PR_PREFIX: &str = "SCOREPR#"; +pub const AGG_PREFIX: &str = "SCORE#"; +pub const BRANCH_PREFIX: &str = "SCOREBR#"; +pub const SHA_PREFIX: &str = "SCORESHA#"; +/// The period of the all-time counters. +pub const ALL: &str = "ALL"; +/// How long a pull request's record and pointers are kept after their last +/// change (a revert a year later still finds them). The counters stay. +pub const KEEP_DAYS: i64 = 400; +/// Most review ids and commit ids kept on one record. +pub const MAX_IDS: usize = 60; +/// Tries at writing a record another writer changed meanwhile. +const MAX_TRIES: usize = 5; + +/// Upper bounds, in hours, of the time-to-merge buckets (the last bucket is +/// everything longer). +pub const MERGE_HOURS: &[u64] = &[1, 4, 8, 24, 48, 72, 168, 336]; + +/// The markers of the sections a pull request's description lists open +/// items under: findings of CoderHelm's own review still open, and what the +/// run deferred. (The worker's tests hold these to the sections it writes.) +pub const OPEN_FINDINGS_START: &str = ""; +pub const OPEN_FINDINGS_END: &str = ""; +pub const DEFERRED_HEADING: &str = "## Deferred"; + +pub fn pr_sk(repo: &str, pr: u64) -> String { + format!("{PR_PREFIX}{repo}#{pr:06}") +} + +pub fn branch_sk(repo: &str, branch: &str) -> String { + format!("{BRANCH_PREFIX}{repo}#{branch}") +} + +pub fn sha_sk(repo: &str, sha: &str) -> String { + format!("{SHA_PREFIX}{repo}#{}", sha.to_ascii_lowercase()) +} + +pub fn team_sk(period: &str) -> String { + format!("{AGG_PREFIX}{period}#T") +} + +pub fn repo_agg_sk(period: &str, repo: &str) -> String { + format!("{AGG_PREFIX}{period}#R#{repo}") +} + +/// The month (`YYYY-MM`) of an RFC 3339 time; empty when it isn't one. +pub fn month_of(at: &str) -> String { + match chrono::DateTime::parse_from_rfc3339(at) { + Ok(t) => t.with_timezone(&chrono::Utc).format("%Y-%m").to_string(), + Err(_) => String::new(), + } +} + +/// Whether a pull request's description lists open items: an open-findings +/// section with at least one item, or a "Deferred" section with text in it. +pub fn has_open_items(body: &str) -> bool { + if let Some(start) = body.find(OPEN_FINDINGS_START) { + let rest = &body[start + OPEN_FINDINGS_START.len()..]; + let section = &rest[..rest.find(OPEN_FINDINGS_END).unwrap_or(rest.len())]; + if section + .lines() + .any(|l| l.trim_start().starts_with("- ") || l.trim_start().starts_with("* ")) + { + return true; + } + } + let mut lines = body.lines(); + while let Some(l) = lines.next() { + if l.trim() != DEFERRED_HEADING { + continue; + } + for next in lines.by_ref() { + let t = next.trim(); + if t.starts_with("## ") || t.starts_with("# ") { + break; + } + if !t.is_empty() && !t.starts_with(""; +pub const END: &str = ""; + +/// What running a test with and without the change showed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Verdict { + /// Fails without the change, passes with it. + Proven, + /// Passes with and without the change. + PassesEitherWay, + /// Fails without the change before any assertion runs (it can't build + /// or import there): it shows the code is new, not that the bug existed. + FailsBeforeAsserting, + /// Fails with the change too. + FailsWithChange, + /// Couldn't be run here. + NotRun, +} + +/// One test file's result. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct TestResult { + pub path: String, + pub verdict: Verdict, + /// The failure it printed without the change, or why it didn't run. + #[serde(default)] + pub detail: String, +} + +/// A changed file that is no part of the plan. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct OutsidePlan { + pub path: String, + /// The coder's reason; empty when it gave none. + #[serde(default)] + pub why: String, +} + +/// What the check found, for the pull request. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PrFacts { + #[serde(default)] + pub bug: bool, + #[serde(default)] + pub tests: Vec, + /// Why no test was run at all, when none was. + #[serde(default)] + pub no_tests: String, + #[serde(default)] + pub outside_plan: Vec, + /// Dependents the plan updates that the branch doesn't touch. + #[serde(default)] + pub not_updated: Vec, +} + +/// Why the check didn't give a result. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GateStop { + /// The sandbox runs need a step of their own. + NeedsTime, + /// The check couldn't read the change. + Why(String), +} + +/// One test file's run: its exit code and, when it failed, what it printed. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FileRun { + pub code: Option, + pub output: String, +} + +/// Both runs of the changed test files, in the files' order. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Runs { + pub with: Vec, + pub without: Vec, +} + +/// Where the test files are run with and without the change. +#[async_trait::async_trait] +pub trait Bench: Send + Sync { + /// Runs each file on its own on the branch and on the base with only + /// these files added. `Err` says why nothing ran. + async fn run(&self, files: &[String]) -> Result; +} + +const NOT_FOUND_MARKS: &[&str] = &[ + "no tests found", + "no test files found", + "no tests ran", + "no test suite found", + "no tests to run", + "[no test files]", + "collected 0 items", +]; + +const BEFORE_ASSERT_MARKS: &[&str] = &[ + "cannot find module", + "failed to resolve import", + "does not provide an export named", + "is not exported", + "modulenotfounderror", + "importerror", + "cannot import name", + "syntaxerror", + "error ts", + "undefined:", + "has no member named", + "cannot find symbol", + "unresolved import", + "build failed", +]; + +fn has_any(text: &str, marks: &[&str]) -> bool { + let low = text.to_ascii_lowercase(); + marks.iter().any(|m| low.contains(m)) +} + +/// The first line of a failing run that says what failed. +fn excerpt(output: &str) -> String { + let lines: Vec<&str> = output + .lines() + .map(str::trim) + .filter(|l| !l.is_empty() && !l.starts_with("---")) + .collect(); + let with_any = |words: &[&str]| { + lines.iter().find(|l| { + let low = l.to_ascii_lowercase(); + words.iter().any(|w| low.contains(w)) + }) + }; + let line = with_any(&["expected", "assert", "error", "panic", "received"]) + .or_else(|| with_any(&["fail"])) + .or(lines.first()) + .copied() + .unwrap_or(""); + common::truncate_str(line, 200).replace('`', "'") +} + +/// What one file's two runs show. +pub fn verdict(with: &FileRun, without: &FileRun) -> (Verdict, String) { + match (with.code, without.code) { + (None, _) | (_, None) => ( + Verdict::NotRun, + "the sandbox gave no result for it".to_string(), + ), + (Some(w), _) if w != 0 && has_any(&with.output, NOT_FOUND_MARKS) => ( + Verdict::NotRun, + "the test command, scoped to this file, found no tests in it".to_string(), + ), + (Some(w), _) if w != 0 => (Verdict::FailsWithChange, excerpt(&with.output)), + (Some(_), Some(0)) => (Verdict::PassesEitherWay, String::new()), + (Some(_), Some(_)) if has_any(&without.output, NOT_FOUND_MARKS) => ( + Verdict::NotRun, + "the test command found no tests in it without the change".to_string(), + ), + (Some(_), Some(_)) if has_any(&without.output, BEFORE_ASSERT_MARKS) => { + (Verdict::FailsBeforeAsserting, excerpt(&without.output)) + } + (Some(_), Some(_)) => (Verdict::Proven, excerpt(&without.output)), + } +} + +/// A repository's unit test command narrowed to one test file, or `None` +/// when CoderHelm can't narrow that runner. Never passes with no tests: a +/// filter that matches nothing must not read as a test that passes. +pub fn scoped_cmd(base_cmd: &str, file: &str) -> Option { + let safe = !file.is_empty() + && file + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '/')) + && !file.contains(".."); + if !safe { + return None; + } + let low = base_cmd.to_ascii_lowercase(); + if low.contains("pytest") { + return Some(format!("{base_cmd} {file}")); + } + if low.trim_start().starts_with("go test") { + let dir = file.rsplit_once('/').map_or(".", |(d, _)| d); + return Some(format!("go test ./{dir}/")); + } + super::build_scoped_test_cmd(base_cmd, &[file.to_string()]) + .map(|c| c.replace(" --passWithNoTests", "")) +} + +/// The output of each failing step of a sandbox script, in step order. +pub fn failing_outputs(output: &str, kind: &str) -> Vec { + let mark = format!("--- {kind} failed (exit "); + output + .split(&mark) + .skip(1) + .map(|block| { + let body = block.split_once('\n').map_or("", |(_, b)| b); + let end = body + .find(&format!("--- {kind} failed")) + .or_else(|| body.find(test_package::STEP_MARK)) + .unwrap_or(body.len()); + body[..end].trim().to_string() + }) + .collect() +} + +/// Each step's run from a sandbox script's codes and output: the failing +/// steps' outputs are printed in order. +pub fn file_runs(codes: &[Option], output: &str, kind: &str) -> Vec { + let mut failures = failing_outputs(output, kind).into_iter(); + codes + .iter() + .map(|c| FileRun { + code: *c, + output: match c { + Some(n) if *n != 0 => failures.next().unwrap_or_default(), + _ => String::new(), + }, + }) + .collect() +} + +// ── What the diff shows ──────────────────────────────────────────────────── + +/// The change as the check reads it: every changed path and its status. +pub type Diff = [(String, String, String)]; + +/// The new and changed test files (never a removed one, never a snapshot). +pub fn changed_tests(diff: &Diff) -> Vec { + diff.iter() + .filter(|(p, status, _)| { + status != "removed" && is_test_path(p) && !p.contains("__snapshots__/") + }) + .map(|(p, _, _)| p.clone()) + .collect() +} + +fn changes_code(diff: &Diff) -> bool { + diff.iter().any(|(p, _, _)| !is_test_path(p)) +} + +const OUTSIDE_LINE: &str = "outside the plan:"; + +/// The coder's reasons for files outside the plan, from its notes +/// (`Outside the plan: : `). +pub fn reasons(notes: &str) -> Vec<(String, String)> { + notes + .lines() + .filter_map(|l| { + let l = l.trim().trim_start_matches(['-', '*']).trim(); + let at = l.to_ascii_lowercase().find(OUTSIDE_LINE)?; + let rest = l[at + OUTSIDE_LINE.len()..].trim(); + let (path, why) = rest.split_once(": ")?; + let path = path.trim().trim_matches('`').trim(); + let why = why.trim(); + (!path.is_empty() && !why.is_empty()).then(|| (path.to_string(), why.to_string())) + }) + .collect() +} + +fn norm(p: &str) -> String { + super::generators::normalize_path(p) +} + +/// The changed files that are no part of the plan: not a task's file (or +/// under a task's directory), not a test, lockfile or settled generated +/// output, not a dependent the plan updates. Each carries the coder's +/// reason when its notes give one. +pub fn outside_plan( + changed: &[String], + plan: &PlanResult, + generated: &[String], + notes: &str, +) -> Vec { + let planned: Vec = super::feature::plan_files::planned_files(&plan.tasks) + .into_iter() + .map(|f| norm(&f.path)) + .collect(); + // A plan that names no files states no scope to hold the change to. + if planned.is_empty() { + return Vec::new(); + } + let updates: Vec = plan + .fix + .as_ref() + .map(|d| { + d.habits + .affected + .iter() + .filter(|a| a.updates()) + .map(|a| norm(a.path())) + .collect() + }) + .unwrap_or_default(); + let why = reasons(notes); + changed + .iter() + .filter(|c| { + let c = norm(c); + let in_plan = planned + .iter() + .any(|p| *p == c || (p.ends_with('/') && c.starts_with(p.as_str()))); + !(in_plan + || updates.contains(&c) + || is_test_path(&c) + || common::lockfile_sync::lock_manager(&c).is_some() + || generated + .iter() + .any(|g| super::generators::glob_match(g, &c))) + }) + .map(|c| OutsidePlan { + path: c.clone(), + why: why + .iter() + .find(|(p, _)| norm(p) == norm(c)) + .map(|(_, w)| w.clone()) + .unwrap_or_default(), + }) + .collect() +} + +/// The dependents of this repository the plan updates that the branch +/// doesn't touch. +pub fn not_updated(changed: &[String], plan: &PlanResult, own_repo: &str) -> Vec { + let Some(d) = plan.fix.as_ref() else { + return Vec::new(); + }; + d.habits + .affected + .iter() + .filter(|a| a.updates() && a.repo().is_none_or(|r| r.eq_ignore_ascii_case(own_repo))) + .map(|a| a.path().to_string()) + .filter(|p| !p.is_empty() && !changed.iter().any(|c| norm(c) == norm(p))) + .collect() +} + +/// Reads the change against the plan and runs the changed tests with and +/// without it. +pub async fn check_once( + bench: &dyn Bench, + diff: &Diff, + plan: &PlanResult, + own_repo: &str, + generated: &[String], + notes: &str, +) -> PrFacts { + let changed: Vec = diff.iter().map(|(p, _, _)| p.clone()).collect(); + let fix = plan.fix.as_ref(); + let mut facts = PrFacts { + bug: fix.is_some_and(|d| d.intent.is_bug()), + outside_plan: outside_plan(&changed, plan, generated, notes), + not_updated: not_updated(&changed, plan, own_repo), + ..Default::default() + }; + let tests = changed_tests(diff); + if tests.is_empty() { + facts.no_tests = "the change adds or changes no test file".to_string(); + return facts; + } + if !changes_code(diff) { + facts.no_tests = "the change is only tests, so there is no fix to take out".to_string(); + return facts; + } + let (run, extra) = tests.split_at(tests.len().min(MAX_TEST_FILES)); + match bench.run(run).await { + Ok(runs) => { + let none = FileRun::default(); + for (i, path) in run.iter().enumerate() { + let (verdict, detail) = verdict( + runs.with.get(i).unwrap_or(&none), + runs.without.get(i).unwrap_or(&none), + ); + facts.tests.push(TestResult { + path: path.clone(), + verdict, + detail, + }); + } + } + Err(why) => { + for path in run { + facts.tests.push(TestResult { + path: path.clone(), + verdict: Verdict::NotRun, + detail: why.clone(), + }); + } + } + } + for path in extra { + facts.tests.push(TestResult { + path: path.clone(), + verdict: Verdict::NotRun, + detail: format!("only the first {MAX_TEST_FILES} test files are run on their own"), + }); + } + facts +} + +/// Whether a bug's plan says no failing test can be written. +fn repro_waived(plan: &PlanResult) -> bool { + plan.fix + .as_ref() + .is_some_and(|d| !d.habits.repro.not_feasible.trim().is_empty()) +} + +/// What the coder must fix, one line each. Empty when the change holds. +pub fn blocking(f: &PrFacts, plan: &PlanResult) -> Vec { + let mut out = Vec::new(); + let repro = plan + .fix + .as_ref() + .map(|d| d.habits.repro.test.trim().to_string()) + .unwrap_or_default(); + for t in &f.tests { + match t.verdict { + Verdict::PassesEitherWay => out.push(format!( + "`{}` passes with the change taken out, so it doesn't test the change. Make it assert the behaviour the change adds or fixes (it must fail on the base code), through code that exists on the base.", + t.path + )), + Verdict::FailsWithChange => out.push(format!( + "`{}` fails with the change in place ({}). Fix the code or the test until it passes.", + t.path, t.detail + )), + Verdict::FailsBeforeAsserting if f.bug && (repro.is_empty() || norm(&repro) == norm(&t.path)) => out.push(format!( + "`{}` fails on the base code before any assertion runs ({}), so it doesn't show the reported failure. Test through an entry point that exists on the base, so the test builds there and fails on its assertion.", + t.path, t.detail + )), + _ => {} + } + } + if f.bug && f.tests.is_empty() && !repro_waived(plan) && f.no_tests.contains("no test file") { + out.push("This is a bug fix and the change has no test that fails without it. Add the test that reproduces the reported failure (it must fail on the base code and pass with the fix).".to_string()); + } + for o in f.outside_plan.iter().filter(|o| o.why.is_empty()) { + out.push(format!( + "`{}` was changed and is no task of the plan. Put it back with `restore_file` (omit `from_ref`), or, when the change truly needs it, say why in your Evidence on a line `Outside the plan: {}: `.", + o.path, o.path + )); + } + for p in &f.not_updated { + out.push(format!( + "The plan says `{p}` depends on this change and is updated with it, but the branch doesn't touch it. Update it." + )); + } + out +} + +/// The fix round's instructions. +pub fn fix_feedback(lines: &[String]) -> String { + format!( + "The check after the build ran each new or changed test with and without your change, and compared the changed files with the plan. Fix every item:\n{}\nDo not delete or skip a test to settle an item.", + lines + .iter() + .map(|l| format!("- {l}")) + .collect::>() + .join("\n") + ) +} + +/// What is still open after the fix rounds, for Open items. +pub fn open_findings(f: &PrFacts, plan: &PlanResult) -> Vec { + blocking(f, plan) + .into_iter() + .map(|l| { + let (point, settle) = if l.contains("no task of the plan") { + ( + "Changed outside the plan", + "CoderHelm restores it or records why the change needs it in its next round on this pull request.", + ) + } else if l.contains("depends on this change") { + ( + "Dependent not updated", + "CoderHelm updates it in its next round on this pull request.", + ) + } else { + ( + "Test doesn't prove the change", + "CoderHelm rewrites the test in its next round on this pull request; CI's result alone doesn't settle it.", + ) + }; + Finding { + point: point.to_string(), + detail: l.split(". ").next().unwrap_or(&l).trim_end_matches('.').to_string() + ".", + settle: settle.to_string(), + ..Default::default() + } + }) + .collect() +} + +fn test_line(t: &TestResult) -> String { + let detail = |d: &str| { + if d.is_empty() { + String::new() + } else { + format!(": `{d}`") + } + }; + match t.verdict { + Verdict::Proven => format!( + "- `{}`: fails without the change{}; passes with it.", + t.path, + detail(&t.detail) + ), + Verdict::FailsBeforeAsserting => format!( + "- `{}`: can't build or load without the change{}; passes with it. It covers the new code, it doesn't show a failure on the old.", + t.path, + detail(&t.detail) + ), + Verdict::PassesEitherWay => format!( + "- `{}`: passes with and without the change, so it doesn't test it yet.", + t.path + ), + Verdict::FailsWithChange => format!( + "- `{}`: fails with the change{}.", + t.path, + detail(&t.detail) + ), + Verdict::NotRun => format!("- `{}`: not run both ways here ({}).", t.path, t.detail), + } +} + +/// The pull request's section: the proof the tests give, what the files' +/// history showed, who the change affects, and what changed outside the +/// plan. Empty when there is nothing to say. +pub fn section(plan: &PlanResult, f: &PrFacts) -> String { + let mut out = String::new(); + let h = plan.fix.as_ref().map(|d| &d.habits); + let repro = h.map(|h| &h.repro); + if !f.tests.is_empty() { + out.push_str(if f.bug { + "**Reproduced, then fixed** (each new or changed test run on the base code with only the tests added, then on this branch)\n" + } else { + "**The tests fail without the change** (each new or changed test run on the base code with only the tests added, then on this branch)\n" + }); + for t in &f.tests { + out.push_str(&test_line(t)); + out.push('\n'); + } + out.push('\n'); + } else if let Some(r) = repro.filter(|r| f.bug && !r.not_feasible.trim().is_empty()) { + out.push_str(&format!( + "**No failing test for this fix:** {}. Proof instead: {}.\n\n", + r.not_feasible.trim().trim_end_matches('.'), + r.next_best.trim().trim_end_matches('.') + )); + } + if let Some(h) = h { + let hist: Vec<&habits::AreaHistory> = h + .area_history + .iter() + .filter(|a| !a.found.trim().is_empty()) + .collect(); + if !hist.is_empty() { + out.push_str("**History of the touched files**\n"); + for a in hist { + let refs = if a.refs.is_empty() { + String::new() + } else { + format!(" ({})", a.refs.join(", ")) + }; + out.push_str(&format!("- `{}`{refs}: {}", a.path.trim(), a.found.trim())); + if !a.bearing.trim().is_empty() { + out.push_str(&format!(" For this change: {}", a.bearing.trim())); + } + out.push('\n'); + } + out.push('\n'); + } + let affected: Vec<&habits::Affected> = h + .affected + .iter() + .filter(|a| !a.where_.trim().is_empty()) + .collect(); + if !affected.is_empty() { + out.push_str("**Who this affects**\n"); + for a in affected { + let uses = if a.uses.trim().is_empty() { + String::new() + } else { + format!(" (uses {})", a.uses.trim()) + }; + let state = if a.action.trim() == habits::UNCHECKED { + "found by a search of the team's repositories; the plan didn't settle whether it must change".to_string() + } else if !a.updates() { + format!("safe: {}", a.why.trim()) + } else if f.not_updated.iter().any(|p| norm(p) == norm(a.path())) { + "planned to change with this, not changed yet".to_string() + } else if a.repo().is_some() { + format!("changes in its own pull request: {}", a.why.trim()) + } else { + "updated in this pull request".to_string() + }; + out.push_str(&format!("- `{}`{uses}: {state}\n", a.where_.trim())); + } + out.push('\n'); + } else if !h.no_outside_use.trim().is_empty() { + out.push_str(&format!( + "**Who this affects:** nothing outside this repository ({}).\n\n", + h.no_outside_use.trim().trim_end_matches('.') + )); + } + } + if !f.outside_plan.is_empty() { + out.push_str("**Changed outside the plan's files**\n"); + for o in &f.outside_plan { + out.push_str(&format!( + "- `{}`: {}\n", + o.path, + if o.why.is_empty() { + "no reason recorded yet" + } else { + o.why.as_str() + } + )); + } + out.push('\n'); + } + if out.is_empty() { + return out; + } + format!( + "{START}\n### Before and after the code\n{}\n{END}", + out.trim_end() + ) +} + +/// The description with the section in place: replaced where it stands, +/// added at the end the first time, taken out when there is none. +pub fn shape_body(body: String, section: &str) -> String { + let stripped = match (body.find(START), body.find(END)) { + (Some(s), Some(e)) if e > s => { + format!("{}{}", &body[..s], &body[e + END.len()..]) + } + _ => body.clone(), + }; + if section.is_empty() { + return if stripped == body { + body + } else { + format!("{}\n", stripped.trim_end()) + }; + } + match (body.find(START), body.find(END)) { + (Some(s), Some(e)) if e > s => { + format!("{}{section}{}", &body[..s], &body[e + END.len()..]) + } + _ => format!("{}\n\n{section}\n", body.trim_end()), + } +} + +// ── The sandbox ──────────────────────────────────────────────────────────── + +/// Runs the test files in the sandbox on the branch and on a temporary +/// branch holding the base with only those files. +pub struct SandboxBench<'a> { + pub runner: super::test_bug::Runner<'a>, + pub base_branch: &'a str, + pub branch: &'a str, +} + +const KIND: &str = "unit"; + +#[async_trait::async_trait] +impl Bench for SandboxBench<'_> { + async fn run(&self, files: &[String]) -> Result { + let r = &self.runner; + let base_cmd = super::detect_ci_test(r.github, r.owner, r.repo, self.base_branch) + .await + .ok_or("the repository's CI runs no unit test command CoderHelm can read")?; + let mut steps: Vec = Vec::new(); + let tree: Vec = r + .github + .get_tree(r.owner, r.repo, self.branch) + .await + .map_err(|e| e.to_string())? + .into_iter() + .map(|e| e.path) + .collect(); + let install: Vec = files + .first() + .and_then(|f| test_package::package_of(&tree, f, &|_| None)) + .and_then(|p| test_package::check_steps(&p)) + .map(|s| s.into_iter().filter(|s| s.kind == "install").collect()) + .unwrap_or_default(); + let installs = install.len(); + steps.extend(install); + for f in files { + let cmd = scoped_cmd(&base_cmd, f).ok_or_else(|| { + format!("the test command `{base_cmd}` can't be narrowed to one file") + })?; + steps.push(Step { kind: KIND, cmd }); + } + let head = r + .github + .get_ref(r.owner, r.repo, self.branch) + .await + .map_err(|e| e.to_string())?; + let base_sha = r + .github + .get_ref(r.owner, r.repo, self.base_branch) + .await + .map_err(|e| e.to_string())?; + let temp = format!("{}-without-change", self.branch); + // One left by a step that was cut off is in the way of a new one. + let _ = r.github.delete_branch(r.owner, r.repo, &temp).await; + r.github + .create_branch(r.owner, r.repo, &temp, &base_sha) + .await + .map_err(|e| format!("a branch for the check couldn't be made ({e})"))?; + let both = async { + for f in files { + let content = r + .github + .read_file(r.owner, r.repo, f, self.branch) + .await + .map_err(|e| e.to_string())?; + let sha = r.github.get_file_sha(r.owner, r.repo, f, &temp).await.ok(); + r.github + .write_file( + r.owner, + r.repo, + f, + &content, + &temp, + "test: the changed tests on the code before the change", + sha.as_deref(), + ) + .await + .map_err(|e| e.to_string())?; + } + let before_sha = r + .github + .get_ref(r.owner, r.repo, &temp) + .await + .map_err(|e| e.to_string())?; + // Side by side: each waits on its own sandbox build. + let (with, without) = tokio::join!( + r.run_at(&head, &steps, None), + r.run_at(&before_sha, &steps, None) + ); + Ok::<_, String>((with?, without?)) + } + .await; + if let Err(e) = r.github.delete_branch(r.owner, r.repo, &temp).await { + warn!(error = %e, branch = %temp, "Could not delete the branch of the test check"); + } + let ((with_codes, with_out), (without_codes, without_out)) = both?; + let per_file = |codes: &[Option], out: &str| { + let failed_installs = codes.iter().take(installs).any(|c| *c != Some(0)); + let runs = file_runs(&codes[installs.min(codes.len())..], out, KIND); + (failed_installs, runs) + }; + let (with_broken, with) = per_file(&with_codes, &with_out); + let (without_broken, without) = per_file(&without_codes, &without_out); + if with_broken || without_broken { + return Err("the package's install failed in the sandbox".to_string()); + } + Ok(Runs { with, without }) + } +} + +/// The check on the open pull request. `Ok(None)` when the plan plans no +/// code. A problem gets a fix round; what is still open after the rounds is +/// in the facts ([`open_findings`]). +pub async fn gate( + w: &super::proof::Work<'_>, + evidence: &mut super::proof::RunEvidence, + usage: &mut crate::models::TokenUsage, + has_time: impl Fn() -> bool, + secs_left: impl Fn() -> u64, +) -> Result, GateStop> { + let head = w.head().await; + let standing = w.ledger.update(|l| { + if !l.habits.unchanged(&head) { + return None; + } + l.habits.reused(); + l.habits_outcome.clone() + }); + if let Some(standing) = standing { + return standing.map_err(GateStop::Why); + } + let outcome = check_and_fix(w, evidence, usage, has_time, secs_left).await; + if outcome == Err(GateStop::NeedsTime) { + return outcome; + } + let head = w.head().await; + let kept = outcome.clone().map_err(|e| match e { + GateStop::Why(why) => why, + GateStop::NeedsTime => String::new(), + }); + w.ledger.update(|l| { + l.habits.head = head; + l.habits_outcome = Some(kept); + }); + w.save_ledger().await; + outcome +} + +/// A bench for a step with no time for the sandbox: nothing runs, and each +/// test says so. +struct NoTime; + +#[async_trait::async_trait] +impl Bench for NoTime { + async fn run(&self, _files: &[String]) -> Result { + Err("no step of the run had the time for the two sandbox runs; the repository's CI runs the tests on this pull request".to_string()) + } +} + +async fn check_and_fix( + w: &super::proof::Work<'_>, + evidence: &mut super::proof::RunEvidence, + usage: &mut crate::models::TokenUsage, + has_time: impl Fn() -> bool, + secs_left: impl Fn() -> u64, +) -> Result, GateStop> { + let own_repo = format!("{}/{}", w.msg.repo_owner, w.msg.repo_name); + if super::feature::plan_files::planned_files(&w.plan.tasks).is_empty() { + return Ok(None); + } + loop { + let diff = w + .github + .compare_files_with_patches( + &w.msg.repo_owner, + &w.msg.repo_name, + &w.msg.base_branch, + w.branch, + ) + .await + .map_err(|e| GateStop::Why(format!("the diff couldn't be read ({e})")))?; + let paths: Vec = diff.iter().map(|(p, _, _)| p.clone()).collect(); + let work = super::run_end::work_files(&paths, &w.msg.ticket_id); + let diff: Vec<(String, String, String)> = diff + .into_iter() + .filter(|(p, _, _)| work.contains(p)) + .collect(); + let needs_sandbox = !changed_tests(&diff).is_empty() && changes_code(&diff); + let short = needs_sandbox && secs_left() < SANDBOX_STEP_SECS; + if short + && !w + .ledger + .update(|l| std::mem::replace(&mut l.habits_waited, true)) + { + w.save_ledger().await; + return Err(GateStop::NeedsTime); + } + let sandbox = SandboxBench { + runner: super::test_bug::Runner { + state: w.state, + github: w.github, + owner: &w.msg.repo_owner, + repo: &w.msg.repo_name, + team_id: &w.msg.team_id, + run_id: w.run_id, + provider: w.provider, + }, + base_branch: &w.msg.base_branch, + branch: w.branch, + }; + let bench: &dyn Bench = if short { &NoTime } else { &sandbox }; + let facts = check_once( + bench, + &diff, + w.plan, + &own_repo, + w.generated, + &evidence.notes, + ) + .await; + let blocking = blocking(&facts, w.plan); + info!( + run_id = w.run_id, + tests = facts.tests.len(), + outside_plan = facts.outside_plan.len(), + blocking = blocking.len(), + rounds = w.ledger.update(|l| l.habits.rounds), + "Check of the change against the plan's habits complete" + ); + let proven = facts + .tests + .iter() + .filter(|t| t.verdict == Verdict::Proven) + .count(); + if blocking.is_empty() { + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + &format!( + "Tests and scope check passed: {proven} of {} changed test file(s) fail without the change and pass with it; no file changed outside the plan without a reason", + facts.tests.len() + ), + ) + .await; + return Ok(Some(facts)); + } + w.report_findings("habits", blocking.len()).await; + let head = w.head().await; + w.ledger.update(|l| l.habits.checked(&head, blocking.len())); + let licence = if w.ledger.update(|l| l.habits.may_fix(MAX_FIX_ROUNDS)) && has_time() { + super::stop_judge::cycle_licence( + w.state, + w.msg, + w.run_id, + "habits_check", + w.ledger.update(|l| l.habits.rounds), + MAX_FIX_ROUNDS, + &super::stop_judge::evidence_lines("tests and scope check", &blocking), + ) + .await + } else { + None + }; + let Some(licence) = licence else { + w.save_ledger().await; + return Ok(Some(facts)); + }; + w.ledger.update(|l| l.habits.start_fix(licence)); + w.save_ledger().await; + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + &format!( + "Tests and scope check found {} item(s), fixing: {}", + blocking.len(), + common::truncate_str(&blocking.join(" "), 600) + ), + ) + .await; + let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "implement").await; + let fixed = super::implement::run( + w.state, + w.msg, + w.github, + w.plan, + w.branch, + w.rules, + w.repo_instructions, + Some(&fix_feedback(&blocking)), + "medium", + w.provider, + usage, + w.file_cache, + Some(w.run_id), + w.deadline, + true, + ) + .await; + w.ledger.update(|l| l.habits.end_fix()); + w.save_ledger().await; + let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, super::PASS_CHECKS).await; + match fixed { + Ok(r) => evidence.merge(r.evidence), + Err(e) => { + warn!(run_id = w.run_id, error = %e, "The fix round of the tests and scope check failed"); + return Ok(Some(facts)); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::passes::fix_location::FixDecision; + use crate::passes::habits::{Affected, AreaHistory, Habits, Repro}; + use crate::passes::triage::TicketIntent; + + fn run(code: i32, output: &str) -> FileRun { + FileRun { + code: Some(code), + output: output.into(), + } + } + + pub(crate) struct Fake(pub Result); + + #[async_trait::async_trait] + impl Bench for Fake { + async fn run(&self, _files: &[String]) -> Result { + self.0.clone() + } + } + + fn plan(tasks: &str, intent: TicketIntent, habits: Habits) -> PlanResult { + PlanResult { + proposal: String::new(), + design: String::new(), + tasks: tasks.into(), + spec: String::new(), + repo_tasks: Vec::new(), + fix: Some(FixDecision { + intent, + habits, + ..Default::default() + }), + } + } + + fn diff(paths: &[&str]) -> Vec<(String, String, String)> { + paths + .iter() + .map(|p| (p.to_string(), "modified".to_string(), String::new())) + .collect() + } + + const TASKS: &str = "- [ ] src/cart/total.test.ts: [modify] Three lines of 0.335\n- [ ] src/cart/total.ts: [modify] Round per line\n"; + + #[test] + fn two_runs_of_one_test_read_as_one_verdict() { + let pass = run(0, ""); + let assertion = run( + 1, + "FAIL src/cart/total.test.ts\nAssertionError: expected 1 to be 1.01", + ); + assert_eq!( + verdict(&pass, &assertion), + ( + Verdict::Proven, + "AssertionError: expected 1 to be 1.01".to_string() + ) + ); + assert_eq!(verdict(&pass, &pass).0, Verdict::PassesEitherWay); + let import = run( + 1, + "Error: Failed to resolve import \"./perLine\" from src/cart/total.test.ts", + ); + assert_eq!(verdict(&pass, &import).0, Verdict::FailsBeforeAsserting); + assert_eq!(verdict(&assertion, &assertion).0, Verdict::FailsWithChange); + // A filter that matched nothing is never a test that failed or passed. + let none = run(1, "No test files found, exiting with code 1"); + assert_eq!(verdict(&none, &none).0, Verdict::NotRun); + assert_eq!(verdict(&pass, &none).0, Verdict::NotRun); + assert_eq!(verdict(&FileRun::default(), &pass).0, Verdict::NotRun); + } + + #[test] + fn a_test_command_is_narrowed_to_one_file_and_never_passes_on_nothing() { + let c = scoped_cmd("pnpm exec vitest run", "src/cart/total.test.ts").unwrap(); + assert_eq!(c, "pnpm exec vitest run total.test.ts"); + assert!(!scoped_cmd("pnpm test", "src/a.test.ts") + .unwrap() + .contains("passWithNoTests")); + assert_eq!( + scoped_cmd("python -m pytest -q", "tests/test_total.py").as_deref(), + Some("python -m pytest -q tests/test_total.py") + ); + assert_eq!( + scoped_cmd("go test ./...", "pkg/cart/total_test.go").as_deref(), + Some("go test ./pkg/cart/") + ); + assert_eq!(scoped_cmd("cargo test", "src/total.rs"), None); + assert_eq!(scoped_cmd("pytest", "tests/$(id).py"), None); + assert_eq!(scoped_cmd("pytest", "../outside.py"), None); + } + + #[test] + fn each_failing_step_gets_its_own_output() { + let steps = vec![ + Step { + kind: KIND, + cmd: "a".into(), + }, + Step { + kind: KIND, + cmd: "b".into(), + }, + Step { + kind: KIND, + cmd: "c".into(), + }, + ]; + // The script's own shape: failing steps' tails, then one mark per step. + assert!(test_package::sandbox_script(&steps, None) + .contains("--- unit failed (exit $ch_t1) ---")); + let out = "--- unit failed (exit 1) ---\nexpected 1 to be 1.01\n\n--- unit failed (exit 2) ---\nNo test files found\n\nCODERHELM_TEST_STEP 1 1\nCODERHELM_TEST_STEP 2 0\nCODERHELM_TEST_STEP 3 2\n"; + let codes = test_package::step_codes(out, 3); + let runs = file_runs(&codes, out, KIND); + assert_eq!(runs[0], run(1, "expected 1 to be 1.01")); + assert_eq!(runs[1], run(0, "")); + assert_eq!(runs[2], run(2, "No test files found")); + } + + #[tokio::test] + async fn a_test_that_passes_either_way_goes_back_to_the_coder() { + let p = plan(TASKS, TicketIntent::Bug, Habits::default()); + let bench = Fake(Ok(Runs { + with: vec![run(0, "")], + without: vec![run(0, "")], + })); + let d = diff(&["src/cart/total.ts", "src/cart/total.test.ts"]); + let f = check_once(&bench, &d, &p, "acme/shop-api", &[], "").await; + assert_eq!(f.tests[0].verdict, Verdict::PassesEitherWay); + let b = blocking(&f, &p); + assert_eq!(b.len(), 1); + assert!(b[0].contains("passes with the change taken out")); + assert!(fix_feedback(&b).contains("Do not delete or skip a test")); + let open = open_findings(&f, &p); + assert_eq!(open[0].point, "Test doesn't prove the change"); + assert!(section(&p, &f).contains("passes with and without the change")); + } + + #[tokio::test] + async fn a_bug_fix_carries_the_failing_then_passing_result() { + let p = plan( + TASKS, + TicketIntent::Bug, + Habits { + repro: Repro { + test: "src/cart/total.test.ts".into(), + ..Default::default() + }, + ..Default::default() + }, + ); + let bench = Fake(Ok(Runs { + with: vec![run(0, "")], + without: vec![run(1, "AssertionError: expected 1 to be 1.01")], + })); + let d = diff(&["src/cart/total.ts", "src/cart/total.test.ts"]); + let f = check_once(&bench, &d, &p, "acme/shop-api", &[], "").await; + assert!(blocking(&f, &p).is_empty()); + let s = section(&p, &f); + assert!(s.starts_with(START) && s.ends_with(END)); + assert!(s.contains("**Reproduced, then fixed**")); + assert!(s.contains("- `src/cart/total.test.ts`: fails without the change: `AssertionError: expected 1 to be 1.01`; passes with it.")); + } + + #[tokio::test] + async fn a_bug_test_that_cannot_build_on_the_base_does_not_reproduce() { + let p = plan(TASKS, TicketIntent::Bug, Habits::default()); + let bench = Fake(Ok(Runs { + with: vec![run(0, "")], + without: vec![run(1, "Error: Cannot find module './perLine'")], + })); + let d = diff(&["src/cart/total.ts", "src/cart/total.test.ts"]); + let f = check_once(&bench, &d, &p, "acme/shop-api", &[], "").await; + assert!(blocking(&f, &p)[0].contains("before any assertion runs")); + // For new work the same result is a test of new code: noted, not blocking. + let feature = plan(TASKS, TicketIntent::Feature, Habits::default()); + let f = check_once(&bench, &d, &feature, "acme/shop-api", &[], "").await; + assert!(blocking(&f, &feature).is_empty()); + assert!(section(&feature, &f).contains("It covers the new code")); + } + + #[tokio::test] + async fn a_bug_without_a_test_needs_the_plans_reason_and_next_best_proof() { + let d = diff(&["config/limits.yml"]); + let tasks = "- [ ] config/limits.yml: [modify] Raise the limit\n"; + let bare = plan(tasks, TicketIntent::Bug, Habits::default()); + let f = check_once( + &Fake(Err("unused".into())), + &d, + &bare, + "acme/shop-api", + &[], + "", + ) + .await; + assert!(blocking(&f, &bare)[0].contains("no test that fails without it")); + let waived = plan( + tasks, + TicketIntent::Bug, + Habits { + repro: Repro { + not_feasible: "a value in a YAML file no test loads".into(), + next_best: "GET /limits returns 50 before and 100 after".into(), + ..Default::default() + }, + ..Default::default() + }, + ); + let f = check_once( + &Fake(Err("unused".into())), + &d, + &waived, + "acme/shop-api", + &[], + "", + ) + .await; + assert!(blocking(&f, &waived).is_empty()); + let s = section(&waived, &f); + assert!(s.contains("**No failing test for this fix:** a value in a YAML file no test loads. Proof instead: GET /limits returns 50 before and 100 after.")); + } + + #[tokio::test] + async fn tests_that_could_not_run_are_said_so_and_block_nothing() { + let p = plan(TASKS, TicketIntent::Feature, Habits::default()); + let d = diff(&["src/cart/total.ts", "src/cart/total.test.ts"]); + let f = check_once(&NoTime, &d, &p, "acme/shop-api", &[], "").await; + assert_eq!(f.tests[0].verdict, Verdict::NotRun); + assert!(blocking(&f, &p).is_empty()); + assert!(section(&p, &f).contains("not run both ways here (no step of the run had the time")); + // More files than are run on their own: the rest are named. + let many: Vec = (0..10).map(|i| format!("src/t{i}.test.ts")).collect(); + let mut paths: Vec<&str> = many.iter().map(String::as_str).collect(); + paths.push("src/cart/total.ts"); + let runs = Runs { + with: vec![run(0, ""); MAX_TEST_FILES], + without: vec![run(1, "expected"); MAX_TEST_FILES], + }; + let f = check_once(&Fake(Ok(runs)), &diff(&paths), &p, "acme/shop-api", &[], "").await; + assert_eq!(f.tests.len(), 10); + assert_eq!( + f.tests + .iter() + .filter(|t| t.verdict == Verdict::NotRun) + .count(), + 2 + ); + } + + #[test] + fn a_file_outside_the_plan_is_restored_or_carries_its_reason() { + let p = plan( + "- [ ] src/cart/total.ts: [modify] Round per line\n- [ ] docs/: [modify] The rounding note\n", + TicketIntent::Feature, + Habits { + affected: vec![Affected { where_: "src/invoice/pdf.ts".into(), action: "update".into(), ..Default::default() }], + ..Default::default() + }, + ); + let changed: Vec = [ + "src/cart/total.ts", + "src/cart/total.test.ts", + "docs/rounding.md", + "pnpm-lock.yaml", + "src/generated/schema.ts", + "src/invoice/pdf.ts", + "src/utils/format.ts", + "src/money.ts", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let notes = "Evidence: none needed\n- Outside the plan: `src/money.ts`: total.ts imports the new roundLine helper from it"; + let out = outside_plan(&changed, &p, &["src/generated/**".to_string()], notes); + assert_eq!( + out, + vec![ + OutsidePlan { + path: "src/utils/format.ts".into(), + why: String::new() + }, + OutsidePlan { + path: "src/money.ts".into(), + why: "total.ts imports the new roundLine helper from it".into() + }, + ] + ); + let f = PrFacts { + outside_plan: out, + ..Default::default() + }; + let b = blocking(&f, &p); + assert_eq!(b.len(), 1); + assert!(b[0].contains("`src/utils/format.ts` was changed and is no task of the plan")); + assert_eq!(open_findings(&f, &p)[0].point, "Changed outside the plan"); + let s = section(&p, &f); + assert!(s.contains("- `src/money.ts`: total.ts imports the new roundLine helper from it")); + assert!(s.contains("- `src/utils/format.ts`: no reason recorded yet")); + // A plan that names no files states no scope. + let open = plan("Do the thing", TicketIntent::Feature, Habits::default()); + assert!(outside_plan(&changed, &open, &[], "").is_empty()); + } + + #[test] + fn a_dependent_the_plan_updates_must_be_in_the_branch() { + let p = plan( + "- [ ] src/cart/total.ts: [modify] x\n- [ ] src/invoice/pdf.ts: [modify] y\n", + TicketIntent::Feature, + Habits { + affected: vec![ + Affected { + where_: "src/invoice/pdf.ts".into(), + uses: "cartTotal".into(), + action: "update".into(), + ..Default::default() + }, + Affected { + where_: "acme/storefront:src/checkout.ts".into(), + action: "update".into(), + why: "reads the per-line total".into(), + ..Default::default() + }, + Affected { + where_: "src/report.ts".into(), + action: "safe".into(), + why: "reads `amount`, unchanged".into(), + ..Default::default() + }, + ], + area_history: vec![AreaHistory { + path: "src/cart/total.ts".into(), + found: "Per-line rounding was reverted in #74.".into(), + refs: vec!["#74".into()], + bearing: "The export changes with it this time.".into(), + }], + ..Default::default() + }, + ); + let changed = vec!["src/cart/total.ts".to_string()]; + let missing = not_updated(&changed, &p, "acme/shop-api"); + assert_eq!(missing, vec!["src/invoice/pdf.ts"]); + let f = PrFacts { + not_updated: missing, + ..Default::default() + }; + assert!(blocking(&f, &p)[0].contains("the branch doesn't touch it")); + let s = section(&p, &f); + assert!(s.contains( + "- `src/invoice/pdf.ts` (uses cartTotal): planned to change with this, not changed yet" + )); + assert!(s.contains("- `acme/storefront:src/checkout.ts`: changes in its own pull request: reads the per-line total")); + assert!(s.contains("- `src/report.ts`: safe: reads `amount`, unchanged")); + assert!(s.contains("- `src/cart/total.ts` (#74): Per-line rounding was reverted in #74. For this change: The export changes with it this time.")); + let done = PrFacts::default(); + assert!(section(&p, &done) + .contains("- `src/invoice/pdf.ts` (uses cartTotal): updated in this pull request")); + } + + #[test] + fn the_section_is_replaced_in_place_and_removed_when_empty() { + let body = "## Summary\nx\n".to_string(); + let one = shape_body(body.clone(), &format!("{START}\none\n{END}")); + assert!(one.contains("one")); + let two = shape_body(one.clone(), &format!("{START}\ntwo\n{END}")); + assert!(two.contains("two") && !two.contains("one")); + assert_eq!(two.matches(START).count(), 1); + assert_eq!( + shape_body(two.clone(), &format!("{START}\ntwo\n{END}")), + two + ); + assert_eq!(shape_body(two, ""), body); + assert_eq!(shape_body(body.clone(), ""), body); + } +} diff --git a/services/worker/src/passes/health_check.rs b/services/worker/src/passes/health_check.rs index 991489d05..139cf5b91 100644 --- a/services/worker/src/passes/health_check.rs +++ b/services/worker/src/passes/health_check.rs @@ -837,8 +837,10 @@ pub async fn run(state: &WorkerState, msg: HealthCheckMessage) -> Result<(), Box delay, } => { msg.green_since = None; - let body = render_interim(&msg.merge_sha, finished, &failed, &waiting, &follows); - upsert_comment(&github, &msg, &body).await; + if speaks(msg.quiet, None) { + let body = render_interim(&msg.merge_sha, finished, &failed, &waiting, &follows); + upsert_comment(&github, &msg, &body).await; + } info!( pr = msg.pr_number, sha = %msg.merge_sha, @@ -876,7 +878,19 @@ pub async fn run(state: &WorkerState, msg: HealthCheckMessage) -> Result<(), Box "Health check: SAFETY CEILING reached with the deploy still running" ); } - let body = render(&msg.merge_sha, &verdict, &follows); + if !speaks(msg.quiet, Some(&verdict)) { + info!(pr = msg.pr_number, sha = %msg.merge_sha, ?verdict, "Health check: quiet watch, nothing failed, nothing to report"); + return Ok(()); + } + let mut body = render(&msg.merge_sha, &verdict, &follows); + // A failed deploy of CoderHelm's own change: the revert is + // opened, ready for the team's approval, with these failures as + // its evidence. Never merged here. + if let Verdict::Failed(jobs) = &verdict { + if let Some(line) = propose_revert(state, &github, &msg, jobs).await { + body = with_revert_line(&body, &line); + } + } upsert_comment(&github, &msg, &body).await; info!(pr = msg.pr_number, sha = %msg.merge_sha, ?verdict, "Health check reported"); } @@ -884,6 +898,78 @@ pub async fn run(state: &WorkerState, msg: HealthCheckMessage) -> Result<(), Box Ok(()) } +/// Whether a look's result is said on the pull request. A quiet watch (a +/// merge nobody asked a report for) speaks only for a failed deploy. +pub fn speaks(quiet: bool, verdict: Option<&Verdict>) -> bool { + !quiet || matches!(verdict, Some(Verdict::Failed(_))) +} + +/// The failed verdict's comment with what CoderHelm did about it: the +/// question it used to end on is answered by the revert's own line. +pub fn with_revert_line(body: &str, line: &str) -> String { + const ASK: &str = " Rolling a deploy back needs the approval"; + const ASK_END: &str = "be rolled back?"; + if let (Some(a), Some(b)) = (body.find(ASK), body.find(ASK_END)) { + if b > a { + return format!("{} {line}{}", &body[..a], &body[b + ASK_END.len()..]); + } + } + match body.rfind("\n\n"; +pub const END: &str = ""; + +/// Passed checks named one by one; the rest are counted. +const MAX_PASSED_LINES: usize = 8; + +fn is_test(path: &str) -> bool { + let l = path.to_ascii_lowercase(); + l.contains(".test.") + || l.contains(".spec.") + || l.contains("_test.") + || l.contains("__tests__") + || l.contains("/test/") + || l.contains("/tests/") + || l.starts_with("test/") + || l.starts_with("tests/") +} + +/// Files nobody reviews line by line: lockfiles, snapshots, generated code. +fn is_generated(path: &str) -> bool { + let l = path.to_ascii_lowercase(); + let name = l.rsplit('/').next().unwrap_or(&l); + name.ends_with(".lock") + || name.ends_with("-lock.json") + || name.ends_with("-lock.yaml") + || name == "go.sum" + || name.ends_with(".snap") + || name.ends_with(".min.js") + || l.contains("/generated/") + || l.contains("/__snapshots__/") +} + +fn added_lines(patch: &str) -> usize { + patch + .lines() + .filter(|l| l.starts_with('+') && !l.starts_with("+++")) + .count() +} + +/// The first path a risk reason names in backticks, when the diff has it. +fn path_in_reason(reason: &str, files: &[(String, String, String)]) -> Option { + reason + .split('`') + .skip(1) + .step_by(2) + .find(|p| files.iter().any(|(f, _, _)| f == p)) + .map(str::to_string) +} + +/// Where the reviewer looks first, and why: the file the diff's risk floor +/// names, else the code file with the most added lines. None for a diff +/// with nothing to read (only removed, generated or test files). +pub fn look_first(files: &[(String, String, String)], floor: &Floor) -> Option<(String, String)> { + for reason in &floor.reasons { + if let Some(path) = path_in_reason(reason, files) { + return Some((path, reason.clone())); + } + } + files + .iter() + .filter(|(p, status, _)| status != "removed" && !is_test(p) && !is_generated(p)) + .map(|(p, _, patch)| (p, added_lines(patch))) + .filter(|(_, n)| *n > 0) + // The first of equals, so the answer never depends on file order + // beyond the diff's own. + .fold(None::<(&String, usize)>, |best, cur| match best { + Some(b) if b.1 >= cur.1 => Some(b), + _ => Some(cur), + }) + .map(|(p, n)| { + ( + p.clone(), + format!( + "the largest change to code ({n} added line{})", + if n == 1 { "" } else { "s" } + ), + ) + }) +} + +/// What reverting the code leaves in place, by the kind of file changed. +const NOT_UNDONE: &[(&str, &[&str])] = &[ + ( + "a migration that already ran stays applied", + &["/migrations/", "/migration/", "/migrate/", "db/migrate"], + ), + ( + "infrastructure already applied stays as it is until the stack is applied again", + &[ + ".tf", + ".tfvars", + "cloudformation", + "/cdk/", + "/infra/", + "/helm/", + "/k8s/", + ], + ), +]; + +/// How to roll the change back: a revert of the pull request, and what that +/// revert does not undo, each with the changed file that says so. +pub fn rollback(files: &[(String, String, String)]) -> String { + let mut caveats: Vec = Vec::new(); + for (what, marks) in NOT_UNDONE { + let hit = files.iter().find(|(p, status, _)| { + let l = format!("/{}", p.to_ascii_lowercase()); + status != "removed" + && marks.iter().any(|m| match m.strip_prefix('.') { + // An extension ends the path; a directory is anywhere in it. + Some(_) => l.ends_with(m), + None => l.contains(m), + }) + }); + if let Some((p, _, _)) = hit { + caveats.push(format!("{what} (`{p}`)")); + } + } + if caveats.is_empty() { + "revert this pull request; nothing outside the code changes with it.".to_string() + } else { + format!( + "revert this pull request. The revert does not undo everything: {}.", + caveats.join("; ") + ) + } +} + +/// One check's standing on the head commit. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Check { + pub name: String, + pub url: String, + pub state: State, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum State { + Passed, + Failed, + Running, + /// Skipped, neutral or cancelled: it reported, and proved nothing. + DidNotRun, +} + +/// The newest run of each check in a `check-runs` listing (commit statuses +/// included, see `common::commit_ci`), by name. +pub fn checks_of(listing: &Value) -> Vec { + let mut latest: HashMap<&str, &Value> = HashMap::new(); + let mut order: Vec<&str> = Vec::new(); + for c in listing["check_runs"].as_array().into_iter().flatten() { + let Some(name) = c["name"].as_str().filter(|n| !n.is_empty()) else { + continue; + }; + let ts = c["started_at"].as_str().unwrap_or(""); + match latest.get(name) { + Some(prev) if prev["started_at"].as_str().unwrap_or("") > ts => {} + Some(_) => { + latest.insert(name, c); + } + None => { + order.push(name); + latest.insert(name, c); + } + } + } + order + .into_iter() + .map(|name| { + let c = latest[name]; + let state = if c["status"].as_str() != Some("completed") { + State::Running + } else { + match c["conclusion"].as_str().unwrap_or("") { + "success" => State::Passed, + "skipped" | "neutral" | "cancelled" | "stale" => State::DidNotRun, + _ => State::Failed, + } + }; + Check { + name: name.to_string(), + url: c["html_url"] + .as_str() + .or_else(|| c["details_url"].as_str()) + .unwrap_or("") + .to_string(), + state, + } + }) + .collect() +} + +fn short(sha: &str) -> &str { + sha.get(..7).unwrap_or(sha) +} + +fn linked(c: &Check) -> String { + if c.url.starts_with("https://") { + format!("[`{}`]({})", c.name.replace('`', "'"), c.url) + } else { + format!("`{}`", c.name.replace('`', "'")) + } +} + +/// The verification lines: what passed on `head` (each with its recorded +/// result), then what did not verify the change and why. Empty when no +/// check reported: no claim is made without a result behind it. +pub fn verified_lines(checks: &[Check], head: &str) -> Vec { + let mut out = Vec::new(); + let passed: Vec<&Check> = checks.iter().filter(|c| c.state == State::Passed).collect(); + if !passed.is_empty() { + let shown: Vec = passed + .iter() + .take(MAX_PASSED_LINES) + .map(|c| linked(c)) + .collect(); + let more = passed.len().saturating_sub(MAX_PASSED_LINES); + out.push(format!( + "**Verified by:** {}{} passed on `{}`.", + shown.join(", "), + if more > 0 { + format!(" and {more} more") + } else { + String::new() + }, + short(head) + )); + } + let mut not: Vec = Vec::new(); + for (state, word) in [ + (State::Failed, "failed"), + (State::Running, "still running"), + (State::DidNotRun, "did not run"), + ] { + let names: Vec = checks + .iter() + .filter(|c| c.state == state) + .map(linked) + .collect(); + if !names.is_empty() { + not.push(format!("{} ({word})", names.join(", "))); + } + } + if !not.is_empty() { + out.push(format!( + "**Not verified on `{}`:** {}.", + short(head), + not.join("; ") + )); + } + out +} + +/// The section, from the diff's files (path, status, patch), its risk +/// floor, the head commit and that commit's checks. Empty when there is +/// nothing to say. +pub fn section( + files: &[(String, String, String)], + floor: &Floor, + head: &str, + checks: &[Check], +) -> String { + let mut lines: Vec = Vec::new(); + if let Some((path, why)) = look_first(files, floor) { + // A reason that already names the file reads on its own. + lines.push(if why.contains(&format!("`{path}`")) { + format!("**Look first:** {why}.") + } else { + format!("**Look first:** `{path}`, {why}.") + }); + } + if !files.is_empty() { + lines.push(format!("**Roll back:** {}", rollback(files))); + } + lines.extend(verified_lines(checks, head)); + if lines.is_empty() { + return String::new(); + } + format!( + "{START}\n**For the reviewer**\n{}\n{END}", + lines + .iter() + .map(|l| format!("* {l}")) + .collect::>() + .join("\n") + ) +} + +/// `body` with the section rebuilt for the current diff and head. +pub fn put(body: &str, section: String) -> String { + super::completeness::with_section(body, super::completeness::Section::ReviewerGuide, section) +} + +/// The section for a pull request as it stands: its current diff's files +/// and floor, and the checks on `head`. An unreadable check listing leaves +/// the verification lines out rather than guessing them. +pub async fn build( + github: &GitHubClient, + owner: &str, + repo: &str, + files: &[(String, String, String)], + floor: &Floor, + head: &str, +) -> String { + let checks = if head.is_empty() { + Vec::new() + } else { + match github.list_ci_for_ref(owner, repo, head).await { + Ok(listing) => checks_of(&listing), + Err(e) => { + warn!(owner, repo, head, error = %e, "Reviewer guide: could not read the head's checks"); + Vec::new() + } + } + }; + section(files, floor, head, &checks) +} + +/// Rebuilds the section on an open pull request from what GitHub shows now. +/// Costs no model call. Leaves the description alone when nothing changed +/// or anything can't be read. +pub async fn refresh(github: &GitHubClient, owner: &str, repo: &str, pr_number: u64) { + let Ok(pr) = github.get_pull_request(owner, repo, pr_number).await else { + return; + }; + let (Some(base), Some(head_ref)) = (pr["base"]["ref"].as_str(), pr["head"]["ref"].as_str()) + else { + return; + }; + let head = pr["head"]["sha"].as_str().unwrap_or(""); + let body = pr["body"].as_str().unwrap_or(""); + let Ok(diff) = github.get_diff(owner, repo, base, head_ref).await else { + return; + }; + let files = super::pr_risk::diff_files(&diff); + let floor = super::pr_risk::floor(&files, &HashMap::new()); + let out = put(body, build(github, owner, repo, &files, &floor, head).await); + if out != body { + if let Err(e) = github.update_pr_body(owner, repo, pr_number, &out).await { + warn!(pr_number, error = %e, "Reviewer guide: could not save the description"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::passes::pr_risk::Level; + use serde_json::json; + + const HEAD: &str = "0a1b2c3d4e5f60718293a4b5c6d7e8f901234567"; + + fn file(path: &str, status: &str, added: usize) -> (String, String, String) { + ( + path.to_string(), + status.to_string(), + format!("@@ -1 +1,{added} @@\n{}", "+line\n".repeat(added)), + ) + } + + fn low() -> Floor { + Floor { + level: Level::Low, + reasons: Vec::new(), + } + } + + fn run(name: &str, status: &str, conclusion: Option<&str>, started: &str) -> Value { + json!({ + "name": name, "status": status, "conclusion": conclusion, + "started_at": started, + "html_url": format!("https://github.com/acme/shop/actions/runs/7/job/{}", name.len()), + }) + } + + #[test] + fn the_risk_floors_file_is_looked_at_first() { + let files = vec![ + file("apps/web/src/pages/cart.tsx", "modified", 90), + file("apps/web/src/middleware.ts", "modified", 4), + ]; + let floor = Floor { + level: Level::Medium, + reasons: vec!["`apps/web/src/middleware.ts` runs on every request".to_string()], + }; + let (path, why) = look_first(&files, &floor).unwrap(); + assert_eq!(path, "apps/web/src/middleware.ts"); + assert!(why.contains("every request")); + // A reason naming a file the diff no longer has is not followed. + let stale = Floor { + level: Level::Medium, + reasons: vec!["`apps/web/src/gone.ts` is shared".to_string()], + }; + assert_eq!( + look_first(&files, &stale).unwrap().0, + "apps/web/src/pages/cart.tsx" + ); + } + + #[test] + fn without_a_floor_the_largest_code_change_is_first_never_a_test_or_lockfile() { + let files = vec![ + file("pnpm-lock.yaml", "modified", 900), + file("apps/web/src/cart/total.test.ts", "added", 120), + file("apps/web/src/cart/total.ts", "modified", 31), + file("apps/web/src/cart/format.ts", "modified", 31), + file("apps/web/src/cart/old.ts", "removed", 0), + ]; + let (path, why) = look_first(&files, &low()).unwrap(); + assert_eq!(path, "apps/web/src/cart/total.ts"); + assert_eq!(why, "the largest change to code (31 added lines)"); + assert_eq!( + look_first(&[file("pnpm-lock.yaml", "modified", 9)], &low()), + None + ); + } + + #[test] + fn rollback_says_what_a_revert_does_not_undo() { + assert_eq!( + rollback(&[file("apps/web/src/a.ts", "modified", 3)]), + "revert this pull request; nothing outside the code changes with it." + ); + let r = rollback(&[ + file("services/api/migrations/0042_orders.sql", "added", 12), + file("infra/queues.tf", "modified", 5), + ]); + assert!(r.starts_with("revert this pull request. The revert does not undo everything:")); + assert!(r.contains( + "a migration that already ran stays applied (`services/api/migrations/0042_orders.sql`)" + )); + assert!(r.contains("(`infra/queues.tf`)")); + // A removed migration file is no new migration. + assert!( + !rollback(&[file("services/api/migrations/0001.sql", "removed", 0)]) + .contains("does not undo") + ); + } + + #[test] + fn every_verification_claim_points_at_a_recorded_result() { + let listing = json!({"check_runs": [ + run("unit", "completed", Some("failure"), "2026-02-01T10:00:00Z"), + // The re-run of the same check is the one that counts. + run("unit", "completed", Some("success"), "2026-02-01T10:20:00Z"), + run("lint", "completed", Some("success"), "2026-02-01T10:00:00Z"), + run("e2e", "in_progress", None, "2026-02-01T10:00:00Z"), + run("deploy-preview", "completed", Some("skipped"), "2026-02-01T10:00:00Z"), + run("types", "completed", Some("timed_out"), "2026-02-01T10:00:00Z"), + ]}); + let checks = checks_of(&listing); + let lines = verified_lines(&checks, HEAD); + assert_eq!(lines.len(), 2); + assert_eq!( + lines[0], + "**Verified by:** [`unit`](https://github.com/acme/shop/actions/runs/7/job/4), \ + [`lint`](https://github.com/acme/shop/actions/runs/7/job/4) passed on `0a1b2c3`." + ); + assert!(lines[1].starts_with("**Not verified on `0a1b2c3`:**")); + assert!(lines[1].contains("job/5) (failed)"), "{}", lines[1]); + assert!(lines[1].contains("job/3) (still running)"), "{}", lines[1]); + assert!(lines[1].contains("job/14) (did not run)"), "{}", lines[1]); + // A check that did not pass is never among the verified. + assert!(!lines[0].contains("e2e") && !lines[0].contains("types")); + } + + #[test] + fn no_check_result_means_no_verification_claim() { + assert!(verified_lines(&[], HEAD).is_empty()); + let s = section(&[file("src/a.ts", "modified", 2)], &low(), HEAD, &[]); + assert!(s.contains("**Look first:** `src/a.ts`")); + assert!(s.contains("**Roll back:**")); + assert!(!s.contains("Verified")); + } + + #[test] + fn many_passed_checks_are_counted_not_listed() { + let checks: Vec = (0..MAX_PASSED_LINES + 3) + .map(|i| Check { + name: format!("job-{i}"), + url: String::new(), + state: State::Passed, + }) + .collect(); + let lines = verified_lines(&checks, HEAD); + assert!( + lines[0].contains("`job-7` and 3 more passed"), + "{}", + lines[0] + ); + } + + #[test] + fn nothing_to_say_is_no_section_and_the_section_is_replaced_in_place() { + assert_eq!(section(&[], &low(), HEAD, &[]), ""); + let body = + "Closes #4\n\n**Summary** x\n\n**Risk** **Low**: small.\n\n**Verification**\n1. CI."; + let first = put( + body, + section(&[file("src/a.ts", "modified", 2)], &low(), HEAD, &[]), + ); + assert!(first.find(START).unwrap() < first.find("**Risk**").unwrap()); + assert!(first.find("**Summary**").unwrap() < first.find(START).unwrap()); + let second = put( + &first, + section(&[file("src/b.ts", "modified", 9)], &low(), HEAD, &[]), + ); + assert_eq!(second.matches(START).count(), 1); + assert!(second.contains("`src/b.ts`") && !second.contains("`src/a.ts`")); + assert_eq!(put(&second, String::new()), body); + } +} diff --git a/services/worker/src/passes/rewards.rs b/services/worker/src/passes/rewards.rs index f1ce429e1..7c701e3d3 100644 --- a/services/worker/src/passes/rewards.rs +++ b/services/worker/src/passes/rewards.rs @@ -93,6 +93,8 @@ pub use common::rewards::lessons::is_coder_setback; /// Most of people's commits read for what they changed. const MAX_EDIT_COMMITS: usize = 20; +/// Most of them whose patches are read for the lesson. +const MAX_PATCH_COMMITS: usize = 5; /// What people changed on top of CoderHelm's work: their own non-merge /// commits, each measured by its own stats. `None` when GitHub couldn't say @@ -111,7 +113,8 @@ async fn people_edits( let mut read = 0usize; let mut touched: BTreeMap = BTreeMap::new(); let mut subjects = Vec::new(); - for c in mine.iter().take(MAX_EDIT_COMMITS) { + let mut patches: Vec<(String, String)> = Vec::new(); + for (i, c) in mine.iter().take(MAX_EDIT_COMMITS).enumerate() { let Some(sha) = c["sha"].as_str() else { continue; }; @@ -122,6 +125,16 @@ async fn people_edits( *touched.entry(f).or_default() += 1; } } + // What they changed, for the lesson: their first few commits' own + // patches (a later one overrides an earlier one on the same file). + if i < MAX_PATCH_COMMITS { + if let Ok(files) = github.commit_changes(owner, name, sha).await { + for f in files { + patches.retain(|(p, _)| p != &f.path); + patches.push((f.path, f.patch)); + } + } + } let subject = common::pr_outcome::commit_subject(c); if !subject.is_empty() { subjects.push(subject); @@ -137,6 +150,7 @@ async fn people_edits( lines, files: files.into_iter().map(|(f, _)| f).collect(), subjects, + diff: mapping::diff_excerpts(&patches), }) } @@ -237,6 +251,21 @@ pub async fn score_outcome(state: &WorkerState, msg: RewardOutcomeMessage) -> Re &state.http, ) .map_err(|e| e.to_string())?; + match msg.trigger.as_str() { + common::rewards::TRIGGER_REVERTED => return learn_from_revert(state, &github, &msg).await, + common::rewards::TRIGGER_GUIDE_CLOSED => { + return super::guide_pr::closed( + state, + &github, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + ) + .await + } + _ => {} + } let pr = github .get_pull_request(&msg.repo_owner, &msg.repo_name, msg.pr_number) .await @@ -246,6 +275,9 @@ pub async fn score_outcome(state: &WorkerState, msg: RewardOutcomeMessage) -> Re let coder = !msg.review_only && !msg.run_id.is_empty(); let mut events = Vec::new(); let mut area = String::new(); + let mut paths_touched: Vec = Vec::new(); + let mut people: Option = None; + let mut run_close_reason = String::new(); if coder { let run = load_run(state, &msg.team_id, &msg.run_id) .await @@ -276,6 +308,25 @@ pub async fn score_outcome(state: &WorkerState, msg: RewardOutcomeMessage) -> Re vec![] }; area = main_area(&paths); + // The scorecard counts the close here too: the webhook counted it + // already (then this changes nothing), or it was missed and this + // is the reconcile sweep's message. + if !closed_at.is_empty() + && (common::scorecard::counts(&pr, github.bot_login().await.as_deref()) + || common::scorecard::counts(&pr, None)) + { + if let Some(e) = common::scorecard::pr_event("closed", &pr, human) { + let sc = common::scorecard::Dynamo::new( + &state.dynamo, + &state.config.settings_table_name, + ); + if let Err(err) = + common::scorecard::record(&sc, &msg.team_id, &repo, msg.pr_number, &e).await + { + warn!(error = %err, "Could not count the pull request on the scorecard"); + } + } + } let ctx = RunContext { team_id: msg.team_id.clone(), run_id: msg.run_id.clone(), @@ -298,6 +349,9 @@ pub async fn score_outcome(state: &WorkerState, msg: RewardOutcomeMessage) -> Re edits.as_ref(), ci_of(&run), )); + run_close_reason = ctx.close_reason.clone(); + paths_touched = paths; + people = edits; } // What became of each of CoderHelm's review comments, notes (Nit, @@ -382,6 +436,152 @@ pub async fn score_outcome(state: &WorkerState, msg: RewardOutcomeMessage) -> Re if events.iter().any(is_coder_setback) { learn_from_setbacks(state, &msg.team_id, &repo, &area).await; } + + // What people did with this pull request, in their own words and code: + // one lesson at most, and what its reviewers asked for. + let source = if !merged { + lessons::SOURCE_CLOSED + } else if people.as_ref().is_some_and(|p| p.commits > 0) { + lessons::SOURCE_EDITED + } else { + "" + }; + let mut words: Vec = Vec::new(); + if merged { + if let Some(p) = &people { + words.extend(p.subjects.iter().take(mapping::MAX_EDIT_NOTES).cloned()); + } + } else { + if !run_close_reason.trim().is_empty() { + words.push(run_close_reason.trim().to_string()); + } + if let Ok(comments) = github + .list_issue_comments(&msg.repo_owner, &msg.repo_name, msg.pr_number) + .await + { + words.extend(super::outcome_learning::closing_comment( + &comments, &closed_at, + )); + } + } + let reviews = github + .list_pr_reviews(&msg.repo_owner, &msg.repo_name, msg.pr_number) + .await + .ok() + .and_then(|v| v.as_array().cloned()) + .unwrap_or_default(); + let review_comments = github + .get_review_comments(&msg.repo_owner, &msg.repo_name, msg.pr_number) + .await + .unwrap_or_default(); + let outcome = super::outcome_learning::Outcome { + repo: repo.clone(), + pr: msg.pr_number, + run_id: msg.run_id.clone(), + source: source.to_string(), + title: pr["title"].as_str().unwrap_or("").to_string(), + summary: pr["body"].as_str().unwrap_or("").to_string(), + files: people + .as_ref() + .map(|p| { + p.files + .iter() + .take(mapping::MAX_EDIT_FILES) + .cloned() + .collect() + }) + .unwrap_or_default(), + words, + diff: people.map(|p| p.diff).unwrap_or_default(), + reviews: super::outcome_learning::reviews_from(&reviews, &review_comments), + }; + let areas: std::collections::BTreeSet = paths_touched + .iter() + .map(|p| rev::file_area(p)) + .filter(|a| !a.is_empty()) + .collect(); + learn_from_outcome(state, &github, &msg, &outcome, &areas).await; + Ok(()) +} + +/// Distils one outcome with the team's model (`outcome_learning`), then +/// proposes the repository's guide pull request when a lesson reached the +/// confidence for it. Best effort. +async fn learn_from_outcome( + state: &WorkerState, + github: &GitHubClient, + msg: &RewardOutcomeMessage, + outcome: &super::outcome_learning::Outcome, + areas: &std::collections::BTreeSet, +) { + if !outcome.teaches() && outcome.reviews.is_empty() { + return; + } + let provider = match crate::agent::provider::ModelProvider::load_for_team( + &state.dynamo, + &state.config.settings_table_name, + &msg.team_id, + ) + .await + { + Ok(p) => p, + Err(e) => { + warn!(error = %e, "No model to learn from the outcome with"); + return; + } + }; + let mut usage = crate::models::TokenUsage::default(); + let kept = { + let mut model = super::review_lessons::TeamModel { + state, + provider: &provider, + usage: &mut usage, + }; + super::outcome_learning::learn(state, &mut model, &msg.team_id, outcome, areas).await + }; + if kept.lesson.is_some() { + super::guide_pr::maybe_propose( + state, + github, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + ) + .await; + } +} + +/// A merged CoderHelm change was reverted (the gateway recorded the event): +/// the area's lesson is written again with it, and the reason people gave +/// is distilled into a lesson of its own. +async fn learn_from_revert( + state: &WorkerState, + github: &GitHubClient, + msg: &RewardOutcomeMessage, +) -> Result<(), String> { + let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); + let run = load_run(state, &msg.team_id, &msg.run_id) + .await + .unwrap_or_default(); + learn_from_setbacks(state, &msg.team_id, &repo, &gs(&run, "reward_area")).await; + let pr = github + .get_pull_request(&msg.repo_owner, &msg.repo_name, msg.pr_number) + .await + .map_err(|e| e.to_string())?; + let outcome = super::outcome_learning::Outcome { + repo, + pr: msg.pr_number, + run_id: msg.run_id.clone(), + source: lessons::SOURCE_REVERTED.to_string(), + title: pr["title"].as_str().unwrap_or("").to_string(), + summary: pr["body"].as_str().unwrap_or("").to_string(), + words: Some(msg.note.trim().to_string()) + .filter(|n| !n.is_empty()) + .into_iter() + .collect(), + ..Default::default() + }; + learn_from_outcome(state, github, msg, &outcome, &Default::default()).await; Ok(()) } @@ -795,7 +995,12 @@ pub async fn coder_learning( let examples = examples_block(state, team_id, repo, exemplars::KIND_FIX, &[], query, &by).await; let kept = st.lessons(team_id, Some(repo)).await.unwrap_or_default(); let recalled = lessons::recall(&kept, rev::AGENT_CODER, chrono::Utc::now()); - let lesson_block = lessons::prompt_block(&recalled); + // What the likely reviewers of this repository's changes ask for (the + // files are not chosen yet, so: its code owners and whoever reviewed + // here recently). + let reviewer_block = + reviewer_asks(state, team_id, repo, gu(&run, "installation_id"), &[]).await; + let lesson_block = format!("{}{reviewer_block}", lessons::prompt_block(&recalled)); info!( team_id, repo, @@ -803,6 +1008,7 @@ pub async fn coder_learning( arm = %arm, lessons = recalled.len(), examples = !examples.is_empty(), + reviewer_asks = !reviewer_block.is_empty(), "Coder learning loaded" ); CoderLearning { @@ -811,6 +1017,39 @@ pub async fn coder_learning( } } +/// What the likely reviewers of a change to `paths` in `repo` repeatedly +/// ask for, as a prompt block (`common::reviewer_prefs`); empty when +/// nothing is kept for them. With no paths (the build has not chosen files) +/// the likely reviewers are the repository's catch-all code owners and its +/// recent reviewers. Reads CODEOWNERS only when the team has asks kept. +pub async fn reviewer_asks( + state: &WorkerState, + team_id: &str, + repo: &str, + installation_id: u64, + paths: &[String], +) -> String { + let store = + common::reviewer_prefs::Store::new(&state.dynamo, &state.config.settings_table_name); + if !matches!(store.prefs(team_id, None).await, Ok(p) if !p.is_empty()) { + return String::new(); + } + let codeowners = match (repo.split_once('/'), installation_id) { + (Some((owner, name)), id) if id > 0 => match GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + id, + &state.http, + ) { + Ok(github) => super::outcome_learning::read_codeowners(&github, owner, name).await, + Err(_) => None, + }, + _ => None, + }; + super::outcome_learning::reviewer_block(state, team_id, repo, codeowners.as_deref(), paths) + .await +} + /// Notes the coder arm on the run, only when none is noted yet. True when /// this call wrote it. async fn note_coder_arm(state: &WorkerState, team_id: &str, run_id: &str, arm: &str) -> bool { diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index 9d1d1d502..5aeaa5f73 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -1021,6 +1021,16 @@ pub struct Ledger { pub links: CheckRecord, #[serde(default)] pub test_fix: CheckRecord, + /// The tests and scope check (`habits_check`). + #[serde(default)] + pub habits: CheckRecord, + /// What the tests and scope check last came to. + #[serde(default)] + pub habits_outcome: Option, String>>, + /// That check has asked once for a step of its own for its sandbox + /// runs: it never asks twice. + #[serde(default)] + pub habits_waited: bool, /// What the proof check last found (`None`: the judge couldn't answer). #[serde(default)] pub proof_findings: Option>, @@ -1072,6 +1082,7 @@ impl Ledger { &mut self.rules, &mut self.links, &mut self.test_fix, + &mut self.habits, ]; if records.iter().any(|r| r.fixing) { for r in records { @@ -1134,6 +1145,9 @@ impl Ledger { "they didn't finish", )), } + if let Some(Err(why)) = &self.habits_outcome { + open.push(proof::check_item("The tests and scope check", why)); + } open } @@ -1154,6 +1168,8 @@ impl Ledger { smaller.links.head = String::new(); smaller.test_outcome = None; smaller.test_fix.head = String::new(); + smaller.habits_outcome = None; + smaller.habits.head = String::new(); serde_json::to_string(&smaller).unwrap_or_default() } }