diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 937a175b0..87a99409c 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -1,6 +1,102 @@ { "components": { "schemas": { + "ActivityGroup": { + "description": "Consecutive steps of one kind while the reviewer read the pull request\n(\"Search 3 times\", \"View 4 files\"), or one note it wrote on what it was\nchecking. Only where it looked is kept, never what it read.", + "properties": { + "ended_at": { + "description": "When its last step happened (RFC 3339, milliseconds).", + "examples": [ + "2026-10-22T14:18:12.020+00:00" + ], + "type": "string" + }, + "items": { + "description": "Its steps, oldest first. Empty for a note.", + "items": { + "$ref": "#/components/schemas/ActivityItem" + }, + "type": "array" + }, + "kind": { + "description": "`search`, `view`, `find`, `lookup`, `note` or `comment`.", + "examples": [ + "view" + ], + "type": "string" + }, + "started_at": { + "description": "When its first step happened (RFC 3339, milliseconds).", + "examples": [ + "2026-10-22T14:18:09.412+00:00" + ], + "type": "string" + }, + "text": { + "description": "A note's sentences. Empty for other groups.", + "examples": [ + "" + ], + "type": "string" + }, + "title": { + "description": "The group in words, or a note's heading.", + "examples": [ + "View 2 files" + ], + "type": "string" + } + }, + "required": [ + "kind", + "title", + "started_at", + "ended_at", + "text", + "items" + ], + "type": "object" + }, + "ActivityItem": { + "description": "One entry of an activity group: a search query, a `path:lines` the\nreviewer read, a comment's place.", + "properties": { + "at": { + "description": "When (RFC 3339, milliseconds).", + "examples": [ + "2026-10-22T14:18:09.412+00:00" + ], + "type": "string" + }, + "detail": { + "description": "A comment's title, or the tool's name in words. Empty otherwise.", + "examples": [ + "" + ], + "type": "string" + }, + "failed": { + "description": "The call failed or was refused.", + "examples": [ + false + ], + "type": "boolean" + }, + "label": { + "description": "What it looked at: a query, `path:10-40`, a comment's `path:line`.\nEmpty for a tool shown by its name only.", + "examples": [ + "src/orders/sort.ts:10-48" + ], + "type": "string" + } + }, + "required": [ + "at", + "label", + "detail", + "failed" + ], + "type": "object" + }, "AnswerRun": { "description": "Answers to a run's questions.", "properties": { @@ -1708,6 +1804,30 @@ }, "type": "object" }, + "OverviewFile": { + "description": "One row of the overview's file table.", + "properties": { + "description": { + "description": "What the change does in that file, in one short line.", + "examples": [ + "Sorts orders before the status filter" + ], + "type": "string" + }, + "path": { + "description": "The file, as the diff names it.", + "examples": [ + "src/orders/sort.ts" + ], + "type": "string" + } + }, + "required": [ + "path", + "description" + ], + "type": "object" + }, "Plan": { "description": "A plan.", "properties": { @@ -3014,9 +3134,72 @@ ], "type": "object" }, + "ReviewOverview": { + "description": "The \"PR Overview\" the review led with on GitHub.", + "properties": { + "changes": { + "description": "What it changes, a few short bullets.", + "examples": [ + [ + "Sort runs before the status filter" + ] + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "files": { + "description": "One line per changed file, in the diff's order (at most 100).", + "items": { + "$ref": "#/components/schemas/OverviewFile" + }, + "type": "array" + }, + "files_total": { + "description": "How many files the pull request changed.", + "examples": [ + 3 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "summary": { + "description": "What the pull request does, in one sentence.", + "examples": [ + "Sorts the order list before filtering it by status." + ], + "type": "string" + } + }, + "required": [ + "summary", + "changes", + "files", + "files_total" + ], + "type": "object" + }, "ReviewSession": { "description": "One review job, step by step: what CoderHelm's \"CoderHelm review\" check\nlinks to. Each job has its own session, so an older check keeps showing\nits own review.", "properties": { + "activity": { + "description": "What the reviewer did while it read the pull request, live while it\nruns: its searches, file views and lookups in groups, the notes it\nwrote, and the comments it kept. Oldest first.", + "items": { + "$ref": "#/components/schemas/ActivityGroup" + }, + "type": "array" + }, + "activity_dropped": { + "description": "Steps left out of `activity` because the review passed its cap.", + "examples": [ + 0 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, "attempt": { "description": "Which try this job is, from 0.", "examples": [ @@ -3085,6 +3268,17 @@ ], "type": "string" }, + "overview": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/ReviewOverview", + "description": "The \"PR Overview\" the review posted, once there is one." + } + ] + }, "pr_number": { "description": "The pull request number.", "examples": [ @@ -3174,7 +3368,9 @@ "reason", "verdict", "review_url", - "steps" + "steps", + "activity", + "activity_dropped" ], "type": "object" }, diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index d98bdeee7..d7f12bfdb 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -121,6 +121,8 @@ pub mod plugins; pub mod public_urls; /// Who asked for a run: one identity per person, for per-person analytics. pub mod requester; +/// What the reviewer did while it read a pull request, for the session page. +pub mod review_activity; /// The PR's "CoderHelm review" check run, from scheduled to finished. pub mod review_check; /// Lessons the reviewer learns from people's pushback on its findings. @@ -128,6 +130,8 @@ pub mod review_lessons; /// Where the reviewer is with each PR right now (queued, reviewing, retrying, /// done), and the one status a PR shows on the dashboard. pub mod review_live; +/// The "PR Overview" a review leads with: what the PR does, file by file. +pub mod review_overview; pub mod review_session; pub mod review_stats; /// Learning from outcomes: reward events, scores, calibration, variants, diff --git a/services/common/src/review_activity.rs b/services/common/src/review_activity.rs new file mode 100644 index 000000000..116aba7b5 --- /dev/null +++ b/services/common/src/review_activity.rs @@ -0,0 +1,678 @@ +//! What the reviewer did while it read a pull request: every search, file +//! view and lookup it made, the short notes it wrote on what it was checking, +//! and the comments it kept. The review's session page shows them live, in +//! groups of consecutive steps of one kind ("Search 3 times", "View 4 files"). +//! +//! Only where the reviewer looked is recorded, never what it saw: a file view +//! keeps its path and line range, a search its query, any other tool its name +//! (and the symbol it asked about). Tool results and file contents are never +//! recorded, and every text passes the secret scrubber +//! ([`crate::log_findings::scrub`]) and a size cap first. A review keeps at +//! most [`MAX_EVENTS`] events; the rest are counted, not kept. +//! +//! The events are appended to the job's session record +//! ([`crate::review_session::append_activity`]) while the review runs, and +//! grouped when they are read ([`group`]). + +use std::sync::Mutex; + +use serde_json::Value; + +/// A code or knowledge search (its query). +pub const KIND_SEARCH: &str = "search"; +/// A file read (its path and line range). +pub const KIND_VIEW: &str = "view"; +/// A folder listing or file pattern (its path or pattern). +pub const KIND_FIND: &str = "find"; +/// Any other tool: history, live sources, registries, team agents (its name). +pub const KIND_LOOKUP: &str = "lookup"; +/// A short note the reviewer wrote on what it is checking. +pub const KIND_NOTE: &str = "note"; +/// A comment the review kept for the pull request (its place and title). +pub const KIND_COMMENT: &str = "comment"; + +/// Most events one review keeps. +pub const MAX_EVENTS: usize = 200; +/// Most notes one review keeps (they are the longest events). +pub const MAX_NOTES: usize = 40; +/// Longest label (a query, a path and range), in bytes. +pub const MAX_LABEL: usize = 160; +/// Longest note heading, in bytes. +pub const MAX_HEADING: usize = 80; +/// Longest note or comment text, in bytes. +pub const MAX_TEXT: usize = 400; + +/// One thing the reviewer did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Event { + /// When, in milliseconds since the epoch. + pub at_ms: i64, + /// One of the `KIND_*` words. + pub kind: String, + /// Where it looked: a query, `path:10-40`, a tool name. Empty for a note. + pub label: String, + /// A note's heading, or a comment's title. + pub heading: String, + /// A note's sentences. Empty for everything else. + pub text: String, + /// The tool call failed or was refused. + pub failed: bool, +} + +/// Pure: one line, no control characters, secrets scrubbed, at most `max` +/// bytes (cut on a char boundary, with an ellipsis when cut). +pub fn clean(text: &str, max: usize) -> String { + let one_line: String = text + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .collect::() + .split_whitespace() + .collect::>() + .join(" "); + let scrubbed = crate::log_findings::scrub(&one_line); + if scrubbed.len() <= max { + return scrubbed; + } + let cut = crate::truncate_str(&scrubbed, max.saturating_sub('…'.len_utf8())); + format!("{}…", cut.trim_end()) +} + +fn str_of<'a>(input: &'a Value, key: &str) -> &'a str { + input.get(key).and_then(Value::as_str).unwrap_or("").trim() +} + +fn num_of(input: &Value, key: &str) -> Option { + input.get(key).and_then(Value::as_u64) +} + +/// Pure: what kind of step a tool call is, and its label. Only the fields +/// that say WHERE the reviewer looked are read (`path`, line numbers, +/// `query`, `pattern`, `name`, `paths`); any other input is left out. +pub fn classify(tool: &str, input: &Value) -> (&'static str, String) { + let path = str_of(input, "path"); + let query = str_of(input, "query"); + let name = str_of(input, "name"); + match tool { + "read_file_lines" | "read_lines" => { + let start = num_of(input, "start_line"); + let end = num_of(input, "end_line"); + let label = match (start, end) { + (Some(s), Some(e)) if e > s => format!("{path}:{s}-{e}"), + (Some(s), _) => format!("{path}:{s}"), + _ => path.to_string(), + }; + (KIND_VIEW, label) + } + "read_file" => (KIND_VIEW, path.to_string()), + "list_directory" | "list_files" => ( + KIND_FIND, + if path.is_empty() { + "/".into() + } else { + path.into() + }, + ), + "glob" | "find_files" => (KIND_FIND, str_of(input, "pattern").to_string()), + "graph_callers" => (KIND_SEARCH, format!("callers of {name}")), + "graph_definition" => (KIND_SEARCH, format!("definition of {name}")), + "graph_impact" => { + let paths: Vec<&str> = input + .get("paths") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + (KIND_SEARCH, format!("what depends on {}", paths.join(", "))) + } + _ if !query.is_empty() && tool.contains("search") => (KIND_SEARCH, query.to_string()), + "check_package" => { + let registry = str_of(input, "registry"); + let version = str_of(input, "version"); + let label = match (registry.is_empty(), version.is_empty()) { + (false, false) => format!("{registry}: {name}@{version}"), + (false, true) => format!("{registry}: {name}"), + _ => name.to_string(), + }; + (KIND_LOOKUP, label) + } + _ => (KIND_LOOKUP, String::new()), + } +} + +/// Pure: a tool name in words ("github_history" reads "Github history"). +pub fn tool_words(tool: &str) -> String { + let words = tool.replace(['_', '-'], " "); + let mut c = words.trim().chars(); + match c.next() { + Some(f) => f.to_uppercase().collect::() + c.as_str(), + None => "Tool".into(), + } +} + +impl Event { + /// A tool call at `at_ms`. Never holds the call's result. + pub fn tool(at_ms: i64, tool: &str, input: &Value, failed: bool) -> Event { + let (kind, label) = classify(tool, input); + // A lookup is shown by the tool's name; its label, when it has one, + // says what it looked up. + let heading = if kind == KIND_LOOKUP { + clean(&tool_words(tool), MAX_HEADING) + } else { + String::new() + }; + Event { + at_ms, + kind: kind.to_string(), + label: clean(&label, MAX_LABEL), + heading, + text: String::new(), + failed, + } + } + + /// A note the reviewer wrote before its next tool calls. `None` when + /// nothing is left once code blocks are dropped. + pub fn note(at_ms: i64, written: &str) -> Option { + let (heading, text) = split_note(written); + let heading = clean(&heading, MAX_HEADING); + let text = clean(&text, MAX_TEXT); + if heading.is_empty() && text.is_empty() { + return None; + } + Some(Event { + at_ms, + kind: KIND_NOTE.into(), + label: String::new(), + heading, + text, + failed: false, + }) + } + + /// A comment the review kept, at `path:line`. + pub fn comment(at_ms: i64, path: &str, line: u64, title: &str) -> Event { + let place = if line > 0 { + format!("{path}:{line}") + } else { + path.to_string() + }; + Event { + at_ms, + kind: KIND_COMMENT.into(), + label: clean(&place, MAX_LABEL), + heading: clean(title, MAX_HEADING), + text: String::new(), + failed: false, + } + } +} + +/// Pure: a note's heading and sentences. Fenced code is dropped (a note +/// never carries code or file contents). The heading is a first line in +/// bold (`**Checking callers**`) or a markdown heading; a short first line +/// followed by more text counts too. Otherwise there is no heading. +pub fn split_note(written: &str) -> (String, String) { + let mut lines: Vec<&str> = Vec::new(); + let mut in_fence = false; + for line in written.lines() { + if line.trim_start().starts_with("```") { + in_fence = !in_fence; + continue; + } + if !in_fence && !line.trim().is_empty() { + lines.push(line.trim()); + } + } + let Some((first, rest)) = lines.split_first() else { + return (String::new(), String::new()); + }; + let bold = first + .strip_prefix("**") + .and_then(|s| s.split_once("**")) + .map(|(h, after)| (h.trim().trim_end_matches(':').trim_end(), after.trim())); + if let Some((heading, after)) = bold { + let after = after.trim_start_matches([':', '.', '-']).trim(); + let mut text = vec![after]; + text.extend(rest.iter().copied()); + return (heading.to_string(), join_text(&text)); + } + if let Some(h) = first.strip_prefix('#') { + let h = h.trim_start_matches('#').trim().trim_end_matches(':'); + return (h.to_string(), join_text(rest)); + } + let short = first.len() <= MAX_HEADING && !first.ends_with(['.', '?', '!', ':']); + if short && !rest.is_empty() { + return (first.to_string(), join_text(rest)); + } + (String::new(), join_text(&lines)) +} + +fn join_text(parts: &[&str]) -> String { + parts + .iter() + .map(|p| p.trim()) + .filter(|p| !p.is_empty()) + .collect::>() + .join(" ") +} + +/// The events of one review, as it runs: the reviewer's tool loop adds them, +/// and a writer takes them in batches ([`Recorder::drain`]) to append to the +/// session. Keeps the caps across the whole review. +#[derive(Default)] +pub struct Recorder { + inner: Mutex, +} + +#[derive(Default)] +struct RecorderState { + pending: Vec, + kept: usize, + notes: usize, + dropped: u64, +} + +impl Recorder { + pub fn new() -> Self { + Self::default() + } + + fn state(&self) -> std::sync::MutexGuard<'_, RecorderState> { + self.inner.lock().unwrap_or_else(|p| p.into_inner()) + } + + /// Keep `e` unless the review is past its caps (then count it). + pub fn push(&self, e: Event) { + let mut s = self.state(); + let is_note = e.kind == KIND_NOTE; + if s.kept >= MAX_EVENTS || (is_note && s.notes >= MAX_NOTES) { + s.dropped += 1; + return; + } + s.kept += 1; + if is_note { + s.notes += 1; + } + s.pending.push(e); + } + + /// A tool call that just ended. + pub fn tool(&self, tool: &str, input: &Value, failed: bool) { + self.push(Event::tool(now_ms(), tool, input, failed)); + } + + /// What the reviewer wrote before its next tool calls. + pub fn note(&self, written: &str) { + if let Some(e) = Event::note(now_ms(), written) { + self.push(e); + } + } + + /// A comment the review kept. + pub fn comment(&self, path: &str, line: u64, title: &str) { + self.push(Event::comment(now_ms(), path, line, title)); + } + + /// The events since the last drain, and how many were dropped since. + pub fn drain(&self) -> (Vec, u64) { + let mut s = self.state(); + let dropped = std::mem::take(&mut s.dropped); + (std::mem::take(&mut s.pending), dropped) + } +} + +fn now_ms() -> i64 { + chrono::Utc::now().timestamp_millis() +} + +/// One entry of a group: a query, a `path:lines`, a comment's place. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Item { + pub at_ms: i64, + pub label: String, + /// A comment's title, or a lookup's tool in words; empty otherwise. + pub detail: String, + pub failed: bool, +} + +/// Consecutive events of one kind, as the session page shows them. A note +/// is always a group of its own. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Group { + pub kind: String, + /// "Search 3 times", "View 4 files", a note's heading. + pub title: String, + pub started_ms: i64, + pub ended_ms: i64, + /// A note's sentences; empty for other groups. + pub text: String, + pub items: Vec, +} + +fn plural(n: usize, one: &str, many: &str) -> String { + if n == 1 { + one.to_string() + } else { + format!("{n} {many}") + } +} + +/// Pure: a group's title from its kind and entries. +pub fn group_title(kind: &str, items: &[Item]) -> String { + let n = items.len(); + match kind { + KIND_SEARCH => format!("Search {}", plural(n, "once", "times")), + KIND_VIEW => { + let mut files: Vec<&str> = items + .iter() + .map(|i| { + i.label + .rsplit_once(':') + .map_or(i.label.as_str(), |(p, _)| p) + }) + .collect(); + files.sort_unstable(); + files.dedup(); + format!("View {}", plural(files.len(), "1 file", "files")) + } + KIND_FIND => "Find files".into(), + KIND_COMMENT => format!("Store {}", plural(n, "comment", "comments")), + _ => { + let mut tools: Vec<&str> = items.iter().map(|i| i.detail.as_str()).collect(); + tools.dedup(); + match tools.as_slice() { + [one] if n == 1 => one.to_string(), + [one] => format!("{one} ({n} times)"), + _ => format!("Use {n} tools"), + } + } + } +} + +/// Pure: `events` in groups of consecutive events of one kind, oldest first +/// (a note on its own). Events are taken in the order given (the order they +/// were appended). +pub fn group(events: &[Event]) -> Vec { + let mut out: Vec = Vec::new(); + for e in events { + if e.kind == KIND_NOTE { + out.push(Group { + kind: KIND_NOTE.into(), + title: if e.heading.is_empty() { + "Note".into() + } else { + e.heading.clone() + }, + started_ms: e.at_ms, + ended_ms: e.at_ms, + text: e.text.clone(), + items: Vec::new(), + }); + continue; + } + let item = Item { + at_ms: e.at_ms, + label: e.label.clone(), + detail: e.heading.clone(), + failed: e.failed, + }; + match out.last_mut() { + Some(g) if g.kind == e.kind => { + g.ended_ms = g.ended_ms.max(e.at_ms); + g.items.push(item); + } + _ => out.push(Group { + kind: e.kind.clone(), + title: String::new(), + started_ms: e.at_ms, + ended_ms: e.at_ms, + text: String::new(), + items: vec![item], + }), + } + } + for g in &mut out { + if g.kind != KIND_NOTE { + g.title = group_title(&g.kind, &g.items); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn ev(at: i64, tool: &str, input: Value) -> Event { + Event::tool(at, tool, &input, false) + } + + #[test] + fn a_tool_call_keeps_where_it_looked_and_nothing_else() { + let e = ev( + 1, + "read_file_lines", + json!({"path": "src/order.rs", "start_line": 10, "end_line": 42}), + ); + assert_eq!( + (e.kind.as_str(), e.label.as_str()), + (KIND_VIEW, "src/order.rs:10-42") + ); + let e = ev( + 1, + "read_file_lines", + json!({"path": "a.rs", "start_line": 7, "end_line": 7}), + ); + assert_eq!(e.label, "a.rs:7"); + assert_eq!(ev(1, "read_file", json!({"path": "a.rs"})).label, "a.rs"); + let e = ev(1, "search_code", json!({"query": "fn settle"})); + assert_eq!( + (e.kind.as_str(), e.label.as_str()), + (KIND_SEARCH, "fn settle") + ); + assert_eq!( + ev(1, "search_knowledge", json!({"query": "refunds"})).kind, + KIND_SEARCH + ); + assert_eq!(ev(1, "list_directory", json!({"path": ""})).label, "/"); + assert_eq!(ev(1, "list_directory", json!({})).kind, KIND_FIND); + assert_eq!( + ev(1, "graph_callers", json!({"name": "settle"})).label, + "callers of settle" + ); + assert_eq!( + ev(1, "graph_impact", json!({"paths": ["a.rs", "b.rs"]})).label, + "what depends on a.rs, b.rs" + ); + assert_eq!( + ev( + 1, + "check_package", + json!({"registry": "npm", "name": "next", "version": "15.3.0"}) + ) + .label, + "npm: next@15.3.0" + ); + // Any other tool: its name only, never its input (a SQL query, a URL, + // a payload). + let e = ev( + 1, + "db_query", + json!({"sql": "select email from users where token = 'abc'"}), + ); + assert_eq!(e.kind, KIND_LOOKUP); + assert_eq!(e.label, ""); + assert_eq!(e.heading, "Db query"); + assert!(!format!("{e:?}").contains("email")); + let e = ev(1, "api_get", json!({"path": "/v1/orders?key=secret"})); + assert_eq!(e.kind, KIND_LOOKUP); + assert_eq!(e.label, ""); + } + + #[test] + fn secrets_and_long_text_never_reach_an_event() { + let token = format!("ghp_{}", "a".repeat(40)); + let e = ev(1, "search_code", json!({"query": format!("token {token}")})); + assert!(!e.label.contains(&token), "{}", e.label); + assert!(e.label.contains("[GITHUB_TOKEN]")); + let long = "x".repeat(1_000); + let e = ev(1, "search_code", json!({"query": long})); + assert!(e.label.len() <= MAX_LABEL); + assert!(e.label.ends_with('…')); + let note = Event::note(1, &format!("**Checking**\n{}", "word ".repeat(400))).unwrap(); + assert!(note.text.len() <= MAX_TEXT); + // Multi-byte text is cut on a char boundary. + let e = ev(1, "search_code", json!({"query": "é".repeat(300)})); + assert!(e.label.len() <= MAX_LABEL); + // Control characters and newlines become one line. + let e = ev(1, "search_code", json!({"query": "a\nb\tc\u{7}"})); + assert_eq!(e.label, "a b c"); + } + + #[test] + fn a_note_has_a_heading_and_never_code() { + assert_eq!( + split_note("**Evaluating order semantics**\nThe new sort runs before the filter."), + ( + "Evaluating order semantics".into(), + "The new sort runs before the filter.".into() + ) + ); + assert_eq!( + split_note("**Checking callers:** three places call it."), + ("Checking callers".into(), "three places call it.".into()) + ); + assert_eq!( + split_note("## Reading the tests\nTwo cover it."), + ("Reading the tests".into(), "Two cover it.".into()) + ); + assert_eq!( + split_note("Checking the retry path\nIt retries twice."), + ("Checking the retry path".into(), "It retries twice.".into()) + ); + assert_eq!( + split_note("I will read the callers next."), + (String::new(), "I will read the callers next.".into()) + ); + let (h, t) = split_note( + "**Comparing**\nThe handler reads:\n```rust\nlet key = \"sk_live_123\";\n```\nThen returns.", + ); + assert_eq!(h, "Comparing"); + assert_eq!(t, "The handler reads: Then returns."); + assert!(Event::note(1, "```\nonly code\n```").is_none()); + assert!(Event::note(1, " \n").is_none()); + } + + #[test] + fn the_recorder_keeps_its_caps_and_counts_the_rest() { + let r = Recorder::new(); + for i in 0..(MAX_NOTES + 5) { + r.push(Event::note(i as i64, "**Step**\nmore").unwrap()); + } + let (kept, dropped) = r.drain(); + assert_eq!(kept.len(), MAX_NOTES); + assert_eq!(dropped, 5); + // The caps hold across drains. + for i in 0..MAX_EVENTS { + r.push(ev(i as i64, "read_file", json!({"path": "a.rs"}))); + } + let (kept, dropped) = r.drain(); + assert_eq!(kept.len(), MAX_EVENTS - MAX_NOTES); + assert_eq!(dropped, MAX_NOTES as u64); + r.comment("a.rs", 3, "Off by one"); + assert_eq!(r.drain(), (vec![], 1)); + assert_eq!(r.drain(), (vec![], 0)); + } + + #[test] + fn consecutive_steps_of_one_kind_group_like_copilot() { + let events = vec![ + Event::note(1, "**Evaluating order semantics**\nThe sort moved.").unwrap(), + ev(2, "search_code", json!({"query": "sort_by"})), + ev(3, "search_code", json!({"query": "filter_orders"})), + ev(4, "search_org", json!({"query": "OrderList"})), + ev( + 5, + "read_file_lines", + json!({"path": "a.rs", "start_line": 1, "end_line": 9}), + ), + ev( + 6, + "read_file_lines", + json!({"path": "a.rs", "start_line": 20, "end_line": 30}), + ), + ev(7, "read_file", json!({"path": "b.rs"})), + ev(8, "list_directory", json!({"path": "src"})), + ev(9, "search_code", json!({"query": "again"})), + ev(10, "github_history", json!({"path": "a.rs"})), + ev(11, "github_history", json!({})), + ev(12, "check_package", json!({"registry": "npm", "name": "x"})), + Event::comment(13, "a.rs", 4, "Sort runs after the filter"), + Event::comment(14, "b.rs", 0, "Missing test"), + ]; + let groups = group(&events); + let titles: Vec<&str> = groups.iter().map(|g| g.title.as_str()).collect(); + assert_eq!( + titles, + vec![ + "Evaluating order semantics", + "Search 3 times", + "View 2 files", + "Find files", + "Search once", + "Use 3 tools", + "Store 2 comments", + ] + ); + let note = &groups[0]; + assert_eq!(note.kind, KIND_NOTE); + assert_eq!(note.text, "The sort moved."); + assert!(note.items.is_empty()); + let search = &groups[1]; + assert_eq!((search.started_ms, search.ended_ms), (2, 4)); + let labels: Vec<&str> = search.items.iter().map(|i| i.label.as_str()).collect(); + assert_eq!(labels, vec!["sort_by", "filter_orders", "OrderList"]); + assert_eq!(groups[2].items[1].label, "a.rs:20-30"); + assert_eq!(groups[6].items[0].label, "a.rs:4"); + assert_eq!(groups[6].items[0].detail, "Sort runs after the filter"); + assert_eq!(groups[6].items[1].label, "b.rs"); + assert!(group(&[]).is_empty()); + } + + #[test] + fn titles_read_in_plain_words() { + let item = |label: &str, detail: &str| Item { + at_ms: 0, + label: label.into(), + detail: detail.into(), + failed: false, + }; + assert_eq!( + group_title(KIND_VIEW, &[item("a.rs:1-2", "")]), + "View 1 file" + ); + assert_eq!( + group_title(KIND_COMMENT, &[item("a.rs:1", "t")]), + "Store comment" + ); + assert_eq!( + group_title(KIND_LOOKUP, &[item("", "Github history")]), + "Github history" + ); + assert_eq!( + group_title( + KIND_LOOKUP, + &[item("", "Github history"), item("", "Github history")] + ), + "Github history (2 times)" + ); + assert_eq!(tool_words("check_url"), "Check url"); + assert_eq!(tool_words(""), "Tool"); + } + + #[test] + fn a_failed_call_stays_marked() { + let e = Event::tool(1, "read_file", &json!({"path": "gone.rs"}), true); + assert!(group(&[e])[0].items[0].failed); + } +} diff --git a/services/common/src/review_overview.rs b/services/common/src/review_overview.rs new file mode 100644 index 000000000..de6af5b5f --- /dev/null +++ b/services/common/src/review_overview.rs @@ -0,0 +1,468 @@ +//! The "PR Overview" a review leads with: one sentence on what the pull +//! request does, a few bullets of what it changes, and one short line per +//! changed file. The reviewer writes it with its findings +//! ([`ModelOverview`]); [`build`] holds it to the diff (only files the diff +//! changed, in its order, each with a line even when the model left one +//! out), [`markdown`] renders it for the GitHub review, and the session +//! record keeps it for the dashboard ([`to_attr`], [`of_item`]). + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use serde::Deserialize; + +/// Longest overview sentence, in bytes. +pub const MAX_SUMMARY: usize = 300; +/// Most "Changes" bullets. +pub const MAX_CHANGES: usize = 8; +/// Longest bullet, in bytes. +pub const MAX_CHANGE: usize = 200; +/// Longest file description, in bytes. +pub const MAX_DESCRIPTION: usize = 140; +/// Longest path kept, in bytes. +pub const MAX_PATH: usize = 300; +/// Most file rows kept (the rest are counted in `files_total`). +pub const MAX_FILES: usize = 100; +/// Above this many rows the table is folded in a `
`. +pub const FOLD_AFTER: usize = 15; + +/// What the model wrote, as it wrote it. +#[derive(Debug, Clone, Default, Deserialize)] +pub struct ModelOverview { + #[serde(default)] + pub summary: String, + #[serde(default)] + pub changes: Vec, + #[serde(default)] + pub files: Vec, +} + +#[derive(Debug, Clone, Default, Deserialize)] +pub struct ModelFile { + #[serde(default)] + pub path: String, + #[serde(default)] + pub description: String, +} + +/// One file the diff changed. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ChangedFile { + pub path: String, + /// GitHub's word: added, removed, modified, renamed. + pub status: String, + pub additions: u64, + pub deletions: u64, +} + +/// Pure: the changed files of a compare (`files[]` of GitHub's compare API). +pub fn changed_files(compare: &serde_json::Value) -> Vec { + compare["files"] + .as_array() + .map(|files| { + files + .iter() + .filter_map(|f| { + let path = f["filename"].as_str()?; + Some(ChangedFile { + path: path.to_string(), + status: f["status"].as_str().unwrap_or("").to_string(), + additions: f["additions"].as_u64().unwrap_or(0), + deletions: f["deletions"].as_u64().unwrap_or(0), + }) + }) + .collect() + }) + .unwrap_or_default() +} + +/// One row of the "Reviewed Changes" table. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FileRow { + pub path: String, + pub description: String, +} + +/// The overview as posted and shown. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Overview { + pub summary: String, + pub changes: Vec, + /// At most [`MAX_FILES`], in the diff's order. + pub files: Vec, + /// How many files the diff changed. + pub files_total: usize, +} + +impl Overview { + pub fn is_empty(&self) -> bool { + self.summary.is_empty() && self.changes.is_empty() && self.files.is_empty() + } +} + +/// Pure: one line, at most `max` bytes, cut on a char boundary. +fn line(text: &str, max: usize) -> String { + let one = text.split_whitespace().collect::>().join(" "); + if one.len() <= max { + return one; + } + let cut = crate::truncate_str(&one, max.saturating_sub('…'.len_utf8())); + format!("{}…", cut.trim_end()) +} + +/// Pure: what a file's row says when the model wrote nothing for it. +pub fn fallback_description(f: &ChangedFile) -> String { + match f.status.as_str() { + "added" => format!("New file (+{})", f.additions), + "removed" => "Removed".into(), + "renamed" if f.additions + f.deletions == 0 => "Renamed".into(), + "renamed" => format!("Renamed and changed (+{}/-{})", f.additions, f.deletions), + _ => format!("Changed (+{}/-{})", f.additions, f.deletions), + } +} + +/// Pure: the overview held to the diff. The summary is its first sentence; +/// a file the model described that the diff didn't change is dropped; a +/// changed file it didn't describe gets [`fallback_description`]. +pub fn build(model: &ModelOverview, changed: &[ChangedFile]) -> Overview { + let summary = { + let prose = model + .summary + .split_whitespace() + .collect::>() + .join(" "); + let first = crate::prose::first_sentences(&prose, 1, MAX_SUMMARY); + line(if first.is_empty() { &prose } else { first }, MAX_SUMMARY) + }; + let changes = model + .changes + .iter() + .map(|c| line(c.trim().trim_start_matches(['-', '*']).trim(), MAX_CHANGE)) + .filter(|c| !c.is_empty()) + .take(MAX_CHANGES) + .collect(); + let described: HashMap<&str, &str> = model + .files + .iter() + .map(|f| (f.path.trim().trim_matches('`'), f.description.trim())) + .filter(|(p, d)| !p.is_empty() && !d.is_empty()) + .collect(); + let files = changed + .iter() + .take(MAX_FILES) + .map(|f| FileRow { + path: line(&f.path, MAX_PATH), + description: match described.get(f.path.as_str()) { + Some(d) => line(d, MAX_DESCRIPTION), + None => fallback_description(f), + }, + }) + .collect(); + Overview { + summary, + changes, + files, + files_total: changed.len(), + } +} + +/// Pure: text safe inside a markdown table cell. +fn cell(text: &str) -> String { + text.replace('\\', "\\\\") + .replace('|', "\\|") + .replace(['\n', '\r'], " ") +} + +/// Pure: a path as inline code, whatever backticks it holds. +fn code(path: &str) -> String { + format!("`{}`", cell(&path.replace('`', "'"))) +} + +/// Pure: the overview as the GitHub review's opening section. Empty when the +/// overview is. +pub fn markdown(o: &Overview) -> String { + if o.is_empty() { + return String::new(); + } + let mut out = String::from("## PR Overview\n"); + if !o.summary.is_empty() { + out.push_str(&format!("\n{}\n", o.summary)); + } + if !o.changes.is_empty() { + out.push_str("\n**Changes**\n"); + for c in &o.changes { + out.push_str(&format!("- {c}\n")); + } + } + if !o.files.is_empty() { + let count = if o.files_total == 1 { + "1 changed file".to_string() + } else { + format!("{} changed files", o.files_total) + }; + out.push_str(&format!("\n**Reviewed Changes**\n\n{count}.\n")); + let mut table = String::from("\n| File | Description |\n| --- | --- |\n"); + for f in &o.files { + table.push_str(&format!( + "| {} | {} |\n", + code(&f.path), + cell(&f.description) + )); + } + let more = o.files_total.saturating_sub(o.files.len()); + if more > 0 { + table.push_str(&format!( + "\nAnd {more} more {}.\n", + if more == 1 { "file" } else { "files" } + )); + } + if o.files.len() > FOLD_AFTER { + out.push_str(&format!( + "\n
\nShow a summary per file\n{table}\n
\n" + )); + } else { + out.push_str(&table); + } + } + out +} + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +/// The overview as one session-record attribute. +pub fn to_attr(o: &Overview) -> AttributeValue { + let files = o + .files + .iter() + .map(|f| { + AttributeValue::M(HashMap::from([ + ("path".to_string(), s(&f.path)), + ("description".to_string(), s(&f.description)), + ])) + }) + .collect(); + AttributeValue::M(HashMap::from([ + ("summary".to_string(), s(&o.summary)), + ( + "changes".to_string(), + AttributeValue::L(o.changes.iter().map(|c| s(c)).collect()), + ), + ("files".to_string(), AttributeValue::L(files)), + ( + "files_total".to_string(), + AttributeValue::N(o.files_total.to_string()), + ), + ])) +} + +/// Pure: the overview a session record holds, if any. Read back with the +/// same caps it was written with. +pub fn of_item(item: &HashMap) -> Option { + let m = item.get("overview")?.as_m().ok()?; + let text = + |v: Option<&AttributeValue>| v.and_then(|v| v.as_s().ok()).cloned().unwrap_or_default(); + let list = |k: &str| { + m.get(k) + .and_then(|v| v.as_l().ok()) + .cloned() + .unwrap_or_default() + }; + let changes: Vec = list("changes") + .iter() + .filter_map(|v| v.as_s().ok().cloned()) + .take(MAX_CHANGES) + .collect(); + let files: Vec = list("files") + .iter() + .filter_map(|v| v.as_m().ok()) + .map(|f| FileRow { + path: text(f.get("path")), + description: text(f.get("description")), + }) + .take(MAX_FILES) + .collect(); + let files_total = m + .get("files_total") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(files.len()) + .max(files.len()); + let o = Overview { + summary: text(m.get("summary")), + changes, + files, + files_total, + }; + (!o.is_empty()).then_some(o) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn changed(path: &str, status: &str) -> ChangedFile { + ChangedFile { + path: path.into(), + status: status.into(), + additions: 4, + deletions: 1, + } + } + + fn model(files: &[(&str, &str)]) -> ModelOverview { + ModelOverview { + summary: "Sorts orders before filtering them. It also renames a helper.".into(), + changes: vec!["- Sort first".into(), "".into(), "Rename `helper`".into()], + files: files + .iter() + .map(|(p, d)| ModelFile { + path: p.to_string(), + description: d.to_string(), + }) + .collect(), + } + } + + #[test] + fn the_overview_is_held_to_the_diff() { + let diff = vec![ + changed("src/a.rs", "modified"), + changed("src/new.rs", "added"), + ]; + let o = build( + &model(&[ + ("src/a.rs", "Sorts before the filter"), + ("src/invented.rs", "Not in the diff"), + ]), + &diff, + ); + assert_eq!(o.summary, "Sorts orders before filtering them."); + assert_eq!(o.changes, vec!["Sort first", "Rename `helper`"]); + assert_eq!( + o.files, + vec![ + FileRow { + path: "src/a.rs".into(), + description: "Sorts before the filter".into() + }, + FileRow { + path: "src/new.rs".into(), + description: "New file (+4)".into() + }, + ] + ); + assert_eq!(o.files_total, 2); + assert!(build(&ModelOverview::default(), &[]).is_empty()); + } + + #[test] + fn caps_hold() { + let diff: Vec = (0..(MAX_FILES + 7)) + .map(|i| changed(&format!("f{i}.rs"), "modified")) + .collect(); + let mut m = model(&[("f0.rs", &"long words ".repeat(100))]); + m.changes = (0..20).map(|i| format!("change {i}")).collect(); + m.summary = "x".repeat(2_000); + let o = build(&m, &diff); + assert_eq!(o.files.len(), MAX_FILES); + assert_eq!(o.files_total, MAX_FILES + 7); + assert_eq!(o.changes.len(), MAX_CHANGES); + assert!(o.summary.len() <= MAX_SUMMARY); + assert!(o.files[0].description.len() <= MAX_DESCRIPTION); + let md = markdown(&o); + assert!(md.contains("And 7 more files."), "{md}"); + } + + #[test] + fn a_small_pr_renders_an_open_table() { + let o = build( + &model(&[("src/a.rs", "Sorts | filters")]), + &[changed("src/a.rs", "modified")], + ); + let md = markdown(&o); + assert_eq!( + md, + "## PR Overview\n\nSorts orders before filtering them.\n\n**Changes**\n- Sort first\n\ + - Rename `helper`\n\n**Reviewed Changes**\n\n1 changed file.\n\n\ + | File | Description |\n| --- | --- |\n| `src/a.rs` | Sorts \\| filters |\n" + ); + assert!(!md.contains("
")); + } + + #[test] + fn a_large_pr_folds_the_table() { + let diff: Vec = (0..(FOLD_AFTER + 1)) + .map(|i| changed(&format!("f{i}.rs"), "modified")) + .collect(); + let md = markdown(&build(&model(&[]), &diff)); + assert!(md.contains("
\nShow a summary per file")); + assert!(md.trim_end().ends_with("
")); + assert!(md.contains("| `f0.rs` | Changed (+4/-1) |")); + // The summary and bullets stay outside the fold. + let fold = md.find("
").unwrap(); + assert!(md.find("**Changes**").unwrap() < fold); + let at_limit: Vec = diff[..FOLD_AFTER].to_vec(); + assert!(!markdown(&build(&model(&[]), &at_limit)).contains("
")); + } + + #[test] + fn fallbacks_say_what_happened_to_the_file() { + let mut f = changed("a", "removed"); + assert_eq!(fallback_description(&f), "Removed"); + f.status = "renamed".into(); + f.additions = 0; + f.deletions = 0; + assert_eq!(fallback_description(&f), "Renamed"); + f.status = "modified".into(); + assert_eq!(fallback_description(&f), "Changed (+0/-0)"); + } + + #[test] + fn cells_never_break_the_table() { + let o = Overview { + summary: String::new(), + changes: vec![], + files: vec![FileRow { + path: "we`ird|path".into(), + description: "a\nb | c".into(), + }], + files_total: 1, + }; + let md = markdown(&o); + assert!(md.contains("| `we'ird\\|path` | a b \\| c |"), "{md}"); + assert_eq!(markdown(&Overview::default()), ""); + } + + #[test] + fn the_session_keeps_it_as_written() { + let o = build( + &model(&[("src/a.rs", "Sorts")]), + &[changed("src/a.rs", "modified"), changed("b.rs", "added")], + ); + let item = HashMap::from([("overview".to_string(), to_attr(&o))]); + assert_eq!(of_item(&item), Some(o)); + assert_eq!(of_item(&HashMap::new()), None); + let empty = HashMap::from([("overview".to_string(), to_attr(&Overview::default()))]); + assert_eq!(of_item(&empty), None); + } + + #[test] + fn changed_files_read_the_compare() { + let compare = serde_json::json!({"files": [ + {"filename": "a.rs", "status": "modified", "additions": 3, "deletions": 2}, + {"status": "added"} + ]}); + assert_eq!( + changed_files(&compare), + vec![ChangedFile { + path: "a.rs".into(), + status: "modified".into(), + additions: 3, + deletions: 2 + }] + ); + assert!(changed_files(&serde_json::json!({})).is_empty()); + } +} diff --git a/services/common/src/review_session.rs b/services/common/src/review_session.rs index 0ec90b7bc..2d1571cde 100644 --- a/services/common/src/review_session.rs +++ b/services/common/src/review_session.rs @@ -312,6 +312,134 @@ pub async fn close( log_unless_missing(named(req, &update).send().await.err(), job, "close"); } +/// Pure: one entry of `activity` ([`crate::review_activity::Event`]). +pub fn activity_value(e: &crate::review_activity::Event) -> AttributeValue { + let mut m = HashMap::from([ + ("at".to_string(), n(e.at_ms)), + ("kind".to_string(), s(&e.kind)), + ]); + for (k, v) in [ + ("label", &e.label), + ("heading", &e.heading), + ("text", &e.text), + ] { + if !v.is_empty() { + m.insert(k.to_string(), s(v)); + } + } + if e.failed { + m.insert("failed".to_string(), AttributeValue::Bool(true)); + } + AttributeValue::M(m) +} + +/// Pure: the update that appends a batch of activity (`:ev`, a list) and +/// counts the events the review's caps dropped (`:d`). +pub fn activity_update() -> String { + "SET #activity = list_append(if_not_exists(#activity, :none), :ev), #updated_at = :at \ + ADD #activity_dropped :d" + .to_string() +} + +/// Append a batch of what the reviewer did to `job`'s session. The events +/// are already capped and scrubbed ([`crate::review_activity::Recorder`]). +pub async fn append_activity( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + job: &str, + events: &[crate::review_activity::Event], + dropped: u64, +) { + if events.is_empty() && dropped == 0 { + return; + } + let update = activity_update(); + let req = dynamo + .update_item() + .table_name(table) + .key("pk", s(team_id)) + .key("sk", s(&record_sk(job))) + .update_expression(&update) + .condition_expression(EXISTS) + .expression_attribute_values(":none", AttributeValue::L(vec![])) + .expression_attribute_values( + ":ev", + AttributeValue::L(events.iter().map(activity_value).collect()), + ) + .expression_attribute_values(":d", n(dropped as i64)) + .expression_attribute_values(":at", s(&chrono::Utc::now().to_rfc3339())); + log_unless_missing(named(req, &update).send().await.err(), job, "activity"); +} + +/// Pure: the activity of a record, in the order it was appended, at most +/// [`crate::review_activity::MAX_EVENTS`]. +pub fn activity_of(item: &HashMap) -> Vec { + let Some(list) = item.get("activity").and_then(|v| v.as_l().ok()) else { + return Vec::new(); + }; + list.iter() + .filter_map(|v| v.as_m().ok()) + .map(|m| { + let get = |k: &str| { + m.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + crate::review_activity::Event { + at_ms: m + .get("at") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0), + kind: get("kind"), + label: get("label"), + heading: get("heading"), + text: get("text"), + failed: m + .get("failed") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false), + } + }) + .take(crate::review_activity::MAX_EVENTS) + .collect() +} + +/// Pure: how many events the review's caps left out. +pub fn activity_dropped(item: &HashMap) -> u64 { + item.get("activity_dropped") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0) +} + +/// Record the review's "PR Overview" on `job`'s session. +pub async fn set_overview( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + job: &str, + overview: &crate::review_overview::Overview, +) { + if overview.is_empty() { + return; + } + let update = "SET #overview = :o, #updated_at = :at"; + let req = dynamo + .update_item() + .table_name(table) + .key("pk", s(team_id)) + .key("sk", s(&record_sk(job))) + .update_expression(update) + .condition_expression(EXISTS) + .expression_attribute_values(":o", crate::review_overview::to_attr(overview)) + .expression_attribute_values(":at", s(&chrono::Utc::now().to_rfc3339())); + log_unless_missing(named(req, update).send().await.err(), job, "overview"); +} + /// A condition miss is a job that never opened a session (it stopped before /// real work); anything else is logged and dropped. fn log_unless_missing( @@ -464,6 +592,45 @@ mod tests { assert!(with.contains("#reason = :why") && with.ends_with("REMOVE #expires_at")); } + #[test] + fn activity_appends_and_reads_back_in_order() { + use crate::review_activity::{Event, MAX_EVENTS}; + let update = activity_update(); + assert!(update.contains("list_append(if_not_exists(#activity, :none), :ev)")); + assert!(update.contains("ADD #activity_dropped :d")); + assert_eq!( + placeholders(&update), + vec!["activity", "updated_at", "activity_dropped"] + ); + let events = vec![ + Event::note(1, "**Checking callers**\nTwo places.").unwrap(), + Event::tool(2, "read_file", &serde_json::json!({"path": "a.rs"}), true), + Event::comment(3, "a.rs", 9, "Off by one"), + ]; + let item = HashMap::from([ + ( + "activity".to_string(), + AttributeValue::L(events.iter().map(activity_value).collect()), + ), + ("activity_dropped".to_string(), n(4)), + ]); + assert_eq!(activity_of(&item), events); + assert_eq!(activity_dropped(&item), 4); + // Empty fields aren't written. + let AttributeValue::M(m) = activity_value(&events[1]) else { + panic!() + }; + assert!(!m.contains_key("text") && m.contains_key("failed")); + // A record past the cap is read back capped. + let many = HashMap::from([( + "activity".to_string(), + AttributeValue::L(vec![activity_value(&events[1]); MAX_EVENTS + 10]), + )]); + assert_eq!(activity_of(&many).len(), MAX_EVENTS); + assert!(activity_of(&HashMap::new()).is_empty()); + assert_eq!(activity_dropped(&HashMap::new()), 0); + } + #[test] fn placeholders_are_distinct_and_complete() { let p = placeholders(&open_update(true)); diff --git a/services/gateway/src/routes/reviewer.rs b/services/gateway/src/routes/reviewer.rs index 1eaeada62..3e2c88f7b 100644 --- a/services/gateway/src/routes/reviewer.rs +++ b/services/gateway/src/routes/reviewer.rs @@ -1263,6 +1263,123 @@ pub struct SessionStep { pub detail: String, } +/// One entry of an activity group: a search query, a `path:lines` the +/// reviewer read, a comment's place. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct ActivityItem { + /// When (RFC 3339, milliseconds). + #[schema(example = "2026-10-22T14:18:09.412+00:00")] + pub at: String, + /// What it looked at: a query, `path:10-40`, a comment's `path:line`. + /// Empty for a tool shown by its name only. + #[schema(example = "src/orders/sort.ts:10-48")] + pub label: String, + /// A comment's title, or the tool's name in words. Empty otherwise. + #[schema(example = "")] + pub detail: String, + /// The call failed or was refused. + #[schema(example = false)] + pub failed: bool, +} + +/// Consecutive steps of one kind while the reviewer read the pull request +/// ("Search 3 times", "View 4 files"), or one note it wrote on what it was +/// checking. Only where it looked is kept, never what it read. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct ActivityGroup { + /// `search`, `view`, `find`, `lookup`, `note` or `comment`. + #[schema(example = "view")] + pub kind: String, + /// The group in words, or a note's heading. + #[schema(example = "View 2 files")] + pub title: String, + /// When its first step happened (RFC 3339, milliseconds). + #[schema(example = "2026-10-22T14:18:09.412+00:00")] + pub started_at: String, + /// When its last step happened (RFC 3339, milliseconds). + #[schema(example = "2026-10-22T14:18:12.020+00:00")] + pub ended_at: String, + /// A note's sentences. Empty for other groups. + #[schema(example = "")] + pub text: String, + /// Its steps, oldest first. Empty for a note. + pub items: Vec, +} + +/// One row of the overview's file table. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct OverviewFile { + /// The file, as the diff names it. + #[schema(example = "src/orders/sort.ts")] + pub path: String, + /// What the change does in that file, in one short line. + #[schema(example = "Sorts orders before the status filter")] + pub description: String, +} + +/// The "PR Overview" the review led with on GitHub. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct ReviewOverview { + /// What the pull request does, in one sentence. + #[schema(example = "Sorts the order list before filtering it by status.")] + pub summary: String, + /// What it changes, a few short bullets. + #[schema(example = json!(["Sort runs before the status filter"]))] + pub changes: Vec, + /// One line per changed file, in the diff's order (at most 100). + pub files: Vec, + /// How many files the pull request changed. + #[schema(example = 3)] + pub files_total: u64, +} + +fn rfc3339_ms(ms: i64) -> String { + chrono::DateTime::from_timestamp_millis(ms) + .map(|d| d.to_rfc3339_opts(chrono::SecondsFormat::Millis, false)) + .unwrap_or_default() +} + +/// Pure: the session's activity in groups, as the API returns it. +fn activity_groups(item: &HashMap) -> Vec { + common::review_activity::group(&common::review_session::activity_of(item)) + .into_iter() + .map(|g| ActivityGroup { + kind: g.kind, + title: g.title, + started_at: rfc3339_ms(g.started_ms), + ended_at: rfc3339_ms(g.ended_ms), + text: g.text, + items: g + .items + .into_iter() + .map(|i| ActivityItem { + at: rfc3339_ms(i.at_ms), + label: i.label, + detail: i.detail, + failed: i.failed, + }) + .collect(), + }) + .collect() +} + +/// Pure: the overview a session holds, as the API returns it. +fn overview_of(item: &HashMap) -> Option { + common::review_overview::of_item(item).map(|o| ReviewOverview { + summary: o.summary, + changes: o.changes, + files: o + .files + .into_iter() + .map(|f| OverviewFile { + path: f.path, + description: f.description, + }) + .collect(), + files_total: o.files_total as u64, + }) +} + /// One review job, step by step: what CoderHelm's "CoderHelm review" check /// links to. Each job has its own session, so an older check keeps showing /// its own review. @@ -1323,6 +1440,15 @@ pub struct ReviewSession { pub check_run_id: Option, /// The steps so far, oldest first. pub steps: Vec, + /// What the reviewer did while it read the pull request, live while it + /// runs: its searches, file views and lookups in groups, the notes it + /// wrote, and the comments it kept. Oldest first. + pub activity: Vec, + /// Steps left out of `activity` because the review passed its cap. + #[schema(example = 0)] + pub activity_dropped: u64, + /// The "PR Overview" the review posted, once there is one. + pub overview: Option, } /// Pure: the session in `item` as `team_id` sees it. `None` for a record @@ -1373,6 +1499,9 @@ fn session_of( detail: s.detail, }) .collect(), + activity: activity_groups(item), + activity_dropped: common::review_session::activity_dropped(item), + overview: overview_of(item), }) } @@ -1781,6 +1910,71 @@ mod tests { assert_eq!(done.check_run_id, Some(77)); } + #[test] + fn a_session_returns_its_activity_in_groups_and_its_overview() { + use common::review_activity::Event; + use common::review_session as rs; + let mut it = session_item("t", "reviewing", 2_000); + let events = [ + Event::note(1_000_500, "**Checking callers**\nThree places call it.").unwrap(), + Event::tool( + 1_001_000, + "search_code", + &serde_json::json!({"query": "settle("}), + false, + ), + Event::tool( + 1_002_000, + "search_code", + &serde_json::json!({"query": "Settle"}), + false, + ), + Event::tool( + 1_003_250, + "read_file_lines", + &serde_json::json!({"path": "a.rs", "start_line": 3, "end_line": 9}), + false, + ), + ]; + it.insert( + "activity".into(), + AttributeValue::L(events.iter().map(rs::activity_value).collect()), + ); + it.insert("activity_dropped".into(), attr_n(2)); + let s = session_of(&it, "t", 1_500).unwrap(); + let titles: Vec<&str> = s.activity.iter().map(|g| g.title.as_str()).collect(); + assert_eq!( + titles, + vec!["Checking callers", "Search 2 times", "View 1 file"] + ); + assert_eq!(s.activity[0].text, "Three places call it."); + assert_eq!(s.activity[1].items[0].label, "settle("); + assert_eq!(s.activity[1].started_at, "1970-01-01T00:16:41.000+00:00"); + assert_eq!(s.activity[2].items[0].label, "a.rs:3-9"); + assert_eq!(s.activity_dropped, 2); + assert!(s.overview.is_none()); + + let o = common::review_overview::build( + &common::review_overview::ModelOverview { + summary: "Sorts orders first.".into(), + changes: vec!["Sort first".into()], + files: vec![], + }, + &[common::review_overview::ChangedFile { + path: "a.rs".into(), + status: "modified".into(), + additions: 1, + deletions: 0, + }], + ); + it.insert("overview".into(), common::review_overview::to_attr(&o)); + let s = session_of(&it, "t", 1_500).unwrap(); + let ov = s.overview.unwrap(); + assert_eq!(ov.summary, "Sorts orders first."); + assert_eq!(ov.files[0].description, "Changed (+1/-0)"); + assert_eq!(ov.files_total, 1); + } + #[test] fn live_rows_join_review_status_and_gate_per_pr() { let now = 1_000_000; diff --git a/services/worker/src/agent/anthropic.rs b/services/worker/src/agent/anthropic.rs index fc581befe..2e9e27625 100644 --- a/services/worker/src/agent/anthropic.rs +++ b/services/worker/src/agent/anthropic.rs @@ -707,7 +707,7 @@ pub async fn converse_tool_loop( max_tokens: i32, deadline: Option, effort: Option<&str>, - on_tool_call: Option<&super::llm::OnToolCall>, + observer: Option<&dyn super::llm::LoopObserver>, mut conversation_log: Option<&mut Vec>, ) -> Result> { let family = ModelFamily::of(model_id); @@ -885,6 +885,19 @@ pub async fn converse_tool_loop( }) .collect::>() .join(" "); + if let Some(o) = observer { + // The blocks joined by line, so a heading stays on its own line. + let written: Vec<&str> = blocks + .iter() + .filter_map(|b| match b { + ContentBlock::Text { text } if !text.trim().is_empty() => Some(text.as_str()), + _ => None, + }) + .collect(); + if !written.is_empty() { + o.on_text(&written.join("\n")); + } + } // Execute tools, each only after the policy gate allows it. let mut tool_results: Vec = Vec::new(); @@ -916,8 +929,8 @@ pub async fn converse_tool_loop( { super::policy::Gated::Ran(r) => r, super::policy::Gated::Refused(message) => { - if let Some(cb) = on_tool_call { - cb(tool_name, 0, &truncate_input_summary(tool_input), true); + if let Some(o) = observer { + o.on_tool_call(tool_name, tool_input, 0, true); } info!(tool = %tool_name, "Tool not run: the policy gate said no"); tool_results.push(json!({ @@ -937,9 +950,8 @@ pub async fn converse_tool_loop( Ok(result) => { let duration_ms = tool_start.elapsed().as_millis() as u64; usage.record_tool_call(tool_name, duration_ms); - if let Some(cb) = on_tool_call { - let input_summary = truncate_input_summary(tool_input); - cb(tool_name, duration_ms, &input_summary, false); + if let Some(o) = observer { + o.on_tool_call(tool_name, tool_input, duration_ms, false); } info!(tool = %tool_name, duration_ms, "Tool completed"); tool_results.push(json!({ @@ -951,9 +963,8 @@ pub async fn converse_tool_loop( Err(e) => { let duration_ms = tool_start.elapsed().as_millis() as u64; usage.record_tool_call(tool_name, duration_ms); - if let Some(cb) = on_tool_call { - let input_summary = truncate_input_summary(tool_input); - cb(tool_name, duration_ms, &input_summary, true); + if let Some(o) = observer { + o.on_tool_call(tool_name, tool_input, duration_ms, true); } warn!(tool = %tool_name, error = %e, duration_ms, "Tool execution failed"); // GitHub refusing for a while is not an answer to retry: @@ -1109,26 +1120,6 @@ pub(crate) fn shared_prefix_bytes( // --- Internal helpers --- -/// Produce a short summary of tool input for live event display. -fn truncate_input_summary(input: &Value) -> String { - // For common tools, extract the most relevant field - let summary = if let Some(path) = input.get("path").and_then(|v| v.as_str()) { - path.to_string() - } else if let Some(pattern) = input.get("pattern").and_then(|v| v.as_str()) { - format!("pattern: {pattern}") - } else if let Some(command) = input.get("command").and_then(|v| v.as_str()) { - command.chars().take(200).collect() - } else { - let s = input.to_string(); - if s.len() > 200 { - format!("{}…", common::truncate_str(&s, 200)) - } else { - s - } - }; - summary -} - /// Sends one Messages request, streamed, and counts it: every attempt into /// the team's counters as it happens (`common::model_stream`, a reply that /// broke off and was retried included), and into the run's own totals diff --git a/services/worker/src/agent/llm.rs b/services/worker/src/agent/llm.rs index 48c7ad575..0e5423c05 100644 --- a/services/worker/src/agent/llm.rs +++ b/services/worker/src/agent/llm.rs @@ -30,6 +30,46 @@ impl Default for ConverseOptions { /// Observer invoked after each tool call: (tool_name, duration_ms, input_summary, is_error). pub type OnToolCall = dyn Fn(&str, u64, &str, bool) + Send + Sync; +/// Watches a tool loop as it runs: what the agent wrote before each batch +/// of tool calls, and each call once it ended (or was refused). Called +/// inline, so an observer only records and never waits. +pub trait LoopObserver: Send + Sync { + /// The text the agent wrote in a turn that goes on to call tools. + fn on_text(&self, _text: &str) {} + /// One tool call ended: its name, its input, how long it took, and + /// whether it failed or was refused. + fn on_tool_call(&self, name: &str, input: &Value, duration_ms: u64, is_error: bool); +} + +/// A plain [`OnToolCall`] closure as a loop observer: it sees each call with +/// a short summary of its input ([`input_summary`]), never the text. +pub struct ToolCallFn(pub Box); + +impl LoopObserver for ToolCallFn { + fn on_tool_call(&self, name: &str, input: &Value, duration_ms: u64, is_error: bool) { + (self.0)(name, duration_ms, &input_summary(input), is_error); + } +} + +/// A tool call's input in one short line: its path, pattern or command when +/// it has one, else the input itself cut to 200 bytes. +pub fn input_summary(input: &Value) -> String { + if let Some(path) = input.get("path").and_then(|v| v.as_str()) { + path.to_string() + } else if let Some(pattern) = input.get("pattern").and_then(|v| v.as_str()) { + format!("pattern: {pattern}") + } else if let Some(command) = input.get("command").and_then(|v| v.as_str()) { + command.chars().take(200).collect() + } else { + let s = input.to_string(); + if s.len() > 200 { + format!("{}…", common::truncate_str(&s, 200)) + } else { + s + } + } +} + pub struct ToolDefinition { pub name: String, pub description: String, diff --git a/services/worker/src/agent/provider.rs b/services/worker/src/agent/provider.rs index 662047ba4..107eeb8fa 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -245,7 +245,7 @@ pub async fn converse( tool_executor: &dyn ToolExecutor, usage: &mut TokenUsage, opts: ConverseOptions, - on_tool_call: Option<&super::llm::OnToolCall>, + observer: Option<&dyn super::llm::LoopObserver>, conversation_log: Option<&mut Vec>, ) -> Result> { // A switch in Settings, System, Models reaches the next loop. @@ -268,7 +268,7 @@ pub async fn converse( opts.max_tokens, opts.deadline, opts.effort, - on_tool_call, + observer, conversation_log, ) .await diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 32e5b5e92..7eb789fe8 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -780,7 +780,7 @@ pub async fn run( effort: None, }; - let on_tool: Option> = if let Some(rid) = run_id { + let on_tool: Option = if let Some(rid) = run_id { let dynamo = state.dynamo.clone(); let s3 = state.s3.clone(); let bucket = state.config.bucket_name.clone(); @@ -788,7 +788,7 @@ pub async fn run( let events_table = state.config.events_table_name.clone(); let team = msg.team_id.clone(); let rid = rid.to_string(); - Some(Box::new( + Some(llm::ToolCallFn(Box::new( move |tool_name: &str, duration_ms: u64, input_summary: &str, is_error: bool| { let dynamo = dynamo.clone(); let s3 = s3.clone(); @@ -868,7 +868,7 @@ pub async fn run( } }); }, - )) + ))) } else { None }; @@ -887,7 +887,7 @@ pub async fn run( &executor, usage, opts, - on_tool.as_ref().map(|b| b.as_ref()), + on_tool.as_ref().map(|o| o as &dyn llm::LoopObserver), Some(&mut conv_log), ) .await?; @@ -945,7 +945,7 @@ pub async fn run( &executor, usage, remediation_opts, - on_tool.as_ref().map(|b| b.as_ref()), + on_tool.as_ref().map(|o| o as &dyn llm::LoopObserver), Some(&mut conv_log), ) .await @@ -1022,7 +1022,7 @@ pub async fn run( &executor, usage, opts, - on_tool.as_ref().map(|b| b.as_ref()), + on_tool.as_ref().map(|o| o as &dyn llm::LoopObserver), Some(&mut conv_log), ) .await diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 85fa89c8e..9b427932c 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1104,6 +1104,7 @@ pub mod restack; pub mod resume; mod review; pub mod review_actions; +pub mod review_activity; pub mod review_agent; pub mod review_configs; #[cfg(test)] diff --git a/services/worker/src/passes/review_activity.rs b/services/worker/src/passes/review_activity.rs new file mode 100644 index 000000000..22c0ec14a --- /dev/null +++ b/services/worker/src/passes/review_activity.rs @@ -0,0 +1,137 @@ +//! The reviewer's activity, live: the review's tool loop reports each call +//! and each note to a [`common::review_activity::Recorder`], and a feed +//! appends what was recorded to the review's session every few seconds, so +//! the session page shows the review as it happens. The writes are +//! best-effort (the session is a view): a failed one is logged and the +//! review goes on. + +use std::sync::Arc; +use std::time::Duration; + +use common::review_activity::Recorder; +use serde_json::Value; + +use crate::agent::llm::LoopObserver; + +/// How often the feed appends what was recorded. +pub(crate) const FLUSH_EVERY: Duration = Duration::from_secs(3); + +/// The reviewer's tool loop, seen by its recorder. +pub(crate) struct ActivityObserver(pub Arc); + +impl LoopObserver for ActivityObserver { + fn on_text(&self, text: &str) { + self.0.note(text); + } + fn on_tool_call(&self, name: &str, input: &Value, _duration_ms: u64, is_error: bool) { + self.0.tool(name, input, is_error); + } +} + +/// Where a feed writes: one review job's session. +#[derive(Clone)] +pub(crate) struct SessionTarget { + pub dynamo: aws_sdk_dynamodb::Client, + pub table: String, + pub team_id: String, + pub job: String, +} + +/// Appends a recorder's events to a session while a review runs. Closing it +/// writes the rest; dropping it without closing (an early return) still +/// writes the rest, in the background. +pub(crate) struct ActivityFeed { + recorder: Arc, + stop: Option>, + task: Option>, +} + +impl ActivityFeed { + pub(crate) fn start(target: SessionTarget) -> Self { + let recorder = Arc::new(Recorder::new()); + let (stop, mut stopped) = tokio::sync::oneshot::channel::<()>(); + let rec = recorder.clone(); + let task = tokio::spawn(async move { + loop { + // A sent stop and a dropped sender both end the feed. + let last = tokio::select! { + _ = &mut stopped => true, + _ = tokio::time::sleep(FLUSH_EVERY) => false, + }; + flush(&target, &rec).await; + if last { + break; + } + } + }); + Self { + recorder, + stop: Some(stop), + task: Some(task), + } + } + + /// The recorder the review's tool loop reports to. + pub(crate) fn recorder(&self) -> &Arc { + &self.recorder + } + + /// Write what is left and stop. + pub(crate) async fn close(mut self) { + if let Some(stop) = self.stop.take() { + let _ = stop.send(()); + } + if let Some(task) = self.task.take() { + let _ = task.await; + } + } +} + +impl Drop for ActivityFeed { + fn drop(&mut self) { + // The sender drops with the feed; the task sees it, writes what is + // left and ends on its own. + self.stop.take(); + } +} + +async fn flush(target: &SessionTarget, recorder: &Recorder) { + let (events, dropped) = recorder.drain(); + common::review_session::append_activity( + &target.dynamo, + &target.table, + &target.team_id, + &target.job, + &events, + dropped, + ) + .await; +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn the_observer_records_notes_and_calls_but_never_results() { + let rec = Arc::new(Recorder::new()); + let o = ActivityObserver(rec.clone()); + o.on_text("**Checking callers**\nTwo places call `settle`."); + o.on_tool_call("search_code", &json!({"query": "settle("}), 12, false); + o.on_tool_call( + "db_query", + &json!({"sql": "select secret from t"}), + 40, + true, + ); + let (events, dropped) = rec.drain(); + assert_eq!(dropped, 0); + let kinds: Vec<&str> = events.iter().map(|e| e.kind.as_str()).collect(); + assert_eq!(kinds, vec!["note", "search", "lookup"]); + assert_eq!(events[0].heading, "Checking callers"); + assert_eq!(events[1].label, "settle("); + assert!(events[2].failed); + assert!(!format!("{events:?}").contains("secret")); + } +} diff --git a/services/worker/src/passes/review_agent.rs b/services/worker/src/passes/review_agent.rs index 5a056215a..a780c5a84 100644 --- a/services/worker/src/passes/review_agent.rs +++ b/services/worker/src/passes/review_agent.rs @@ -247,6 +247,11 @@ pub struct ReviewOutput { /// same commit: what new information changed it, in one sentence. #[serde(default)] pub change_of_mind: String, + /// What the PR does, in one sentence, a few bullets and a line per + /// changed file: the "PR Overview" the posted review leads with + /// ([`common::review_overview`]). + #[serde(default)] + pub overview: common::review_overview::ModelOverview, } /// A fact the PR's own evidence says is unconfirmed, and whether the change @@ -519,6 +524,14 @@ pub const TONE_RULE: &str = "TONE: write like a helpful colleague: calm, plain a changes until\"), and never argue with a decision a person has made. "; /// Most replies shown per thread, and most conversation comments shown. +/// The notes the session page shows while the review runs +/// ([`common::review_activity`]). +pub const PROGRESS_NOTES_RULE: &str = "PROGRESS NOTES: the team watches your work live. \ + Before each batch of tool calls, write one short note: a bold heading of two to five \ + words (**Checking the callers**), then one or two plain sentences on what you are \ + about to check and why. Never put code, file contents, secrets or credentials in a \ + note. "; + const MAX_THREAD_REPLIES: usize = 10; pub const MAX_DISCUSSION_COMMENTS: usize = 12; @@ -1498,13 +1511,15 @@ pub fn review_system_prompt( {PROOF_RULE}\ {COPY_RULE}\ {TONE_RULE}\ + {PROGRESS_NOTES_RULE}\ CI EVIDENCE: this PR's current CI results are provided below. Never claim an install, \ build, or typecheck \"will fail\" when a GREEN check on this same head already ran it — \ cite the check instead. A RED check is evidence for a finding; name it.\ {instructions_block}\n\n\ When done exploring, output ONLY a fenced ```json block, no prose after it, matching:\n\ {{\n \"verdict\": \"APPROVE\" | \"REQUEST_CHANGES\",\n \"risk\": \"LOW\" | \"MEDIUM\" | \"HIGH\",\n \ - \"summary\": \"2-4 sentence overview\",\n \"findings\": [{{\n \"file\": \"path\", \"line\": ,\n \ + \"overview\": {{\"summary\": \"one sentence: what the PR does\", \"changes\": [\"3-6 short bullets: what it changes\"], \"files\": [{{\"path\": \"a changed file, as in the diff\", \"description\": \"what the change does in it, one short line\"}}] (every changed file)}},\n \ + \"summary\": \"2-4 sentences: what you checked and what you found (what the PR does goes in overview)\",\n \"findings\": [{{\n \"file\": \"path\", \"line\": ,\n \ \"end_line\": , \"severity\": \"blocking|high|medium|low|nit\",\n \ \"category\": \"bug|security|correctness|perf|convention|style|logging|hardening|follow-up|scope|tests|source-data-override|manual-check|question\", \"title\": \"short\",\n \ \"evidence\": \"verified-defect|unverified-concern|question\",\n \ @@ -1584,6 +1599,7 @@ pub async fn generate_review( web: Option<&super::web_check::WebCheck>, mcp: Option<&super::remote_mcp::RemoteMcp>, knowledge: Option<&super::knowledge::KnowledgeTools>, + observer: Option<&dyn llm::LoopObserver>, usage: &mut TokenUsage, ) -> Result { let graph_tools = graph.map(|g| g.tools()).unwrap_or_default(); @@ -1664,7 +1680,7 @@ pub async fn generate_review( deadline: None, effort: None, }, - None, + observer, None, ) .await; @@ -2502,6 +2518,25 @@ mod tests { assert!(ask_schema().to_string().contains("continue_work")); } + #[test] + fn a_review_carries_its_overview_and_the_prompt_asks_for_notes() { + let reply = r#"Done. +```json +{"verdict": "APPROVE", "summary": "Checked the callers.", "findings": [], + "overview": {"summary": "Sorts orders first.", "changes": ["Sort first"], + "files": [{"path": "src/a.rs", "description": "Sorts before the filter"}]}} +```"#; + let out = parse_review(reply).unwrap(); + assert_eq!(out.overview.summary, "Sorts orders first."); + assert_eq!(out.overview.files[0].path, "src/a.rs"); + // An older answer without an overview still reads. + let old = parse_review(r#"{"verdict": "APPROVE", "summary": "ok"}"#).unwrap(); + assert!(old.overview.files.is_empty()); + let prompt = review_system_prompt("acme", "web", "", false); + assert!(prompt.contains("\"overview\": {"), "{prompt}"); + assert!(prompt.contains(PROGRESS_NOTES_RULE)); + } + #[test] fn the_ask_classifier_is_told_about_outstanding_work() { let p = ask_prompt( diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 0c0546df5..a8e5f5042 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -2811,6 +2811,15 @@ async fn run_once( "Against the repository's rules, the team's standards and what earlier reviews taught.", ) .await; + // What the reviewer does from here, live on the session page. + let activity = + super::review_activity::ActivityFeed::start(super::review_activity::SessionTarget { + dynamo: state.dynamo.clone(), + table: state.config.settings_table_name.clone(), + team_id: msg.team_id.clone(), + job: live_job.id.clone(), + }); + let observer = super::review_activity::ActivityObserver(activity.recorder().clone()); let output = review_agent::generate_review( state, &provider, @@ -2832,6 +2841,7 @@ async fn run_once( Some(&web), mcp.as_ref(), knowledge.as_ref(), + Some(&observer), &mut usage, ) .await; @@ -3329,6 +3339,11 @@ async fn run_once( // demoted finding is posted as a note. let hunks = review_agent::right_line_hunks(&compare); let postable = review_agent::to_postable(&findings, &changed, &hunks); + // The comments the review keeps close its activity. + for f in &findings { + activity.recorder().comment(&f.file, f.line, &f.title); + } + activity.close().await; let blocking_facts = unconfirmed.iter().filter(|f| f.blocks).count(); if !unconfirmed.is_empty() { info!( @@ -3372,6 +3387,17 @@ async fn run_once( } else { verdict_line }; + // The review leads with what the PR does, file by file. + let overview = common::review_overview::build( + &output.overview, + &common::review_overview::changed_files(&compare), + ); + let overview_md = common::review_overview::markdown(&overview); + let verdict_line = if overview_md.is_empty() { + verdict_line + } else { + format!("{overview_md}\n{verdict_line}") + }; let mut full_body = match &stable.note { Some(n) => format!( "{verdict_line}\n\n{n}\n\n{summary}\n\n{}", @@ -3664,6 +3690,14 @@ async fn run_once( live_job .verdict(state, &msg, verdict, findings.len(), &review_url) .await; + common::review_session::set_overview( + &state.dynamo, + &state.config.settings_table_name, + &msg.team_id, + &live_job.id, + &overview, + ) + .await; let posted_step = if should_comment { "Posted the review on GitHub" } else if already_answered {