diff --git a/services/common/src/rewards/example_text.rs b/services/common/src/rewards/example_text.rs new file mode 100644 index 000000000..58ea4fdba --- /dev/null +++ b/services/common/src/rewards/example_text.rs @@ -0,0 +1,334 @@ +//! How an example reads: a one-line title, a short cleaned summary and the +//! reason it is an example. +//! +//! Examples are made from pull request bodies and review comments, which +//! carry markup meant for GitHub: HTML comments (``), +//! callout markers (`> [!WARNING]`), section labels (`**Summary**`) and +//! boilerplate lines (`Source ticket: X`, `Closes #4`). [`summary`] keeps the +//! markdown a reader wants (lists, code, emphasis) and drops the rest; +//! [`plain`] drops all markup, for titles, search and prompts. Examples kept +//! before titles were stored are read through [`legacy_split`], so old and +//! new ones look the same. + +use regex::Regex; +use std::sync::LazyLock; + +/// Longest title, in characters. +pub const MAX_TITLE: usize = 120; +/// Longest summary kept with an example, in characters. +pub const MAX_SUMMARY: usize = 600; + +static UNVERIFIED_BLOCK: LazyLock = LazyLock::new(|| { + Regex::new(r"(?s).*?(|\z)") + .unwrap() +}); +static COMMENT: LazyLock = LazyLock::new(|| Regex::new(r"(?s)|\z)").unwrap()); +static TAG: LazyLock = + LazyLock::new(|| Regex::new(r"]*)?/?>").unwrap()); +static CALLOUT: LazyLock = LazyLock::new(|| { + Regex::new(r"(?i)^\s*>\s*\[!(note|tip|important|warning|caution)\]\s*$").unwrap() +}); +static BOILERPLATE: LazyLock = LazyLock::new(|| { + Regex::new( + r"(?i)^\s*(source ticket\s*:|(closes|fixes|resolves|refs?|related to)\s*:?\s*([\w.-]+/[\w.-]+)?#\d+\s*$|(closes|fixes|resolves)\s*:?\s*[A-Z][A-Z0-9]+-\d+\s*$)", + ) + .unwrap() +}); +/// A section label on its own (`**Summary**`, `## Changes`, `Risk:`). +static LABEL_LINE: LazyLock = LazyLock::new(|| { + Regex::new(r"(?i)^\s*(#{1,6}\s*)?(\*\*|__)?(summary|problem|changes?|risk|verification|why|what|context|notes?|details?|open items|testing|tests?)(\*\*|__)?\s*:?\s*$").unwrap() +}); +/// A section label leading its text (`**Summary** x`, `Problem: x`). +static LABEL_LEAD: LazyLock = LazyLock::new(|| { + Regex::new(r"(?i)^\s*(\*\*|__)(summary|problem|changes?|risk|verification|why|what|context|notes?)(:)?(\*\*|__)\s*:?\s*").unwrap() +}); +static HEADING: LazyLock = LazyLock::new(|| Regex::new(r"^\s*#{1,6}\s+").unwrap()); +static QUOTE: LazyLock = LazyLock::new(|| Regex::new(r"^\s*>\s?").unwrap()); +static BULLET: LazyLock = + LazyLock::new(|| Regex::new(r"^\s*([-*+]|\d+[.)])\s+(\[[ xX]\]\s+)?").unwrap()); +static IMAGE: LazyLock = LazyLock::new(|| Regex::new(r"!\[([^\]]*)\]\([^)]*\)").unwrap()); +static LINK: LazyLock = LazyLock::new(|| Regex::new(r"\[([^\]]+)\]\([^)]*\)").unwrap()); +static STRONG: LazyLock = + LazyLock::new(|| Regex::new(r"(\*\*|__)([^*_]+?)(\*\*|__)").unwrap()); +static EM: LazyLock = + LazyLock::new(|| Regex::new(r"(^|[\s(])\*([^*\s][^*]*?)\*([\s).,;:!?]|$)").unwrap()); +static CODE: LazyLock = LazyLock::new(|| Regex::new(r"`+([^`]*)`+").unwrap()); +static SPACES: LazyLock = LazyLock::new(|| Regex::new(r"[ \t]+").unwrap()); +static BLANKS: LazyLock = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap()); +/// A conventional-commit prefix (`fix`, `feat(api)!`), never a title on its own. +static COMMIT_TYPE: LazyLock = + LazyLock::new(|| Regex::new(r"^[a-z]+(\([^)]*\))?!?$").unwrap()); + +/// Markdown with GitHub-only markup and boilerplate removed. Lists, code, +/// emphasis and headings stay; HTML comments and tags, callout markers and +/// `Source ticket:`/`Closes #N` lines go. +pub fn clean(md: &str) -> String { + let md = md.replace("\r\n", "\n"); + let md = UNVERIFIED_BLOCK.replace_all(&md, ""); + let md = COMMENT.replace_all(&md, ""); + let md = TAG.replace_all(&md, ""); + let mut out: Vec = vec![]; + for line in md.lines() { + if CALLOUT.is_match(line) || BOILERPLATE.is_match(line) { + continue; + } + let line = line.trim_end(); + // A quote line left empty by a removed marker. + if QUOTE.is_match(line) && QUOTE.replace(line, "").trim().is_empty() { + continue; + } + out.push(line.to_string()); + } + BLANKS + .replace_all(out.join("\n").trim(), "\n\n") + .into_owned() +} + +/// One line of text with every mark removed. +pub fn plain(md: &str) -> String { + let mut lines: Vec = vec![]; + let mut fenced = false; + for line in clean(md).lines() { + if line.trim_start().starts_with("```") || line.trim_start().starts_with("~~~") { + fenced = !fenced; + continue; + } + if fenced || LABEL_LINE.is_match(line) { + continue; + } + let l = HEADING.replace(line, ""); + let l = QUOTE.replace(&l, ""); + let l = BULLET.replace(&l, ""); + let l = LABEL_LEAD.replace(&l, ""); + let l = IMAGE.replace_all(&l, "$1"); + let l = LINK.replace_all(&l, "$1"); + let l = STRONG.replace_all(&l, "$2"); + let l = EM.replace_all(&l, "$1$2$3"); + let l = CODE.replace_all(&l, "$1"); + let l = l.trim(); + if !l.is_empty() { + lines.push(l.to_string()); + } + } + SPACES.replace_all(&lines.join(" "), " ").trim().to_string() +} + +/// `s` cut to at most `max` characters at a word, with "…" when cut. +pub fn cut_words(s: &str, max: usize) -> String { + let s = s.trim(); + if s.chars().count() <= max { + return s.to_string(); + } + let hard: String = s.chars().take(max.saturating_sub(1)).collect(); + let at = hard + .rfind(char::is_whitespace) + .filter(|&i| i >= hard.len() / 2) + .unwrap_or(hard.len()); + format!( + "{}…", + hard[..at].trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c)) + ) +} + +/// The first sentence worth reading, as a title. +pub fn first_sentence(md: &str) -> String { + let p = plain(md); + let end = p + .char_indices() + .find(|&(i, c)| { + matches!(c, '.' | '?' | '!') && p[i + c.len_utf8()..].starts_with(char::is_whitespace) + }) + .map(|(i, c)| i + c.len_utf8()) + .unwrap_or(p.len()); + cut_words(p[..end].trim_end_matches('.'), MAX_TITLE) +} + +/// A title from a pull request title or a review comment's heading; when +/// that is empty, the body's first sentence. +pub fn title(raw_title: &str, body: &str) -> String { + let t = plain(raw_title); + if t.is_empty() { + first_sentence(body) + } else { + cut_words(&t, MAX_TITLE) + } +} + +/// The cleaned markdown, cut at a word to [`MAX_SUMMARY`] characters, with +/// an open code fence closed. +pub fn summary(body: &str) -> String { + summary_of(&clean(body), false) +} + +fn summary_of(cleaned: &str, was_cut: bool) -> String { + let mut s = cleaned.to_string(); + // Leading section labels add nothing in a summary of a few lines. + while let Some(first) = s.lines().next() { + if LABEL_LINE.is_match(first) { + s = s[first.len()..].trim_start().to_string(); + } else { + break; + } + } + let s = LABEL_LEAD.replace(&s, "").into_owned(); + let mut out = if was_cut { + // The stored text ended mid-word: drop the broken word. + let at = s.rfind(char::is_whitespace).unwrap_or(s.len()); + format!("{}…", s[..at].trim_end()) + } else { + cut_words(&s, MAX_SUMMARY) + }; + if out + .lines() + .filter(|l| l.trim_start().starts_with("```")) + .count() + % 2 + == 1 + { + out.push_str("\n```"); + } + out +} + +/// Splits an example's stored text, kept as `title: body` before titles +/// were stored, into a title and a cleaned summary. `body_cap` is the length +/// the body was cut to when stored (and [`super::exemplars::MAX_TEXT`] the +/// whole text's), so a body cut mid-word ends in "…". +pub fn legacy_split(text: &str, body_cap: usize) -> (String, String) { + let near = |len: usize, cap: usize| len + 8 >= cap && len <= cap; + let whole_cut = near(text.len(), super::exemplars::MAX_TEXT); + let mut from = 0; + let mut split = None; + while let Some(i) = text[from..].find(": ") { + let at = from + i; + let head = text[..at].trim(); + if COMMIT_TYPE.is_match(head) || (head.contains('(') && !head.contains(')')) { + from = at + 2; + continue; + } + if head.chars().count() <= 160 && !head.contains('\n') { + split = Some(at); + } + break; + } + let (t, s) = match split { + Some(at) => { + let body = &text[at + 2..]; + ( + title(&text[..at], body), + summary_of(&clean(body), whole_cut || near(body.len(), body_cap)), + ) + } + None => ( + first_sentence(text), + summary_of(&clean(text), whole_cut || near(text.len(), body_cap)), + ), + }; + // A summary that only repeats the title adds nothing. + let s = if plain(&s).trim_end_matches('.') == t { + String::new() + } else { + s + }; + (t, s) +} + +#[cfg(test)] +mod tests { + use super::*; + + const PR_BODY: &str = "Source ticket: OPS-1\n\n\n> [!WARNING]\n> **Not yet verified**\n> - **Waiting on CI:** lint \n\n\n**Summary** Retry the import once with the same key.\n\n## Changes\n- Add `retry_once` to the client\n- Keep the key\n\nCloses #4\n
Logsok
"; + + #[test] + fn clean_drops_comments_callouts_and_boilerplate() { + let c = clean(PR_BODY); + assert!(!c.contains("**Summary** Retry once.\n\n- Keep the key", + ); + assert_eq!(e.title, "fix(api): retry payments"); + assert_eq!(e.summary, "Retry once.\n\n- Keep the key"); + assert_eq!(e.text, "fix(api): retry payments: Retry once. Keep the key"); + assert_eq!(e.display().title, e.title); + } + + #[test] + fn old_examples_read_the_same_way() { + let e = Exemplar { + kind: KIND_FINDING.into(), + text: "Missing test: The **retry** path has no test.".into(), + reward: -2.0, + ..Default::default() + }; + let d = e.display(); + assert_eq!(d.title, "Missing test"); + assert_eq!(d.summary, "The **retry** path has no test."); + assert_eq!(d.reason, "The team dismissed it or left it open"); + let b = prompt_block(KIND_FINDING, &[], &[e]); + assert!( + b.contains("- Missing test: The retry path has no test."), + "{b}" + ); + } + + #[test] + fn reasons_say_what_happened() { + assert_eq!( + fix_reason(&[ + (RewardKind::PrMergedUnchanged, 1.0), + (RewardKind::CiFirstTry, 1.0) + ]), + "CI passed on the first try, merged without changes" + ); + assert_eq!( + fix_reason(&[ + (RewardKind::CiFixRounds, 3.0), + (RewardKind::PrMergedEdited, 0.4) + ]), + "CI needed 3 fix rounds, merged after people changed 40% of it" + ); + assert_eq!( + fix_reason(&[(RewardKind::PrClosedUnmerged, 1.0)]), + "Closed without merging" + ); + assert_eq!(fix_reason(&[]), ""); + assert!(finding_reason(RewardKind::FindingIgnored).starts_with("Still open")); + } + + #[test] + fn keeps_the_latest_uses() { + let mut e = Exemplar::default(); + for i in 0..7 { + e.used_by = e.uses_after(Use { + at: format!("t{i}"), + agent: "coder".into(), + run_id: format!("r{i}"), + pr: 0, + }); + } + assert_eq!(e.used_by.len(), MAX_USES_KEPT); + assert_eq!(e.used_by[0].at, "t2"); + assert_eq!(e.used_by.last().unwrap().at, "t6"); + } + #[test] fn embeddings_pack_and_compare() { let v = vec![0.5f32, -1.25, 3.0]; diff --git a/services/common/src/rewards/mod.rs b/services/common/src/rewards/mod.rs index 6d2be1d39..bc19bab3d 100644 --- a/services/common/src/rewards/mod.rs +++ b/services/common/src/rewards/mod.rs @@ -21,6 +21,7 @@ pub mod bandit; pub mod calibration; pub mod changes; pub mod event; +pub mod example_text; pub mod exemplars; pub mod lessons; pub mod mapping; diff --git a/services/common/src/rewards/store.rs b/services/common/src/rewards/store.rs index 499a33d3e..463e017fd 100644 --- a/services/common/src/rewards/store.rs +++ b/services/common/src/rewards/store.rs @@ -752,6 +752,27 @@ impl Store { #area = if_not_exists(#area, :area), #t = if_not_exists(#t, :text), \ #pr = if_not_exists(#pr, :pr), #ca = if_not_exists(#ca, :at)" .to_string(); + // How it reads on the page: written once; the reason follows the + // latest outcome. + for (alias, name, value, always) in [ + ("#ti", "title", &ex.title, false), + ("#su", "summary", &ex.summary, false), + ("#ri", "run_id", &ex.run_id, false), + ("#re", "reason", &ex.reason, true), + ] { + if value.is_empty() { + continue; + } + let v = format!(":{}", &alias[1..]); + if always { + expr.push_str(&format!(", {alias} = {v}")); + } else { + expr.push_str(&format!(", {alias} = if_not_exists({alias}, {v})")); + } + req = req + .expression_attribute_names(alias, name) + .expression_attribute_values(v, s(value)); + } for (alias, name) in [ ("#reward", "reward"), ("#events", "events"), @@ -803,8 +824,17 @@ impl Store { Ok(items.iter().map(exemplar_of).collect()) } - pub async fn count_exemplar_use(&self, team_id: &str, ex: &[Exemplar]) { + /// Counts one use of each example and keeps when and by what: the + /// latest [`exemplars::MAX_USES_KEPT`] uses, from the copies read for + /// this prompt (two prompts at once may each keep only their own). + pub async fn count_exemplar_use(&self, team_id: &str, ex: &[Exemplar], by: &exemplars::Use) { for e in ex { + let kept: Vec = e + .uses_after(by.clone()) + .iter() + .filter_map(|u| serde_json::to_string(u).ok()) + .map(AttributeValue::S) + .collect(); let _ = self .dynamo .update_item() @@ -812,9 +842,13 @@ impl Store { .key("pk", s(team_id)) .key("sk", s(&exemplars::sk(&e.repo, &e.id))) .condition_expression("attribute_exists(sk)") - .update_expression("ADD #u :one") + .update_expression("ADD #u :one SET #lu = :at, #ub = :ub") .expression_attribute_names("#u", "uses") + .expression_attribute_names("#lu", "last_used_at") + .expression_attribute_names("#ub", "used_by") .expression_attribute_values(":one", n(1)) + .expression_attribute_values(":at", s(&by.at)) + .expression_attribute_values(":ub", AttributeValue::L(kept)) .send() .await; } @@ -1030,6 +1064,21 @@ pub fn exemplar_of(i: &Item) -> Exemplar { category: gs(i, "category"), area: gs(i, "area"), text: gs(i, "text"), + title: gs(i, "title"), + summary: gs(i, "summary"), + reason: gs(i, "reason"), + run_id: gs(i, "run_id"), + last_used_at: gs(i, "last_used_at"), + used_by: i + .get("used_by") + .and_then(|v| v.as_l().ok()) + .map(|l| { + l.iter() + .filter_map(|v| v.as_s().ok()) + .filter_map(|s| serde_json::from_str(s).ok()) + .collect() + }) + .unwrap_or_default(), reward: gf(i, "reward"), events: gu(i, "events"), uses: gu(i, "uses"), @@ -1147,6 +1196,21 @@ mod tests { ])); assert_eq!(e.embedding, vec![1.0, 2.0]); assert_eq!(e.polarity(), Some("good")); + assert!(e.used_by.is_empty() && e.title.is_empty()); + let e = exemplar_of(&item(&[ + ("title", s("Retry once")), + ("last_used_at", s("2026-01-02T00:00:00Z")), + ( + "used_by", + AttributeValue::L(vec![ + s(r#"{"at":"2026-01-02T00:00:00Z","agent":"coder","run_id":"R1"}"#), + s("not json"), + ]), + ), + ])); + assert_eq!(e.title, "Retry once"); + assert_eq!(e.used_by.len(), 1); + assert_eq!(e.used_by[0].run_id, "R1"); let l = lesson_of(&item(&[ ("id", s("L")), ("text", s("t")), diff --git a/services/common/src/rewards/summary.rs b/services/common/src/rewards/summary.rs index ff621d2be..7b0237217 100644 --- a/services/common/src/rewards/summary.rs +++ b/services/common/src/rewards/summary.rs @@ -8,6 +8,9 @@ use super::exemplars::Exemplar; use super::score::{self, Dim, Weights}; use serde_json::{json, Value}; +/// Most examples listed on the page. +pub const MAX_EXEMPLARS: usize = 200; + /// Everything the page is built from. pub struct Inputs<'a> { pub team_id: &'a str, @@ -104,21 +107,29 @@ pub fn build(i: &Inputs<'_>) -> Value { .iter() .filter(|e| in_repo(&e.repo) && e.polarity().is_some()) .collect(); + // Most used first, then the biggest reward: the ones shaping prompts. ex.sort_by(|a, b| { - b.reward - .abs() - .partial_cmp(&a.reward.abs()) - .unwrap_or(std::cmp::Ordering::Equal) + b.uses.cmp(&a.uses).then_with(|| { + b.reward + .abs() + .partial_cmp(&a.reward.abs()) + .unwrap_or(std::cmp::Ordering::Equal) + }) }); let exemplars: Vec = ex .into_iter() - .take(60) + .take(MAX_EXEMPLARS) .map(|e| { + let d = e.display(); json!({ "id": e.id, "repo": e.repo, "kind": e.kind, "polarity": e.polarity(), "category": e.category, "area": e.area, - "text": crate::truncate_str(&e.text, 400), - "reward": r3(e.reward), "uses": e.uses, "created_at": e.created_at, "pr": e.pr, + "title": d.title, "summary": d.summary, "reason": d.reason, + // Kept for older dashboards: one clean line, never raw markup. + "text": super::example_text::cut_words(&d.line(), 240), + "reward": r3(e.reward), "events": e.events, "uses": e.uses, + "created_at": e.created_at, "pr": e.pr, "run_id": e.run_id, + "last_used_at": e.last_used_at, "used_by": e.used_by, }) }) .collect(); @@ -259,4 +270,76 @@ mod tests { assert_eq!(all["totals"]["events"], 2); assert_eq!(all["repos"].as_array().unwrap().len(), 2); } + + #[test] + fn examples_read_clean_and_most_used_first() { + use super::super::exemplars::{Exemplar, Use, KIND_FINDING, KIND_FIX}; + let old = Exemplar { + id: "old".into(), + repo: "acme/web".into(), + kind: KIND_FINDING.into(), + text: "Missing test: The **retry** path has no test.".into(), + reward: 2.5, + uses: 1, + ..Default::default() + }; + let used = Exemplar { + id: "used".into(), + repo: "acme/web".into(), + kind: KIND_FIX.into(), + reward: 1.2, + uses: 9, + reason: "CI passed on the first try, merged without changes".into(), + run_id: "R1".into(), + last_used_at: "2026-10-02T00:00:00Z".into(), + used_by: vec![Use { + at: "2026-10-02T00:00:00Z".into(), + agent: "coder".into(), + run_id: "R2".into(), + pr: 0, + }], + ..Default::default() + } + .with_text( + "Retry payments", + "Source ticket: OPS-1\n\n**Summary** Retry once.", + ); + let neutral = Exemplar { + id: "neutral".into(), + repo: "acme/web".into(), + reward: 0.2, + uses: 50, + ..Default::default() + }; + let w = Weights::default(); + let v = build(&Inputs { + team_id: "TEAM#a", + days: 30, + repo: "", + can_manage: true, + weights: &w, + events: &[], + categories: &[], + changes: &[], + exemplars: &[old, used, neutral], + arms: &[], + }); + let ex = v["exemplars"].as_array().unwrap(); + assert_eq!(ex.len(), 2, "no polarity, not listed"); + assert_eq!(ex[0]["id"], "used"); + assert_eq!(ex[0]["title"], "Retry payments"); + assert_eq!(ex[0]["summary"], "Retry once."); + assert_eq!( + ex[0]["reason"], + "CI passed on the first try, merged without changes" + ); + assert_eq!(ex[0]["run_id"], "R1"); + assert_eq!(ex[0]["used_by"][0]["run_id"], "R2"); + assert!(ex[0]["used_by"][0].get("pr").is_none()); + assert_eq!(ex[1]["title"], "Missing test"); + assert_eq!(ex[1]["summary"], "The **retry** path has no test."); + assert_eq!(ex[1]["reason"], "The team acted on this comment"); + assert_eq!(ex[1]["text"], "Missing test: The retry path has no test."); + assert!(!ex[1]["text"].as_str().unwrap().contains("