From 1a0833ae8f89e83bb48c2636de395df6a0492831 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 6 Nov 2026 19:53:19 -0500 Subject: [PATCH] Learning loops proven: every reviewed PR teaches calibration, the coder learns specific lessons and its own variants, and a health check shows a quiet loop An audit of production learning found loops that ran but taught little: - Review comments left open were scored only on CoderHelm's own PRs, so calibration of people's PRs could only raise a category, never quiet one. Since the reviewer approves with notes, a person merging over a Nit fed nothing. - Coder lessons said only "read the surrounding code", came in near copies, and rested on an edit share that counted a merge of the base branch as people's edits (100% on almost every updated PR). They never reached the coder's own prompt. - The coder had no prompt variants, so its outcomes credited nothing. - Closes the webhook missed were written to the run but never scored; reverts carried no area or variant. - The stop judge's outcome log never recorded an approval over a block, read every later commit as a fix, and fed only analytics. Changes: - Every PR CoderHelm reviewed is scored at close. Each thread is acted on (resolved by CoderHelm or its lines changed), dismissed (resolved by a person, lines unchanged) or left open (untouched at merge; an FYI never counts), credited to the review's arm, with idempotent keys. - People's edits come from their own non-merge commits, with the files they touched and their commit subjects. The close reason joins the closed event, including an answer given later. - One coder lesson per area names what people changed and said and what to do next. Old generic lessons are replaced, and numbers no longer make a lesson look new. Lessons and the arm's addendum go into the coder's system prompt, capped, as well as the planner's. - The coder has three variants, chosen once per run, noted on the run and credited at close (reverts included). - The reconcile and backfill sweeps score what they record. - Merge outcomes compare each block's head with the merged head. A person approving over a standing block is recorded as overrode. The stop judge is given the team's recent decisions of the same kind that people overturned. - GET /api/learning/health: per loop, the last signal, the 7-day count, what should have fed it, and red when a loop that should fire is quiet. - Replay cases for the four gaps. --- services/common/src/decision_log.rs | 231 ++++++ services/common/src/messages.rs | 11 + services/common/src/pr_outcome.rs | 47 +- services/common/src/rewards/bandit.rs | 37 +- services/common/src/rewards/event.rs | 25 + services/common/src/rewards/health.rs | 703 ++++++++++++++++++ services/common/src/rewards/lessons.rs | 260 ++++++- services/common/src/rewards/mapping.rs | 192 ++++- services/common/src/rewards/mod.rs | 15 +- services/common/src/rewards/store.rs | 150 +++- services/common/src/stop_judge.rs | 41 +- services/gateway/src/main.rs | 1 + services/gateway/src/permissions.rs | 1 + services/gateway/src/routes/github_webhook.rs | 197 ++++- services/gateway/src/routes/learning.rs | 228 +++++- services/gateway/src/routes/review_lessons.rs | 45 +- services/worker/src/clients/github.rs | 34 +- services/worker/src/models.rs | 1 + services/worker/src/passes/e2e.rs | 2 + services/worker/src/passes/e2e_attribution.rs | 1 + services/worker/src/passes/feedback.rs | 2 + services/worker/src/passes/implement.rs | 5 +- services/worker/src/passes/lessons.rs | 28 +- services/worker/src/passes/log_autofix.rs | 1 + services/worker/src/passes/mod.rs | 33 +- services/worker/src/passes/pr_outcomes.rs | 62 +- services/worker/src/passes/replay/README.md | 8 +- ..._merge_over_notes_reaches_calibration.json | 25 + .../11_update_branch_is_not_a_rewrite.json | 15 + ...oder_lesson_names_what_people_changed.json | 22 + ...top_judge_remembers_overturned_blocks.json | 23 + services/worker/src/passes/replay/mod.rs | 213 ++++++ services/worker/src/passes/resume.rs | 1 + services/worker/src/passes/rewards.rs | 600 +++++++++++---- services/worker/src/passes/stop_judge.rs | 29 + 35 files changed, 3030 insertions(+), 259 deletions(-) create mode 100644 services/common/src/rewards/health.rs create mode 100644 services/worker/src/passes/replay/cases/10_merge_over_notes_reaches_calibration.json create mode 100644 services/worker/src/passes/replay/cases/11_update_branch_is_not_a_rewrite.json create mode 100644 services/worker/src/passes/replay/cases/12_coder_lesson_names_what_people_changed.json create mode 100644 services/worker/src/passes/replay/cases/13_stop_judge_remembers_overturned_blocks.json diff --git a/services/common/src/decision_log.rs b/services/common/src/decision_log.rs index ac97af8ae..e7ab17fe2 100644 --- a/services/common/src/decision_log.rs +++ b/services/common/src/decision_log.rs @@ -589,6 +589,188 @@ pub async fn on_merged( .await } +/// A person approved the pull request while CoderHelm's block stood: each +/// open block on it was overridden. +pub async fn on_approved_over_block( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + repo: &str, + pr: u64, +) -> usize { + let subject = Subject::Pr { + repo: repo.to_string(), + number: pr, + }; + land(dynamo, table, team_id, &subject, Group::Block, |_| { + Some(Outcome::Overrode) + }) + .await +} + +/// The pull request heads the open blocks on it were decided on (so a merge +/// can compare each head with the merged one). +pub async fn open_block_heads( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + repo: &str, + pr: u64, +) -> Vec { + let subject = Subject::Pr { + repo: repo.to_string(), + number: pr, + }; + let records = for_subject(dynamo, table, team_id, &subject).await; + let mut heads: Vec = pending(&records, Group::Block) + .iter() + .map(|r| r.head_sha.clone()) + .filter(|h| !h.is_empty()) + .collect(); + heads.sort(); + heads.dedup(); + heads +} + +/// A merge's outcome for one block, given the files changed since each +/// block's head (`changed_by_head`, from a compare of that head with the +/// merged one). A block with no compare falls back to [`merge_outcome`] +/// without one. +pub fn merge_outcome_by_head( + rec: &Record, + merge_head: &str, + changed_by_head: &HashMap>, +) -> Outcome { + merge_outcome( + rec, + merge_head, + changed_by_head.get(&rec.head_sha).map(|v| v.as_slice()), + ) +} + +/// A pull request merged, with the files changed since each open block's +/// head: a block whose flagged file was never touched merged unchanged +/// (it wasn't needed), one whose file changed was fixed. +pub async fn on_merged_by_head( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + repo: &str, + pr: u64, + merge_head: &str, + changed_by_head: &HashMap>, +) -> usize { + let subject = Subject::Pr { + repo: repo.to_string(), + number: pr, + }; + land(dynamo, table, team_id, &subject, Group::Block, |r| { + Some(merge_outcome_by_head(r, merge_head, changed_by_head)) + }) + .await +} + +/// The judge's memory of the outcome log: earlier stops or blocks of `kind` +/// that people's acts showed wrong, newest first, the same step first, one +/// line each (`category`: what it said, and what people did). +pub fn overturned_lines(records: &[Record], kind: &str, step: &str) -> Vec { + let mut wrong: Vec<&Record> = records + .iter() + .filter(|r| r.kind == kind && r.confirmed_wrong()) + .collect(); + wrong.sort_by(|a, b| { + (b.step == step) + .cmp(&(a.step == step)) + .then(b.created_at.cmp(&a.created_at)) + }); + let mut out: Vec = Vec::new(); + for r in wrong { + let line = format!( + "{} by the {} step ({}): \"{}\"; people {}", + r.verdict, + r.step, + if r.category.is_empty() { + "no category" + } else { + r.category.as_str() + }, + crate::truncate_str(r.detail.trim(), 200), + match r.outcome { + Some(Outcome::AnsweredDefault) => "answered with the default it offered", + Some(Outcome::Retried) => "retried the run as it was", + Some(Outcome::Overrode) => "went ahead over it", + Some(Outcome::DismissedReview) => "dismissed the review", + Some(Outcome::MergedFlaggedUnchanged) => "merged with the flagged lines unchanged", + _ => "overturned it", + } + ); + if !out.contains(&line) { + out.push(line); + } + if out.len() >= crate::stop_judge::MAX_OVERTURNED { + break; + } + } + out +} + +/// Decisions newer than `since`, without the stored picture and answers +/// (for counts and the judge's memory: a few kilobytes, not megabytes). +pub async fn since_light( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + since: &str, + max_pages: usize, +) -> Vec { + let mut out = Vec::new(); + if table.is_empty() { + return out; + } + let fields = [ + "sk", + "kind", + "step", + "verdict", + "category", + "detail", + "outcome", + "outcome_at", + "created_at", + "head_sha", + "location", + "repo", + "pr_number", + "run_id", + ]; + let names: Vec = (0..fields.len()).map(|i| format!("#f{i}")).collect(); + let mut start: Option> = None; + for _ in 0..max_pages.max(1) { + let mut q = dynamo + .query() + .table_name(table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .filter_expression("#f8 >= :since") + .expression_attribute_values(":pk", AttributeValue::S(team_id.into())) + .expression_attribute_values(":p", AttributeValue::S(SK_PREFIX.into())) + .expression_attribute_values(":since", AttributeValue::S(since.into())) + .projection_expression(names.join(", ")) + .set_exclusive_start_key(start.take()); + for (alias, name) in names.iter().zip(fields) { + q = q.expression_attribute_names(alias, name); + } + let Ok(page) = q.send().await else { + break; + }; + out.extend(page.items().iter().map(Record::from_item)); + match page.last_evaluated_key() { + Some(k) if !k.is_empty() => start = Some(k.clone()), + _ => break, + } + } + out +} + /// Decisions newer than `since` (RFC 3339), across the team. pub async fn since( dynamo: &aws_sdk_dynamodb::Client, @@ -933,6 +1115,55 @@ mod tests { assert_eq!(merge_outcome(&r, "h2", Some(&touched)), Outcome::Fixed); } + /// The merge webhook used to pass no compare, so every block on a PR + /// with any later commit read as "fixed" and none as a nuisance. + #[test] + fn a_merge_compares_each_blocks_own_head() { + let (j, p) = judged(Kind::Block, hold()); + let pr = Subject::Pr { + repo: "a/b".into(), + number: 1, + }; + let r = Record::new(&pr, &j, &p, "h1"); + let mut by_head = HashMap::new(); + by_head.insert("h1".to_string(), vec!["README.md".to_string()]); + assert_eq!( + merge_outcome_by_head(&r, "h9", &by_head), + Outcome::MergedFlaggedUnchanged + ); + by_head.insert("h1".to_string(), vec!["src/a.rs".to_string()]); + assert_eq!(merge_outcome_by_head(&r, "h9", &by_head), Outcome::Fixed); + } + + #[test] + fn overturned_decisions_become_the_judges_memory() { + let (j, p) = judged(Kind::Block, hold()); + let pr = Subject::Pr { + repo: "a/b".into(), + number: 1, + }; + let mut wrong = Record::new(&pr, &j, &p, "h1"); + wrong.outcome = Some(Outcome::Overrode); + wrong.created_at = "2026-11-02T00:00:00Z".into(); + let mut right = Record::new(&pr, &j, &p, "h1"); + right.outcome = Some(Outcome::Fixed); + let open = Record::new(&pr, &j, &p, "h1"); + let mut other_step = wrong.clone(); + other_step.step = "own_review".into(); + other_step.created_at = "2026-11-05T00:00:00Z".into(); + other_step.detail = "another".into(); + let lines = overturned_lines(&[wrong.clone(), right, open, other_step], "block", "review"); + assert_eq!(lines.len(), 2, "{lines:?}"); + // The same step first, even when older. + assert!( + lines[0].contains("by the review step (correctness)"), + "{lines:?}" + ); + assert!(lines[0].contains("people went ahead over it")); + assert!(lines[1].contains("own_review")); + assert!(overturned_lines(&[wrong], "ask", "review").is_empty()); + } + #[test] fn answers_that_take_the_default() { assert!(answered_default("Monthly totals", "monthly totals")); diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 82f476d41..8ece0930b 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -17,6 +17,11 @@ pub struct WeeklySummaryTestMessage { /// Every message on the worker queues. The gateway, the schedules and the /// worker all read and write this one enum, so a tag one side sends is always /// one the other reads. +/// +/// A message is built once and handed over by value (never kept in bulk), +/// so the ticket variant's size costs nothing; boxing it would only change +/// every match on it. +#[allow(clippy::large_enum_variant)] #[derive(Serialize, Deserialize, Debug)] #[serde(tag = "type")] pub enum WorkerMessage { @@ -1006,6 +1011,11 @@ pub struct TicketMessage { /// serialized. #[serde(skip)] pub team_instructions: String, + /// Set in-process, once per run: what outcomes taught the coder in this + /// repository (its lessons and the prompt variant the coder's bandit + /// picked), for the coder's system prompt. Capped; never serialized. + #[serde(skip)] + pub coder_learning: String, /// A person's direction that started this run (a reply on the ticket /// telling CoderHelm where the fix is and to go ahead), as /// "author: words". The planner's trace checks then inform, not block. @@ -1119,6 +1129,7 @@ impl Default for TicketMessage { ticket_history_note: None, plan_cache_key: None, team_instructions: String::new(), + coder_learning: String::new(), person_direction: None, answers: Vec::new(), new_run_id: None, diff --git a/services/common/src/pr_outcome.rs b/services/common/src/pr_outcome.rs index f2230474d..69cc373c4 100644 --- a/services/common/src/pr_outcome.rs +++ b/services/common/src/pr_outcome.rs @@ -38,8 +38,16 @@ pub fn outcome(pr: &Value) -> Outcome { Outcome::Open } -/// Commits on a pull request that a person pushed (not Coderhelm, not a bot). +/// Commits on a pull request that a person pushed (not Coderhelm, not a bot) +/// and that change the work itself. A merge commit (GitHub's "Update +/// branch", or a person merging the base in) brings other people's merged +/// work along; counting it made every updated PR look rewritten by people. pub fn human_commit_count(commits: &[Value]) -> u64 { + human_edit_commits(commits).len() as u64 +} + +/// The commits [`human_commit_count`] counts, oldest first. +pub fn human_edit_commits(commits: &[Value]) -> Vec<&Value> { commits .iter() .filter(|c| { @@ -48,9 +56,26 @@ pub fn human_commit_count(commits: &[Value]) -> u64 { .or(c["committer"]["login"].as_str()) .unwrap_or(""); let is_bot = c["author"]["type"].as_str() == Some("Bot") || login.ends_with("[bot]"); - !login.contains("coderhelm") && !is_bot && !login.is_empty() + !login.contains("coderhelm") && !is_bot && !login.is_empty() && !is_merge_commit(c) }) - .count() as u64 + .collect() +} + +/// A merge commit: more than one parent. +pub fn is_merge_commit(c: &Value) -> bool { + c["parents"].as_array().is_some_and(|p| p.len() > 1) +} + +/// The first line of a commit's message, as people wrote it. +pub fn commit_subject(c: &Value) -> String { + c["commit"]["message"] + .as_str() + .unwrap_or("") + .lines() + .next() + .unwrap_or("") + .trim() + .to_string() } /// `(owner, repo, number)` from a PR's html URL. @@ -108,6 +133,22 @@ mod tests { assert_eq!(human_commit_count(&[]), 0); } + #[test] + fn a_persons_update_branch_merge_is_not_an_edit() { + let commits = vec![ + json!({"author":{"login":"coderhelm[bot]","type":"Bot"},"parents":[{"sha":"a"}]}), + // GitHub's "Update branch": authored by the person who pressed it. + json!({"author":{"login":"alice","type":"User"},"parents":[{"sha":"b"},{"sha":"c"}], + "commit":{"message":"Merge branch 'main' into fix"}}), + json!({"author":{"login":"alice","type":"User"},"parents":[{"sha":"d"}], + "commit":{"message":"Use the shared client\n\nThe new one leaked."}}), + ]; + assert_eq!(human_commit_count(&commits), 1); + let edits = human_edit_commits(&commits); + assert_eq!(commit_subject(edits[0]), "Use the shared client"); + assert!(is_merge_commit(&commits[1])); + } + #[test] fn parses_pr_urls() { assert_eq!( diff --git a/services/common/src/rewards/bandit.rs b/services/common/src/rewards/bandit.rs index 1bab60a1f..f3c85c0d2 100644 --- a/services/common/src/rewards/bandit.rs +++ b/services/common/src/rewards/bandit.rs @@ -1,6 +1,7 @@ //! Picking between prompt variants by their reward (UCB1, capped). //! -//! An agent with variants (today the reviewer's prompt) has a default arm. +//! An agent with variants (the reviewer's prompt and the coder's) has a +//! default arm. //! The default is used until it and every other arm have enough samples; //! under-sampled arms are tried only while the share of reviews spent off //! the default stays under the exploration cap. Once arms have @@ -52,6 +53,33 @@ pub const REVIEWER_ARMS: &[Arm] = &[ }, ]; +/// The coder's prompt variants (implement and plan). The first is the +/// default. A run keeps the arm it started with across continuations (it is +/// noted on the run), and its PR's outcome (merged as written, rewritten, +/// closed, reverted, CI rounds) is credited to that arm. +pub const CODER_ARMS: &[Arm] = &[ + Arm { + key: "standard", + label: "Standard", + addendum: "", + }, + Arm { + key: "read_first", + label: "Read first", + addendum: "\n\n## Before you write\nRead every file you will change and the tests that \ + cover it, and one neighbouring file that does the same kind of thing. Copy \ + the patterns you find there (helpers, naming, error handling) instead of \ + writing new ones.", + }, + Arm { + key: "smallest_change", + label: "Smallest change", + addendum: "\n\n## Size of the change\nMake the smallest change that does what the ticket \ + asks. Touch no file the ticket doesn't need, add no new abstraction, and \ + leave unrelated code as it is.", + }, +]; + /// The prompt version of each agent's base prompt. Bump when the base prompt /// changes in a way that should start a fresh comparison. pub const REVIEWER_PROMPT_VERSION: &str = "review-2026-10"; @@ -61,6 +89,7 @@ pub const CODER_PROMPT_VERSION: &str = "implement-2026-10"; pub fn arms_for(agent: &str) -> &'static [Arm] { match agent { super::event::AGENT_REVIEWER => REVIEWER_ARMS, + super::event::AGENT_CODER => CODER_ARMS, _ => &[], } } @@ -308,7 +337,11 @@ mod tests { #[test] fn agents_without_variants_have_no_arms() { - assert!(arms_for("coder").is_empty()); + assert!(arms_for("planner").is_empty()); + // The coder has variants too: its outcomes pick between them. + assert_eq!(arms_for("coder").len(), 3); + assert_eq!(arms_for("coder")[0].key, "standard"); + assert!(arm("coder", "read_first").is_some()); let c = choose(&[], &[], Some("x"), MIN_PULLS, EXPLORATION_CAP); assert_eq!(c.arm, ""); assert!(arm("reviewer", "focused").is_some()); diff --git a/services/common/src/rewards/event.rs b/services/common/src/rewards/event.rs index c826b5d7f..64ac2fb4e 100644 --- a/services/common/src/rewards/event.rs +++ b/services/common/src/rewards/event.rs @@ -182,6 +182,12 @@ pub struct RewardEvent { pub source: String, /// What makes two deliveries of the same signal one event. pub dedup: String, + /// The paths people changed on top of CoderHelm's work (a merge after + /// edits), so a lesson can name them. + pub files: Vec, + /// People's own words about it: their commit subjects, the reason a PR + /// was closed. + pub notes: Vec, } impl RewardEvent { @@ -260,6 +266,13 @@ fn get_s(item: &Item, k: &str) -> String { .unwrap_or_default() } +fn get_l(item: &Item, k: &str) -> Vec { + item.get(k) + .and_then(|v| v.as_l().ok()) + .map(|l| l.iter().filter_map(|x| x.as_s().ok().cloned()).collect()) + .unwrap_or_default() +} + fn get_f(item: &Item, k: &str) -> f64 { item.get(k) .and_then(|v| v.as_n().ok()) @@ -318,6 +331,14 @@ impl RewardEvent { AttributeValue::Ss(self.skills.clone()), ); } + for (k, v) in [("files", &self.files), ("notes", &self.notes)] { + if !v.is_empty() { + i.insert( + k.to_string(), + AttributeValue::L(v.iter().map(|x| s(x)).collect()), + ); + } + } i } @@ -351,6 +372,8 @@ impl RewardEvent { detail: get_s(item, "detail"), source: get_s(item, "source"), dedup: get_s(item, "dedup"), + files: get_l(item, "files"), + notes: get_l(item, "notes"), }) } } @@ -402,6 +425,8 @@ mod tests { .with_detail("people changed a quarter"); e.skills = vec!["tests@3".into()]; e.variant = "standard".into(); + e.files = vec!["src/a.ts".into()]; + e.notes = vec!["Use the shared client".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/health.rs b/services/common/src/rewards/health.rs new file mode 100644 index 000000000..a17cdf1e8 --- /dev/null +++ b/services/common/src/rewards/health.rs @@ -0,0 +1,703 @@ +//! Learning health: is every learning loop still getting its signal? +//! +//! Each loop (outcomes of CoderHelm's PRs, outcomes of review comments, +//! calibration, the prompt variants, examples, coder lessons, pushback +//! judgments, the stop judge's outcome log) is shown with the time of its +//! last signal, its count over the window, and what should have fed it. +//! A loop that should have fired and stayed quiet (PRs merged but none +//! scored, reviews posted but no comment outcome) is `quiet`: the page turns +//! red, so a broken loop is seen in days, not found in an audit. +//! +//! Pure: the gateway reads the records (`routes::learning::get_health`) and +//! this decides. + +use super::event::{RewardEvent, RewardKind, AGENT_CODER, AGENT_REVIEWER}; +use super::lessons::{backed, is_coder_setback}; +use crate::decision_log::Record; +use chrono::{DateTime, Utc}; +use serde::Serialize; +use std::collections::{BTreeMap, BTreeSet}; + +/// The window the page looks at. +pub const WINDOW_DAYS: i64 = 7; +/// Time a closed PR gets to be scored before its absence counts. +pub const SCORE_GRACE_MINUTES: i64 = 60; +/// Reviews in the window before "no comment outcome at all" is a problem. +pub const MIN_REVIEWS_FOR_OUTCOMES: usize = 5; +/// A pushback judgment still pending or judging after this long is stuck. +pub const STUCK_PENDING_HOURS: i64 = 2; +/// Stops and blocks in the window before "no outcome on any" is a problem. +pub const MIN_STOPS_FOR_OUTCOMES: usize = 5; +/// Age of the oldest stop before "no outcome yet" is a problem. +pub const STOP_OUTCOME_GRACE_DAYS: i64 = 3; + +/// A loop's state. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum State { + /// It got what it should have. + Ok, + /// It should have fired and didn't: something is broken. + Quiet, + /// Nothing happened that should feed it. + Idle, +} + +/// One loop as the page shows it. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Loop { + pub key: &'static str, + pub label: &'static str, + pub state: State, + /// The newest signal (RFC 3339), empty when none is known. + pub last_signal_at: String, + /// Signals in the window. + pub count: u64, + /// What should have fed it in the window, when that is known. + pub expected: Option, + /// What the numbers mean, in words. + pub detail: String, +} + +/// A CoderHelm pull request that closed (merged or not) in the window. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct ClosedPr { + pub repo: String, + pub pr: u64, + pub closed_at: String, +} + +/// One prompt variant's pull counter. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct ArmPull { + pub agent: String, + pub pulls: u64, + pub last_pull_at: String, +} + +/// One pushback judgment's pending record. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Pending { + pub status: String, + /// Milliseconds since the epoch, as the record keeps it. + pub last_event_at_ms: i64, + pub judged_at: String, + pub learned: u64, +} + +/// What the page is built from (already limited to one team). +#[derive(Debug, Clone, Default)] +pub struct Inputs<'a> { + pub events: &'a [RewardEvent], + pub closed_prs: &'a [ClosedPr], + /// When CoderHelm posted each review in the window. + pub reviews: &'a [String], + /// Each example's last use. + pub exemplar_last_used: &'a [String], + pub arms: &'a [ArmPull], + /// Each calibration counter's last update. + pub categories_updated: &'a [String], + /// Calibration changes: (at, to). + pub calibration_changes: &'a [(String, String)], + /// Each coder lesson's last time written or reinforced. + pub coder_lessons_seen: &'a [String], + pub pending: &'a [Pending], + /// Each review lesson's last time written or seen again. + pub review_lessons_seen: &'a [String], + pub decisions: &'a [Record], +} + +fn parse(t: &str) -> Option> { + DateTime::parse_from_rfc3339(t) + .ok() + .map(|d| d.with_timezone(&Utc)) +} + +fn newest<'a>(it: impl Iterator) -> String { + it.filter(|t| parse(t).is_some()) + .max_by_key(|t| parse(t)) + .unwrap_or("") + .to_string() +} + +fn within(t: &str, since: DateTime) -> bool { + parse(t).is_some_and(|d| d >= since) +} + +/// Every loop's health at `now`. +pub fn loops(i: &Inputs<'_>, now: DateTime) -> Vec { + let since = now - chrono::Duration::days(WINDOW_DAYS); + let events: Vec<&RewardEvent> = i.events.iter().filter(|e| within(&e.at, since)).collect(); + let reviews: Vec<&String> = i.reviews.iter().filter(|t| within(t, since)).collect(); + let mut out = Vec::new(); + + // 1. Outcomes of CoderHelm's own PRs. + let scored: BTreeSet<(String, u64)> = events + .iter() + .filter(|e| e.agent == AGENT_CODER) + .filter(|e| { + matches!( + e.kind, + Some(RewardKind::PrMergedUnchanged) + | Some(RewardKind::PrMergedEdited) + | Some(RewardKind::PrClosedUnmerged) + | Some(RewardKind::TimeToMerge) + ) + }) + .map(|e| (e.repo.clone(), e.pr)) + .collect(); + let grace = now - chrono::Duration::minutes(SCORE_GRACE_MINUTES); + let due: BTreeSet<(String, u64)> = i + .closed_prs + .iter() + .filter(|p| within(&p.closed_at, since) && parse(&p.closed_at).is_some_and(|d| d <= grace)) + .map(|p| (p.repo.clone(), p.pr)) + .collect(); + let missing: Vec = due + .difference(&scored) + .map(|(r, n)| format!("{r}#{n}")) + .collect(); + out.push(Loop { + key: "pr_outcomes", + label: "Outcomes of CoderHelm's pull requests", + state: if due.is_empty() { + State::Idle + } else if missing.is_empty() { + State::Ok + } else { + State::Quiet + }, + last_signal_at: newest( + events + .iter() + .filter(|e| e.agent == AGENT_CODER) + .map(|e| e.at.as_str()), + ), + count: scored.len() as u64, + expected: Some(due.len() as u64), + detail: if missing.is_empty() { + format!( + "{} of {} pull requests that closed were scored", + due.len().min(scored.len()), + due.len() + ) + } else { + format!( + "{} closed pull request(s) were never scored: {}", + missing.len(), + missing + .iter() + .take(5) + .cloned() + .collect::>() + .join(", ") + ) + }, + }); + + // 2. Outcomes of review comments (acted on, dismissed, left open). + let findings: Vec<&&RewardEvent> = events + .iter() + .filter(|e| e.kind.is_some_and(RewardKind::is_finding)) + .collect(); + let by_kind = |k: RewardKind| findings.iter().filter(|e| e.kind == Some(k)).count(); + out.push(Loop { + key: "review_outcomes", + label: "Outcomes of review comments", + state: if reviews.is_empty() { + State::Idle + } else if findings.is_empty() && reviews.len() >= MIN_REVIEWS_FOR_OUTCOMES { + State::Quiet + } else { + State::Ok + }, + last_signal_at: newest(findings.iter().map(|e| e.at.as_str())), + count: findings.len() as u64, + expected: Some(reviews.len() as u64), + detail: format!( + "{} acted on, {} dismissed, {} left open, from {} review(s)", + by_kind(RewardKind::FindingAccepted), + by_kind(RewardKind::FindingDismissed), + by_kind(RewardKind::FindingIgnored), + reviews.len() + ), + }); + + // 3. Calibration (counters, and the changes they make). + let cats_7d = i + .categories_updated + .iter() + .filter(|t| within(t, since)) + .count(); + let changes_7d: Vec<&(String, String)> = i + .calibration_changes + .iter() + .filter(|(at, _)| within(at, since)) + .collect(); + let to = |k: &str| changes_7d.iter().filter(|(_, t)| t == k).count(); + out.push(Loop { + key: "calibration", + label: "Reviewer calibration", + state: if findings.is_empty() { + State::Idle + } else if cats_7d == 0 { + State::Quiet + } else { + State::Ok + }, + last_signal_at: newest(i.categories_updated.iter().map(String::as_str)), + count: cats_7d as u64, + expected: None, + detail: format!( + "{cats_7d} category counter(s) updated; changes: {} raised, {} downgraded, {} suppressed, {} back to none", + to("raise"), + to("downgrade"), + to("suppress"), + to("none") + ), + }); + + // 4 and 5. Prompt variants, per agent. + for (agent, key, label, expected) in [ + ( + AGENT_REVIEWER, + "reviewer_variants", + "Reviewer prompt variants", + reviews.len(), + ), + ( + AGENT_CODER, + "coder_variants", + "Coder prompt variants", + i.closed_prs + .iter() + .filter(|p| within(&p.closed_at, since)) + .count(), + ), + ] { + let arms: Vec<&ArmPull> = i.arms.iter().filter(|a| a.agent == agent).collect(); + let last = newest(arms.iter().map(|a| a.last_pull_at.as_str())); + let credited = events + .iter() + .filter(|e| e.agent == agent && !e.variant.is_empty()) + .count(); + let pulls: u64 = arms.iter().map(|a| a.pulls).sum(); + let recent = within(&last, since); + // The coder's variants are new: PRs of runs started before them + // close with no pull, which is not a broken loop. + let not_started = agent == AGENT_CODER && arms.is_empty(); + out.push(Loop { + key, + label, + state: if expected == 0 || not_started { + State::Idle + } else if recent || (last.is_empty() && pulls > 0 && credited > 0) { + State::Ok + } else { + State::Quiet + }, + last_signal_at: last, + count: credited as u64, + expected: Some(expected as u64), + detail: format!( + "{} arm(s), {pulls} pull(s) in all; {credited} outcome(s) credited to a variant this window", + arms.len() + ), + }); + } + + // 6. Examples put into prompts. + let used_7d = i + .exemplar_last_used + .iter() + .filter(|t| within(t, since)) + .count(); + out.push(Loop { + key: "examples", + label: "Good and avoid examples in prompts", + state: if i.exemplar_last_used.is_empty() || reviews.is_empty() { + State::Idle + } else if used_7d == 0 { + State::Quiet + } else { + State::Ok + }, + last_signal_at: newest(i.exemplar_last_used.iter().map(String::as_str)), + count: used_7d as u64, + expected: None, + detail: format!( + "{used_7d} of {} example(s) used this window", + i.exemplar_last_used.len() + ), + }); + + // 7. Coder lessons: an area with backed setbacks should have one. + let mut by_area: BTreeMap<(String, String), Vec> = BTreeMap::new(); + for e in events.iter().filter(|e| is_coder_setback(e)) { + by_area + .entry((e.repo.clone(), e.area.clone())) + .or_default() + .push((*e).clone()); + } + let backed_areas = by_area.values().filter(|v| backed(v)).count(); + let lessons_7d = i + .coder_lessons_seen + .iter() + .filter(|t| within(t, since)) + .count(); + out.push(Loop { + key: "coder_lessons", + label: "Coder lessons from outcomes", + state: if backed_areas == 0 { + State::Idle + } else if lessons_7d == 0 { + State::Quiet + } else { + State::Ok + }, + last_signal_at: newest(i.coder_lessons_seen.iter().map(String::as_str)), + count: lessons_7d as u64, + expected: Some(backed_areas as u64), + detail: format!( + "{} setback(s) in {} area(s); {backed_areas} area(s) with enough evidence for a lesson; {lessons_7d} lesson(s) written or reinforced", + by_area.values().map(Vec::len).sum::(), + by_area.len() + ), + }); + + // 8. Pushback judgments. + let stuck_before = (now - chrono::Duration::hours(STUCK_PENDING_HOURS)).timestamp_millis(); + let recent_pending: Vec<&Pending> = i + .pending + .iter() + .filter(|p| p.last_event_at_ms >= since.timestamp_millis()) + .collect(); + let stuck = recent_pending + .iter() + .filter(|p| p.status != crate::review_lessons::STATUS_JUDGED) + .filter(|p| p.last_event_at_ms < stuck_before) + .count(); + let judged: Vec<&&Pending> = recent_pending + .iter() + .filter(|p| p.status == crate::review_lessons::STATUS_JUDGED) + .collect(); + let learned: u64 = judged.iter().map(|p| p.learned).sum(); + out.push(Loop { + key: "review_lessons", + label: "Reviewer lessons from people's pushback", + state: if recent_pending.is_empty() { + State::Idle + } else if stuck > 0 { + State::Quiet + } else { + State::Ok + }, + last_signal_at: newest( + i.review_lessons_seen + .iter() + .map(String::as_str) + .chain(judged.iter().map(|p| p.judged_at.as_str())), + ), + count: judged.len() as u64, + expected: Some(recent_pending.len() as u64), + detail: format!( + "{} pull request(s) with pushback, {} judged, {learned} lesson(s) learned, {stuck} stuck", + recent_pending.len(), + judged.len() + ), + }); + + // 9. The stop judge's outcome log. + let stops: Vec<&Record> = i + .decisions + .iter() + .filter(|r| r.stopped() && within(&r.created_at, since)) + .collect(); + let with_outcome = stops.iter().filter(|r| r.outcome.is_some()).count(); + let wrong = stops.iter().filter(|r| r.confirmed_wrong()).count(); + let oldest_old = stops.iter().any(|r| { + parse(&r.created_at) + .is_some_and(|d| d <= now - chrono::Duration::days(STOP_OUTCOME_GRACE_DAYS)) + }); + out.push(Loop { + key: "stop_outcomes", + label: "What people did after asks, stops and blocks", + state: if stops.is_empty() { + State::Idle + } else if with_outcome == 0 && stops.len() >= MIN_STOPS_FOR_OUTCOMES && oldest_old { + State::Quiet + } else { + State::Ok + }, + last_signal_at: newest(stops.iter().map(|r| r.outcome_at.as_str())), + count: with_outcome as u64, + expected: Some(stops.len() as u64), + detail: format!( + "{} ask(s), stop(s) and block(s); {with_outcome} with a person's act recorded, {wrong} shown wrong (the judge is given those)", + stops.len() + ), + }); + out +} + +/// The page: every loop, and red when any is quiet. +pub fn build(i: &Inputs<'_>, now: DateTime) -> serde_json::Value { + let loops = loops(i, now); + let quiet: Vec<&str> = loops + .iter() + .filter(|l| l.state == State::Quiet) + .map(|l| l.key) + .collect(); + serde_json::json!({ + "window_days": WINDOW_DAYS, + "generated_at": now.to_rfc3339(), + "state": if quiet.is_empty() { "ok" } else { "red" }, + "quiet": quiet, + "loops": loops, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::TimeZone; + + fn now() -> DateTime { + Utc.with_ymd_and_hms(2026, 11, 6, 12, 0, 0).unwrap() + } + + fn ev(kind: RewardKind, agent: &str, pr: u64, at: &str) -> RewardEvent { + RewardEvent::new("T", kind, agent, at, &format!("{kind:?}{pr}")).with_repo("acme/web", pr) + } + + fn by_key<'a>(l: &'a [Loop], k: &str) -> &'a Loop { + l.iter().find(|x| x.key == k).unwrap() + } + + /// Production: PRs merged that week, but outcomes for some never + /// landed. The page names them and turns red. + #[test] + fn merged_prs_with_no_outcome_turn_the_page_red() { + let closed = vec![ + ClosedPr { + repo: "acme/web".into(), + pr: 1, + closed_at: "2026-11-05T00:00:00Z".into(), + }, + ClosedPr { + repo: "acme/web".into(), + pr: 2, + closed_at: "2026-11-05T00:00:00Z".into(), + }, + // Closed minutes ago: still within the grace. + ClosedPr { + repo: "acme/web".into(), + pr: 3, + closed_at: "2026-11-06T11:50:00Z".into(), + }, + ]; + let events = vec![ev( + RewardKind::TimeToMerge, + AGENT_CODER, + 1, + "2026-11-05T00:01:00Z", + )]; + let i = Inputs { + events: &events, + closed_prs: &closed, + ..Default::default() + }; + let l = loops(&i, now()); + let pr = by_key(&l, "pr_outcomes"); + assert_eq!(pr.state, State::Quiet); + assert_eq!(pr.expected, Some(2)); + assert!(pr.detail.contains("acme/web#2"), "{}", pr.detail); + let page = build(&i, now()); + assert_eq!(page["state"], "red"); + assert!(page["quiet"] + .as_array() + .unwrap() + .iter() + .any(|q| q == "pr_outcomes")); + } + + #[test] + fn reviews_with_no_comment_outcome_are_quiet_and_outcomes_count() { + let reviews: Vec = (0..6).map(|_| "2026-11-05T00:00:00Z".to_string()).collect(); + let i = Inputs { + reviews: &reviews, + ..Default::default() + }; + let l = loops(&i, now()); + assert_eq!(by_key(&l, "review_outcomes").state, State::Quiet); + assert_eq!(by_key(&l, "reviewer_variants").state, State::Quiet); + // The coder's variants before their first pull: idle, not red. + let closed = vec![ClosedPr { + repo: "acme/web".into(), + pr: 9, + closed_at: "2026-11-05T00:00:00Z".into(), + }]; + let i2 = Inputs { + closed_prs: &closed, + ..Default::default() + }; + assert_eq!( + by_key(&loops(&i2, now()), "coder_variants").state, + State::Idle + ); + let stale = vec![ArmPull { + agent: AGENT_CODER.into(), + pulls: 3, + last_pull_at: "2026-10-01T00:00:00Z".into(), + }]; + let i2 = Inputs { + closed_prs: &closed, + arms: &stale, + ..Default::default() + }; + assert_eq!( + by_key(&loops(&i2, now()), "coder_variants").state, + State::Quiet + ); + let mut events = vec![ + ev( + RewardKind::FindingIgnored, + AGENT_REVIEWER, + 4, + "2026-11-05T01:00:00Z", + ), + ev( + RewardKind::FindingAccepted, + AGENT_REVIEWER, + 4, + "2026-11-05T02:00:00Z", + ), + ]; + events[0].variant = "focused".into(); + let arms = vec![ArmPull { + agent: AGENT_REVIEWER.into(), + pulls: 9, + last_pull_at: "2026-11-05T00:00:00Z".into(), + }]; + let cats = vec!["2026-11-05T02:00:00Z".to_string()]; + let i = Inputs { + reviews: &reviews, + events: &events, + arms: &arms, + categories_updated: &cats, + ..Default::default() + }; + let l = loops(&i, now()); + let r = by_key(&l, "review_outcomes"); + assert_eq!(r.state, State::Ok); + assert!(r.detail.starts_with("1 acted on, 0 dismissed, 1 left open")); + assert_eq!(r.last_signal_at, "2026-11-05T02:00:00Z"); + assert_eq!(by_key(&l, "reviewer_variants").state, State::Ok); + assert_eq!(by_key(&l, "calibration").state, State::Ok); + // Nothing reviewed and nothing closed: idle, never red. + let l = loops(&Inputs::default(), now()); + assert!(l.iter().all(|x| x.state == State::Idle), "{l:?}"); + assert_eq!(build(&Inputs::default(), now())["state"], "ok"); + } + + #[test] + fn backed_setbacks_without_a_lesson_are_quiet() { + let mut a = ev( + RewardKind::PrClosedUnmerged, + AGENT_CODER, + 7, + "2026-11-04T00:00:00Z", + ); + a.area = "apps/web".into(); + let mut b = ev( + RewardKind::CiFixRounds, + AGENT_CODER, + 8, + "2026-11-04T00:00:00Z", + ) + .with_value(3.0); + b.area = "apps/web".into(); + let events = vec![a, b]; + let i = Inputs { + events: &events, + ..Default::default() + }; + assert_eq!( + by_key(&loops(&i, now()), "coder_lessons").state, + State::Quiet + ); + let seen = vec!["2026-11-04T00:01:00Z".to_string()]; + let i = Inputs { + events: &events, + coder_lessons_seen: &seen, + ..Default::default() + }; + assert_eq!(by_key(&loops(&i, now()), "coder_lessons").state, State::Ok); + } + + #[test] + fn a_stuck_pushback_judgment_is_quiet() { + let ms = |t: &str| parse(t).unwrap().timestamp_millis(); + let pending = vec![ + Pending { + status: "judged".into(), + last_event_at_ms: ms("2026-11-05T00:00:00Z"), + judged_at: "2026-11-05T00:05:00Z".into(), + learned: 1, + }, + Pending { + status: "pending".into(), + last_event_at_ms: ms("2026-11-06T11:00:00Z"), + ..Default::default() + }, + ]; + let i = Inputs { + pending: &pending, + ..Default::default() + }; + let l = by_key(&loops(&i, now()), "review_lessons").clone(); + assert_eq!(l.state, State::Ok, "an hour old is still waiting"); + assert!(l.detail.contains("1 lesson(s) learned")); + let mut pending = pending; + pending[1].last_event_at_ms = ms("2026-11-06T08:00:00Z"); + let i = Inputs { + pending: &pending, + ..Default::default() + }; + assert_eq!( + by_key(&loops(&i, now()), "review_lessons").state, + State::Quiet + ); + } + + #[test] + fn stops_with_no_outcome_after_days_are_quiet() { + let rec = |at: &str, outcome| Record { + kind: "block".into(), + verdict: "hold".into(), + created_at: at.into(), + outcome, + ..Default::default() + }; + let stops: Vec = (0..5).map(|_| rec("2026-11-01T00:00:00Z", None)).collect(); + let i = Inputs { + decisions: &stops, + ..Default::default() + }; + assert_eq!( + by_key(&loops(&i, now()), "stop_outcomes").state, + State::Quiet + ); + let mut stops = stops; + stops[0].outcome = Some(crate::decision_log::Outcome::Overrode); + stops[0].outcome_at = "2026-11-02T00:00:00Z".into(); + let i = Inputs { + decisions: &stops, + ..Default::default() + }; + let l = by_key(&loops(&i, now()), "stop_outcomes").clone(); + assert_eq!(l.state, State::Ok); + assert!(l.detail.contains("1 shown wrong")); + assert_eq!(l.last_signal_at, "2026-11-02T00:00:00Z"); + } +} diff --git a/services/common/src/rewards/lessons.rs b/services/common/src/rewards/lessons.rs index 910d71a4b..eb2edf962 100644 --- a/services/common/src/rewards/lessons.rs +++ b/services/common/src/rewards/lessons.rs @@ -49,9 +49,11 @@ fn words(s: &str) -> BTreeSet { "the", "a", "an", "and", "or", "of", "to", "in", "on", "for", "is", "are", "be", "this", "that", "with", "it", "as", "at", "by", "here", "when", "only", ]; + // Numbers (PR numbers, percentages) say which outcome, not what was + // learned: two lessons differing only in them are the same lesson. s.to_ascii_lowercase() .split(|c: char| !c.is_ascii_alphanumeric()) - .filter(|w| w.len() > 1 && !STOP.contains(w)) + .filter(|w| w.len() > 1 && !STOP.contains(w) && !w.chars().all(|c| c.is_ascii_digit())) .map(str::to_string) .collect() } @@ -127,7 +129,13 @@ pub fn prompt_block(lessons: &[Lesson]) -> String { } let lines: Vec = lessons .iter() - .map(|l| format!("- {} (seen {}×)", l.text.trim(), l.seen)) + .map(|l| { + format!( + "- {} (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{}", @@ -156,41 +164,192 @@ pub fn plan(text: &str, evidence: &[RewardEvent], kept: &[Lesson]) -> Plan { } } +/// A coder outcome bad enough to look for a pattern behind it. +pub fn is_coder_setback(e: &RewardEvent) -> bool { + match e.kind { + Some(RewardKind::PrClosedUnmerged) + | Some(RewardKind::PrReverted) + | Some(RewardKind::IncidentLinked) => true, + Some(RewardKind::CiFixRounds) => e.value >= 2.0, + // People changed a real part of it (measured from their own + // commits, so a merge of the base branch no longer counts). + Some(RewardKind::PrMergedEdited) => e.value >= SETBACK_EDIT_SHARE, + _ => false, + } +} + +/// The share of a PR's diff people changed that makes it a setback. +pub const SETBACK_EDIT_SHARE: f64 = 0.3; + +/// Most pull requests one coder lesson names, newest first. +pub const MAX_LESSON_PRS: usize = 4; +/// Longest coder lesson. +pub const MAX_LESSON_CHARS: usize = 900; +/// Longest lesson text put into a prompt. +pub const MAX_PROMPT_LESSON_CHARS: usize = 700; + +/// The id of the one coder lesson kept per (repository, area): later +/// outcomes in the area rewrite it with what people did most recently, +/// instead of piling up near-copies that differ only in PR numbers. +pub fn area_lesson_id(area: &str) -> String { + use sha2::{Digest, Sha256}; + let d = Sha256::digest(area.as_bytes()); + let h: String = d.iter().take(8).map(|b| format!("{b:02x}")).collect(); + format!("AREA-{h}") +} + +/// A coder lesson written before lessons named what people did (`Changes in +/// `area` were ...`): replaced by the area's lesson when it is written. +pub fn is_generic_area_lesson(text: &str, area: &str) -> bool { + let place = if area.is_empty() { + "this repository".to_string() + } else { + format!("`{area}`") + }; + text.starts_with(&format!("Changes in {place} were ")) +} + +fn quote(s: &str) -> String { + format!( + "\"{}\"", + crate::truncate_str(s.trim().trim_matches('"'), 140) + ) +} + +/// What one bad outcome says, specifically: the files people changed and +/// their own words, why a PR was closed, a revert, or CI rounds. +fn outcome_line(e: &RewardEvent) -> Option { + let pr = if e.pr > 0 { + format!("PR #{}", e.pr) + } else { + "a change".to_string() + }; + let notes: Vec = e + .notes + .iter() + .filter(|n| !n.trim().is_empty()) + .take(2) + .map(|n| quote(n)) + .collect(); + let said = if notes.is_empty() { + String::new() + } else { + format!(" ({})", notes.join("; ")) + }; + match e.kind? { + RewardKind::PrMergedEdited => { + let files: Vec = e.files.iter().take(3).map(|f| format!("`{f}`")).collect(); + if files.is_empty() && notes.is_empty() { + return Some(format!( + "{pr} was rewritten by people before merging ({}% of the diff)", + (e.value * 100.0).round() as u64 + )); + } + let what = if files.is_empty() { + "changed it".to_string() + } else { + format!("changed {}", files.join(", ")) + }; + Some(format!("on {pr} people {what} before merging{said}")) + } + RewardKind::PrClosedUnmerged => Some(format!("{pr} was closed without merging{said}")), + RewardKind::PrReverted => Some(format!("{pr} was reverted after merging{said}")), + RewardKind::IncidentLinked => Some(format!("{pr} was tied to an alert{said}")), + RewardKind::CiFixRounds => Some(format!( + "{pr} needed {} CI fix rounds", + e.value.round() as u64 + )), + _ => None, + } +} + /// The lesson an outcome pattern teaches, in plain words, or None. -/// `negatives` are this repo area's recent bad outcomes for the coder. +/// `negatives` are this repo area's recent bad outcomes for the coder. The +/// lesson names what people did (the files they changed and their commit +/// subjects, why they closed a PR), newest first, and what to do about it, +/// so it changes what the coder does rather than restating "be careful". pub fn coder_lesson_text(area: &str, negatives: &[RewardEvent]) -> Option { - if negatives.is_empty() { + let mut newest: Vec<&RewardEvent> = negatives.iter().filter(|e| e.kind.is_some()).collect(); + if newest.is_empty() { + return None; + } + newest.sort_by(|a, b| b.at.cmp(&a.at)); + // One line per pull request: the most telling outcome of it. + let rank = |e: &RewardEvent| match e.kind { + Some(RewardKind::PrReverted) | Some(RewardKind::IncidentLinked) => 0, + Some(RewardKind::PrMergedEdited) if !e.files.is_empty() || !e.notes.is_empty() => 1, + Some(RewardKind::PrClosedUnmerged) if !e.notes.is_empty() => 1, + Some(RewardKind::PrClosedUnmerged) | Some(RewardKind::PrMergedEdited) => 2, + _ => 3, + }; + let mut lines: Vec = Vec::new(); + let mut by_pr: Vec<(&RewardEvent, i32)> = Vec::new(); + for e in &newest { + match by_pr + .iter_mut() + .find(|(x, _)| x.repo == e.repo && x.pr == e.pr) + { + Some(slot) if rank(e) < slot.1 => *slot = (e, rank(e)), + Some(_) => {} + None => by_pr.push((e, rank(e))), + } + } + for (e, _) in &by_pr { + if let Some(l) = outcome_line(e) { + lines.push(l); + } + if lines.len() >= MAX_LESSON_PRS { + break; + } + } + if lines.is_empty() { return None; } - let mut kinds: Vec<&str> = negatives - .iter() - .filter_map(|e| e.kind) - .map(|k| match k { - RewardKind::PrReverted => "reverted", - RewardKind::PrClosedUnmerged => "closed without merging", - RewardKind::IncidentLinked => "tied to an alert", - RewardKind::CiFixRounds => "needed CI fix rounds", - RewardKind::PrMergedEdited => "rewritten by people before merging", - _ => "rejected", - }) - .collect(); - kinds.sort(); - kinds.dedup(); - let prs: BTreeSet = negatives - .iter() - .filter(|e| e.pr > 0) - .map(|e| format!("#{}", e.pr)) - .collect(); let place = if area.is_empty() { "this repository".to_string() } else { format!("`{area}`") }; - Some(format!( - "Changes in {place} were {} ({}). Read the surrounding code and its tests before changing it, and keep the change small.", - kinds.join(", "), - prs.into_iter().collect::>().join(", ") - )) + let edited_files: Vec = { + let mut f: Vec = Vec::new(); + for e in &newest { + for p in &e.files { + if !f.contains(p) { + f.push(p.clone()); + } + } + } + f.into_iter().take(4).collect() + }; + let has = |k: RewardKind| newest.iter().any(|e| e.kind == Some(k)); + let mut todo: Vec = Vec::new(); + if !edited_files.is_empty() { + todo.push(format!( + "read {} first and follow what people changed there", + edited_files + .iter() + .map(|f| format!("`{f}`")) + .collect::>() + .join(", ") + )); + } + if has(RewardKind::PrClosedUnmerged) || has(RewardKind::PrReverted) { + todo.push("check the reasons above against the plan before writing code".into()); + } + if has(RewardKind::CiFixRounds) { + todo.push(format!( + "run the repository's own checks for {place} before finishing" + )); + } + if todo.is_empty() { + todo.push("keep the change to what the ticket asks".into()); + } + let text = format!( + "In {place}: {}. Next time, {}.", + lines.join("; "), + todo.join(", and ") + ); + Some(crate::truncate_str(&text, MAX_LESSON_CHARS).to_string()) } #[cfg(test)] @@ -306,8 +465,49 @@ mod tests { ) .unwrap(); assert!(t.contains("`src/billing`")); - assert!(t.contains("#3, #9")); - assert!(t.contains("closed without merging, reverted")); + assert!(t.contains("PR #3 was reverted"), "{t}"); + assert!(t.contains("PR #9 was closed without merging"), "{t}"); assert!(coder_lesson_text("", &[]).is_none()); } + + /// Production had two lessons for one area that said only "were closed + /// without merging, needed CI fix rounds, rewritten by people... Read + /// the surrounding code": nothing a coder could act on. A lesson names + /// what people changed and said, newest first, and what to do. + #[test] + fn coder_lessons_say_what_people_changed() { + let mut edited = ev(RewardKind::PrMergedEdited, 12).with_value(0.4); + edited.at = "2026-10-03T00:00:00Z".into(); + edited.files = vec!["apps/web/src/api.ts".into(), "apps/web/src/hooks.ts".into()]; + edited.notes = vec!["Use the shared fetch hook".into()]; + let mut closed = ev(RewardKind::PrClosedUnmerged, 15); + closed.at = "2026-10-04T00:00:00Z".into(); + closed.notes = vec!["The flag lives in the CMS, not in code".into()]; + let mut ci = ev(RewardKind::CiFixRounds, 15).with_value(3.0); + ci.at = "2026-10-04T00:00:00Z".into(); + let t = coder_lesson_text("apps/web", &[edited, closed, ci]).unwrap(); + assert!(t.starts_with("In `apps/web`: PR #15 was closed without merging (\"The flag lives in the CMS, not in code\")"), "{t}"); + assert!(t.contains("on PR #12 people changed `apps/web/src/api.ts`, `apps/web/src/hooks.ts` before merging (\"Use the shared fetch hook\")"), "{t}"); + assert!( + t.contains("read `apps/web/src/api.ts`, `apps/web/src/hooks.ts` first"), + "{t}" + ); + assert!(!t.contains("Read the surrounding code")); + assert!(t.len() <= MAX_LESSON_CHARS); + // One lesson per area, and the old generic ones are recognised. + assert_eq!(area_lesson_id("apps/web"), area_lesson_id("apps/web")); + assert_ne!(area_lesson_id("apps/web"), area_lesson_id("apps/api")); + assert!(is_generic_area_lesson( + "Changes in `apps/web` were closed without merging (#1). Read the surrounding code.", + "apps/web" + )); + assert!(!is_generic_area_lesson(&t, "apps/web")); + // PR numbers alone don't make a different lesson. + assert!( + similarity( + "closed without merging #12 #13", + "closed without merging #99" + ) > 0.99 + ); + } } diff --git a/services/common/src/rewards/mapping.rs b/services/common/src/rewards/mapping.rs index 53762c797..2f0a492b0 100644 --- a/services/common/src/rewards/mapping.rs +++ b/services/common/src/rewards/mapping.rs @@ -20,6 +20,35 @@ pub struct RunContext { pub plugin: String, /// The area most of the change touched. pub area: String, + /// Why people closed the PR, when they said (the run's close reason or + /// their answer to CoderHelm's one question). + pub close_reason: String, +} + +/// What people changed on top of CoderHelm's work before merging: their own +/// commits only (a merge of the base branch is not an edit), measured from +/// each commit's own stats. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct PeopleEdits { + /// Their non-merge commits. + pub commits: u64, + /// Lines they added and removed, summed over those commits. + pub lines: u64, + /// The paths they touched, most touched first. + pub files: Vec, + /// Their commit subjects, oldest first. + pub subjects: Vec, +} + +/// Most paths and commit subjects kept on one event. +pub const MAX_EDIT_FILES: usize = 6; +pub const MAX_EDIT_NOTES: usize = 4; + +impl PeopleEdits { + /// The share of the PR's diff they changed, 0..1. + pub fn share(&self, pr_lines: u64) -> f64 { + edit_fraction(self.lines, pr_lines) + } } impl RunContext { @@ -78,9 +107,10 @@ pub fn pr_closed_events( ctx: &RunContext, pr: &Value, human_commits: Option, - edit_share: Option, + edits: Option<&PeopleEdits>, ci: CiSummary, ) -> Vec { + let pr_lines = pr["additions"].as_u64().unwrap_or(0) + pr["deletions"].as_u64().unwrap_or(0); let mut out = vec![]; let key = format!("{}#{}", ctx.repo, ctx.pr); let opened = pr["created_at"].as_str().unwrap_or(""); @@ -101,9 +131,10 @@ pub fn pr_closed_events( .with_detail(&format!("PR #{} merged as written by {merged_by}", ctx.pr)), ), Some(n) => { - if let Some(share) = edit_share { - out.push( - ctx.event( + if let Some(ed) = edits { + let share = ed.share(pr_lines); + let mut e = ctx + .event( RewardKind::PrMergedEdited, AGENT_CODER, &merged_at, @@ -114,8 +145,16 @@ pub fn pr_closed_events( "PR #{} merged after {n} commit(s) from people, {}% of the diff changed", ctx.pr, (share * 100.0).round() as u64 - )), - ); + )); + e.files = ed.files.iter().take(MAX_EDIT_FILES).cloned().collect(); + e.notes = ed + .subjects + .iter() + .filter(|t| !t.trim().is_empty()) + .take(MAX_EDIT_NOTES) + .map(|t| crate::truncate_str(t.trim(), 160).to_string()) + .collect(); + out.push(e); } } None => {} @@ -138,15 +177,18 @@ pub fn pr_closed_events( out.extend(ci_event(ctx, &merged_at, &key, ci)); } crate::pr_outcome::Outcome::Closed { closed_at, .. } => { - out.push( - ctx.event( + let mut e = ctx + .event( RewardKind::PrClosedUnmerged, AGENT_CODER, &closed_at, &format!("closed#{key}"), ) - .with_detail(&format!("PR #{} closed without merging", ctx.pr)), - ); + .with_detail(&format!("PR #{} closed without merging", ctx.pr)); + if !ctx.close_reason.trim().is_empty() { + e.notes = vec![crate::truncate_str(ctx.close_reason.trim(), 240).to_string()]; + } + out.push(e); out.extend(ci_event(ctx, &closed_at, &key, ci)); } crate::pr_outcome::Outcome::Open => {} @@ -228,6 +270,64 @@ pub fn thread_title(body: &str) -> String { } } +/// What one of CoderHelm's review threads says about the comment once the +/// PR closed, for the reviewer's calibration. Read from the thread itself, so +/// a note on an approved review (a Nit or a Suggestion) counts the same as a +/// blocker: +/// +/// * a person replied: their words are the review-lesson judge's to read, so +/// nothing here (the judge records a dismissal when the reviewer was wrong); +/// * CoderHelm resolved it (a later review saw it fixed), or the lines it +/// pointed at changed: acted on; +/// * a person resolved it with the lines unchanged: dismissed; +/// * merged with it still open and untouched: left open (an FYI asks for +/// nothing, so it never counts as left open); +/// * closed without merging and untouched: nothing (the PR was dropped, not +/// the comment). +pub fn thread_outcome(t: &ThreadAtClose, merged: bool) -> Option { + if t.person_replied { + return None; + } + if (t.resolved && !t.resolved_by_person) || t.outdated { + return Some(RewardKind::FindingAccepted); + } + if t.resolved && t.resolved_by_person { + return Some(RewardKind::FindingDismissed); + } + if merged && !is_fyi(&t.body) { + return Some(RewardKind::FindingIgnored); + } + None +} + +/// A review thread as it stood when the PR closed. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct ThreadAtClose { + pub resolved: bool, + pub resolved_by_person: bool, + /// GitHub marks a thread outdated when the lines it is anchored on changed. + pub outdated: bool, + /// A person (not a bot) wrote under it. + pub person_replied: bool, + pub body: String, +} + +/// An FYI note: information, nothing to act on. +pub fn is_fyi(body: &str) -> bool { + body.lines().next().unwrap_or("").contains("**FYI: ") +} + +/// The words people read for a thread outcome, as evidence. +pub fn thread_outcome_detail(kind: RewardKind, body: &str, path: &str) -> String { + let why = match kind { + RewardKind::FindingAccepted => "acted on before the PR closed", + RewardKind::FindingDismissed => "resolved by a person with the lines unchanged", + RewardKind::FindingIgnored => "still open and untouched when the PR merged", + _ => "", + }; + format!("{} ({path}): {why}", thread_title(body)) +} + /// A finding event for one of CoderHelm's review threads. #[allow(clippy::too_many_arguments)] pub fn finding_event( @@ -386,7 +486,16 @@ mod tests { passed: true, known: true, }; - let v = pr_closed_events(&ctx(), &merged(), Some(3), Some(0.4), ci); + let ed = PeopleEdits { + commits: 3, + lines: 40, + files: vec!["src/api/a.ts".into()], + subjects: vec!["Use the shared client".into(), " ".into()], + }; + let mut pr = merged(); + pr["additions"] = json!(80); + pr["deletions"] = json!(20); + let v = pr_closed_events(&ctx(), &pr, Some(3), Some(&ed), ci); assert_eq!( kinds(&v), vec![ @@ -397,6 +506,9 @@ mod tests { ); assert_eq!(v[0].value, 0.4); assert!(v[0].detail.contains("40% of the diff")); + // 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()]); assert_eq!(v[2].value, 2.0); // Unmeasured edits are not guessed. let v = pr_closed_events(&ctx(), &merged(), Some(3), None, CiSummary::default()); @@ -412,6 +524,14 @@ mod tests { let v = pr_closed_events(&ctx(), &pr, Some(0), None, CiSummary::default()); assert_eq!(kinds(&v), vec![RewardKind::PrClosedUnmerged]); assert_eq!(v[0].at, "2026-10-03T00:00:00Z"); + assert!(v[0].notes.is_empty()); + let mut c = ctx(); + c.close_reason = "Wrong approach: the flag lives in the CMS".into(); + let v = pr_closed_events(&c, &pr, Some(0), None, CiSummary::default()); + assert_eq!( + v[0].notes, + vec!["Wrong approach: the flag lives in the CMS".to_string()] + ); let open = json!({"state":"open"}); assert!(pr_closed_events(&ctx(), &open, Some(0), None, CiSummary::default()).is_empty()); } @@ -448,6 +568,56 @@ mod tests { assert_eq!(revert_target("Revert \"x\"", "no ref", "acme/web"), None); } + #[test] + fn threads_at_close_feed_calibration_both_ways() { + let t = |resolved, by_person, outdated, replied, body: &str| ThreadAtClose { + resolved, + resolved_by_person: by_person, + outdated, + person_replied: replied, + body: body.into(), + }; + let nit = "💬 **Nit: Rename the flag** (style, not verified)"; + let fyi = "💬 **FYI: The cache is per region** (other, not verified)"; + // Untouched at merge: left open, a Nit as much as a blocker. + assert_eq!( + thread_outcome(&t(false, false, false, false, nit), true), + Some(RewardKind::FindingIgnored) + ); + // An FYI asks for nothing; a dropped PR says nothing about a note. + assert_eq!( + thread_outcome(&t(false, false, false, false, fyi), true), + None + ); + assert_eq!( + thread_outcome(&t(false, false, false, false, nit), false), + None + ); + // Lines changed under it, or CoderHelm saw it fixed: acted on. + assert_eq!( + thread_outcome(&t(false, false, true, false, nit), true), + Some(RewardKind::FindingAccepted) + ); + assert_eq!( + thread_outcome(&t(true, false, false, false, nit), false), + Some(RewardKind::FindingAccepted) + ); + // A person resolved it with the lines unchanged: dismissed. + assert_eq!( + thread_outcome(&t(true, true, false, false, nit), true), + Some(RewardKind::FindingDismissed) + ); + // Words under it are the judge's to read. + assert_eq!( + thread_outcome(&t(false, false, false, true, nit), true), + None + ); + assert!( + thread_outcome_detail(RewardKind::FindingIgnored, nit, "a.rs") + .starts_with("Nit: Rename the flag (a.rs)") + ); + } + #[test] fn edit_share_is_bounded() { assert_eq!(edit_fraction(0, 100), 0.0); diff --git a/services/common/src/rewards/mod.rs b/services/common/src/rewards/mod.rs index bc19bab3d..33711681a 100644 --- a/services/common/src/rewards/mod.rs +++ b/services/common/src/rewards/mod.rs @@ -23,6 +23,7 @@ pub mod changes; pub mod event; pub mod example_text; pub mod exemplars; +pub mod health; pub mod lessons; pub mod mapping; pub mod score; @@ -31,10 +32,13 @@ pub mod summary; pub use event::{RewardEvent, RewardKind}; -/// The outcome of a CoderHelm pull request to score (gateway → worker, on -/// the `pull_request.closed` webhook). The worker reads the PR, its commits -/// and CoderHelm's open review threads, and records the events. -#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] +/// The outcome of a closed pull request to score (gateway to worker, on the +/// `pull_request.closed` webhook, and from the worker's reconcile sweep for a +/// close the webhook missed). For CoderHelm's own PR the worker reads the PR, +/// its commits and CoderHelm's review threads and records the coder's and +/// the reviewer's events; for a person's PR CoderHelm reviewed +/// (`review_only`) it records only what became of the review's comments. +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Default)] pub struct RewardOutcomeMessage { pub team_id: String, pub installation_id: u64, @@ -42,4 +46,7 @@ pub struct RewardOutcomeMessage { pub repo_owner: String, pub repo_name: String, pub pr_number: u64, + /// A PR CoderHelm reviewed but didn't write: no coder outcome. + #[serde(default)] + pub review_only: bool, } diff --git a/services/common/src/rewards/store.rs b/services/common/src/rewards/store.rs index 463e017fd..968e81be9 100644 --- a/services/common/src/rewards/store.rs +++ b/services/common/src/rewards/store.rs @@ -126,6 +126,45 @@ impl Store { Ok(out) } + /// Like [`Self::query_prefix`], reading only `projection` (comma-separated + /// attribute names, no reserved words), for counts that need no payload + /// (an example's embedding or a decision's picture stay unread). + pub async fn query_projected( + &self, + team_id: &str, + prefix: &str, + projection: &[&str], + max_pages: usize, + ) -> Result, String> { + let mut out = vec![]; + let mut start: Option = None; + let names: Vec = (0..projection.len()).map(|i| format!("#p{i}")).collect(); + for _ in 0..max_pages.max(1) { + let mut q = self + .dynamo + .query() + .table_name(&self.table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", s(team_id)) + .expression_attribute_values(":p", s(prefix)) + .projection_expression(names.join(", ")) + .set_exclusive_start_key(start.take()); + for (alias, name) in names.iter().zip(projection) { + q = q.expression_attribute_names(alias, *name); + } + let page = q + .send() + .await + .map_err(|e| 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) + } + async fn get(&self, team_id: &str, sk: &str) -> Result, String> { self.dynamo .get_item() @@ -400,11 +439,13 @@ impl Store { .table_name(&self.table) .key("pk", s(team_id)) .key("sk", s(&arm_sk(agent, arm))) - .update_expression("ADD #p :one SET #rt = :rt, #ag = :a, #arm = :k") + .update_expression("ADD #p :one SET #rt = :rt, #ag = :a, #arm = :k, #lp = :now") .expression_attribute_names("#p", "pulls") .expression_attribute_names("#rt", "record_type") .expression_attribute_names("#ag", "agent") .expression_attribute_names("#arm", "arm") + .expression_attribute_names("#lp", "last_pull_at") + .expression_attribute_values(":now", s(&chrono::Utc::now().to_rfc3339())) .expression_attribute_values(":one", n(1)) .expression_attribute_values(":rt", s("reward_arm")) .expression_attribute_values(":a", s(agent)) @@ -865,6 +906,113 @@ impl Store { Ok(items.iter().map(lesson_of).collect()) } + /// The coder's one lesson for (`repo`, `area`), written or rewritten from + /// the area's recent setbacks when the evidence backs it (two independent + /// outcomes, one strong): the text follows what people did most + /// recently, `seen` counts the outcomes behind it, an admin's revert + /// stays, and the area's older generic lessons are removed. A new lesson + /// is logged as a change. Returns the lesson's id, or None when the + /// evidence does not back one. + pub async fn learn_area( + &self, + team_id: &str, + repo: &str, + area: &str, + text: &str, + evidence: &[RewardEvent], + ) -> Result, String> { + if text.trim().is_empty() || !super::lessons::backed(evidence) { + return Ok(None); + } + let id = super::lessons::area_lesson_id(area); + let sk = lesson_sk(repo, &id); + let kept = self.lessons(team_id, Some(repo)).await?; + let existing = kept.iter().find(|l| l.id == id); + let now = chrono::Utc::now().to_rfc3339(); + let seen = evidence + .iter() + .map(|e| format!("{}#{}", e.repo, e.pr)) + .collect::>() + .len() + .max(1); + let lines: Vec = evidence + .iter() + .take(12) + .map(|e| { + s(&format!( + "{} PR #{}: {}", + e.kind.map(RewardKind::label).unwrap_or(""), + e.pr, + e.detail + )) + }) + .collect(); + self.dynamo + .put_item() + .table_name(&self.table) + .item("pk", s(team_id)) + .item("sk", s(&sk)) + .item("record_type", s("reward_lesson")) + .item("id", s(&id)) + .item("repo", s(repo)) + .item("agent", s(super::event::AGENT_CODER)) + .item("area", s(area)) + .item("text", s(text)) + .item("seen", n(seen)) + .item( + "created_at", + s(existing.map(|l| l.created_at.as_str()).unwrap_or(&now)), + ) + .item("last_seen_at", s(&now)) + .item("evidence", AttributeValue::L(lines)) + .item( + "reverted", + AttributeValue::Bool(existing.is_some_and(|l| l.reverted)), + ) + .send() + .await + .map_err(|e| DisplayErrorContext(e).to_string())?; + for old in kept + .iter() + .filter(|l| l.id != id && l.agent == super::event::AGENT_CODER) + .filter(|l| super::lessons::is_generic_area_lesson(&l.text, area)) + { + let _ = self + .dynamo + .delete_item() + .table_name(&self.table) + .key("pk", s(team_id)) + .key("sk", s(&lesson_sk(repo, &old.id))) + .send() + .await; + } + if existing.is_none() { + 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(text, 300).to_string(), + reason: format!("New coder lesson for `{area}` backed by {seen} outcomes"), + evidence: evidence + .iter() + .take(12) + .map(|e| { + serde_json::json!({ + "kind": e.kind.map(RewardKind::key).unwrap_or(""), + "at": e.at, "pr": e.pr, "run_id": e.run_id, "detail": e.detail, + }) + }) + .collect(), + at: now, + ..Default::default() + }; + self.apply_change(team_id, &change).await?; + } + Ok(Some(id)) + } + /// Writes a lesson the evidence backs, or reinforces the one it repeats, /// and logs a new one as a change. Returns the lesson's id, or None when /// the evidence does not back it. diff --git a/services/common/src/stop_judge.rs b/services/common/src/stop_judge.rs index aca4c2512..500bbcf8f 100644 --- a/services/common/src/stop_judge.rs +++ b/services/common/src/stop_judge.rs @@ -283,11 +283,19 @@ pub struct Picture { /// The decision is still recorded here, without a model call. #[serde(default, skip_serializing_if = "String::is_empty")] pub cannot_proceed: String, + /// Earlier decisions of this kind on this team that people's acts + /// showed wrong (a question answered with its default, a block dismissed + /// or merged over), one line each: what the judge learns from the outcome + /// log (`decision_log::overturned_lines`). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub overturned: Vec, } /// Longest text of one field in the prompt and the stored record. const MAX_FIELD: usize = 6_000; const MAX_ITEMS: usize = 40; +/// Most overturned decisions shown to the judge. +pub const MAX_OVERTURNED: usize = 5; impl Picture { pub fn new(kind: Kind, step: &str, reason: &str) -> Self { @@ -307,6 +315,7 @@ impl Picture { self.threads.truncate(MAX_ITEMS); self.related.truncate(MAX_ITEMS); self.results.truncate(MAX_ITEMS); + self.overturned.truncate(MAX_OVERTURNED); for (i, e) in self.evidence.iter_mut().enumerate() { if e.id.trim().is_empty() { e.id = format!("E{}", i + 1); @@ -320,7 +329,8 @@ impl Picture { self } - fn kind(&self) -> Kind { + /// The decision proposed (a stop when unset). + pub fn kind(&self) -> Kind { self.kind.unwrap_or(Kind::Stop) } @@ -700,6 +710,17 @@ pub fn prompt(p: &Picture) -> String { } s.push('\n'); } + if !p.overturned.is_empty() { + s.push_str( + "## Earlier decisions like this one that people overturned\nWhat people did after \ + them shows they weren't needed. Don't repeat one unless this case differs in a way \ + you can name.\n", + ); + for o in &p.overturned { + s.push_str(&format!("- {}\n", clip(o))); + } + s.push('\n'); + } s.push_str(&format!("## Budget\n{}\n", p.budget.line())); s } @@ -972,6 +993,24 @@ mod tests { "evidence":evidence,"category":category,"location":location}) } + #[test] + fn overturned_decisions_reach_the_prompt_bounded() { + let mut p = picture(Kind::Block); + assert!(!prompt(&p).contains("people overturned")); + p.overturned = (0..9).map(|i| format!("hold number {i}")).collect(); + let p = p.with_ids(); + assert_eq!(p.overturned.len(), MAX_OVERTURNED); + let text = prompt(&p); + assert!(text.contains("## Earlier decisions like this one that people overturned")); + assert!(text.contains("- hold number 0")); + assert!(!text.contains("hold number 5")); + // Older stored pictures without the field still read. + let old: Picture = serde_json::from_value(json!({"kind":"block","step":"review", + "reason":"r","reversible":true,"ticket_title":"","ticket_body":""})) + .unwrap(); + assert!(old.overturned.is_empty()); + } + fn proceed(a: &str) -> Value { json!({"verdict":"proceed","assumption":a,"question":"","person_only":"","tried":[], "options":[],"default":"","deadline_hours":0,"blocker":"","evidence":[], diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 1d78ae1cb..07ccf44e3 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -522,6 +522,7 @@ async fn main() -> Result<(), Error> { ) // What CoderHelm learned from outcomes, and the admin controls .route("/learning", get(routes::learning::get_learning)) + .route("/learning/health", get(routes::learning::get_health)) .route("/learning/pin", post(routes::learning::pin_variant)) .route("/learning/revert", post(routes::learning::revert_change)) .route("/learning/restore", post(routes::learning::restore_change)) diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index acab1cedd..b0542a94e 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -117,6 +117,7 @@ pub const CAPABILITIES: &[Capability] = &[ "reviewer::open_prs", "review_lessons::list_lessons", "learning::get_learning", + "learning::get_health", "tests::summary", "tests::list_tests", "api::get_usage", diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 6c8863b44..681d6bbfe 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -1875,24 +1875,10 @@ async fn handle_pull_request( warn!(pr_number, error = %e, "Could not record a stopped auto-merge's PR as closed"); } // Merged with CoderHelm's request for changes on it: the flagged - // lines left as they were, or fixed first (the outcome log). + // lines left as they were, or fixed first (the outcome log), + // read from what changed since each block's head. if merged { - common::decision_log::on_merged( - &state.dynamo, - &state.config.settings_table_name, - team_id, - &format!( - "{}/{}", - repo["owner"]["login"].as_str().unwrap_or(""), - repo["name"].as_str().unwrap_or("") - ), - pr_number, - payload["pull_request"]["head"]["sha"] - .as_str() - .unwrap_or(""), - None, - ) - .await; + record_blocks_at_merge(state, payload, installation_id, team_id, pr_number).await; } } } @@ -1907,21 +1893,31 @@ async fn handle_pull_request( let pr_user = payload["pull_request"]["user"]["login"] .as_str() .unwrap_or(""); + let pr_number = payload["pull_request"]["number"].as_u64().unwrap_or(0); + let repo = &payload["repository"]; + let owner = repo["owner"]["login"].as_str().unwrap_or(""); + let name = repo["name"].as_str().unwrap_or(""); if !pr_user.contains("coderhelm") { + // A person's PR CoderHelm reviewed: what became of each review + // comment (a Nit or a Suggestion on an approval as much as a + // blocker) is the reviewer's outcome. + if pr_number != 0 { + queue_review_outcome(state, team_id, installation_id, owner, name, pr_number).await; + } return Ok(StatusCode::OK); } - let pr_number = payload["pull_request"]["number"].as_u64().unwrap_or(0); if pr_number == 0 { return Ok(StatusCode::OK); } - let repo = &payload["repository"]; - let owner = repo["owner"]["login"].as_str().unwrap_or(""); - let name = repo["name"].as_str().unwrap_or(""); - // The run that opened this PR: its own PR, or one of a multi-repo run's. let found = lookup_run_item_by_pr(state, team_id, owner, name, pr_number).await; + if found.is_none() { + // CoderHelm's PR with no run behind it (opened by hand from the + // app, or its record expired): its review comments still count. + queue_review_outcome(state, team_id, installation_id, owner, name, pr_number).await; + } // A multi-repo run's other PR: its own outcome goes on its entry in // `prs`; the run's status and outcome follow the PR its record names. let is_primary = found @@ -2172,12 +2168,139 @@ async fn queue_reward_outcome( repo_owner: owner.to_string(), repo_name: name.to_string(), pr_number, + review_only: false, }); if let Err(e) = send_to_queue(state, &state.config.ticket_queue_url, &msg).await { warn!(team_id, run_id, pr_number, status = ?e, "Could not queue the PR's reward outcome"); } } +/// Hands a closed PR CoderHelm reviewed (and didn't write, or has no run +/// for) to the worker, to record what became of each review comment. Only +/// PRs with a CoderHelm review record are queued. +async fn queue_review_outcome( + state: &AppState, + team_id: &str, + installation_id: u64, + owner: &str, + name: &str, + pr_number: u64, +) { + if !super::review_lessons::reviewed_by_coderhelm(state, team_id, owner, name, pr_number).await { + return; + } + let msg = WorkerMessage::RewardOutcome(common::rewards::RewardOutcomeMessage { + team_id: team_id.to_string(), + installation_id, + run_id: String::new(), + repo_owner: owner.to_string(), + repo_name: name.to_string(), + pr_number, + review_only: true, + }); + match send_to_queue(state, &state.config.ticket_queue_url, &msg).await { + Ok(_) => info!( + team_id, + owner, name, pr_number, "Reviewed PR closed: review outcome queued" + ), + Err(e) => { + warn!(team_id, pr_number, status = ?e, "Could not queue the reviewed PR's outcome") + } + } +} + +/// A merged PR's open blocks in the outcome log: for each block's head, the +/// files changed between it and the merged head decide whether the flagged +/// lines were fixed or merged as they were. Without the compare every block +/// with a later commit read as fixed. +async fn record_blocks_at_merge( + state: &AppState, + payload: &Value, + installation_id: u64, + team_id: &str, + pr_number: u64, +) { + let repo = &payload["repository"]; + let owner = repo["owner"]["login"].as_str().unwrap_or(""); + let name = repo["name"].as_str().unwrap_or(""); + let full = format!("{owner}/{name}"); + let merge_head = payload["pull_request"]["head"]["sha"] + .as_str() + .unwrap_or(""); + let table = &state.config.settings_table_name; + let heads = + common::decision_log::open_block_heads(&state.dynamo, table, team_id, &full, pr_number) + .await; + if heads.is_empty() { + return; + } + let mut changed: std::collections::HashMap> = Default::default(); + for h in heads.iter().filter(|h| h.as_str() != merge_head).take(3) { + if let Some(files) = + changed_files_between(state, installation_id, owner, name, h, merge_head).await + { + changed.insert(h.clone(), files); + } + } + let n = common::decision_log::on_merged_by_head( + &state.dynamo, + table, + team_id, + &full, + pr_number, + merge_head, + &changed, + ) + .await; + info!(team_id, repo = %full, pr_number, blocks = n, "Merge outcome recorded on the PR's blocks"); +} + +/// The files changed between two commits, from GitHub's compare. `None` +/// when GitHub couldn't be asked. +async fn changed_files_between( + state: &AppState, + installation_id: u64, + owner: &str, + name: &str, + base: &str, + head: &str, +) -> Option> { + if base.is_empty() || head.is_empty() { + return None; + } + let token = crate::auth::github_app::get_installation_token(state, installation_id) + .await + .ok()?; + let url = format!("https://api.github.com/repos/{owner}/{name}/compare/{base}...{head}"); + let v: Value = state + .http + .get(&url) + .header("Authorization", format!("Bearer {token}")) + .header("Accept", "application/vnd.github+json") + .header("User-Agent", "Coderhelm-bot") + .send() + .await + .ok()? + .error_for_status() + .ok()? + .json() + .await + .ok()?; + Some(compare_files(&v)) +} + +/// The file names of a GitHub compare. +pub(crate) fn compare_files(v: &Value) -> Vec { + v["files"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|f| f["filename"].as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default() +} + fn reward_store(state: &AppState) -> common::rewards::store::Store { common::rewards::store::Store::new(&state.dynamo, &state.config.settings_table_name) } @@ -2222,10 +2345,18 @@ async fn record_revert(state: &AppState, payload: &Value, team_id: &str) { ) else { return; }; - let run_id = lookup_run_by_pr(state, team_id, owner, name, target).await; - if run_id.is_empty() { + let Some(run) = lookup_run_item_by_pr(state, team_id, owner, name, target).await else { return; // not one of CoderHelm's - } + }; + let Some(run_id) = common::paged::run_id_of(&run) else { + return; + }; + let run_s = |k: &str| { + run.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; let at = pr["merged_at"] .as_str() .map(str::to_string) @@ -2244,6 +2375,17 @@ async fn record_revert(state: &AppState, payload: &Value, team_id: &str) { )) .with_source("webhook:pull_request"); ev.run_id = run_id; + // The area and the coder arm the reverted run's own outcome was scored + // under: the revert counts for the area's lesson and against that arm. + ev.area = run_s("reward_area"); + if bandit_arm_ok(&run_s("prompt_variant")) { + ev.variant = run_s("prompt_variant"); + } + ev.prompt_version = common::rewards::bandit::CODER_PROMPT_VERSION.to_string(); + let title = pr["title"].as_str().unwrap_or("").trim().to_string(); + if !title.is_empty() { + ev.notes = vec![common::truncate_str(&title, 200).to_string()]; + } if let Err(e) = reward_store(state).record(&ev).await { warn!(error = %e, "Could not record the revert"); } else { @@ -2251,6 +2393,11 @@ async fn record_revert(state: &AppState, payload: &Value, team_id: &str) { } } +/// One of the coder's prompt variants. +fn bandit_arm_ok(arm: &str) -> bool { + common::rewards::bandit::arm(common::rewards::event::AGENT_CODER, arm).is_some() +} + /// Counts people's commits on a merged pull request. `None` when GitHub /// couldn't be asked, so analytics leave the run out rather than guess. async fn count_human_commits( diff --git a/services/gateway/src/routes/learning.rs b/services/gateway/src/routes/learning.rs index 9e24fe5e7..14c230f62 100644 --- a/services/gateway/src/routes/learning.rs +++ b/services/gateway/src/routes/learning.rs @@ -7,7 +7,7 @@ use axum::extract::{Query, State}; use axum::{http::StatusCode, Extension, Json}; -use common::rewards::{bandit, event::AGENTS, store::Store, summary}; +use common::rewards::{bandit, event::AGENTS, health, store::Store, summary}; use serde::Deserialize; use serde_json::{json, Value}; use std::sync::Arc; @@ -94,6 +94,194 @@ pub async fn get_learning( }))) } +/// Pages read per record kind for the health page (keys and a few fields +/// only, never an example's embedding or a decision's picture). +const HEALTH_PAGES: usize = 10; + +type Item = std::collections::HashMap; + +fn item_s(i: &Item, k: &str) -> String { + i.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() +} + +fn item_n(i: &Item, k: &str) -> f64 { + i.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse().ok()) + .unwrap_or(0.0) +} + +/// Pure: the CoderHelm pull requests that closed, from run items +/// (`pr_url`, `merged_at` or `pr_closed_at`). +pub fn closed_prs_of(runs: &[Item]) -> Vec { + runs.iter() + .filter_map(|r| { + let (owner, name, pr) = common::pr_outcome::parse_pr_url(&item_s(r, "pr_url"))?; + let closed_at = match item_s(r, "merged_at") { + m if !m.is_empty() => m, + _ => item_s(r, "pr_closed_at"), + }; + (!closed_at.is_empty()).then(|| health::ClosedPr { + repo: format!("{owner}/{name}"), + pr, + closed_at, + }) + }) + .collect() +} + +/// The team's runs whose PR merged or closed since `since`. +async fn closed_runs(state: &AppState, team: &str, since: &str) -> Vec { + let mut out = Vec::new(); + let mut start: Option = None; + for _ in 0..HEALTH_PAGES { + let page = state + .dynamo + .query() + .table_name(&state.config.runs_table_name) + .key_condition_expression("team_id = :t") + .filter_expression("merged_at >= :s OR pr_closed_at >= :s") + .projection_expression("pr_url, merged_at, pr_closed_at") + .expression_attribute_values( + ":t", + aws_sdk_dynamodb::types::AttributeValue::S(team.into()), + ) + .expression_attribute_values( + ":s", + aws_sdk_dynamodb::types::AttributeValue::S(since.into()), + ) + .set_exclusive_start_key(start.take()) + .send() + .await; + let Ok(page) = page else { + break; + }; + out.extend(page.items().iter().cloned()); + match page.last_evaluated_key() { + Some(k) if !k.is_empty() => start = Some(k.clone()), + _ => break, + } + } + out +} + +/// GET /api/learning/health — per learning loop: its last signal, its count +/// over the last 7 days, what should have fed it, and `quiet` (the page red) +/// when a loop that should have fired stayed silent. +pub async fn get_health( + State(state): State>, + Extension(claims): Extension, +) -> Result, StatusCode> { + let team = claims.team_id.as_str(); + let st = store(&state); + let now = chrono::Utc::now(); + let since = (now - chrono::Duration::days(health::WINDOW_DAYS)).to_rfc3339(); + let fields = |prefix: &'static str, f: &'static [&'static str]| { + let st = st.clone(); + let team = team.to_string(); + async move { + st.query_projected(&team, prefix, f, HEALTH_PAGES) + .await + .unwrap_or_default() + } + }; + let events = st.events_since(team, &since).await.map_err(internal)?; + let runs = closed_runs(&state, team, &since).await; + let reviews: Vec = fields("REVIEW#", &["created_at"]) + .await + .iter() + .map(|i| item_s(i, "created_at")) + .filter(|t| t.as_str() >= since.as_str()) + .collect(); + let exemplar_last_used: Vec = + fields(common::rewards::exemplars::PREFIX, &["last_used_at"]) + .await + .iter() + .map(|i| item_s(i, "last_used_at")) + .collect(); + let arms: Vec = fields( + common::rewards::store::ARM_PREFIX, + &["agent", "pulls", "last_pull_at"], + ) + .await + .iter() + .map(|i| health::ArmPull { + agent: item_s(i, "agent"), + pulls: item_n(i, "pulls").max(0.0) as u64, + last_pull_at: item_s(i, "last_pull_at"), + }) + .collect(); + let categories_updated: Vec = + fields(common::rewards::store::CAT_PREFIX, &["updated_at"]) + .await + .iter() + .map(|i| item_s(i, "updated_at")) + .collect(); + let calibration_changes: Vec<(String, String)> = st + .changes(team) + .await + .unwrap_or_default() + .into_iter() + .filter(|c| c.kind == common::rewards::changes::KIND_CALIBRATION) + .map(|c| (c.at, c.to)) + .collect(); + let coder_lessons_seen: Vec = st + .lessons(team, None) + .await + .unwrap_or_default() + .into_iter() + .filter(|l| l.agent == common::rewards::event::AGENT_CODER) + .map(|l| l.last_seen_at) + .collect(); + let pending: Vec = fields( + common::review_lessons::PENDING_SK_PREFIX, + &["status", "last_event_at", "judged_at", "learned"], + ) + .await + .iter() + .map(|i| health::Pending { + status: item_s(i, "status"), + last_event_at_ms: item_n(i, "last_event_at") as i64, + judged_at: item_s(i, "judged_at"), + learned: item_n(i, "learned").max(0.0) as u64, + }) + .collect(); + let review_lessons_seen: Vec = + fields(common::review_lessons::LESSON_SK_PREFIX, &["last_seen_at"]) + .await + .iter() + .map(|i| item_s(i, "last_seen_at")) + .collect(); + let decisions = common::decision_log::since_light( + &state.dynamo, + &state.config.settings_table_name, + team, + &since, + HEALTH_PAGES, + ) + .await; + let closed = closed_prs_of(&runs); + Ok(Json(health::build( + &health::Inputs { + events: &events, + closed_prs: &closed, + reviews: &reviews, + exemplar_last_used: &exemplar_last_used, + arms: &arms, + categories_updated: &categories_updated, + calibration_changes: &calibration_changes, + coder_lessons_seen: &coder_lessons_seen, + pending: &pending, + review_lessons_seen: &review_lessons_seen, + decisions: &decisions, + }, + now, + ))) +} + #[derive(Deserialize)] pub struct PinBody { agent: String, @@ -255,10 +443,46 @@ mod tests { check_pin("reviewer", Some("bogus")), Err(StatusCode::BAD_REQUEST) ); - assert_eq!(check_pin("coder", None), Err(StatusCode::BAD_REQUEST)); + // The coder has variants now, so they can be pinned too. + assert_eq!(check_pin("coder", None), Ok(())); + assert_eq!(check_pin("coder", Some("read_first")), Ok(())); + assert_eq!(check_pin("planner", None), Err(StatusCode::BAD_REQUEST)); assert_eq!(check_pin("nope", Some("x")), Err(StatusCode::BAD_REQUEST)); } + #[test] + fn closed_prs_are_read_from_runs() { + use aws_sdk_dynamodb::types::AttributeValue as A; + let run = |url: &str, merged: &str, closed: &str| { + let mut i = Item::new(); + i.insert("pr_url".into(), A::S(url.into())); + if !merged.is_empty() { + i.insert("merged_at".into(), A::S(merged.into())); + } + if !closed.is_empty() { + i.insert("pr_closed_at".into(), A::S(closed.into())); + } + i + }; + let got = closed_prs_of(&[ + run( + "https://github.com/acme/web/pull/3", + "2026-11-05T00:00:00Z", + "", + ), + run( + "https://github.com/acme/web/pull/4", + "", + "2026-11-04T00:00:00Z", + ), + run("https://github.com/acme/web/pull/5", "", ""), + run("not a url", "2026-11-05T00:00:00Z", ""), + ]); + assert_eq!(got.len(), 2); + assert_eq!((got[0].repo.as_str(), got[0].pr), ("acme/web", 3)); + assert_eq!(got[1].closed_at, "2026-11-04T00:00:00Z"); + } + #[test] fn change_ids_are_ulids() { assert!(valid_change_id(&ulid::Ulid::new().to_string())); diff --git a/services/gateway/src/routes/review_lessons.rs b/services/gateway/src/routes/review_lessons.rs index 492456873..a1684b61d 100644 --- a/services/gateway/src/routes/review_lessons.rs +++ b/services/gateway/src/routes/review_lessons.rs @@ -171,6 +171,19 @@ pub fn qualifies(verdicts_newest_first: &[String], needs_changes_requested: bool .is_some_and(|v| v == "REQUEST_CHANGES") } +/// Pure: why a trigger is not judged, in the log's words. A person +/// approving or merging over an approval with notes (a Nit, a Suggestion) +/// pushes back on nothing; what became of each note is recorded when the PR +/// closes (`rewards::score_outcome`, review only), so it still reaches +/// calibration. +pub fn not_judged_reason(verdicts_newest_first: &[String]) -> &'static str { + if verdicts_newest_first.is_empty() { + "CoderHelm hasn't reviewed this PR" + } else { + "CoderHelm's verdict doesn't request changes: its notes are scored when the PR closes" + } +} + /// CoderHelm reviewed this PR (it has a review record of it). pub async fn reviewed_by_coderhelm( state: &AppState, @@ -258,11 +271,23 @@ pub async fn on_webhook( return; } } - if !qualifies( - &verdicts(state, team_id, &t).await, - t.needs_changes_requested, - ) { - info!(owner = %t.owner, name = %t.name, pr = t.pr_number, trigger = t.trigger, reason = "CoderHelm hasn't reviewed this PR, or its verdict doesn't request changes", "Pushback on a review not judged"); + let verdicts = verdicts(state, team_id, &t).await; + // A person approving while CoderHelm's request for changes stands + // overrode it: the stop judge's outcome log hears it, whatever the + // judgment below decides. (A block already cleared by a later approval + // was not overridden; the merge records it as fixed.) + if t.trigger == rl::TRIGGER_APPROVED_OVER_BLOCK && qualifies(&verdicts, true) { + common::decision_log::on_approved_over_block( + &state.dynamo, + &state.config.settings_table_name, + team_id, + &format!("{}/{}", t.owner, t.name), + t.pr_number, + ) + .await; + } + if !qualifies(&verdicts, t.needs_changes_requested) { + info!(owner = %t.owner, name = %t.name, pr = t.pr_number, trigger = t.trigger, reason = not_judged_reason(&verdicts), "Pushback on a review not judged"); return; } let event_at = match rl::mark_event( @@ -608,6 +633,16 @@ mod tests { assert_eq!(detect("pull_request", &p), None); } + /// Production logged 90 "not judged" in a week, mostly approvals over an + /// approval with notes: the log now says where those notes go. + #[test] + fn approvals_over_notes_say_the_notes_are_scored_at_close() { + let v = |xs: &[&str]| xs.iter().map(|s| s.to_string()).collect::>(); + assert!(!qualifies(&v(&["APPROVE"]), true)); + assert!(not_judged_reason(&v(&["APPROVE"])).contains("scored when the PR closes")); + assert_eq!(not_judged_reason(&[]), "CoderHelm hasn't reviewed this PR"); + } + #[test] fn only_prs_coderhelm_reviewed_qualify() { let v = |xs: &[&str]| xs.iter().map(|s| s.to_string()).collect::>(); diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index f9e770c24..f454da1d1 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -3952,26 +3952,30 @@ impl GitHubClient { .unwrap_or_default()) } - /// Lines added plus removed between two commits (the compare's files). - pub async fn compare_line_changes( + /// One commit's own size and files: lines added plus removed (its + /// `stats`), and the paths it touched (first page, up to 300). + pub async fn commit_stats( &self, owner: &str, repo: &str, - base: &str, - head: &str, - ) -> Result> { - let url = format!("{API_BASE}/repos/{owner}/{repo}/compare/{base}...{head}"); - let data = self.get(&url).await?; - Ok(data["files"] + sha: &str, + ) -> Result<(u64, Vec), Box> { + let v = self + .get(&format!("{API_BASE}/repos/{owner}/{repo}/commits/{sha}")) + .await?; + let total = v["stats"]["total"].as_u64().unwrap_or_else(|| { + v["stats"]["additions"].as_u64().unwrap_or(0) + + v["stats"]["deletions"].as_u64().unwrap_or(0) + }); + let files = v["files"] .as_array() - .map(|arr| { - arr.iter() - .map(|f| { - f["additions"].as_u64().unwrap_or(0) + f["deletions"].as_u64().unwrap_or(0) - }) - .sum() + .map(|a| { + a.iter() + .filter_map(|f| f["filename"].as_str().map(String::from)) + .collect() }) - .unwrap_or(0)) + .unwrap_or_default(); + Ok((total, files)) } /// Find the most recent closed-but-unmerged PR for a head branch. diff --git a/services/worker/src/models.rs b/services/worker/src/models.rs index 7d8e6fb2e..291a71edf 100644 --- a/services/worker/src/models.rs +++ b/services/worker/src/models.rs @@ -320,6 +320,7 @@ mod tests { ticket_history_note: None, plan_cache_key: None, team_instructions: String::new(), + coder_learning: String::new(), person_direction: None, answers: Vec::new(), new_run_id: None, diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index ddf8821b3..4b5da8079 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -1638,6 +1638,7 @@ async fn start_fix_ticket( ticket_history_note: None, plan_cache_key: None, team_instructions: String::new(), + coder_learning: String::new(), person_direction: None, answers: Vec::new(), new_run_id: None, @@ -1892,6 +1893,7 @@ pub async fn act(state: &WorkerState, a: TestAction) -> Result<(), Err> { ticket_history_note: None, plan_cache_key: None, team_instructions: String::new(), + coder_learning: String::new(), person_direction: None, answers: Vec::new(), new_run_id: None, diff --git a/services/worker/src/passes/e2e_attribution.rs b/services/worker/src/passes/e2e_attribution.rs index 78245b47d..681ef0e4e 100644 --- a/services/worker/src/passes/e2e_attribution.rs +++ b/services/worker/src/passes/e2e_attribution.rs @@ -468,6 +468,7 @@ async fn start_fix( ticket_history_note: None, plan_cache_key: None, team_instructions: String::new(), + coder_learning: String::new(), person_direction: None, answers: Vec::new(), new_run_id: None, diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 5a5a6fc8e..d07599618 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -277,6 +277,7 @@ pub async fn run( ticket_history_note: None, plan_cache_key: None, team_instructions: String::new(), + coder_learning: String::new(), person_direction: None, answers: Vec::new(), new_run_id: None, @@ -2980,6 +2981,7 @@ async fn handle_wrong_repo( ticket_history_note: None, plan_cache_key: None, team_instructions: String::new(), + coder_learning: String::new(), person_direction: None, answers: Vec::new(), new_run_id: None, diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 476b1ef70..4b7b58e64 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -181,10 +181,13 @@ pub async fn run( "" }; // The team's instructions are never trimmed: they are its working rules. + // What outcomes taught the coder here (lessons naming what people + // changed, and the prompt variant its bandit picked) sits with the + // repository's own instructions, capped by `rewards::implement_block`. let system = coder_system( &msg.repo_owner, &msg.repo_name, - &format!("{rules_block}{instructions_block}"), + &format!("{rules_block}{instructions_block}{}", msg.coder_learning), &msg.team_instructions, tests_block, ); diff --git a/services/worker/src/passes/lessons.rs b/services/worker/src/passes/lessons.rs index b8b9379ce..fb7fefe06 100644 --- a/services/worker/src/passes/lessons.rs +++ b/services/worker/src/passes/lessons.rs @@ -475,7 +475,19 @@ pub async fn run( return Ok(()); } if msg.trigger == TRIGGER_CLOSE_REASON { - record_answer(state, &msg, &ctx).await; + // The PR was scored when it closed; the reason joins that + // outcome and the coder's lesson for the area. + if let Some(answer) = record_answer(state, &msg, &ctx).await { + super::rewards::note_close_reason( + state, + &msg.team_id, + &item, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + msg.pr_number, + &answer, + ) + .await; + } } let mut usage = TokenUsage::default(); let judged = judge(state, &provider, &ctx, &mut usage).await; @@ -581,15 +593,16 @@ async fn ask_close_reason(state: &WorkerState, github: &GitHubClient, msg: &Less /// The answer to the one question: kept on the run (the planner reads it /// with the ticket's history) and the signal moved to "closed with reason". -async fn record_answer(state: &WorkerState, msg: &LessonMessage, ctx: &LessonContext) { - let Some((_, answer)) = ctx +async fn record_answer( + state: &WorkerState, + msg: &LessonMessage, + ctx: &LessonContext, +) -> Option { + let (_, answer) = ctx .comments .iter() .rev() - .find(|(_, t)| !t.trim().is_empty()) - else { - return; - }; + .find(|(_, t)| !t.trim().is_empty())?; let _ = state .dynamo .update_item() @@ -605,6 +618,7 @@ async fn record_answer(state: &WorkerState, msg: &LessonMessage, ctx: &LessonCon .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) .send() .await; + Some(answer.clone()) } async fn mark(state: &WorkerState, msg: &LessonMessage, field: &str, value: Option<&str>) { diff --git a/services/worker/src/passes/log_autofix.rs b/services/worker/src/passes/log_autofix.rs index 3709c81d1..b164b581e 100644 --- a/services/worker/src/passes/log_autofix.rs +++ b/services/worker/src/passes/log_autofix.rs @@ -122,6 +122,7 @@ impl StartEnv for WorkerEnv<'_> { ticket_history_note: None, plan_cache_key: None, team_instructions: String::new(), + coder_learning: String::new(), person_direction: None, answers: Vec::new(), new_run_id: None, diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 0ab8e6e38..b214ba917 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -2139,18 +2139,18 @@ async fn run_passes( }; // What outcomes taught the coder in this repository: changes merged as // written and ones closed, rewritten or reverted, and evidence-backed - // lessons. - let memory_context = format!( - "{memory_context}{}", - rewards::coder_learning( - state, - &msg.team_id, - &format!("{}/{}", msg.repo_owner, msg.repo_name), - run_id, - &format!("{} {}", msg.title, common::truncate_str(&msg.body, 1500)), - ) - .await - ); + // lessons, for the planner; the lessons and the prompt variant the + // coder's bandit picked, for the coder itself. + let coder_learned = rewards::coder_learning( + state, + &msg.team_id, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + run_id, + &format!("{} {}", msg.title, common::truncate_str(&msg.body, 1500)), + ) + .await; + msg.coder_learning = coder_learned.implement.clone(); + let memory_context = format!("{memory_context}{}", coder_learned.context); // --- A continuation of this same run (Lambda time limit, step budget, // a transient model error) picks up this run's own triage and plan: the @@ -2659,6 +2659,15 @@ async fn run_passes( // go into the plan made there. repo_instructions = load_repo_instructions(&github, &msg.repo_owner, &msg.repo_name).await; + msg.coder_learning = rewards::coder_learning( + state, + &msg.team_id, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + run_id, + &format!("{} {}", msg.title, common::truncate_str(&msg.body, 1500)), + ) + .await + .implement; msg.team_instructions = load_team_instructions(state, &msg.team_id, &msg.repo_owner, &msg.repo_name) .await; diff --git a/services/worker/src/passes/pr_outcomes.rs b/services/worker/src/passes/pr_outcomes.rs index ec1bb37a2..e6d6e002d 100644 --- a/services/worker/src/passes/pr_outcomes.rs +++ b/services/worker/src/passes/pr_outcomes.rs @@ -15,6 +15,7 @@ use crate::passes::{attr_n, attr_s}; use crate::WorkerState; use aws_sdk_dynamodb::types::AttributeValue; use common::pr_outcome::{human_commit_count, outcome, parse_pr_url, Outcome}; +use common::rewards::RewardOutcomeMessage; use std::collections::HashMap; use tracing::{info, warn}; @@ -98,7 +99,10 @@ pub async fn backfill(state: &WorkerState) -> Result<(), Box filled += 1, + Ok(_) => { + filled += 1; + score_missed(state, &p, &owner, &repo, number).await; + } Err(e) => warn!(run_id = %p.run_id, error = %e, "Backfill: could not save the merge"), } } @@ -222,7 +226,10 @@ async fn reconcile_finished( req = req.expression_attribute_values(*placeholder, attr_s(value)); } match req.send().await { - Ok(_) => recorded += 1, + Ok(_) => { + recorded += 1; + score_missed(state, &p, &owner, &repo, number).await; + } Err(e) => { warn!(run_id = %p.run_id, error = %e, "Reconcile: could not save the PR outcome") } @@ -302,6 +309,33 @@ async fn find_runs( Ok(out) } +/// The reward message for a run whose close the webhook never delivered. +fn missed_outcome(p: &Pending, owner: &str, repo: &str, number: u64) -> RewardOutcomeMessage { + RewardOutcomeMessage { + team_id: p.team_id.clone(), + installation_id: p.installation_id, + run_id: p.run_id.clone(), + repo_owner: owner.to_string(), + repo_name: repo.to_string(), + pr_number: number, + review_only: false, + } +} + +/// A close the webhook missed is learned from like any other: the run's +/// outcome was only written on the run before, so the coder's and the +/// reviewer's rewards never saw it. Scoring is idempotent per signal, so a +/// webhook that arrives late counts nothing twice. +async fn score_missed(state: &WorkerState, p: &Pending, owner: &str, repo: &str, number: u64) { + if let Err(e) = + super::rewards::score_outcome(state, missed_outcome(p, owner, repo, number)).await + { + warn!(run_id = %p.run_id, error = %e, "Reconcile: could not score the PR outcome"); + } else { + info!(run_id = %p.run_id, pr = number, "Reconcile: scored a PR outcome the webhook missed"); + } +} + /// Stops retrying a run GitHub can't answer for. async fn mark_unknown(state: &WorkerState, p: &Pending, why: &str) { let _ = state @@ -367,6 +401,30 @@ mod tests { } } + /// "Reconciled PR outcomes on finished runs" wrote the outcome on the + /// run and nothing else: a close the webhook missed never reached the + /// rewards. The message it now scores names the run and the PR. + #[test] + fn a_missed_close_is_scored_for_its_run() { + let p = Pending { + team_id: "TEAM#a".into(), + run_id: "R1".into(), + pr_url: "https://github.com/acme/web/pull/7".into(), + installation_id: 42, + }; + let m = missed_outcome(&p, "acme", "web", 7); + assert_eq!( + (m.team_id.as_str(), m.run_id.as_str(), m.pr_number), + ("TEAM#a", "R1", 7) + ); + assert_eq!( + (m.repo_owner.as_str(), m.repo_name.as_str()), + ("acme", "web") + ); + assert_eq!(m.installation_id, 42); + assert!(!m.review_only); + } + #[test] fn finished_statuses_cover_completed_cancelled_closed_retried() { assert_eq!( diff --git a/services/worker/src/passes/replay/README.md b/services/worker/src/passes/replay/README.md index 1bdd63761..b525a04e0 100644 --- a/services/worker/src/passes/replay/README.md +++ b/services/worker/src/passes/replay/README.md @@ -23,8 +23,12 @@ only (no company, customer, repository, ticket or person names). - `case` picks the decision path (see `mod.rs`): `stop_judge`, `ticket_route`, `registration`, `run_loop`, `review_settled`, - `blocker_comment`, `deploy_count`. Each reads its own `input` and - `expect`; the existing cases show both. + `blocker_comment`, `deploy_count`, and the learning loops: + `learning_threads` (review threads at close, what calibration hears), + `learning_edits` (what counts as people rewriting a change), + `learning_coder_lesson` (what a coder lesson says) and + `decision_overturned` (the outcome log in the stop judge's prompt). Each + reads its own `input` and `expect`; the existing cases show both. - `replies`: where the stop judge is called, the model's recorded answers, one list per trial, in call order (a rule-breaking first answer followed by the re-asked one is two entries). Three trials (`k` = 3), and every trial diff --git a/services/worker/src/passes/replay/cases/10_merge_over_notes_reaches_calibration.json b/services/worker/src/passes/replay/cases/10_merge_over_notes_reaches_calibration.json new file mode 100644 index 000000000..8d7b90fc5 --- /dev/null +++ b/services/worker/src/passes/replay/cases/10_merge_over_notes_reaches_calibration.json @@ -0,0 +1,25 @@ +{ + "name": "A person merging over an approval with notes still teaches calibration, both ways", + "about": "Since the reviewer approves with notes instead of requesting changes, 'approved over block' and 'merged over block' found no block and were logged as not judged (90 in a week), and comments left open were scored only on CoderHelm's own PRs, so a category the team ignored never reached downgrade or suppress. At close every thread now records: untouched at merge is left open, lines changed or CoderHelm resolving it is acted on, a person resolving it unchanged is dismissed. Words under it stay the judge's; an FYI asks for nothing.", + "case": "learning_threads", + "input": { + "merged": true, + "threads": [ + { "id": "T1", "path": "src/a.ts", "body": "💬 **Nit: Rename the flag** (style, not verified)" }, + { "id": "T2", "path": "src/a.ts", "body": "💬 **Suggestion: Extract the retry** (maintainability, not verified)", "outdated": true }, + { "id": "T3", "path": "src/b.ts", "body": "💬 **Nit: Reorder imports** (style, not verified)", "resolved": true, "resolved_by_person": true }, + { "id": "T4", "path": "src/b.ts", "body": "💬 **Suggestion: Log the id** (logging, not verified)", "person_replied": true }, + { "id": "T5", "path": "src/c.ts", "body": "💬 **FYI: The cache is per region** (other, not verified)" }, + { "id": "T6", "path": "src/c.ts", "body": "🔴 **Blocking (correctness): Stale cursor** (correctness)", "resolved": true } + ] + }, + "expect": { + "kinds": { + "T1": "finding_ignored", + "T2": "finding_accepted", + "T3": "finding_dismissed", + "T6": "finding_accepted" + }, + "none": ["T4", "T5"] + } +} diff --git a/services/worker/src/passes/replay/cases/11_update_branch_is_not_a_rewrite.json b/services/worker/src/passes/replay/cases/11_update_branch_is_not_a_rewrite.json new file mode 100644 index 000000000..1672cd7fe --- /dev/null +++ b/services/worker/src/passes/replay/cases/11_update_branch_is_not_a_rewrite.json @@ -0,0 +1,15 @@ +{ + "name": "Pressing Update branch is not people rewriting CoderHelm's change", + "about": "Coder lessons said changes in one area were 'rewritten by people before merging, 100% of the diff changed' on PR after PR. The share compared CoderHelm's last commit with the merged head, so the base branch a person merged in with Update branch counted as their edits, and that merge commit counted as a person's commit. Only people's own non-merge commits count now, each by its own size.", + "case": "learning_edits", + "input": { + "pr_lines": 200, + "commits": [ + { "sha": "c1", "author": { "login": "coderhelm[bot]", "type": "Bot" }, "parents": [{ "sha": "p0" }] }, + { "sha": "m1", "author": { "login": "a-person", "type": "User" }, "parents": [{ "sha": "c1" }, { "sha": "b9" }], "commit": { "message": "Merge branch 'main' into fix" } }, + { "sha": "h1", "author": { "login": "a-person", "type": "User" }, "parents": [{ "sha": "m1" }], "commit": { "message": "Use the shared date helper" } } + ], + "lines": { "c1": 200, "m1": 4800, "h1": 12 } + }, + "expect": { "human_commits": 1, "share_at_most": 0.1, "setback": false } +} diff --git a/services/worker/src/passes/replay/cases/12_coder_lesson_names_what_people_changed.json b/services/worker/src/passes/replay/cases/12_coder_lesson_names_what_people_changed.json new file mode 100644 index 000000000..2872cb8e6 --- /dev/null +++ b/services/worker/src/passes/replay/cases/12_coder_lesson_names_what_people_changed.json @@ -0,0 +1,22 @@ +{ + "name": "A coder lesson names what people changed and said, not 'read the surrounding code'", + "about": "The two coder lessons in production said only that changes in an area 'were closed without merging, needed CI fix rounds, rewritten by people' and to 'read the surrounding code and keep the change small': nothing the coder could act on, and the second was a near copy of the first with more PR numbers. A lesson now names the files people changed with their commit subjects, why a PR was closed, and what to do next, one lesson per area.", + "case": "learning_coder_lesson", + "input": { + "area": "apps/site", + "events": [ + { "kind": "pr_merged_edited", "pr": 21, "at": "2026-11-02T10:00:00Z", "value": 0.45, "files": ["apps/site/src/fetch.ts", "apps/site/src/hooks/useSlots.ts"], "notes": ["Use the shared fetch hook instead of a new client"] }, + { "kind": "pr_closed_unmerged", "pr": 24, "at": "2026-11-04T10:00:00Z", "notes": ["The banner text lives in the CMS, not in code"] }, + { "kind": "ci_fix_rounds", "pr": 24, "at": "2026-11-04T10:00:00Z", "value": 3 } + ] + }, + "expect": { + "contains": [ + "In `apps/site`", + "PR #24 was closed without merging (\"The banner text lives in the CMS, not in code\")", + "people changed `apps/site/src/fetch.ts`, `apps/site/src/hooks/useSlots.ts` before merging (\"Use the shared fetch hook instead of a new client\")", + "read `apps/site/src/fetch.ts`, `apps/site/src/hooks/useSlots.ts` first" + ], + "not_contains": ["Read the surrounding code", "100%"] + } +} diff --git a/services/worker/src/passes/replay/cases/13_stop_judge_remembers_overturned_blocks.json b/services/worker/src/passes/replay/cases/13_stop_judge_remembers_overturned_blocks.json new file mode 100644 index 000000000..0dec058b5 --- /dev/null +++ b/services/worker/src/passes/replay/cases/13_stop_judge_remembers_overturned_blocks.json @@ -0,0 +1,23 @@ +{ + "name": "The stop judge is shown the blocks people overrode, so the outcome log feeds the next decision", + "about": "What people did after an ask, stop or block was recorded only for analytics and the weekly email: nothing the judge saw changed. The merge also passed no compare, so every block with a later commit read as fixed. The judge's picture now carries the team's recent decisions of the same kind that people's acts showed wrong (same step first), and a merge compares each block's own head.", + "case": "decision_overturned", + "input": { + "kind": "block", + "step": "review", + "records": [ + { "kind": "block", "step": "review", "verdict": "hold", "category": "other", "detail": "Log level should be warn", "outcome": "overrode", "created_at": "2026-11-01T00:00:00Z" }, + { "kind": "block", "step": "review", "verdict": "hold", "category": "correctness", "detail": "Null cursor on the last page", "outcome": "fixed", "created_at": "2026-11-02T00:00:00Z" }, + { "kind": "block", "step": "own_review", "verdict": "hold", "category": "other", "detail": "Rename the helper", "outcome": "merged_flagged_unchanged", "created_at": "2026-11-03T00:00:00Z" }, + { "kind": "ask", "step": "plan", "verdict": "ask", "category": "business_rule", "detail": "Monthly or weekly totals?", "outcome": "answered_default", "created_at": "2026-11-03T00:00:00Z" } + ] + }, + "expect": { + "lines": 2, + "prompt_contains": [ + "## Earlier decisions like this one that people overturned", + "hold by the review step (other): \"Log level should be warn\"; people went ahead over it", + "people merged with the flagged lines unchanged" + ] + } +} diff --git a/services/worker/src/passes/replay/mod.rs b/services/worker/src/passes/replay/mod.rs index fc5bda8df..506694b54 100644 --- a/services/worker/src/passes/replay/mod.rs +++ b/services/worker/src/passes/replay/mod.rs @@ -16,6 +16,14 @@ //! - `blocker_comment`: a person's comment naming a blocker on an unchanged //! commit, through `review_policy` and `review_verdict::decide`. //! - `deploy_count`: workflow runs through `common::deploy_stats`. +//! - `learning_threads`: review threads at a PR's close through +//! `rewards::thread_events` (what calibration hears). +//! - `learning_edits`: a merged PR's commits through `common::pr_outcome` +//! (what counts as people rewriting CoderHelm's work). +//! - `learning_coder_lesson`: an area's setbacks through +//! `lessons::coder_lesson_text` (what the coder is told). +//! - `decision_overturned`: the outcome log through +//! `decision_log::overturned_lines` into the stop judge's prompt. //! //! Where the stop judge is involved the case carries the model's recorded //! answers for `k` trials (pass^k: every trial must pass, k = 3), so CI is @@ -528,8 +536,209 @@ fn run_deploy_count(c: &Case, _: &Model) -> Result<(), String> { Ok(()) } +/// What became of CoderHelm's review threads when a PR closed, through +/// `rewards::thread_events`: `expect.kinds` maps thread ids to the event +/// kind each must record; `expect.none` lists threads that record nothing. +fn run_learning_threads(c: &Case, _: &Model) -> Result<(), String> { + use crate::clients::github::{BotReviewThread, ThreadReply}; + let i = &c.input; + let threads: Vec = i["threads"] + .as_array() + .into_iter() + .flatten() + .map(|t| BotReviewThread { + root_id: 0, + id: s(t, "id").to_string(), + path: s(t, "path").to_string(), + line: 1, + outdated: t["outdated"].as_bool().unwrap_or(false), + body: s(t, "body").to_string(), + replies: if t["person_replied"].as_bool().unwrap_or(false) { + vec![ThreadReply { + author: "a-person".into(), + by_bot: false, + body: "a reply".into(), + }] + } else { + vec![] + }, + resolved: t["resolved"].as_bool().unwrap_or(false), + resolved_by_person: t["resolved_by_person"].as_bool().unwrap_or(false), + }) + .collect(); + let events = crate::passes::rewards::thread_events( + "TEAM#replay", + "example/site", + 1, + &threads, + i["merged"].as_bool().unwrap_or(false), + "2026-11-05T00:00:00Z", + &None, + ); + let got: std::collections::BTreeMap = events + .iter() + .map(|e| { + ( + e.dedup.split('#').nth(1).unwrap_or("").to_string(), + e.kind.map(|k| k.key()).unwrap_or("").to_string(), + ) + }) + .collect(); + for (id, want) in c.expect["kinds"].as_object().into_iter().flatten() { + let want = want.as_str().unwrap_or(""); + match got.get(id) { + Some(k) if k == want => {} + other => return Err(format!("thread {id}: got {other:?}, want {want}")), + } + } + for id in strings(&c.expect["none"]) { + if let Some(k) = got.get(&id) { + return Err(format!("thread {id} recorded {k}, want nothing")); + } + } + Ok(()) +} + +/// What people changed on a merged PR, through `common::pr_outcome` and +/// `PeopleEdits::share`: `input.commits` as GitHub lists them, `input.lines` +/// each commit's own size by sha, `input.pr_lines` the PR's diff. +fn run_learning_edits(c: &Case, _: &Model) -> Result<(), String> { + let i = &c.input; + let commits: Vec = i["commits"].as_array().cloned().unwrap_or_default(); + let mine = common::pr_outcome::human_edit_commits(&commits); + let lines: u64 = mine + .iter() + .map(|c| { + i["lines"][c["sha"].as_str().unwrap_or("")] + .as_u64() + .unwrap_or(0) + }) + .sum(); + let ed = common::rewards::mapping::PeopleEdits { + commits: mine.len() as u64, + lines, + ..Default::default() + }; + let share = ed.share(i["pr_lines"].as_u64().unwrap_or(0)); + let e = &c.expect; + if let Some(n) = e["human_commits"].as_u64() { + if ed.commits != n { + return Err(format!("{} human commits, want {n}", ed.commits)); + } + } + if let Some(max) = e["share_at_most"].as_f64() { + if share > max { + return Err(format!("edit share {share:.2}, want at most {max}")); + } + } + let setback = share >= common::rewards::lessons::SETBACK_EDIT_SHARE; + if let Some(want) = e["setback"].as_bool() { + if setback != want { + return Err(format!("setback {setback}, want {want}")); + } + } + Ok(()) +} + +/// The coder lesson an area's setbacks write, through +/// `lessons::coder_lesson_text`: it must contain `expect.contains` and none +/// of `expect.not_contains`. +fn run_learning_coder_lesson(c: &Case, _: &Model) -> Result<(), String> { + use common::rewards::event::{RewardEvent, RewardKind, AGENT_CODER}; + let i = &c.input; + let events: Vec = i["events"] + .as_array() + .into_iter() + .flatten() + .filter_map(|e| { + let kind = RewardKind::from_key(s(e, "kind"))?; + let pr = e["pr"].as_u64().unwrap_or(0); + let mut ev = RewardEvent::new("T", kind, AGENT_CODER, s(e, "at"), &format!("{pr}")) + .with_repo("example/site", pr) + .with_value(e["value"].as_f64().unwrap_or(0.0)); + ev.area = s(i, "area").to_string(); + ev.files = strings(&e["files"]); + ev.notes = strings(&e["notes"]); + Some(ev) + }) + .collect(); + let setbacks: Vec = events + .into_iter() + .filter(common::rewards::lessons::is_coder_setback) + .collect(); + if !common::rewards::lessons::backed(&setbacks) { + return Err("the setbacks don't back a lesson".into()); + } + let text = + common::rewards::lessons::coder_lesson_text(s(i, "area"), &setbacks).ok_or("no lesson")?; + for want in strings(&c.expect["contains"]) { + if !text.contains(&want) { + return Err(format!("the lesson misses `{want}`: {text}")); + } + } + for bad in strings(&c.expect["not_contains"]) { + if text.contains(&bad) { + return Err(format!("the lesson says `{bad}`: {text}")); + } + } + Ok(()) +} + +/// The stop judge's memory of the outcome log, through +/// `decision_log::overturned_lines` and the judge's prompt. +fn run_decision_overturned(c: &Case, _: &Model) -> Result<(), String> { + use common::decision_log::{Outcome, Record}; + let i = &c.input; + let records: Vec = i["records"] + .as_array() + .into_iter() + .flatten() + .map(|r| Record { + kind: s(r, "kind").into(), + step: s(r, "step").into(), + verdict: s(r, "verdict").into(), + category: s(r, "category").into(), + detail: s(r, "detail").into(), + created_at: s(r, "created_at").into(), + outcome: Outcome::parse(s(r, "outcome")), + ..Default::default() + }) + .collect(); + let lines = common::decision_log::overturned_lines(&records, s(i, "kind"), s(i, "step")); + let e = &c.expect; + if let Some(n) = e["lines"].as_u64() { + if lines.len() as u64 != n { + return Err(format!( + "{} overturned lines, want {n}: {lines:?}", + lines.len() + )); + } + } + let mut p = Picture::new( + if s(i, "kind") == "block" { + judge::Kind::Block + } else { + judge::Kind::Ask + }, + s(i, "step"), + "replay", + ); + p.overturned = lines; + let prompt = judge::prompt(&p.with_ids()); + for want in strings(&e["prompt_contains"]) { + if !prompt.contains(&want) { + return Err(format!("the judge's prompt misses `{want}`")); + } + } + Ok(()) +} + fn run_one(c: &Case, model: &Model) -> Result<(), String> { match c.case.as_str() { + "learning_threads" => run_learning_threads(c, model), + "learning_edits" => run_learning_edits(c, model), + "learning_coder_lesson" => run_learning_coder_lesson(c, model), + "decision_overturned" => run_decision_overturned(c, model), "stop_judge" => run_stop_judge(c, model), "ticket_route" => run_ticket_route(c, model), "registration" => run_registration(c, model), @@ -627,6 +836,10 @@ fn the_seed_incidents_are_all_here() { "review_settled", "blocker_comment", "deploy_count", + "learning_threads", + "learning_edits", + "learning_coder_lesson", + "decision_overturned", ] { assert!(kinds.iter().any(|x| x == k), "no `{k}` case"); } diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index e3b2f0f69..c2a05e2c4 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -2996,6 +2996,7 @@ async fn fix_context( // message. team_instructions: super::load_team_instructions(state, &msg.team_id, t.owner, t.repo) .await, + coder_learning: String::new(), person_direction: None, answers: Vec::new(), new_run_id: None, diff --git a/services/worker/src/passes/rewards.rs b/services/worker/src/passes/rewards.rs index 78d2a192d..0b8592504 100644 --- a/services/worker/src/passes/rewards.rs +++ b/services/worker/src/passes/rewards.rs @@ -63,22 +63,6 @@ async fn embed(state: &WorkerState, team_id: &str, text: &str) -> Option Option { - commits - .iter() - .rev() - .find(|c| { - let login = c["author"]["login"] - .as_str() - .or(c["committer"]["login"].as_str()) - .unwrap_or(""); - login.contains("coderhelm") - }) - .and_then(|c| c["sha"].as_str().map(str::to_string)) -} - /// The area most of the changed paths are in. pub fn main_area(paths: &[String]) -> String { let mut counts: BTreeMap = BTreeMap::new(); @@ -105,15 +89,74 @@ pub fn ci_of(run: &Item) -> CiSummary { } } -/// A coder outcome bad enough to look for a pattern behind it. -pub fn is_coder_setback(e: &RewardEvent) -> bool { - match e.kind { - Some(RewardKind::PrClosedUnmerged) - | Some(RewardKind::PrReverted) - | Some(RewardKind::IncidentLinked) => true, - Some(RewardKind::CiFixRounds) => e.value >= 2.0, - Some(RewardKind::PrMergedEdited) => e.value >= 0.5, - _ => false, +pub use common::rewards::lessons::is_coder_setback; + +/// Most of people's commits read for what they changed. +const MAX_EDIT_COMMITS: usize = 20; + +/// What people changed on top of CoderHelm's work: their own non-merge +/// commits, each measured by its own stats. `None` when GitHub couldn't say +/// for any of them (then no merged-after-edits event is guessed). +async fn people_edits( + github: &GitHubClient, + owner: &str, + name: &str, + commits: &[serde_json::Value], +) -> Option { + let mine = common::pr_outcome::human_edit_commits(commits); + if mine.is_empty() { + return Some(mapping::PeopleEdits::default()); + } + let mut lines = 0u64; + let mut read = 0usize; + let mut touched: BTreeMap = BTreeMap::new(); + let mut subjects = Vec::new(); + for c in mine.iter().take(MAX_EDIT_COMMITS) { + let Some(sha) = c["sha"].as_str() else { + continue; + }; + if let Ok((n, files)) = github.commit_stats(owner, name, sha).await { + read += 1; + lines += n; + for f in files { + *touched.entry(f).or_default() += 1; + } + } + let subject = common::pr_outcome::commit_subject(c); + if !subject.is_empty() { + subjects.push(subject); + } + } + if read == 0 { + return None; + } + let mut files: Vec<(String, usize)> = touched.into_iter().collect(); + files.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + Some(mapping::PeopleEdits { + commits: mine.len() as u64, + lines, + files: files.into_iter().map(|(f, _)| f).collect(), + subjects, + }) +} + +/// Why people closed a run's PR, when they said: the reason picked when the +/// run was closed in CoderHelm, or their answer to CoderHelm's one question. +pub fn close_reason_of(run: &Item) -> String { + let picked = gs(run, "close_reason"); + if !picked.trim().is_empty() { + return picked; + } + gs(run, "close_reason_answer") +} + +/// The coder arm a run used, when it is one of the coder's arms. +pub fn coder_arm_of(run: &Item) -> String { + let a = gs(run, "prompt_variant"); + if bandit::arm(rev::AGENT_CODER, &a).is_some() { + a + } else { + String::new() } } @@ -187,9 +230,6 @@ async fn add_example(state: &WorkerState, team_id: &str, mut ex: Exemplar, score pub async fn score_outcome(state: &WorkerState, msg: RewardOutcomeMessage) -> Result<(), String> { let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); - let run = load_run(state, &msg.team_id, &msg.run_id) - .await - .unwrap_or_default(); let github = GitHubClient::new( &state.secrets.github_app_id, &state.secrets.github_private_key, @@ -201,84 +241,104 @@ pub async fn score_outcome(state: &WorkerState, msg: RewardOutcomeMessage) -> Re .get_pull_request(&msg.repo_owner, &msg.repo_name, msg.pr_number) .await .map_err(|e| e.to_string())?; - let commits = github - .list_pr_commits(&msg.repo_owner, &msg.repo_name, msg.pr_number) - .await - .ok(); - let human = commits - .as_deref() - .map(common::pr_outcome::human_commit_count); - let head = pr["head"]["sha"].as_str().unwrap_or("").to_string(); - let base = pr["base"]["sha"].as_str().unwrap_or("").to_string(); - // How much of the diff people changed after CoderHelm's last commit. - let mut edit_share = None; - if let (Some(n), Some(c)) = (human, commits.as_deref()) { - if n > 0 { - if let Some(last) = last_coderhelm_sha(c) { - if let Ok(changed) = github - .compare_line_changes(&msg.repo_owner, &msg.repo_name, &last, &head) - .await - { - let total = pr["additions"].as_u64().unwrap_or(0) - + pr["deletions"].as_u64().unwrap_or(0); - edit_share = Some(mapping::edit_fraction(changed, total)); - } + let closed_at = pr["closed_at"].as_str().unwrap_or("").to_string(); + let merged = pr["merged_at"].as_str().is_some_and(|m| !m.is_empty()); + let coder = !msg.review_only && !msg.run_id.is_empty(); + let mut events = Vec::new(); + let mut area = String::new(); + if coder { + let run = load_run(state, &msg.team_id, &msg.run_id) + .await + .unwrap_or_default(); + let commits = github + .list_pr_commits(&msg.repo_owner, &msg.repo_name, msg.pr_number) + .await + .ok(); + let human = commits + .as_deref() + .map(common::pr_outcome::human_commit_count); + // What people changed after CoderHelm, from their own commits (a + // merge of the base branch brings other work and is not an edit). + let edits = match (human, commits.as_deref()) { + (Some(n), Some(c)) if n > 0 => { + people_edits(&github, &msg.repo_owner, &msg.repo_name, c).await } - } + _ => None, + }; + let head = pr["head"]["sha"].as_str().unwrap_or("").to_string(); + let base = pr["base"]["sha"].as_str().unwrap_or("").to_string(); + let paths = if !base.is_empty() && !head.is_empty() { + github + .compare_changed_files(&msg.repo_owner, &msg.repo_name, &base, &head) + .await + .unwrap_or_default() + } else { + vec![] + }; + area = main_area(&paths); + let ctx = RunContext { + team_id: msg.team_id.clone(), + run_id: msg.run_id.clone(), + repo: repo.clone(), + pr: msg.pr_number, + model: gs(&run, "model"), + prompt_version: bandit::CODER_PROMPT_VERSION.to_string(), + // The arm the run used: its outcome is what the coder's bandit + // learns from. + variant: coder_arm_of(&run), + skills: vec![], + plugin: gs(&run, "plugin"), + area: area.clone(), + close_reason: close_reason_of(&run), + }; + events.extend(mapping::pr_closed_events( + &ctx, + &pr, + human, + edits.as_ref(), + ci_of(&run), + )); } - let paths = if !base.is_empty() && !head.is_empty() { - github - .compare_changed_files(&msg.repo_owner, &msg.repo_name, &base, &head) - .await - .unwrap_or_default() - } else { - vec![] - }; - let ctx = RunContext { - team_id: msg.team_id.clone(), - run_id: msg.run_id.clone(), - repo: repo.clone(), - pr: msg.pr_number, - model: gs(&run, "model"), - prompt_version: bandit::CODER_PROMPT_VERSION.to_string(), - variant: String::new(), - skills: vec![], - plugin: gs(&run, "plugin"), - area: main_area(&paths), - }; - let mut events = mapping::pr_closed_events(&ctx, &pr, human, edit_share, ci_of(&run)); - // Review comments CoderHelm left that nobody acted on or answered. - let closed_at = pr["closed_at"].as_str().unwrap_or("").to_string(); + // What became of each of CoderHelm's review comments, notes (Nit, + // Suggestion) as much as blockers, on its own PRs and on people's. if !closed_at.is_empty() { if let Ok(threads) = github .list_bot_review_threads(&msg.repo_owner, &msg.repo_name, msg.pr_number) .await { let review = latest_review(state, &msg.team_id, &repo, msg.pr_number).await; - for t in threads.iter().filter(|t| ignored_at_close(t)) { - let mut e = mapping::finding_event( - &msg.team_id, - RewardKind::FindingIgnored, - &repo, - msg.pr_number, - &t.id, - &t.path, - &t.body, - &closed_at, - ); - credit(&mut e, &review); - events.push(e); - } + events.extend(thread_events( + &msg.team_id, + &repo, + msg.pr_number, + &threads, + merged, + &closed_at, + &review, + )); } } let st = store(state); let fresh = st.record_all(&events).await; - info!(team_id = %msg.team_id, pr = msg.pr_number, events = events.len(), fresh, "Pull request outcome scored"); - if fresh == 0 { - return Ok(()); // already scored (a redelivered webhook) + let findings = events + .iter() + .filter(|e| e.kind.is_some_and(RewardKind::is_finding)) + .count(); + info!( + team_id = %msg.team_id, + pr = msg.pr_number, + review_only = msg.review_only, + events = events.len(), + findings, + fresh, + "Pull request outcome scored" + ); + if fresh == 0 || !coder { + return Ok(()); // already scored (a redelivered webhook), or no coder part } + note_reward_area(state, &msg.team_id, &msg.run_id, &area).await; // Keep the change as an example for the coder. let weights = st.weights(&msg.team_id).await; @@ -305,7 +365,7 @@ pub async fn score_outcome(state: &WorkerState, msg: RewardOutcomeMessage) -> Re id: exemplars::id_for(&repo, msg.pr_number, "fix"), repo: repo.clone(), kind: exemplars::KIND_FIX.into(), - area: ctx.area.clone(), + area: area.clone(), pr: msg.pr_number, run_id: msg.run_id.clone(), reason: exemplars::fix_reason(&outcome), @@ -320,20 +380,69 @@ pub async fn score_outcome(state: &WorkerState, msg: RewardOutcomeMessage) -> Re // A setback: look for a pattern in this area worth a lesson. if events.iter().any(is_coder_setback) { - learn_from_setbacks(state, &msg.team_id, &repo, &ctx.area).await; + learn_from_setbacks(state, &msg.team_id, &repo, &area).await; } Ok(()) } -/// A thread still open when the PR closed: not resolved, not answered by a -/// person, and its code not replaced. -pub fn ignored_at_close(t: &BotReviewThread) -> bool { - !t.resolved && !t.outdated && !t.replies.iter().any(|r| !r.by_bot) +/// The calibration events of CoderHelm's review threads on a closed PR (see +/// `mapping::thread_outcome`), each credited to the review that left it. +pub fn thread_events( + team_id: &str, + repo: &str, + pr: u64, + threads: &[BotReviewThread], + merged: bool, + closed_at: &str, + review: &Option<(String, String, String, String)>, +) -> Vec { + let mut out = Vec::new(); + for t in threads { + let Some(kind) = mapping::thread_outcome(&thread_at_close(t), merged) else { + continue; + }; + let mut e = + mapping::finding_event(team_id, kind, repo, pr, &t.id, &t.path, &t.body, closed_at) + .with_detail(&mapping::thread_outcome_detail(kind, &t.body, &t.path)); + credit(&mut e, review); + out.push(e); + } + out +} + +/// A thread as `mapping::thread_outcome` reads it. +pub fn thread_at_close(t: &BotReviewThread) -> mapping::ThreadAtClose { + mapping::ThreadAtClose { + resolved: t.resolved, + resolved_by_person: t.resolved_by_person, + outdated: t.outdated, + person_replied: t.replies.iter().any(|r| !r.by_bot), + body: t.body.clone(), + } +} + +/// Keeps the area a run's PR touched on the run (`reward_area`), so a later +/// revert of it is credited to the same area and its lesson. +async fn note_reward_area(state: &WorkerState, team_id: &str, run_id: &str, area: &str) { + if area.is_empty() { + return; + } + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", crate::passes::attr_s(team_id)) + .key("run_id", crate::passes::attr_s(run_id)) + .condition_expression("attribute_exists(run_id)") + .update_expression("SET reward_area = :a") + .expression_attribute_values(":a", crate::passes::attr_s(area)) + .send() + .await; } -/// Writes (or reinforces) a coder lesson when this area's recent setbacks -/// back one. -async fn learn_from_setbacks(state: &WorkerState, team_id: &str, repo: &str, area: &str) { +/// Writes (or rewrites) the coder's lesson for this area when its recent +/// setbacks back one: what people changed, why they closed or reverted it. +pub async fn learn_from_setbacks(state: &WorkerState, team_id: &str, repo: &str, area: &str) { let st = store(state); let since = (chrono::Utc::now() - chrono::Duration::days(90)).to_rfc3339(); let Ok(events) = st.events_since(team_id, &since).await else { @@ -347,10 +456,7 @@ async fn learn_from_setbacks(state: &WorkerState, team_id: &str, repo: &str, are let Some(text) = lessons::coder_lesson_text(area, &setbacks) else { return; }; - match st - .learn(team_id, repo, rev::AGENT_CODER, &text, &setbacks) - .await - { + match st.learn_area(team_id, repo, area, &text, &setbacks).await { Ok(Some(id)) => { info!(team_id, repo, area, lesson = %id, "Coder lesson written or reinforced") } @@ -359,6 +465,45 @@ async fn learn_from_setbacks(state: &WorkerState, team_id: &str, repo: &str, are } } +/// A person said why they closed CoderHelm's PR after it was scored (the +/// answer to its one question): the reason joins the closed event's notes +/// and the area's lesson is written again with it. +pub async fn note_close_reason( + state: &WorkerState, + team_id: &str, + run: &Item, + repo: &str, + pr: u64, + reason: &str, +) { + let closed_at = gs(run, "pr_closed_at"); + if closed_at.is_empty() || reason.trim().is_empty() || pr == 0 { + return; + } + let sk = rev::event_sk(&closed_at, &format!("closed#{repo}#{pr}")); + let r = state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", crate::passes::attr_s(team_id)) + .key("sk", crate::passes::attr_s(&sk)) + .condition_expression("attribute_exists(sk)") + .update_expression("SET notes = :n") + .expression_attribute_values( + ":n", + aws_sdk_dynamodb::types::AttributeValue::L(vec![crate::passes::attr_s( + common::truncate_str(reason.trim(), 240), + )]), + ) + .send() + .await; + if r.is_err() { + return; // never scored, or scored under another time: nothing to add to + } + let area = gs(run, "reward_area"); + learn_from_setbacks(state, team_id, repo, &area).await; +} + // ── Review comments acted on or dismissed ───────────────────────────── /// Records the earlier review comments this head fixed as acted on, and @@ -574,16 +719,73 @@ pub async fn note_review_variant( } } -/// The coder's learning for `repo`: examples of merged and rejected changes -/// and evidence-backed lessons. Empty when there are none. +/// What the coder is given for one run. +#[derive(Debug, Default, Clone)] +pub struct CoderLearning { + /// For the planner (through the triage summary): examples of merged and + /// rejected changes, and the lessons. + pub context: String, + /// For the coder's own system prompt: the lessons and the variant's + /// addendum, capped at [`MAX_CODER_PROMPT_CHARS`]. + pub implement: String, +} + +/// Longest learning block in the coder's system prompt. +pub const MAX_CODER_PROMPT_CHARS: usize = 3_000; + +/// The coder's block: the variant's addendum, then the lessons, capped. +pub fn implement_block(addendum: &str, lesson_block: &str) -> String { + let text = format!("{addendum}{lesson_block}"); + common::truncate_str(&text, MAX_CODER_PROMPT_CHARS).to_string() +} + +/// The coder's learning for `repo`: examples of merged and rejected changes, +/// evidence-backed lessons, and the prompt variant the coder's bandit picks. +/// A run keeps the arm it started with (continuations and retries read it +/// back from the run) and its pull is counted once. pub async fn coder_learning( state: &WorkerState, team_id: &str, repo: &str, run_id: &str, query: &str, -) -> String { +) -> CoderLearning { let st = store(state); + let run = load_run(state, team_id, run_id).await.unwrap_or_default(); + let arm = match coder_arm_of(&run) { + a if !a.is_empty() => a, + _ => { + let weights = st.weights(team_id).await; + let stats = st + .arm_stats(team_id, rev::AGENT_CODER, &weights) + .await + .unwrap_or_default(); + let pinned = st.pin(team_id, rev::AGENT_CODER).await; + let choice = bandit::choose( + bandit::arms_for(rev::AGENT_CODER), + &stats, + pinned.as_deref(), + bandit::MIN_PULLS, + bandit::EXPLORATION_CAP, + ); + // Only the first writer counts the pull: a continuation racing + // its own start doesn't count twice. + if note_coder_arm(state, team_id, run_id, &choice.arm).await { + st.count_pull(team_id, rev::AGENT_CODER, &choice.arm).await; + info!(team_id, repo, run_id, arm = %choice.arm, why = ?choice.why, "Coder variant chosen"); + choice.arm + } else { + let again = load_run(state, team_id, run_id).await.unwrap_or_default(); + match coder_arm_of(&again) { + a if !a.is_empty() => a, + _ => choice.arm, + } + } + } + }; + let addendum = bandit::arm(rev::AGENT_CODER, &arm) + .map(|a| a.addendum) + .unwrap_or(""); let by = exemplars::Use { at: chrono::Utc::now().to_rfc3339(), agent: rev::AGENT_CODER.into(), @@ -592,12 +794,42 @@ pub async fn coder_learning( }; let examples = examples_block(state, team_id, repo, exemplars::KIND_FIX, &[], query, &by).await; let kept = st.lessons(team_id, Some(repo)).await.unwrap_or_default(); - let lesson_block = lessons::prompt_block(&lessons::recall( - &kept, - rev::AGENT_CODER, - chrono::Utc::now(), - )); - format!("{examples}{lesson_block}") + let recalled = lessons::recall(&kept, rev::AGENT_CODER, chrono::Utc::now()); + let lesson_block = lessons::prompt_block(&recalled); + info!( + team_id, + repo, + run_id, + arm = %arm, + lessons = recalled.len(), + examples = !examples.is_empty(), + "Coder learning loaded" + ); + CoderLearning { + implement: implement_block(addendum, &lesson_block), + context: format!("{examples}{lesson_block}"), + } +} + +/// Notes the coder arm on the run, only when none is noted yet. True when +/// this call wrote it. +async fn note_coder_arm(state: &WorkerState, team_id: &str, run_id: &str, arm: &str) -> bool { + if run_id.is_empty() || arm.is_empty() { + return false; + } + state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", crate::passes::attr_s(team_id)) + .key("run_id", crate::passes::attr_s(run_id)) + .condition_expression("attribute_exists(run_id) AND attribute_not_exists(prompt_variant)") + .update_expression("SET prompt_variant = :v, prompt_version = :p") + .expression_attribute_values(":v", crate::passes::attr_s(arm)) + .expression_attribute_values(":p", crate::passes::attr_s(bandit::CODER_PROMPT_VERSION)) + .send() + .await + .is_ok() } async fn examples_block( @@ -736,14 +968,7 @@ mod tests { } #[test] - fn last_coderhelm_commit_and_main_area() { - let commits = vec![ - json!({"sha":"a1","author":{"login":"coderhelm[bot]"}}), - json!({"sha":"b2","author":{"login":"coderhelm[bot]"}}), - json!({"sha":"c3","author":{"login":"pat"}}), - ]; - assert_eq!(last_coderhelm_sha(&commits).as_deref(), Some("b2")); - assert_eq!(last_coderhelm_sha(&[]), None); + fn main_area_is_where_most_paths_are() { let paths: Vec = ["src/api/a.ts", "src/api/b.ts", "docs/x.md", "README.md"] .iter() .map(|s| s.to_string()) @@ -765,28 +990,131 @@ mod tests { assert!(!ci_of(&Item::new()).known); } + /// Since the reviewer approves with notes, a person merging over a Nit + /// is no pushback to judge; what became of each note is still a signal, + /// and it reaches calibration both ways, credited to the review's arm. #[test] - fn only_untouched_threads_count_as_ignored() { - let t = |resolved, outdated, replies: Vec| BotReviewThread { - root_id: 0, - id: "T".into(), - path: "a".into(), - line: 1, - outdated, - body: "x".into(), - replies, - resolved, - resolved_by_person: false, + fn notes_at_close_become_calibration_events() { + let t = |id: &str, resolved, by_person, outdated, replies: Vec, body: &str| { + BotReviewThread { + root_id: 0, + id: id.into(), + path: "src/a.rs".into(), + line: 1, + outdated, + body: body.into(), + replies, + resolved, + resolved_by_person: by_person, + } }; - assert!(ignored_at_close(&t(false, false, vec![]))); - assert!(!ignored_at_close(&t(true, false, vec![]))); - assert!(!ignored_at_close(&t(false, true, vec![]))); let person = ThreadReply { author: "pat".into(), by_bot: false, body: "no".into(), }; - assert!(!ignored_at_close(&t(false, false, vec![person]))); + let nit = "💬 **Nit: Rename** (style, not verified)"; + let threads = vec![ + t("T1", false, false, false, vec![], nit), + t("T2", false, false, true, vec![], nit), + t("T3", true, true, false, vec![], nit), + t("T4", false, false, false, vec![person], nit), + t( + "T5", + false, + false, + false, + vec![], + "💬 **FYI: Cache** (other)", + ), + ]; + let review = Some(( + "REVIEW#acme/web#000003#t".to_string(), + "focused".to_string(), + "m".to_string(), + "v".to_string(), + )); + let ev = thread_events( + "TEAM#a", + "acme/web", + 3, + &threads, + true, + "2026-11-05T00:00:00Z", + &review, + ); + let kinds: Vec<(String, RewardKind)> = ev + .iter() + .map(|e| (e.dedup.clone(), e.kind.unwrap())) + .collect(); + assert_eq!( + kinds, + vec![ + ("finding_ignored#T1".to_string(), RewardKind::FindingIgnored), + ( + "finding_accepted#T2".to_string(), + RewardKind::FindingAccepted + ), + ( + "finding_dismissed#T3".to_string(), + RewardKind::FindingDismissed + ), + ] + ); + assert!(ev + .iter() + .all(|e| e.category == "style" && e.variant == "focused")); + assert!(ev[0] + .detail + .contains("still open and untouched when the PR merged")); + // Closed without merging: untouched notes say nothing. + let ev = thread_events( + "TEAM#a", + "acme/web", + 3, + &threads, + false, + "2026-11-05T00:00:00Z", + &None, + ); + assert_eq!(ev.len(), 2); + } + + /// The coder's lessons and its arm's addendum reach its own system + /// prompt (not only the planner's triage summary), capped. + #[test] + fn the_coders_block_carries_the_arm_and_lessons_capped() { + let addendum = bandit::arm(rev::AGENT_CODER, "read_first") + .unwrap() + .addendum; + let lesson = lessons::prompt_block(&[lessons::Lesson { + text: "In `apps/site`: on PR #4 people changed `apps/site/a.ts` before merging.".into(), + seen: 2, + ..Default::default() + }]); + let b = implement_block(addendum, &lesson); + assert!(b.contains("## Before you write")); + assert!(b.contains("people changed `apps/site/a.ts`")); + let long = "x".repeat(10_000); + assert!(implement_block(addendum, &long).len() <= MAX_CODER_PROMPT_CHARS); + assert_eq!(implement_block("", ""), ""); + } + + #[test] + fn a_runs_arm_and_close_reason_are_read_back() { + use aws_sdk_dynamodb::types::AttributeValue as A; + let run = Item::from([ + ("prompt_variant".to_string(), A::S("read_first".into())), + ("close_reason_answer".to_string(), A::S("Not needed".into())), + ]); + assert_eq!(coder_arm_of(&run), "read_first"); + assert_eq!(close_reason_of(&run), "Not needed"); + let other = Item::from([("prompt_variant".to_string(), A::S("focused".into()))]); + assert_eq!( + coder_arm_of(&other), + "", + "a reviewer arm is not the coder's" + ); } #[test] diff --git a/services/worker/src/passes/stop_judge.rs b/services/worker/src/passes/stop_judge.rs index 84265aa4d..f4bad5e6f 100644 --- a/services/worker/src/passes/stop_judge.rs +++ b/services/worker/src/passes/stop_judge.rs @@ -77,6 +77,10 @@ pub async fn decide( model: provider.judgment_model_id().to_string(), usage: Mutex::new(TokenUsage::default()), }; + let mut picture = picture; + if picture.overturned.is_empty() { + picture.overturned = overturned(state, team_id, &picture).await; + } let picture = picture.with_ids(); let judged = judge::judge(&model, picture.clone()).await; if let Ok(u) = model.usage.lock() { @@ -86,6 +90,31 @@ pub async fn decide( judged } +/// Days of the outcome log the judge remembers. +const OVERTURNED_DAYS: i64 = 60; +/// Pages of the light decision query read for it. +const OVERTURNED_PAGES: usize = 3; + +/// The team's recent decisions of this kind that people's acts showed +/// wrong, for the judge's picture: the outcome log closes the loop instead +/// of only feeding analytics. Best effort: empty on any failure. +async fn overturned(state: &WorkerState, team_id: &str, picture: &Picture) -> Vec { + let since = (chrono::Utc::now() - chrono::Duration::days(OVERTURNED_DAYS)).to_rfc3339(); + let records = decision_log::since_light( + &state.dynamo, + &state.config.settings_table_name, + team_id, + &since, + OVERTURNED_PAGES, + ) + .await; + let lines = decision_log::overturned_lines(&records, picture.kind().as_str(), &picture.step); + if !lines.is_empty() { + info!(team_id, step = %picture.step, overturned = lines.len(), "Stop judge given the decisions people overturned"); + } + lines +} + /// Records a judged decision (best effort). async fn keep( state: &WorkerState,