diff --git a/docs/incidents.md b/docs/incidents.md index 3db737cd7..9c4b97e6f 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -64,6 +64,7 @@ pipeline still calls it there. | ag. `ag_red_ci_ships_what_passes` | Three ways were left for a run to end badly over red checks or a refused landing. A dependency fix whose CI stayed red was taken apart by planned task (one task per lockfile, so a lockfile went back without its manifest), and after three reverts the run ended failed with bumps left in that passed on their own. A run stopped after its work opened its pull request with manifests changed and lockfiles unwritten, and waited for CI to fail first. A review fix or feedback round whose finished work GitHub refused to land was recorded as unfinished at once. | Red checks after every fix take out only what breaks them. A dependency fix takes out its newest commit of verified bumps, defers those bumps with what CI printed, holds their findings out of later bundles and keeps the commits before it, again while CI stays red, never emptying the pull request. Any other run is taken apart task by task (up to eight reverts) down to the part that passes; what ships is green with the rest under "Deferred". A stopped run's lockfiles are written by their package managers before its pull request opens, and one that can't be written is named without stopping it. Every kind of fix round takes one classified decision about a fault (`round::plan_for_fault`): while it may continue it runs again in a fresh step, keeping its work when only the landing failed and starting from the pull request's head otherwise. | | ah. `ah_dep_run_choice_and_proof` | A dependency security run of 64 packages finished with its checks passed. Two packages had been forced onto a new major version through an override although a patched release existed on the installed line (a unit listed one bump per package, to the highest target of all of the package's copies); CoderHelm's reviewer caught it and a fix round pinned them back. Four overrides did have to cross a major version and nothing showed their parents work on it: the sandbox ran the install, the type check, the linter and the unit tests, never the application's build or its start. One pull request carried all 64 bumps, and it did not say how many advisories stayed open or why. | A bump stays on its installed version line with that line's lowest patched release, one bump per package and line; it crosses a major version only when the advisory data lists no patched release on the line, and says which advisory. A fix that crosses a major version is a pull request of its own from the start (a person who asks for one pull request still gets one), its release notes read before any patch bump's, with the parent of a transitive package named and the range it declares. After the batches, the repository's real build (the command its CI runs, else its build script) and its declared start command run in a sandbox build of their own with a full time window, on the base branch and on the branch; what passes on the base and fails with the bumps takes out the newest commit of bumps and defers it with the cause, and only the set whose removal made it pass is held as breaking. What did not run is said, never claimed. The description ends with the advisories that stay open, counted by reason. | | ai. `ai_open_items_settled` | A dependency update finished completed with five Open items on its pull request for a person: the package manager's audit never ran so the advisory counts were unknown (listed twice, in different words), nothing showed that the packages an override moved still built and passed their tests, a README line claimed checks no run had made (and was still listed after a later round rewrote it), and the plan had no end-to-end checklist for a change with nothing to deploy. The coder's full checks had been refused twice for lack of time after two lockfile regenerations in one step, and nothing carried them anywhere. | A run settles its own open items before it finishes (`settle`). Each item is classified: CoderHelm runs it in its sandbox, the repository's CI settles it, it does not apply to the run, or only a person has what it needs (a reason on the human-only list). What CoderHelm can run it runs in a step with a full sandbox window, a fresh step when this one has too little time, and a check the coder was refused for lack of time is owed whether or not an item names it. A change to the dependencies is always audited by its package manager after the bumps (`common::dep_audit`, one row per manager) and the counts left are quoted. A passing result closes the item and is quoted under "Checked by CoderHelm"; a failing one takes out a dependency fix's newest verified set of bumps, or gives any other run a fix round with the real output. An end-to-end checklist is not raised for upkeep, the same missing fact is one item, every item names the head it was written on, and a run about to finish with items of an earlier head derives them again first. What stays says why. Lockfiles are regenerated once per state of the branch. | +| 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. | ## Adding a case 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..3675a3a75 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -153,6 +153,8 @@ pub mod run_prs; // review_stats: time-ordered review records for analytics pub mod decision_log; pub mod deploy_stats; +/// 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 +179,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 +187,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 +206,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/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("