From f042e1b203bb1c9d5f1b242f90a6cfb8441dc4a4 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Wed, 4 Nov 2026 19:10:02 -0500 Subject: [PATCH] Cut model spend: fewer and smaller reviews, cached prefixes, resumed retries, capped fix rounds - The PR reviewer skips CoderHelm's own pushes while its run is still in its review and fix loop; a run that completes asks for the review of its head. People's pushes are reviewed as always. - Push reviews wait three minutes for the PR to go quiet. A push after a review that didn't approve is reviewed from that review's commit (the hunks changed since and the earlier findings' status), and never approves without a full review. The unchanged-code skip compares the PR's own change after a merge or a rebase, after any verdict. - The coder's system prompt marks its shared prefix: sent as its own block with a 1-hour cache, as is the last tool definition; server-side clearing is rarer and larger (200k trigger, 100k minimum). - A person's Retry takes up the earlier run's plan and branch unless the plan was what failed. - CoderHelm's own review gets at most two fix rounds, then a person; each round is told what the earlier rounds were asked and looked up. - Plan review runs at low effort, for every ticket. - Analytics shows the metered cost (every model call) next to what the run records add up to; the feedback pass's run-record update no longer fails on a record without token counts. The dashboard pin moves to CoderHelm/coderhelm@7d2e215. Model routing is unchanged. --- selfhost/versions.json | 2 +- services/common/src/messages.rs | 18 + services/common/src/run_status.rs | 52 +++ services/gateway/src/routes/analytics.rs | 275 ++++++++++++- services/gateway/src/routes/api.rs | 14 +- services/gateway/src/routes/github_webhook.rs | 6 +- services/worker/src/agent/anthropic.rs | 365 ++++++++++++++---- services/worker/src/models.rs | 2 + services/worker/src/passes/e2e.rs | 4 + services/worker/src/passes/e2e_attribution.rs | 2 + services/worker/src/passes/feedback.rs | 6 +- services/worker/src/passes/implement.rs | 11 +- .../passes/incidents/k_own_review_findings.rs | 16 +- services/worker/src/passes/log_autofix.rs | 2 + services/worker/src/passes/mod.rs | 50 ++- services/worker/src/passes/own_review.rs | 223 ++++++++++- services/worker/src/passes/plan.rs | 3 + services/worker/src/passes/resume.rs | 197 +++++++++- services/worker/src/passes/review_eval.rs | 1 + services/worker/src/passes/review_pr.rs | 270 ++++++++++++- services/worker/src/passes/review_scope.rs | 235 +++++++++++ services/worker/src/passes/review_sweep.rs | 1 + services/worker/src/passes/skills.rs | 40 +- 23 files changed, 1656 insertions(+), 139 deletions(-) diff --git a/selfhost/versions.json b/selfhost/versions.json index 15a4a06a9..52917007f 100644 --- a/selfhost/versions.json +++ b/selfhost/versions.json @@ -1,4 +1,4 @@ { "about": "The dashboard commit each platform release ships: a full 40-character commit SHA of CoderHelm/coderhelm, never a branch or tag (scripts/check-dashboard-ref.mjs fails CI and the release otherwise). The release workflow builds exactly this commit (dashboard/) into dashboard.tar.gz. Move it with scripts/bump-dashboard.sh in a reviewed PR, in the same PR as any API change the dashboard needs.", - "dashboardRef": "dbfbd17a51c80c6feb95be3a5444676ddc51bff0" + "dashboardRef": "7d2e215d04058dd17ec087c3c16ae775abaedc9b" } diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index dda7763fe..5dbb42814 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -722,6 +722,11 @@ pub struct ReviewMessage { /// differs and was already reviewed at this commit, it doesn't run. #[serde(default, skip_serializing_if = "Option::is_none")] pub description_hash: Option, + /// Review the whole PR even after an earlier review of it: set on the + /// review a hunks-only re-review sends before it would approve, so an + /// approval always rests on a full review. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub full_review: bool, } #[derive(Serialize, Deserialize, Debug, Default)] @@ -816,6 +821,17 @@ pub struct TicketMessage { /// Epoch ms of the first attempt — the wall-clock runaway backstop. #[serde(default)] pub first_attempt_ms: u64, + /// A person retried this earlier run (`run_status::retry_resumes`): the + /// new run takes up its plan and the commits on its branch instead of + /// planning and implementing from scratch. Absent when the plan was what + /// failed, and on Start over. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resume_from: Option, + /// Set in-process when the run took up `resume_from`'s plan and branch: + /// the coder is told the branch already holds that run's work and + /// finishes what is left. Never serialized. + #[serde(skip)] + pub retry_of_run: bool, /// Times this run was sent again after a transient model error (a 5xx, /// 429, 529 or network failure that outlasted the client's own retries). /// The run keeps its run_id across these, like a continuation. @@ -882,6 +898,8 @@ impl Default for TicketMessage { continuation: 0, continuation_run_id: None, first_attempt_ms: 0, + resume_from: None, + retry_of_run: false, model_retries: 0, ticket_update_note: None, ticket_history_note: None, diff --git a/services/common/src/run_status.rs b/services/common/src/run_status.rs index 6f1bdd809..2be4be7cb 100644 --- a/services/common/src/run_status.rs +++ b/services/common/src/run_status.rs @@ -65,6 +65,24 @@ pub fn ended_by_person(status: &str) -> bool { ENDED_BY_PERSON.contains(&status) } +/// Whether a person's Retry of an ended run takes up its plan and branch +/// instead of starting over. Superseded runs cost $63 in 17 days, most of it +/// planning and implementing again what the earlier run had already +/// written. It starts over when the plan was what failed: the run stopped in +/// triage or planning (`current_pass`), or its error is about the plan. +/// Start over (`reset`) always starts over. A run that kept no plan of its +/// own has nothing to take up: the new run plans as usual. +pub fn retry_resumes(current_pass: &str, error: &str) -> bool { + let pass = current_pass.trim().to_ascii_lowercase(); + if pass.starts_with("triage") || pass.starts_with("plan") { + return false; + } + let error = error.to_ascii_lowercase(); + !error + .split(|c: char| !c.is_ascii_alphanumeric()) + .any(|w| matches!(w, "plan" | "planning" | "planner")) +} + /// The lesson trigger for a person's answer to "why was this closed?" on /// CoderHelm's PR (the gateway sends it, the worker's lessons read it). pub const CLOSE_REASON_TRIGGER: &str = "close_reason"; @@ -390,3 +408,37 @@ mod tests { ); } } + +#[cfg(test)] +mod retry_resumes_tests { + use super::retry_resumes; + + #[test] + fn a_retry_takes_up_the_plan_and_branch_unless_the_plan_failed() { + assert!(retry_resumes( + "implement", + "Reached the maximum number of steps" + )); + assert!(retry_resumes( + "review", + "the model call failed: 529 overloaded" + )); + assert!(retry_resumes("pr", "")); + // The plan was what failed: plan again. + assert!(!retry_resumes("plan", "out of time")); + assert!(!retry_resumes("plan_review", "")); + assert!(!retry_resumes("triage", "")); + assert!(!retry_resumes( + "implement", + "The plan names a file that doesn't exist" + )); + assert!(!retry_resumes( + "implement", + "planning gap: no task for the migration" + )); + // A finished pass name says nothing about the plan. + assert!(retry_resumes("done", "Reached the maximum number of steps")); + // A word that only contains "plan" isn't about the plan. + assert!(retry_resumes("implement", "the explanation was cut off")); + } +} diff --git a/services/gateway/src/routes/analytics.rs b/services/gateway/src/routes/analytics.rs index 98cc512b5..108fecb55 100644 --- a/services/gateway/src/routes/analytics.rs +++ b/services/gateway/src/routes/analytics.rs @@ -1463,6 +1463,165 @@ async fn load_runs(state: &AppState, team: &str, w: Window) -> Result, +} + +impl MeteredDay { + fn from_item(i: &Item) -> Option { + let day = s(i, "period").strip_prefix("DAY#")?.to_string(); + let mut features = BTreeMap::new(); + for k in i.keys() { + if let Some(f) = k + .strip_prefix("feature#") + .and_then(|r| r.strip_suffix("#cost_usd")) + { + features.insert(f.to_string(), n(i, k)); + } + } + Some(MeteredDay { + day, + cost_usd: n(i, "total_cost_usd"), + tokens: n(i, "total_tokens"), + features, + }) + } +} + +/// The meter's days in `w` (UTC dates from its start to its end). +async fn load_metered(state: &AppState, team: &str, w: Window) -> Vec { + if state.config.analytics_table_name.is_empty() { + return Vec::new(); + } + let lo = format!("DAY#{}", w.start.format("%Y-%m-%d")); + let hi = format!("DAY#{}", w.end.format("%Y-%m-%d")); + let mut out = Vec::new(); + let mut start: Option = None; + for _ in 0..MAX_PAGES { + let resp = match state + .dynamo + .query() + .table_name(&state.config.analytics_table_name) + .key_condition_expression("team_id = :t AND period BETWEEN :lo AND :hi") + .expression_attribute_values(":t", av(team)) + .expression_attribute_values(":lo", av(&lo)) + .expression_attribute_values(":hi", av(&hi)) + .set_exclusive_start_key(start.take()) + .send() + .await + { + Ok(r) => r, + Err(e) => { + warn!(error = %e, "Analytics: metered usage"); + return out; + } + }; + out.extend(resp.items().iter().filter_map(MeteredDay::from_item)); + match resp.last_evaluated_key() { + Some(k) => start = Some(k.clone()), + None => break, + } + } + out +} + +/// The UTC days a window covers, as the daily series keys them. +fn window_days(w: Window) -> Vec { + let mut out = Vec::new(); + let mut d = w.start; + while d < w.end { + out.push(d.format("%Y-%m-%d").to_string()); + d += Duration::days(1); + } + out +} + +/// Puts the metered cost on the page: each period's `cost_usd` is what the +/// meter counted (runs, reviews of people's and CoderHelm's PRs, follow-ups, +/// everything, including work on runs started before the period), with +/// `cost_by_feature` saying what it was for. What the run records add up to +/// stays as `run_cost_usd`, and the cost per run and per merged PR stay on +/// it. Each day's `tokens` is likewise the metered total (`run_tokens` the +/// run records'). `cost_basis` says which one `cost_usd` is: `metered`, or `runs` when +/// one repository is picked (the meter isn't kept per repository) or the +/// meter has nothing for the period. +pub fn apply_metered( + out: &mut Value, + metered: &[MeteredDay], + window: Window, + prev: Window, + repo: Option<&str>, +) { + let by_day: HashMap<&str, &MeteredDay> = metered.iter().map(|m| (m.day.as_str(), m)).collect(); + let period = |w: Window| -> Option<(f64, BTreeMap)> { + let days: Vec<&MeteredDay> = window_days(w) + .iter() + .filter_map(|d| by_day.get(d.as_str()).copied()) + .collect(); + if days.is_empty() { + return None; + } + let mut features: BTreeMap = BTreeMap::new(); + for d in &days { + for (f, c) in &d.features { + *features.entry(f.clone()).or_default() += c; + } + } + Some((days.iter().map(|d| d.cost_usd).sum(), features)) + }; + for (key, w) in [("summary", window), ("previous", prev)] { + let s = &mut out[key]; + let runs = s["cost_usd"].as_f64().unwrap_or(0.0); + s["run_cost_usd"] = json!(round2(runs)); + match period(w).filter(|_| repo.is_none()) { + Some((total, features)) => { + let mut list: Vec<(String, f64)> = features.into_iter().collect(); + list.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); + s["cost_usd"] = json!(round2(total)); + s["cost_basis"] = json!("metered"); + s["cost_by_feature"] = json!(list + .into_iter() + .filter(|(_, c)| *c > 0.0) + .map(|(feature, c)| json!({"feature": feature, "cost_usd": round2(c)})) + .collect::>()); + } + None => { + s["cost_basis"] = json!("runs"); + s["cost_by_feature"] = json!([]); + } + } + } + let metered_days = out["summary"]["cost_basis"] == "metered"; + if let Some(days) = out["daily"].as_array_mut() { + for d in days { + let runs = d["cost_usd"].as_f64().unwrap_or(0.0); + d["run_cost_usd"] = json!(round2(runs)); + d["run_tokens"] = d["tokens"].clone(); + if metered_days { + let day = d["day"].as_str().unwrap_or(""); + let m = by_day.get(day); + d["cost_usd"] = json!(round2(m.map_or(0.0, |m| m.cost_usd))); + d["tokens"] = json!(m.map_or(0.0, |m| m.tokens)); + } + } + } +} + /// Every item in the settings table under `team` with `lo <= sk <= hi`. async fn load_settings_range( state: &AppState, @@ -1887,7 +2046,7 @@ pub async fn get_analytics( .ok() .and_then(|r| r.item().map(|i| s(i, "since"))) }; - let (runs, reviews, lookups, traces, known, deploys, backfilled) = tokio::join!( + let (runs, reviews, lookups, traces, known, deploys, backfilled, metered) = tokio::join!( load_runs(&state, &team, whole), load_settings_range(&state, &team, &stat_lo, &stat_hi), load_settings_range(&state, &team, &log_lo, &log_hi), @@ -1895,6 +2054,7 @@ pub async fn get_analytics( load_known(&state, &team), load_settings_range(&state, &team, &dep_lo, &dep_hi), backfill_marker, + load_metered(&state, &team, whole), ); if backfilled.is_none() && claims.support_view.is_none() { ask_for_deploy_backfill(&state, &team).await; @@ -1933,6 +2093,7 @@ pub async fn get_analytics( &known, repo, ); + apply_metered(&mut out, &metered, window, prev, repo); let since = deploys_since(backfilled.as_deref(), &deploys); add_deploys( &mut out["comparison"], @@ -1957,6 +2118,118 @@ pub async fn get_analytics( Ok(Json(out)) } +#[cfg(test)] +mod metered_tests { + use super::*; + + fn day(day: &str, cost: f64, features: &[(&str, f64)]) -> MeteredDay { + MeteredDay { + day: day.into(), + cost_usd: cost, + tokens: cost * 1000.0, + features: features.iter().map(|(f, c)| (f.to_string(), *c)).collect(), + } + } + + fn page() -> (Value, Window, Window) { + let end = Utc.with_ymd_and_hms(2026, 10, 31, 0, 0, 0).unwrap(); + let (w, p) = Window::last_days(end, 2); + let out = json!({ + "summary": {"cost_usd": 78.08}, + "previous": {"cost_usd": 10.0}, + "daily": [ + {"day": "2026-10-29", "cost_usd": 78.08, "tokens": 5.0}, + {"day": "2026-10-30", "cost_usd": 0.0, "tokens": 0.0}, + ], + }); + (out, w, p) + } + + /// The day a dashboard showed $78 (the run records of runs started that + /// day) metered $168: run work on older runs and reviews included. + #[test] + fn the_cost_shown_is_the_metered_total_not_the_run_records() { + let (mut out, w, p) = page(); + let metered = vec![ + day( + "2026-10-29", + 168.48, + &[ + ("run", 126.20), + ("review", 35.65), + ("feedback", 3.90), + ("other", 2.73), + ], + ), + day("2026-10-30", 20.0, &[("review", 20.0)]), + day("2026-10-27", 5.0, &[("run", 5.0)]), + ]; + apply_metered(&mut out, &metered, w, p, None); + assert_eq!(out["summary"]["cost_usd"], json!(188.48)); + assert_eq!(out["summary"]["run_cost_usd"], json!(78.08)); + assert_eq!(out["summary"]["cost_basis"], "metered"); + assert_eq!( + out["summary"]["cost_by_feature"], + json!([ + {"feature": "run", "cost_usd": 126.2}, + {"feature": "review", "cost_usd": 55.65}, + {"feature": "feedback", "cost_usd": 3.9}, + {"feature": "other", "cost_usd": 2.73}, + ]) + ); + assert_eq!( + out["daily"], + json!([ + {"day": "2026-10-29", "cost_usd": 168.48, "run_cost_usd": 78.08, "tokens": 168480.0, "run_tokens": 5.0}, + {"day": "2026-10-30", "cost_usd": 20.0, "run_cost_usd": 0.0, "tokens": 20000.0, "run_tokens": 0.0}, + ]) + ); + assert_eq!(out["previous"]["cost_usd"], json!(5.0)); + assert_eq!(out["previous"]["cost_basis"], "metered"); + } + + #[test] + fn one_repository_or_no_meter_keeps_the_run_records() { + let (mut out, w, p) = page(); + apply_metered( + &mut out, + &[day("2026-10-29", 168.48, &[])], + w, + p, + Some("acme/shop"), + ); + assert_eq!(out["summary"]["cost_usd"], json!(78.08)); + assert_eq!(out["summary"]["cost_basis"], "runs"); + assert_eq!(out["daily"][0]["cost_usd"], json!(78.08)); + let (mut out, w, p) = page(); + apply_metered(&mut out, &[], w, p, None); + assert_eq!(out["summary"]["cost_basis"], "runs"); + assert_eq!(out["previous"]["cost_basis"], "runs"); + } + + #[test] + fn a_meter_item_reads_its_day_total_and_features() { + let mut i: Item = HashMap::new(); + i.insert("period".into(), av("DAY#2026-10-29")); + i.insert("total_cost_usd".into(), AttributeValue::N("168.48".into())); + i.insert("total_tokens".into(), AttributeValue::N("168480".into())); + i.insert( + "feature#review#cost_usd".into(), + AttributeValue::N("35.65".into()), + ); + i.insert( + "feature#review#tokens_out".into(), + AttributeValue::N("9".into()), + ); + assert_eq!( + MeteredDay::from_item(&i), + Some(day("2026-10-29", 168.48, &[("review", 35.65)])) + ); + i.insert("period".into(), av("2026-10")); + assert_eq!(MeteredDay::from_item(&i), None); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 3ca64db67..3d627b817 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -1942,7 +1942,19 @@ pub async fn retry_run( return Err(StatusCode::BAD_REQUEST); } - let ticket = retry_message(&state, &claims, item).await?; + let mut ticket = retry_message(&state, &claims, item).await?; + // The new run takes up this run's plan and the commits on its branch, + // unless the plan was what failed (Start over always starts over). + let text = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .map(|s| s.as_str()) + .unwrap_or("") + }; + let error = format!("{} {}", text("error_message"), text("error")); + if common::run_status::retry_resumes(text("current_pass"), &error) { + ticket.resume_from = Some(run_id.clone()); + } // Dashboard retry: force-delete existing lock so re-enqueue always succeeds delete_ticket_lock(&state, &claims.team_id, &ticket.ticket_id).await; let message = WorkerMessage::Ticket(ticket); diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index a21798177..777607135 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -3937,7 +3937,11 @@ fn review_delay_secs(action: &str) -> i32 { } } -const REVIEW_PUSH_SETTLE_SECS: i32 = 60; +/// Three minutes: a push is reviewed only after its PR has been quiet that +/// long (every later push's review supersedes it). At one minute, a person or +/// a fix loop pushing a few commits in a row still paid for a review of each +/// (226 re-reviews in 17 days came within 30 minutes of the previous one). +const REVIEW_PUSH_SETTLE_SECS: i32 = 180; /// How long a review claim blocks re-review of the SAME head. Sized to comfortably /// outlast the burst of webhook events GitHub fires for one commit (seconds), while diff --git a/services/worker/src/agent/anthropic.rs b/services/worker/src/agent/anthropic.rs index 4d7bf3fc9..42c811990 100644 --- a/services/worker/src/agent/anthropic.rs +++ b/services/worker/src/agent/anthropic.rs @@ -160,9 +160,15 @@ const BETA_FALLBACK_DEFAULT: &str = "server-side-fallback-2026-07-01"; /// with no minimum (the API default) every turn past the trigger cleared one /// old result near the START of the history and re-wrote nearly the whole /// context to the cache (1.25x input) instead of reading it (0.05x-0.1x). -const CLEAR_AT_LEAST_TOKENS: u64 = 50_000; +/// +/// Clears are rare and large: each one re-writes everything after the first +/// cleared result (16% of all cache writes in measured implement loops came +/// from clears at 120k), while a cleared token saves only a cache read (0.05x +/// of input) on each later turn. A clear of 100k pays for itself within a few +/// turns; one of 50k at 120k often never did. +const CLEAR_AT_LEAST_TOKENS: u64 = 100_000; /// Input size at which old tool results start being cleared. -const CLEAR_TRIGGER_TOKENS: u64 = 120_000; +const CLEAR_TRIGGER_TOKENS: u64 = 200_000; /// Most recent tool results always kept. const CLEAR_KEEP_TOOL_USES: u64 = 4; @@ -179,11 +185,68 @@ fn clear_tool_uses_edit() -> Value { } /// The top-level (automatic) breakpoint for a tool loop turn: only when -/// another turn may read it back. +/// another turn may read it back. Five minutes: turns follow each other +/// within seconds, and a 1-hour entry may never come after a 5-minute one. fn tail_cache(another_turn_may_follow: bool) -> Option { - another_turn_may_follow.then(|| CacheControl { - r#type: "ephemeral".to_string(), - }) + another_turn_may_follow.then(CacheControl::five_minutes) +} + +/// Where a system prompt's shared prefix ends. A caller that builds the +/// same opening for every pass of a run (the coder's rules, the repository's +/// and the team's instructions) puts this between it and what is particular +/// to the pass. The marker never reaches the model: the prompt is sent as +/// two blocks, the shared one cached for an hour, so a pass that starts +/// after a CI wait (often longer than five minutes) reads it instead of +/// writing it again (each pass wrote its own 30k-67k token opener). +pub const SHARED_PREFIX_END: &str = "\u{1f}"; + +/// The system blocks of a request: with [`SHARED_PREFIX_END`], the shared +/// prefix (1-hour cache) and the rest (5-minute cache); without it, one +/// block cached for five minutes, as before. +fn system_blocks(system: &str) -> Vec { + match system.split_once(SHARED_PREFIX_END) { + Some((shared, rest)) => { + let rest = rest.replace(SHARED_PREFIX_END, ""); + let mut blocks = vec![SystemBlock::Text { + text: shared.to_string(), + cache_control: Some(CacheControl::one_hour()), + }]; + if !rest.trim().is_empty() { + blocks.push(SystemBlock::Text { + text: rest, + cache_control: Some(CacheControl::five_minutes()), + }); + } + blocks + } + None => vec![SystemBlock::Text { + text: system.to_string(), + cache_control: Some(CacheControl::five_minutes()), + }], + } +} + +/// The tool definitions of a tool loop, the breakpoint on the last one. It +/// is cached for an hour when the system prompt has a shared prefix (tools +/// render before the system prompt, so the shared prefix is tools plus that +/// block), else for five minutes. +fn api_tools(tools: &[ToolDefinition], shared_prefix: bool) -> Vec { + tools + .iter() + .enumerate() + .map(|(i, t)| ApiTool { + name: t.name.clone(), + description: t.description.clone(), + input_schema: t.input_schema.clone(), + cache_control: (i == tools.len() - 1).then(|| { + if shared_prefix { + CacheControl::one_hour() + } else { + CacheControl::five_minutes() + } + }), + }) + .collect() } /// Fill the model-family fields of a request. `effort` None → "high". @@ -234,6 +297,26 @@ enum SystemBlock { #[derive(Serialize, Clone)] struct CacheControl { r#type: String, + /// `"1h"` for the 1-hour cache (written at 2x input instead of 1.25x); + /// absent for the default five minutes. + #[serde(skip_serializing_if = "Option::is_none")] + ttl: Option, +} + +impl CacheControl { + fn five_minutes() -> Self { + CacheControl { + r#type: "ephemeral".to_string(), + ttl: None, + } + } + + fn one_hour() -> Self { + CacheControl { + r#type: "ephemeral".to_string(), + ttl: Some("1h".to_string()), + } + } } #[derive(Serialize, Clone)] @@ -352,9 +435,7 @@ pub async fn converse_simple( max_tokens: 16384, system: vec![SystemBlock::Text { text: system.to_string(), - cache_control: Some(CacheControl { - r#type: "ephemeral".to_string(), - }), + cache_control: Some(CacheControl::five_minutes()), }], messages: vec![ApiMessage { role: "user".to_string(), @@ -542,9 +623,7 @@ fn json_request( max_tokens, system: vec![SystemBlock::Text { text: system, - cache_control: Some(CacheControl { - r#type: "ephemeral".to_string(), - }), + cache_control: Some(CacheControl::five_minutes()), }], messages: vec![ApiMessage { role: "user".to_string(), @@ -632,23 +711,9 @@ pub async fn converse_tool_loop( mut conversation_log: Option<&mut Vec>, ) -> Result> { let family = ModelFamily::of(model_id); - let api_tools: Vec = tools - .iter() - .enumerate() - .map(|(i, t)| ApiTool { - name: t.name.clone(), - description: t.description.clone(), - input_schema: t.input_schema.clone(), - // Cache breakpoint on the last tool — caches system + all tool defs - cache_control: if i == tools.len() - 1 { - Some(CacheControl { - r#type: "ephemeral".to_string(), - }) - } else { - None - }, - }) - .collect(); + // Cache breakpoint on the last tool: caches the tool definitions, which + // render before the system prompt. + let api_tools = api_tools(tools, system_prompt.contains(SHARED_PREFIX_END)); let mut turns: usize = 0; let mut deadline_warned = false; @@ -718,45 +783,15 @@ pub async fn converse_tool_loop( )); } - // Build API messages from our internal format - let api_messages: Vec = messages - .iter() - .map(|(role, content)| ApiMessage { - role: role.clone(), - content: content.clone(), - }) - .collect(); - - let mut request = MessagesRequest { - model: model_id.to_string(), + let request = tool_loop_request( + model_id, max_tokens, - system: vec![SystemBlock::Text { - text: system_prompt.to_string(), - cache_control: Some(CacheControl { - r#type: "ephemeral".to_string(), - }), - }], - messages: api_messages, - tools: if api_tools.is_empty() { - None - } else { - Some(api_tools.clone()) - }, - // Auto-cache: caches the entire prefix (tools + system + messages) - // up to the last cacheable block, so turn N+1 reads turns 1..N. - // Only when a turn N+1 can follow: on a call that is the last - // (no tools, or the answer-now turn) the tail would be written - // at 1.25x input and never read. The system and tool breakpoints - // still cache what other calls share. - cache_control: tail_cache(!api_tools.is_empty() && !answer_now), - thinking: None, - output_config: None, - context_management: None, - fallbacks: None, - tool_choice: answer_now.then(|| json!({"type": "none"})), - temperature: None, - }; - apply_model_family(&mut request, effort, true); + system_prompt, + messages, + &api_tools, + answer_now, + effort, + ); let response = send_request(client, &request, usage).await?; @@ -951,6 +986,85 @@ pub async fn converse_tool_loop( } } +/// One turn's request of the tool loop. Rendered in the order tools, +/// system, messages: the tools and the system prompt's shared prefix are the +/// same bytes on every turn and every pass that shares them; what changes +/// (the conversation) comes after the last of their breakpoints. History is +/// only ever appended to here. +fn tool_loop_request( + model_id: &str, + max_tokens: i32, + system_prompt: &str, + messages: &[(String, Vec)], + api_tools: &[ApiTool], + answer_now: bool, + effort: Option<&str>, +) -> MessagesRequest { + let api_messages: Vec = messages + .iter() + .map(|(role, content)| ApiMessage { + role: role.clone(), + content: content.clone(), + }) + .collect(); + let mut request = MessagesRequest { + model: model_id.to_string(), + max_tokens, + system: system_blocks(system_prompt), + messages: api_messages, + tools: if api_tools.is_empty() { + None + } else { + Some(api_tools.to_vec()) + }, + // Auto-cache: caches the entire prefix (tools + system + messages) + // up to the last cacheable block, so turn N+1 reads turns 1..N. + // Only when a turn N+1 can follow: on a call that is the last + // (no tools, or the answer-now turn) the tail would be written + // at 1.25x input and never read. The system and tool breakpoints + // still cache what other calls share. + cache_control: tail_cache(!api_tools.is_empty() && !answer_now), + thinking: None, + output_config: None, + context_management: None, + fallbacks: None, + tool_choice: answer_now.then(|| json!({"type": "none"})), + temperature: None, + }; + apply_model_family(&mut request, effort, true); + request +} + +/// The serialized bytes of a tool loop request's shared prefix: the tool +/// definitions and the system prompt's first block. Two passes that share +/// a prefix send these identically. +#[cfg(test)] +pub(crate) fn shared_prefix_bytes( + model_id: &str, + system_prompt: &str, + first_user_message: &str, + tools: &[ToolDefinition], +) -> (String, String) { + let messages = vec![( + "user".to_string(), + vec![json!({"type": "text", "text": first_user_message})], + )]; + let request = tool_loop_request( + model_id, + 16384, + system_prompt, + &messages, + &api_tools(tools, system_prompt.contains(SHARED_PREFIX_END)), + false, + None, + ); + let v = serde_json::to_value(&request).expect("a request serializes"); + ( + serde_json::to_string(&v["tools"]).unwrap(), + serde_json::to_string(&v["system"][0]).unwrap(), + ) +} + // --- Internal helpers --- /// Produce a short summary of tool input for live event display. @@ -1833,3 +1947,120 @@ mod accounting_tests { assert_eq!(b[0]["system"][0]["cache_control"]["type"], "ephemeral"); } } + +#[cfg(test)] +mod shared_prefix_tests { + use super::*; + + fn tool(name: &str) -> ToolDefinition { + ToolDefinition { + name: name.into(), + description: format!("{name} a file"), + input_schema: json!({"type": "object", "properties": {"path": {"type": "string"}}}), + } + } + + /// Every pass of a run (first implement, a review fix, a CI fix) opens + /// with the same tools and the same coder prompt; only the pass's own + /// sections and its first message differ. The bytes up to the shared + /// prefix's breakpoint must be identical, or each pass writes its + /// opener to the cache again. + #[test] + fn the_shared_prefix_is_the_same_bytes_in_every_pass() { + let core = crate::passes::implement::coder_system( + "acme", + "shop", + "## Rules\n- Keep handlers small", + "Use the acme style guide.", + "", + ); + let tools = vec![tool("read_file"), tool("write_file"), tool("run_checks")]; + let first = format!("{core}{SHARED_PREFIX_END}\n## Web\nhosts: shop.acme.test"); + let fix = format!("{core}{SHARED_PREFIX_END}\n## Web\nhosts: api.acme.test"); + let a = shared_prefix_bytes("claude-opus-5-5", &first, "Implement the plan.", &tools); + let b = shared_prefix_bytes( + "claude-opus-5-5", + &fix, + "Fix the review findings: the cursor skips rows.", + &tools, + ); + assert_eq!(a, b); + // The marker never reaches the model. + assert!(!a.1.contains(SHARED_PREFIX_END)); + } + + #[test] + fn the_shared_prefix_is_cached_for_an_hour_and_the_rest_for_five_minutes() { + let tools = vec![tool("read_file"), tool("write_file")]; + let system = format!("core rules{SHARED_PREFIX_END}pass sections"); + let messages = vec![( + "user".to_string(), + vec![json!({"type": "text", "text": "go"})], + )]; + let r = tool_loop_request( + "claude-opus-5-5", + 1024, + &system, + &messages, + &api_tools(&tools, true), + false, + None, + ); + let v = serde_json::to_value(&r).unwrap(); + // Tools render first, then the system blocks, then the messages: + // 1-hour entries come before every 5-minute one. + assert!(v["tools"][0].get("cache_control").is_none()); + assert_eq!( + v["tools"][1]["cache_control"], + json!({"type": "ephemeral", "ttl": "1h"}) + ); + assert_eq!(v["system"][0]["text"], "core rules"); + assert_eq!( + v["system"][0]["cache_control"], + json!({"type": "ephemeral", "ttl": "1h"}) + ); + assert_eq!(v["system"][1]["text"], "pass sections"); + assert_eq!( + v["system"][1]["cache_control"], + json!({"type": "ephemeral"}) + ); + assert_eq!(v["cache_control"], json!({"type": "ephemeral"})); + // At most four breakpoints. + let s = v.to_string(); + assert!(s.matches("\"cache_control\"").count() <= 4); + + // A caller without a shared prefix keeps one five-minute block. + let plain = tool_loop_request( + "claude-opus-5-5", + 1024, + "one prompt", + &messages, + &api_tools(&tools, false), + false, + None, + ); + let v = serde_json::to_value(&plain).unwrap(); + assert_eq!(v["system"].as_array().unwrap().len(), 1); + assert_eq!( + v["system"][0]["cache_control"], + json!({"type": "ephemeral"}) + ); + assert_eq!(v["tools"][1]["cache_control"], json!({"type": "ephemeral"})); + } + + #[test] + fn server_side_clearing_is_rare_and_large() { + let edit = clear_tool_uses_edit(); + let e = &edit["edits"][0]; + assert_eq!(e["trigger"]["value"], 200_000); + assert_eq!(e["clear_at_least"]["value"], 100_000); + } + + #[test] + fn the_coder_marks_its_shared_prefix() { + let src = include_str!("../passes/implement.rs"); + assert!(src.contains( + "let mut full_system = format!(\"{system}{}\", crate::agent::anthropic::SHARED_PREFIX_END);" + )); + } +} diff --git a/services/worker/src/models.rs b/services/worker/src/models.rs index 2d00c595b..67876413b 100644 --- a/services/worker/src/models.rs +++ b/services/worker/src/models.rs @@ -309,6 +309,8 @@ mod tests { continuation: 0, continuation_run_id: None, first_attempt_ms: 0, + resume_from: None, + retry_of_run: false, model_retries: 0, ticket_update_note: None, ticket_history_note: None, diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index d7574afea..8c1b16243 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -1628,6 +1628,8 @@ async fn start_fix_ticket( continuation: 0, continuation_run_id: None, first_attempt_ms: 0, + resume_from: None, + retry_of_run: false, model_retries: 0, ticket_update_note: None, ticket_history_note: None, @@ -1878,6 +1880,8 @@ pub async fn act(state: &WorkerState, a: TestAction) -> Result<(), Err> { continuation: 0, continuation_run_id: None, first_attempt_ms: 0, + resume_from: None, + retry_of_run: false, model_retries: 0, ticket_update_note: None, ticket_history_note: None, diff --git a/services/worker/src/passes/e2e_attribution.rs b/services/worker/src/passes/e2e_attribution.rs index 50f354ac2..da61ce86e 100644 --- a/services/worker/src/passes/e2e_attribution.rs +++ b/services/worker/src/passes/e2e_attribution.rs @@ -459,6 +459,8 @@ async fn start_fix( continuation: 0, continuation_run_id: None, first_attempt_ms: 0, + resume_from: None, + retry_of_run: false, model_retries: 0, ticket_update_note: None, ticket_history_note: None, diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 0bae227cd..78360559a 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -260,6 +260,8 @@ pub async fn run( continuation: 0, continuation_run_id: None, first_attempt_ms: 0, + resume_from: None, + retry_of_run: false, model_retries: 0, ticket_update_note: None, ticket_history_note: None, @@ -1530,7 +1532,7 @@ Rules: aws_sdk_dynamodb::types::AttributeValue::S(msg.run_id.clone()), ) .update_expression(format!( - "SET tokens_in = tokens_in + :ti, tokens_out = tokens_out + :to, \ + "SET tokens_in = if_not_exists(tokens_in, :zero) + :ti, tokens_out = if_not_exists(tokens_out, :zero) + :to, \ cache_read_tokens = if_not_exists(cache_read_tokens, :zero) + :crt, \ cache_write_tokens = if_not_exists(cache_write_tokens, :zero) + :cwt, \ cost_usd = if_not_exists(cost_usd, :zero) + :c, \ @@ -2896,6 +2898,8 @@ async fn handle_wrong_repo( continuation: 0, continuation_run_id: None, first_attempt_ms: 0, + resume_from: None, + retry_of_run: false, model_retries: 0, ticket_update_note: None, ticket_history_note: None, diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 2c9835ee3..d90bd98b1 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -219,7 +219,7 @@ pub async fn run( // holds work, and the agent must change it to match the new ticket. let continuation_note = if let Some(note) = msg.ticket_update_note.as_deref() { note - } else if msg.continuation > 0 { + } else if msg.continuation > 0 || msg.retry_of_run { "\n## CONTINUATION — a PRIOR attempt already committed partial work to THIS branch. \ Do NOT start over. Read the files you intend to touch to see what is already done, then \ complete ONLY the remaining work. Reuse existing correct code; never rewrite or restore it. \ @@ -482,8 +482,13 @@ pub async fn run( } } + // The coder's rules and the repository's and team's instructions are the + // same for every pass of the run (first implement, plan rounds, review, + // proof and CI fixes): they are the shared prefix, cached for an hour. + // Everything after it (the tools' sections, which read the plan) is the + // pass's own; the pass's task and feedback are in its first message. + let mut full_system = format!("{system}{}", crate::agent::anthropic::SHARED_PREFIX_END); // Add MCP context to system prompt - let mut full_system = system.clone(); if !loaded_mcp_plugins.is_empty() { let plugin_lines: Vec = loaded_mcp_plugins .iter() @@ -1112,7 +1117,7 @@ pub(super) const VERIFY_NOTE: &str = /// The coder's system prompt, the same for every task prompt (simple or /// not) and every round of the run, so it stays cached: the rules and repo /// instruction files, the team's instructions, then the test rule. -pub(super) fn coder_system( +pub(crate) fn coder_system( owner: &str, repo: &str, repo_context: &str, diff --git a/services/worker/src/passes/incidents/k_own_review_findings.rs b/services/worker/src/passes/incidents/k_own_review_findings.rs index 6a9aaf07f..717539199 100644 --- a/services/worker/src/passes/incidents/k_own_review_findings.rs +++ b/services/worker/src/passes/incidents/k_own_review_findings.rs @@ -11,8 +11,9 @@ //! the merge armed. The review lists them at the top of the description and //! requests changes; the run takes them in review-fix rounds; the next //! review resolves the threads the new commit settled. It goes on while the -//! rounds make progress, and two rounds without progress stop it with the -//! PR still a draft, the findings listed, and the run `needs_input`. A +//! rounds make progress, for at most two fix rounds; two rounds without +//! progress, or the cap, stop it with the PR still a draft, the findings +//! listed, and the run `needs_input`. A //! verdict is never APPROVE while a finding holds the merge. use super::fixture::*; @@ -121,20 +122,21 @@ fn the_run_fixes_them_in_rounds_and_stops_after_two_without_progress() { let resume = include_str!("../resume.rs"); // A review with open own findings fails the run's review: a fix round // follows, never ready_or_prove. - assert!(resume.contains("own_review::fix_feedback(&rr.open_findings")); + assert!(resume.contains("own_review::fix_feedback(\n")); + assert!(resume.contains("&rr.open_findings,")); let open = vec!["A (`a.py:1`)".to_string(), "B (`b.py:2`)".to_string()]; let mut end = Ending::default(); // Round 1 fixed one of three: progress, another round. assert_eq!( - own_review::next(Some(3), &open, 0, 0), + own_review::next(Some(3), &open, 0, 0, 0), Next::Fix { stalled: 0 } ); // Two rounds in a row with the same two open: stop. assert_eq!( - own_review::next(Some(2), &open, 0, 0), + own_review::next(Some(2), &open, 0, 0, 1), Next::Fix { stalled: 1 } ); - match own_review::next(Some(2), &open, 0, 1) { + match own_review::next(Some(2), &open, 0, 1, 1) { Next::Stop(reason) => { end.status = common::run_status::NEEDS_INPUT.into(); end.draft = true; @@ -147,6 +149,6 @@ fn the_run_fixes_them_in_rounds_and_stops_after_two_without_progress() { assert!(end.says("- A (`a.py:1`)")); assert!(end.says("stays a draft")); // Nothing open: ready. - assert_eq!(own_review::next(Some(2), &[], 1, 1), Next::Ready); + assert_eq!(own_review::next(Some(2), &[], 1, 1, 2), Next::Ready); end.never_says(OLD); } diff --git a/services/worker/src/passes/log_autofix.rs b/services/worker/src/passes/log_autofix.rs index 3cbd15300..527a11e62 100644 --- a/services/worker/src/passes/log_autofix.rs +++ b/services/worker/src/passes/log_autofix.rs @@ -113,6 +113,8 @@ impl StartEnv for WorkerEnv<'_> { continuation: 0, continuation_run_id: None, first_attempt_ms: 0, + resume_from: None, + retry_of_run: false, model_retries: 0, ticket_update_note: None, ticket_history_note: None, diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 73a0e3ecd..f54215a69 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -800,7 +800,7 @@ pub mod health_check; pub mod hidden_suggest; /// Hosted side of hybrid: forward a held event to a self-hosted install again. pub mod hybrid_name_check; -mod implement; +pub(crate) mod implement; #[cfg(test)] mod incidents; pub mod infra_analyze; @@ -1836,12 +1836,34 @@ async fn run_passes( // gave a different plan (memory and history read differently a few // minutes later) for a branch built on the first one. let same_run = msg.continuation > 0 || msg.model_retries > 0; + // A person's Retry of an earlier run (`resume_from`) takes up that + // run's plan the same way, and keeps the commits on its branch (below); + // the plan becomes this run's own, so a continuation of this run reuses + // it too. + let retried_from = msg + .resume_from + .clone() + .filter(|r| !same_run && !r.is_empty() && r != run_id); let own_plan = if same_run { load_run_plan(state, msg, run_id).await + } else if let Some(prev) = &retried_from { + let taken = load_run_plan(state, msg, prev).await; + if let Some(p) = &taken { + plan::mark_plan_run(state, msg, run_id).await; + save_run_triage(state, msg, run_id, &p.triage, &p.used_mcp_ids).await; + info!(run_id, retried = %prev, "Retry: taking up the earlier run's plan"); + } + taken } else { None }; let resumed_plan = own_plan.is_some(); + // The retry takes up the earlier run's branch only with its plan: the + // commits there were made against it. + let retry_keeps_branch = retried_from.is_some() && resumed_plan; + if retry_keeps_branch { + msg.retry_of_run = true; + } // Planning that ran out of time before its first plan keeps this run's // own triage (and what it resolved and recalled). let own_triage = if own_plan.is_none() && plan_resume.is_some() { @@ -3448,7 +3470,7 @@ async fn run_passes( // on it. That holds with an open pull request on the branch too: the // continuation used to go through create_branch there, which kept the // head but said "Created branch" in every step. - let keep_own_branch = same_run + let keep_own_branch = (same_run || retry_keeps_branch) && !skip_branch_reset && ticket_update_pr.is_none() && github @@ -11558,3 +11580,27 @@ mod start_failure_tests { ); } } + +#[cfg(test)] +mod retry_resume_tests { + /// A person's Retry takes up the earlier run's plan and the commits on + /// its branch: the plan is loaded from that run and made this run's own, + /// the branch isn't reset, and the coder is told it continues. + #[test] + fn a_retry_takes_up_the_earlier_runs_plan_and_branch() { + let src = include_str!("mod.rs"); + assert!(src.contains("let taken = load_run_plan(state, msg, prev).await;")); + assert!(src.contains("plan::mark_plan_run(state, msg, run_id).await;")); + assert!(src.contains("let keep_own_branch = (same_run || retry_keeps_branch)")); + assert!(include_str!("implement.rs") + .contains("} else if msg.continuation > 0 || msg.retry_of_run {")); + // The message carries it and serializes only when set. + let mut m = crate::models::TicketMessage::default(); + assert!(!serde_json::to_string(&m).unwrap().contains("resume_from")); + m.resume_from = Some("01RUN".into()); + let back: crate::models::TicketMessage = + serde_json::from_str(&serde_json::to_string(&m).unwrap()).unwrap(); + assert_eq!(back.resume_from.as_deref(), Some("01RUN")); + assert!(!back.retry_of_run); + } +} diff --git a/services/worker/src/passes/own_review.rs b/services/worker/src/passes/own_review.rs index c74bf8165..420661781 100644 --- a/services/worker/src/passes/own_review.rs +++ b/services/worker/src/passes/own_review.rs @@ -17,10 +17,14 @@ //! and the next review of the new head resolves the threads the commit //! settled and rewrites the section, or removes it when nothing is left. //! - It goes on while the rounds make progress (fewer open findings, or a -//! round that pushed changes). Two rounds in a row without progress stop -//! it ([`next`]), with the progress rule ticket runs use between steps: -//! the findings stay listed, the PR stays a draft, and the run waits on a -//! person (`needs_input`). +//! round that pushed changes), for at most [`MAX_FIX_ROUNDS`] rounds. Two +//! rounds in a row without progress, or the cap, stop it ([`next`]): the +//! findings stay listed, the PR stays a draft, and the run waits on a +//! person (`needs_input`). Uncapped, two runs spent $29 in 17 rounds +//! where the count of open findings went down by one and back up. +//! - Each round is told what the rounds before it found and looked up +//! ([`round_note`], [`fix_feedback`]), so it doesn't repeat the same +//! database and live-data lookups from scratch. //! //! People's PRs are unchanged: the findings are posted for the author. @@ -58,6 +62,28 @@ pub fn required(findings: &[Finding], held_late: &[Finding]) -> Vec { .collect() } +/// One line for an earlier review thread still open: its title (the first +/// line of the comment, without markdown emphasis) and where it is, as +/// [`required`] writes a finding. +pub fn thread_line(path: &str, line: u64, body: &str) -> String { + let title = body + .lines() + .map(|l| { + l.trim() + .trim_matches(|c| c == '*' || c == '#' || c == '_') + .trim() + }) + .find(|l| !l.is_empty()) + .unwrap_or("Earlier finding"); + let title = title.split_whitespace().collect::>().join(" "); + let title = common::truncate_str(&title, 160); + if line > 0 { + format!("{title} (`{path}:{line}`)") + } else { + format!("{title} (`{path}`)") + } +} + /// The description section listing them. Empty when nothing is open (the /// section is then removed). pub fn section(items: &[String]) -> String { @@ -99,6 +125,10 @@ pub fn hold(body: &str) -> Option { }) } +/// Fix rounds a run takes on its own review's findings before it hands the +/// PR to a person with the findings still listed. +pub const MAX_FIX_ROUNDS: u32 = 2; + /// What follows a review of CoderHelm's own PR. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Next { @@ -106,19 +136,29 @@ pub enum Next { Ready, /// Another fix round, with this many rounds without progress before it. Fix { stalled: u32 }, - /// Two rounds in a row made no progress: the run stops, the findings - /// stay listed and the PR stays a draft. + /// Two rounds in a row made no progress, or [`MAX_FIX_ROUNDS`] rounds + /// ran: the run stops, the findings stay listed and the PR stays a + /// draft. Stop(String), } /// What follows. `before`: the findings open at the previous review of /// this run (`None` at the first); `after`: those open now; /// `pushed_files`: what the last fix round changed; `stalled`: rounds -/// without progress so far. -pub fn next(before: Option, after: &[String], pushed_files: usize, stalled: u32) -> Next { +/// without progress so far; `rounds`: fix rounds this run already took. +pub fn next( + before: Option, + after: &[String], + pushed_files: usize, + stalled: u32, + rounds: u32, +) -> Next { if after.is_empty() { return Next::Ready; } + if rounds >= MAX_FIX_ROUNDS { + return Next::Stop(cap_reason(after)); + } let progress = before.is_none_or(|b| after.len() < b) || pushed_files > 0; if progress { return Next::Fix { stalled: 0 }; @@ -142,17 +182,92 @@ pub fn stop_reason(items: &[String]) -> String { ) } -/// What a fix round is told: every open finding, fixed now. -pub fn fix_feedback(items: &[String], review_body: &str) -> String { +/// Why the fix rounds stopped at the cap, with the findings still open. +pub fn cap_reason(items: &[String]) -> String { + let list: Vec = items.iter().map(|i| format!("- [ ] {i}")).collect(); + format!( + "Handed to a person: CoderHelm took {MAX_FIX_ROUNDS} fix rounds on its own review's \ + findings and these are still open:\n{}\nThe pull request stays a draft with them listed \ + under \"Open review findings\". Fix them, or say on the pull request why one doesn't \ + apply, then mark it ready.", + list.join("\n") + ) +} + +/// What a fix round is told: every open finding, fixed now, and what the +/// earlier rounds of this run found and looked up (`earlier`, from +/// [`round_note`]; empty on the first round). +pub fn fix_feedback(items: &[String], review_body: &str, earlier: &str) -> String { let todo: Vec = items.iter().map(|i| format!("- [ ] {i}")).collect(); + let earlier = earlier.trim(); + let carried = if earlier.is_empty() { + String::new() + } else { + format!( + "\n\n## Earlier fix rounds on this pull request\nWhat the rounds before this one \ + were asked to fix and what their lookups already returned. Build on it: don't run \ + a lookup again unless its answer may have changed.\n\n{earlier}" + ) + }; format!( "CoderHelm's own review of this pull request found the issues below. Fix every one \ now on this branch; none of them is optional. Where a finding can't be fixed in the \ - code, say why in the pull request description.\n\n{}\n\nThe review:\n\n{review_body}", + code, say why in the pull request description.\n\n{}\n\nThe review:\n\n{review_body}{carried}", todo.join("\n") ) } +/// The most a run carries from its earlier rounds, in bytes. +pub const MAX_CARRIED_BYTES: usize = 12_000; + +/// One fix round's record for the rounds after it: the findings it was +/// given, each lookup it made with what came back, and the coder's own +/// closing account. Appended to `earlier` and kept to the newest +/// [`MAX_CARRIED_BYTES`]. +pub fn round_note( + earlier: &str, + round: u32, + items: &[String], + lookups: &[super::proof::Lookup], + notes: &str, +) -> String { + let mut out = format!("### Round {round}\nAsked to fix:\n"); + for i in items { + out.push_str(&format!("- {i}\n")); + } + if !lookups.is_empty() { + out.push_str("Lookups and what came back:\n"); + for l in lookups { + out.push_str(&format!("{}\n", l.line.trim())); + } + } + let notes = notes.trim(); + if !notes.is_empty() { + out.push_str(&format!( + "The round's own account:\n{}\n", + common::truncate_str(notes, 2_000) + )); + } + let all = if earlier.trim().is_empty() { + out + } else { + format!("{}\n\n{out}", earlier.trim()) + }; + if all.len() <= MAX_CARRIED_BYTES { + return all; + } + // Keep the newest: drop from the front at a line boundary. + let mut cut = all.len() - MAX_CARRIED_BYTES; + while !all.is_char_boundary(cut) { + cut += 1; + } + let tail = &all[cut..]; + match tail.find('\n') { + Some(i) => tail[i + 1..].to_string(), + None => tail.to_string(), + } +} + #[cfg(test)] mod tests { use super::*; @@ -209,12 +324,12 @@ mod tests { #[test] fn rounds_go_on_while_they_make_progress_and_stop_after_two_without() { let two = vec!["a".to_string(), "b".to_string()]; - assert_eq!(next(Some(2), &[], 0, 1), Next::Ready); - assert_eq!(next(None, &two, 0, 0), Next::Fix { stalled: 0 }); - assert_eq!(next(Some(3), &two, 0, 1), Next::Fix { stalled: 0 }); - assert_eq!(next(Some(2), &two, 4, 1), Next::Fix { stalled: 0 }); - assert_eq!(next(Some(2), &two, 0, 0), Next::Fix { stalled: 1 }); - match next(Some(2), &two, 0, 1) { + assert_eq!(next(Some(2), &[], 0, 1, 1), Next::Ready); + assert_eq!(next(None, &two, 0, 0, 0), Next::Fix { stalled: 0 }); + assert_eq!(next(Some(3), &two, 0, 1, 1), Next::Fix { stalled: 0 }); + assert_eq!(next(Some(2), &two, 4, 1, 1), Next::Fix { stalled: 0 }); + assert_eq!(next(Some(2), &two, 0, 0, 1), Next::Fix { stalled: 1 }); + match next(Some(2), &two, 0, 1, 1) { Next::Stop(why) => { assert!(why.contains("- a\n- b")); assert!(why.contains("stays a draft")); @@ -222,4 +337,78 @@ mod tests { other => panic!("{other:?}"), } } + + #[test] + fn two_fix_rounds_at_most_then_a_person() { + let open = vec!["a (`x.rs:1`)".to_string(), "b (`y.rs:2`)".to_string()]; + // Progress every round still stops at the cap: one fewer open each + // time, or a round that pushed changes. + assert_eq!(next(Some(3), &open, 2, 0, 1), Next::Fix { stalled: 0 }); + match next(Some(3), &open, 2, 0, MAX_FIX_ROUNDS) { + Next::Stop(why) => { + assert!(why.contains("2 fix rounds")); + assert!(why.contains("- [ ] a (`x.rs:1`)\n- [ ] b (`y.rs:2`)")); + assert!(why.contains("stays a draft")); + } + other => panic!("{other:?}"), + } + // Nothing open is ready whatever the count. + assert_eq!(next(Some(1), &[], 0, 0, 9), Next::Ready); + } + + #[test] + fn each_round_carries_what_the_earlier_rounds_found_and_looked_up() { + use crate::passes::proof::{Lookup, LookupOutcome}; + let lookups = vec![Lookup::new( + "L1".into(), + "warehouse", + LookupOutcome::Answered, + "select count(*) from orders where status = 'open'", + "412", + )]; + let first = round_note( + "", + 1, + &["Watermark skips rows (`a.rs:3`)".into()], + &lookups, + "Fixed the cursor.", + ); + assert!(first.starts_with("### Round 1\nAsked to fix:\n- Watermark skips rows")); + assert!(first.contains("[L1]") && first.contains("412")); + assert!(first.contains("Fixed the cursor.")); + let second = round_note(&first, 2, &["Late bug (`b.rs`)".into()], &[], ""); + assert!(second.starts_with("### Round 1")); + assert!(second.contains("### Round 2\nAsked to fix:\n- Late bug")); + // The fix round's prompt carries them, after the review. + let fb = fix_feedback(&["Late bug (`b.rs`)".into()], "review body", &second); + let review_at = fb.find("review body").unwrap(); + let carried_at = fb.find("## Earlier fix rounds").unwrap(); + assert!(review_at < carried_at); + assert!(fb.contains("don't run a lookup again")); + // Nothing carried on the first round. + assert!(!fix_feedback(&["x".into()], "r", "").contains("Earlier fix rounds")); + // Bounded: the newest rounds are kept. + let mut big = String::new(); + for r in 1..200 { + big = round_note( + &big, + r, + &["same finding (`a.rs:1`)".into()], + &lookups, + "notes", + ); + } + assert!(big.len() <= MAX_CARRIED_BYTES); + assert!(big.contains("### Round 199")); + assert!(!big.contains("### Round 1\n")); + } + + #[test] + fn an_open_earlier_thread_is_listed_like_a_finding() { + assert_eq!( + thread_line("src/a.rs", 3, "**Watermark skips rows**\n\nThe cursor..."), + "Watermark skips rows (`src/a.rs:3`)" + ); + assert_eq!(thread_line("b.rs", 0, ""), "Earlier finding (`b.rs`)"); + } } diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index e2907fe14..40e3382f2 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -1155,8 +1155,11 @@ Then the ```fix_location.json block described above."#, "user".to_string(), vec![serde_json::json!({"type": "text", "text": revision_prompt(&advice)})], )); + // The revision answers the advice; it doesn't plan again + // from scratch, so it runs at the plan review's low effort. let one_turn = llm::ConverseOptions { max_turns: 1, + effort: Some(super::skills::review_effort("plan")), ..plan_opts }; match provider::converse( diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 3588481f3..2df55a0fb 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -2549,7 +2549,11 @@ pub async fn run( let summary = if rr.open_findings.is_empty() { format!("The PR reviewer requested changes:\n\n{}", rr.body) } else { - super::own_review::fix_feedback(&rr.open_findings, &rr.body) + super::own_review::fix_feedback( + &rr.open_findings, + &rr.body, + &own_review_progress(&run_record).notes, + ) }; review_result = review::ReviewResult { passed: false, @@ -2588,8 +2592,14 @@ pub async fn run( // progress; two rounds in a row without it stop the run with the // PR still a draft and the findings listed at its top. if !own_open.is_empty() { - let (before, stalled) = own_review_progress(&run_record); - match super::own_review::next(before, &own_open, 0, stalled) { + let progress = own_review_progress(&run_record); + match super::own_review::next( + progress.open_before, + &own_open, + 0, + progress.stalled, + progress.rounds, + ) { super::own_review::Next::Stop(reason) => { stop_on_own_findings( state, @@ -2613,6 +2623,7 @@ pub async fn run( &msg.run_id, own_open.len(), stalled, + progress.rounds.saturating_add(1), ) .await; } @@ -2751,13 +2762,14 @@ pub async fn run( open = own_open.len(), "Review fix produced no changes with own review findings open — reviewing again" ); - let (_, stalled) = own_review_progress(&run_record); + let progress = own_review_progress(&run_record); record_own_review_progress( state, &msg.team_id, &msg.run_id, own_open.len(), - stalled, + progress.stalled, + progress.rounds.saturating_add(1), ) .await; if set_run_awaiting_ci( @@ -2927,6 +2939,8 @@ async fn fix_context( continuation: 0, continuation_run_id: None, first_attempt_ms: 0, + resume_from: None, + retry_of_run: false, model_retries: 0, ticket_update_note: None, ticket_history_note: None, @@ -3164,7 +3178,18 @@ async fn run_fix_round( Ok(RoundEnd::Incomplete) } } - Ok(_) => { + Ok(r) => { + // What this round was asked and looked up reaches the next one. + if round.kind == run_round::Kind::ReviewFix { + record_own_round_note( + state, + &msg.team_id, + &msg.run_id, + &round.feedback, + &r.evidence, + ) + .await; + } // Done: the round's changes land on the pull request as one // commit, one push. let message = @@ -4697,21 +4722,39 @@ async fn mark_ready( error!(pr_number, "Failed to mark PR ready after 2 attempts"); } -/// The own-review progress the run recorded: findings open at the previous -/// review (`None` before the first) and rounds without progress so far. +/// The own-review progress a run recorded. +#[derive(Debug, Default, PartialEq)] +struct OwnReviewProgress { + /// Findings open at the previous review (`None` before the first). + open_before: Option, + /// Rounds without progress so far. + stalled: u32, + /// Fix rounds taken on the own review's findings. + rounds: u32, + /// What the earlier rounds were asked and looked up + /// (`own_review::round_note`). + notes: String, +} + fn own_review_progress( run_record: &std::collections::HashMap, -) -> (Option, u32) { +) -> OwnReviewProgress { let n = |k: &str| { run_record .get(k) .and_then(|v| v.as_n().ok()) .and_then(|v| v.parse::().ok()) }; - ( - n("own_review_open").map(|v| v as usize), - n("own_review_stalled").unwrap_or(0) as u32, - ) + OwnReviewProgress { + open_before: n("own_review_open").map(|v| v as usize), + stalled: n("own_review_stalled").unwrap_or(0) as u32, + rounds: n("own_review_rounds").unwrap_or(0) as u32, + notes: run_record + .get("own_review_notes") + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default(), + } } /// Records the own-review progress on the run. Best-effort. @@ -4721,6 +4764,7 @@ async fn record_own_review_progress( run_id: &str, open: usize, stalled: u32, + rounds: u32, ) { if let Err(e) = state .dynamo @@ -4728,9 +4772,12 @@ async fn record_own_review_progress( .table_name(&state.config.runs_table_name) .key("team_id", attr_s(team_id)) .key("run_id", attr_s(run_id)) - .update_expression("SET own_review_open = :o, own_review_stalled = :s") + .update_expression( + "SET own_review_open = :o, own_review_stalled = :s, own_review_rounds = :r", + ) .expression_attribute_values(":o", attr_n(open as u64)) .expression_attribute_values(":s", attr_n(stalled as u64)) + .expression_attribute_values(":r", attr_n(rounds as u64)) .send() .await { @@ -4738,6 +4785,71 @@ async fn record_own_review_progress( } } +/// The findings a review-fix round was asked to fix: the `- [ ]` lines +/// `own_review::fix_feedback` writes before the review itself. +fn own_round_items(feedback: &str) -> Vec { + let head = feedback.split("\n\nThe review:\n\n").next().unwrap_or(""); + head.lines() + .filter_map(|l| l.trim().strip_prefix("- [ ] ")) + .map(|l| l.trim().to_string()) + .filter(|l| !l.is_empty()) + .collect() +} + +/// Adds a finished review-fix round to what the run's next round is told +/// (`own_review::round_note`): the findings, its lookups and its account. +/// Best-effort. +async fn record_own_round_note( + state: &WorkerState, + team_id: &str, + run_id: &str, + feedback: &str, + evidence: &super::proof::RunEvidence, +) { + let items = own_round_items(feedback); + if items.is_empty() { + return; + } + let earlier = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("own_review_notes") + .send() + .await + .ok() + .and_then(|o| { + o.item() + .and_then(|i| i.get("own_review_notes")) + .and_then(|v| v.as_s().ok()) + .cloned() + }) + .unwrap_or_default(); + let round = earlier.matches("### Round ").count() as u32 + 1; + let notes = super::own_review::round_note( + &earlier, + round, + &items, + &evidence.lookups, + evidence.latest_notes(), + ); + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET own_review_notes = :n") + .expression_attribute_values(":n", attr_s(¬es)) + .send() + .await + { + warn!(run_id, error = %e, "Could not record the fix round's notes (non-fatal)"); + } +} + /// The run stops with its own review's findings still open: it says which /// and why, waits on a person (`needs_input`, never `completed`), and the PR /// stays a draft with them listed at its top. @@ -4832,6 +4944,22 @@ async fn complete_run_with_status( // The team's counters already have these tokens: each model call is // counted as it happens (common::usage). info!(run_id, status, "Run completed"); + // CoderHelm's own pushes during the run weren't reviewed by the PR + // reviewer (`review_scope::own_loop_holds_push`): a run that hands its + // PR over asks for the review of its head now. A head the run's own ask + // already reviewed costs nothing (its verdict stands). + if status == common::run_status::COMPLETED { + if let Some((owner, repo, number)) = common::pr_outcome::parse_pr_url(pr_url) { + super::review_pr::review_on_handoff( + state, + &msg.team_id, + msg.installation_id, + (&owner, &repo, number), + run_id, + ) + .await; + } + } Ok(()) } @@ -5152,3 +5280,44 @@ mod end_status_tests { ); } } + +#[cfg(test)] +mod own_round_tests { + use super::*; + + #[test] + fn a_round_records_what_it_was_asked_and_the_next_reads_it_back() { + let feedback = super::super::own_review::fix_feedback( + &["A (`a.rs:1`)".into(), "B (`b.rs`)".into()], + "- [ ] a checklist in the review body is not a finding", + "### Round 1\nAsked to fix:\n- A (`a.rs:1`)\n", + ); + assert_eq!( + own_round_items(&feedback), + vec!["A (`a.rs:1`)".to_string(), "B (`b.rs`)".to_string()] + ); + let mut record = std::collections::HashMap::new(); + record.insert("own_review_open".to_string(), AttributeValue::N("2".into())); + record.insert( + "own_review_rounds".to_string(), + AttributeValue::N("1".into()), + ); + record.insert( + "own_review_notes".to_string(), + AttributeValue::S("### Round 1".into()), + ); + assert_eq!( + own_review_progress(&record), + OwnReviewProgress { + open_before: Some(2), + stalled: 0, + rounds: 1, + notes: "### Round 1".into(), + } + ); + assert_eq!( + own_review_progress(&std::collections::HashMap::new()), + OwnReviewProgress::default() + ); + } +} diff --git a/services/worker/src/passes/review_eval.rs b/services/worker/src/passes/review_eval.rs index 983f48ef9..bed83acdf 100644 --- a/services/worker/src/passes/review_eval.rs +++ b/services/worker/src/passes/review_eval.rs @@ -375,6 +375,7 @@ impl Sim { reconcile_note: None, outstanding_work: None, description_hash: None, + full_review: false, } } diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 49556a127..6f068469f 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -1046,6 +1046,16 @@ async fn run_once( }; *reviewed_head = head_sha.clone(); + // CoderHelm's own push while its run is still fixing the PR: the run + // asks for the verdict itself when CI is green, and hands the PR over + // for review if it ends without one. A person's push is reviewed. + if msg.trigger == super::review_scope::TRIGGER_PUSH && super::is_own_login(pr_author) { + if let Some(reason) = own_loop_hold(state, &github, &msg, &head_sha).await { + info!(pr = msg.pr_number, head = %head_sha, "CoderHelm's own push during its run's fix loop — not reviewed now"); + return Ok(Outcome::Skipped { reason }); + } + } + // A review started by a description edit reads the description as it is // now. When later edits left text this commit was already reviewed with // (an edit after the queued review read it queues its own), it doesn't @@ -1096,6 +1106,39 @@ async fn run_once( } } + // A run's handoff and the PR's ready-for-review event can ask for the + // same commit together: the handoff takes the per-commit claim the + // gateway's push and ready reviews take, so only one of them runs. + if msg.trigger == super::review_scope::HANDOFF_TRIGGER && pr["draft"].as_bool() == Some(true) { + // Still a draft (a proof running, a check holding it): the review + // runs when it is marked ready, as every PR's does. + return Ok(Outcome::Skipped { + reason: "Still a draft: reviewed when it is marked ready.".into(), + }); + } + if msg.trigger == super::review_scope::HANDOFF_TRIGGER && !head_sha.is_empty() { + let sk = super::review_policy::head_claim_sk( + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + &head_sha, + ); + if common::claim::claim( + &state.dynamo, + &state.config.settings_table_name, + &msg.team_id, + &sk, + REVIEW_HEAD_CLAIM_SECS, + ) + .await + == common::claim::Claim::Held + { + return Ok(Outcome::Skipped { + reason: "This commit is already being reviewed.".into(), + }); + } + } + // Real work starts here: the dashboard shows the PR as being reviewed. live_job.reviewing(state, &msg, &head_sha, title).await; @@ -1613,13 +1656,20 @@ async fn run_once( } // A push after CoderHelm approved an earlier commit is reviewed from that - // commit: only what changed since. One that changed no code or data is - // not reviewed at all and the approval stands. A push after a request - // for changes (or questions) gets a full review. + // commit: only what changed since. One that changed no code or data, or + // left the PR's own change as approved (merges of the base branch, or a + // rebase onto it), is not reviewed at all and the approval stands. A + // push after a review that didn't approve is reviewed from that review's + // commit too: only the hunks changed since, with the earlier findings' + // status; it never approves without a full review first. let mut review_diff = diff.clone(); - // The PR's own change is the one CoderHelm approved: every commit since - // brought in only the base branch (merges of work already merged there). + // The PR's own change is the one CoderHelm reviewed: every commit since + // brought in only the base branch (merges of work already merged there, + // or a rebase onto it). let mut own_change_unchanged = false; + // The commit a hunks-only re-review starts from. + let mut since_review: Option = None; + let unconfirmed_in_body = review_agent::unconfirmed_external_facts(pr_body, &[]); if let Some(approved) = super::review_scope::approved_base( &msg.trigger, msg.question.is_some(), @@ -1630,11 +1680,13 @@ async fn run_once( .get_diff(&msg.repo_owner, &msg.repo_name, &approved, &head_sha) .await { - Ok(since) if super::review_scope::builds_on(&since) => { + Ok(since) => { let short = &approved[..approved.len().min(7)]; - let unconfirmed = review_agent::unconfirmed_external_facts(pr_body, &[]); - // Merges of the base branch change code, but not the PR's: - // compare the PR's own change now with the one approved. + let ahead = super::review_scope::builds_on(&since); + // Merges of the base branch change code, but not the PR's, + // and a rebase onto it leaves the approved commit off the + // branch: compare the PR's own change now with the one + // approved, whichever happened. own_change_unchanged = match github .get_diff(&msg.repo_owner, &msg.repo_name, base, &approved) .await @@ -1646,8 +1698,8 @@ async fn run_once( } }; let nothing_new = - !super::review_scope::touches_code(&since) || own_change_unchanged; - if nothing_new && unconfirmed.is_empty() { + (ahead && !super::review_scope::touches_code(&since)) || own_change_unchanged; + if nothing_new && unconfirmed_in_body.is_empty() { info!(pr = msg.pr_number, approved = %approved, head = %head_sha, own_change_unchanged, "Push changed none of the PR's code or data since the approval — review skipped, approval carried"); // Many repos dismiss approvals when commits are pushed: // post the approval again on this head, so the PR never @@ -1697,27 +1749,78 @@ async fn run_once( // marks unconfirmed: the change itself is the approved one. info!(pr = msg.pr_number, approved = %approved, head = %head_sha, "Only the base branch came in since the approval — re-checking the PR's unconfirmed facts"); review_diff = format!( - "(CoderHelm approved {short} earlier. Every commit since only merges the \ - base branch: the PR's own change below is the one approved. Review \ + "(CoderHelm approved {short} earlier. Every commit since only brings in \ + the base branch: the PR's own change below is the one approved. Review \ nothing new in it; triage the facts the description marks \ unconfirmed.)\n{diff}" ); - } else { + } else if ahead { info!(pr = msg.pr_number, approved = %approved, head = %head_sha, files = ?super::review_scope::code_files(&since), "Reviewing only what changed since the approval"); review_diff = format!( "(CoderHelm approved {short} earlier. This review covers only what \ changed since then; the rest of the PR was reviewed and approved.)\n{}", review_agent::format_diff(&since, 40_000) ); + } else { + info!(pr = msg.pr_number, approved = %approved, "Approved commit isn't an ancestor of the head (rebased) and the change differs — full review"); } } - Ok(_) => { - info!(pr = msg.pr_number, approved = %approved, "Approved commit isn't an ancestor of the head (rebased) — full review"); - } Err(e) => { warn!(pr = msg.pr_number, error = %e, "Could not read the diff since the approval — full review"); } } + } else if let Some(reviewed) = super::review_scope::reviewed_base( + &msg.trigger, + msg.question.is_some(), + msg.full_review, + &records, + &head_sha, + ) { + let short = reviewed[..reviewed.len().min(7)].to_string(); + own_change_unchanged = match github + .get_diff(&msg.repo_owner, &msg.repo_name, base, &reviewed) + .await + { + Ok(at_review) => super::review_scope::same_own_change(&at_review, &compare), + Err(_) => false, + }; + if own_change_unchanged && unconfirmed_in_body.is_empty() { + let verdict = records + .iter() + .find(|r| r.is_review() && !r.failed()) + .map(|r| r.verdict.to_lowercase().replace('_', " ")) + .unwrap_or_default(); + info!(pr = msg.pr_number, reviewed = %reviewed, head = %head_sha, "Push left the PR's own change as reviewed — review skipped, verdict stands"); + return Ok(Outcome::Skipped { + reason: format!( + "Not reviewed: the commits since CoderHelm reviewed {short} only bring in \ + the base branch, and the PR's own change is the one reviewed, so that \ + review's verdict ({verdict}) stands." + ), + }); + } + if !own_change_unchanged { + match github + .get_diff(&msg.repo_owner, &msg.repo_name, &reviewed, &head_sha) + .await + { + Ok(since) if super::review_scope::builds_on(&since) => { + info!(pr = msg.pr_number, reviewed = %reviewed, head = %head_sha, files = ?super::review_scope::code_files(&since), "Reviewing only the hunks changed since the previous review"); + review_diff = format!( + "{}\n{}", + super::review_scope::since_review_note(&reviewed), + review_agent::format_diff(&since, 40_000) + ); + since_review = Some(reviewed.clone()); + } + Ok(_) => { + info!(pr = msg.pr_number, reviewed = %reviewed, "Reviewed commit isn't an ancestor of the head (rebased) — full review"); + } + Err(e) => { + warn!(pr = msg.pr_number, error = %e, "Could not read the diff since the previous review — full review"); + } + } + } } // Fold this team's past 👎 feedback into the prompt so the reviewer learns and // stops repeating rejected comment styles ("leave comments to learn"). @@ -2477,17 +2580,50 @@ async fn run_once( // every finding that isn't strictly optional is its own to fix before // the PR is marked ready or the merge armed: the review requests changes // and lists them at the top of the description (`own_review`). - let own_open = if self_authored { + let mut own_open = if self_authored { super::own_review::required(&findings, &held_late) } else { Vec::new() }; + // A hunks-only re-review reports the earlier findings by status, not as + // findings again: those still open that hold the merge stay listed. + if self_authored && since_review.is_some() { + for t in prior_threads + .iter() + .filter(|t| !fixed_threads.iter().any(|f| f.id == t.id)) + .filter(|t| review_agent::thread_holds_merge(&t.body)) + { + let line = super::own_review::thread_line(&t.path, t.line, &t.body); + if !own_open.contains(&line) { + own_open.push(line); + } + } + } let verdict = super::review_severity::consistent_verdict(stable.verdict, &findings); let verdict = if own_open.is_empty() { verdict } else { "REQUEST_CHANGES" }; + // A hunks-only re-review never approves: the whole PR is reviewed first. + if super::review_scope::needs_full_before_approval(since_review.is_some(), verdict) { + let mut full = msg.clone(); + full.full_review = true; + full.dedup_key = format!("full#{head_sha}"); + // Its model calls are already on the team's counters (per call). + if enqueue_review(state, &full, 0).await { + info!(pr = msg.pr_number, head = %head_sha, "Hunks-only re-review found nothing holding the merge — full review queued before approving"); + return Ok(Outcome::Skipped { + reason: "The changes since the previous review settle what it found; the whole \ + pull request is reviewed again before it is approved." + .into(), + }); + } + warn!( + pr = msg.pr_number, + "Could not queue the full review — posting this one" + ); + } if self_authored { let section = super::own_review::section(&own_open); let updated = super::completeness::with_section( @@ -3171,6 +3307,7 @@ pub async fn review_for_run( reconcile_note: None, outstanding_work: None, description_hash: None, + full_review: false, }; let mut reviewed_head = head_sha.to_string(); let job = LiveJob::start(); @@ -3218,8 +3355,9 @@ pub async fn review_for_run( /// How many self-review → self-fix rounds CoderHelm runs on its OWN PR before it /// gives up and hands to a human. Bounds the review↔fix loop so a flip-flopping /// verdict can't churn commits/reviews forever (one PR hit 67 commits / 44 reviews -/// oscillating APPROVE↔REQUEST_CHANGES). -const MAX_SELF_REVIEW_FIX_ROUNDS: u32 = 3; +/// oscillating APPROVE↔REQUEST_CHANGES). The same cap as the run's own fix +/// rounds (`own_review::MAX_FIX_ROUNDS`). +const MAX_SELF_REVIEW_FIX_ROUNDS: u32 = super::own_review::MAX_FIX_ROUNDS; /// Claim one self-review→fix round for this PR (atomic conditional increment). /// True while under MAX_SELF_REVIEW_FIX_ROUNDS (proceed with the fix); false once @@ -3565,6 +3703,96 @@ pub(crate) async fn lookup_run_by_pr( .flatten() } +/// Why a push to CoderHelm's own PR isn't reviewed now, when it isn't: the +/// push is CoderHelm's and the run that owns the PR is still in its review +/// and fix loop (`review_scope::own_loop_holds_push`). Any lookup that fails +/// reviews the push. +async fn own_loop_hold( + state: &WorkerState, + github: &GitHubClient, + msg: &ReviewMessage, + head: &str, +) -> Option { + let commits = github + .list_pr_commits(&msg.repo_owner, &msg.repo_name, msg.pr_number) + .await + .ok()?; + let by_coderhelm = + super::review_scope::head_commit_login(&commits, head).is_some_and(super::is_own_login); + if !by_coderhelm { + return None; + } + let run_id = lookup_run_by_pr( + state, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + ) + .await?; + let item = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("run_id", attr_s(&run_id)) + .projection_expression("#s") + .expression_attribute_names("#s", "status") + .send() + .await + .ok()?; + let status = item + .item() + .and_then(|i| i.get("status")) + .and_then(|v| v.as_s().ok()) + .cloned(); + super::review_scope::own_loop_holds_push(&msg.trigger, true, true, status.as_deref()).then( + || { + "Not reviewed now: CoderHelm pushed this while its run is still fixing the pull \ + request. The run asks for the review itself when its checks pass, and the pull \ + request is reviewed when the run hands it over." + .to_string() + }, + ) +} + +/// The review a run asks for when it hands its PR over without the PR +/// reviewer's verdict on its last head: CoderHelm's own pushes during the +/// run weren't reviewed (`own_loop_hold`). The job reads the PR's head when +/// it runs, and a head already reviewed returns its verdict with no model +/// work (`review_policy::start`). Best-effort. +pub(crate) async fn review_on_handoff( + state: &WorkerState, + team_id: &str, + installation_id: u64, + (owner, repo, pr_number): (&str, &str, u64), + run_id: &str, +) { + if pr_number == 0 || owner.is_empty() || repo.is_empty() { + return; + } + let Some(label) = enabled_trigger_label(state, team_id, owner, repo).await else { + return; + }; + let msg = ReviewMessage { + team_id: team_id.to_string(), + installation_id, + repo_owner: owner.to_string(), + repo_name: repo.to_string(), + pr_number, + label, + trigger: super::review_scope::HANDOFF_TRIGGER.to_string(), + dedup_key: format!("handoff#{run_id}"), + ..Default::default() + }; + if enqueue_review(state, &msg, 0).await { + info!( + pr = pr_number, + run_id, "Run handed its PR over — review queued" + ); + } +} + /// CoderHelm's most recent review of a PR. struct LastReview { verdict: String, @@ -4307,6 +4535,7 @@ mod superseded_tests { reconcile_note: None, outstanding_work: None, description_hash: None, + full_review: false, } } @@ -4666,6 +4895,7 @@ mod failure_tests { reconcile_note: None, outstanding_work: None, description_hash: None, + full_review: false, } } diff --git a/services/worker/src/passes/review_scope.rs b/services/worker/src/passes/review_scope.rs index 5cb8a1a6c..8bf7f5f4c 100644 --- a/services/worker/src/passes/review_scope.rs +++ b/services/worker/src/passes/review_scope.rs @@ -33,6 +33,88 @@ pub fn approved_base( .then(|| latest.head_sha.clone()) } +/// The commit a push's re-review starts from when CoderHelm's latest review +/// of an earlier commit did not approve (it asked for changes, or left +/// questions): that review's head. The push is then reviewed from there, +/// only the hunks changed since plus the status of the earlier findings, +/// instead of the whole PR again. `None` for anything but a push, for a +/// person's question, a forced full review, the same head, or no earlier +/// review. An approved latest review is [`approved_base`]'s. +pub fn reviewed_base( + trigger: &str, + is_question: bool, + full_review: bool, + records_newest_first: &[ReviewRecord], + head: &str, +) -> Option { + if trigger != TRIGGER_PUSH || is_question || full_review { + return None; + } + let latest = records_newest_first + .iter() + .find(|r| r.is_review() && !r.failed())?; + (latest.verdict != "APPROVE" && !latest.head_sha.is_empty() && latest.head_sha != head) + .then(|| latest.head_sha.clone()) +} + +/// The note a hunks-only re-review's diff starts with. +pub fn since_review_note(reviewed: &str) -> String { + let short = &reviewed[..reviewed.len().min(7)]; + format!( + "(CoderHelm reviewed {short} earlier and did not approve it. This review covers only \ + what changed since {short}, plus the status of each earlier finding listed under \ + \"Earlier review threads\"; the rest of the PR was reviewed at {short}. A full review \ + of the whole PR runs before any approval.)" + ) +} + +/// A hunks-only re-review that would approve doesn't post: the whole PR is +/// reviewed first, so an approval always rests on a full review. +pub fn needs_full_before_approval(since_review: bool, verdict: &str) -> bool { + since_review && verdict == "APPROVE" +} + +/// CoderHelm's own PR, a push made by CoderHelm, while the run that owns +/// the PR is still in its own review and fix loop (`running` or +/// `awaiting_ci`): the run asks the PR reviewer for its verdict itself once +/// CI is green (`review_pr::review_for_run`), and a run that ends without +/// it hands the PR over for review ([`HANDOFF_TRIGGER`]). Reviewing each of +/// its intermediate pushes as well paid twice for the same code. A person's +/// push, or a run that has ended, is reviewed as always. +pub fn own_loop_holds_push( + trigger: &str, + self_authored: bool, + head_by_coderhelm: bool, + run_status: Option<&str>, +) -> bool { + trigger == TRIGGER_PUSH + && self_authored + && head_by_coderhelm + && matches!( + run_status, + Some(common::run_status::RUNNING) | Some(common::run_status::AWAITING_CI) + ) +} + +/// The trigger of the review a run asks for when it hands its PR over +/// without the PR reviewer's verdict on the last head. +pub const HANDOFF_TRIGGER: &str = "handoff"; + +/// The author login of `head` in a PR's commit list (oldest first), when the +/// list holds it. +pub fn head_commit_login<'a>(commits: &'a [Value], head: &str) -> Option<&'a str> { + commits + .iter() + .rev() + .find(|c| c["sha"].as_str() == Some(head)) + .map(|c| { + c["author"]["login"] + .as_str() + .or_else(|| c["committer"]["login"].as_str()) + .unwrap_or("") + }) +} + /// The approved commit is an ancestor of the head (the compare is `ahead`). /// After a force-push or rebase it isn't, and the diff since it means /// nothing: review the whole PR. @@ -448,4 +530,157 @@ mod tests { assert!(!same_own_change(&no_patch, &no_patch)); assert!(!same_own_change(&json!({}), &json!({}))); } + + #[test] + fn a_push_after_a_change_request_is_reviewed_from_the_reviewed_commit() { + let requested = [ + record("REQUEST_CHANGES", "REQUEST_CHANGES", "ccc"), + record("APPROVE", "APPROVE", "aaa"), + ]; + assert_eq!( + reviewed_base(TRIGGER_PUSH, false, false, &requested, "ddd"), + Some("ccc".into()) + ); + // Questions left: the same. + let questions = [record("COMMENT", "COMMENT", "ccc")]; + assert_eq!( + reviewed_base(TRIGGER_PUSH, false, false, &questions, "ddd"), + Some("ccc".into()) + ); + // An approval is approved_base's; a forced full review, a question, + // another trigger, the same head or no review: none. + let approved = [record("APPROVE", "APPROVE", "aaa")]; + assert_eq!( + reviewed_base(TRIGGER_PUSH, false, false, &approved, "bbb"), + None + ); + assert_eq!( + reviewed_base(TRIGGER_PUSH, false, true, &requested, "ddd"), + None + ); + assert_eq!( + reviewed_base(TRIGGER_PUSH, true, false, &requested, "ddd"), + None + ); + assert_eq!( + reviewed_base("ready_for_review", false, false, &requested, "ddd"), + None + ); + assert_eq!( + reviewed_base(TRIGGER_PUSH, false, false, &requested, "ccc"), + None + ); + assert_eq!(reviewed_base(TRIGGER_PUSH, false, false, &[], "ddd"), None); + assert!(since_review_note("ccc1234567").contains("only what changed since ccc1234")); + } + + #[test] + fn an_approval_always_rests_on_a_full_review() { + assert!(needs_full_before_approval(true, "APPROVE")); + assert!(!needs_full_before_approval(true, "REQUEST_CHANGES")); + assert!(!needs_full_before_approval(false, "APPROVE")); + } + + #[test] + fn coderhelms_own_pushes_wait_while_its_run_is_in_its_loop() { + use common::run_status::*; + // Its own push while the run fixes and waits on CI: not reviewed. + assert!(own_loop_holds_push(TRIGGER_PUSH, true, true, Some(RUNNING))); + assert!(own_loop_holds_push( + TRIGGER_PUSH, + true, + true, + Some(AWAITING_CI) + )); + // A person's push to the same PR is reviewed. + assert!(!own_loop_holds_push( + TRIGGER_PUSH, + true, + false, + Some(RUNNING) + )); + // The run ended (handed over, waiting on a person) or no run: reviewed. + for s in [COMPLETED, NEEDS_INPUT, FAILED, CANCELLED, CLOSED] { + assert!(!own_loop_holds_push(TRIGGER_PUSH, true, true, Some(s))); + } + assert!(!own_loop_holds_push(TRIGGER_PUSH, true, true, None)); + // A person's PR, or another trigger (marked ready, a handoff): reviewed. + assert!(!own_loop_holds_push( + TRIGGER_PUSH, + false, + true, + Some(RUNNING) + )); + assert!(!own_loop_holds_push( + "ready_for_review", + true, + true, + Some(RUNNING) + )); + assert!(!own_loop_holds_push( + HANDOFF_TRIGGER, + true, + true, + Some(RUNNING) + )); + } + + #[test] + fn the_head_commits_author_is_read_from_the_commit_list() { + let commits = vec![ + json!({"sha": "a", "author": {"login": "acme-dev"}}), + json!({"sha": "b", "author": null, "committer": {"login": "coderhelm[bot]"}}), + ]; + assert_eq!(head_commit_login(&commits, "a"), Some("acme-dev")); + assert_eq!(head_commit_login(&commits, "b"), Some("coderhelm[bot]")); + assert_eq!(head_commit_login(&commits, "zzz"), None); + } + + /// Cost budget: a re-review after a request for changes reads only the + /// hunks changed since, so what it sends is a small part of a full + /// review's diff. A typical fix push touches one hunk of a 12-file PR. + #[test] + fn a_hunks_only_re_review_sends_a_fraction_of_the_full_diff() { + let hunk = |i: usize| { + let mut p = format!("@@ -1,40 +1,40 @@ fn handler_{i}()\n"); + for l in 0..40 { + p.push_str(&format!("- let value_{l} = old_call_{i}({l});\n")); + p.push_str(&format!("+ let value_{l} = new_call_{i}({l}, &ctx);\n")); + } + p + }; + let full = json!({"status": "ahead", "files": (0..12) + .map(|i| file(&format!("src/h{i}.rs"), "modified", Some(&hunk(i)))) + .collect::>()}); + let fix = json!({"status": "ahead", "files": [file( + "src/h3.rs", + "modified", + Some("@@ -7,1 +7,1 @@ fn handler_3()\n- let value_6 = new_call_3(6, &ctx);\n+ let value_6 = new_call_3(6, &ctx)?;"), + )]}); + let format = crate::passes::review_agent::format_diff; + let full_diff = format(&full, 40_000); + let since = format!("{}\n{}", since_review_note("ccc1234"), format(&fix, 40_000)); + // Under a tenth of the full review's diff. + assert!( + since.len() * 10 < full_diff.len(), + "hunks-only {} vs full {}", + since.len(), + full_diff.len() + ); + } + + /// The reviewer uses all of it: its own pushes wait during the run's + /// loop, a push after a non-approving review is reviewed from that + /// review, and that review never approves without a full one. + #[test] + fn the_reviewer_wires_the_scopes_in() { + let src = include_str!("review_pr.rs"); + assert!(src.contains("own_loop_hold(state, &github, &msg, &head_sha).await")); + assert!(src.contains("super::review_scope::reviewed_base(")); + assert!(src.contains( + "super::review_scope::needs_full_before_approval(since_review.is_some(), verdict)" + )); + assert!(src.contains("full.full_review = true;")); + assert!(include_str!("resume.rs").contains("super::review_pr::review_on_handoff(")); + } } diff --git a/services/worker/src/passes/review_sweep.rs b/services/worker/src/passes/review_sweep.rs index 42f604dbd..9d6a0d71f 100644 --- a/services/worker/src/passes/review_sweep.rs +++ b/services/worker/src/passes/review_sweep.rs @@ -411,6 +411,7 @@ fn sweep_message( reconcile_note: None, outstanding_work: None, description_hash: None, + full_review: false, } } diff --git a/services/worker/src/passes/skills.rs b/services/worker/src/passes/skills.rs index 9d5ba2dd2..d4181ac08 100644 --- a/services/worker/src/passes/skills.rs +++ b/services/worker/src/passes/skills.rs @@ -776,7 +776,7 @@ impl TeamSkills { question, context, host, - (ASK_TIMEOUT, ASK_CONTEXT_CHARS), + (ASK_TIMEOUT, ASK_CONTEXT_CHARS, ASK_EFFORT), ) .await; let Some(answer) = c.answer else { @@ -825,7 +825,7 @@ impl TeamSkills { question: &str, context: &str, host: &super::agent_tools::Host<'_>, - (limit, context_chars): (std::time::Duration, usize), + (limit, context_chars, effort): (std::time::Duration, usize, &'static str), ) -> Consult { let st = self.store(state); let mut out = Consult { @@ -895,6 +895,7 @@ impl TeamSkills { common::truncate_str(context, context_chars), &tools, &bounded, + effort, ); let reply = match tokio::time::timeout(limit, call).await { Ok(r) => r, @@ -993,7 +994,7 @@ impl TeamSkills { &question, draft, host, - (REVIEW_TIMEOUT, REVIEW_CONTEXT_CHARS), + (REVIEW_TIMEOUT, REVIEW_CONTEXT_CHARS, review_effort(step)), ) .await; Review { @@ -1455,6 +1456,20 @@ struct AgentReply { ms: i64, } +/// How hard a team agent thinks on a question a run or a person asks it. +const ASK_EFFORT: &str = "medium"; + +/// How hard a team agent thinks when it reviews a step's draft. A plan is +/// read at low effort: plan reviews cost about 13k output tokens each at +/// high effort for advice the planner weighs, not a verdict. The diff and +/// other steps keep medium. +pub fn review_effort(step: &str) -> &'static str { + match step { + "plan" => "low", + _ => ASK_EFFORT, + } +} + /// Puts one question to a team agent: its brief as instructions, the team's /// own model, only `tools` (the read-only ones its file lists that this ask /// can run, through `executor`), capped in calls, length and time. Used by a @@ -1470,6 +1485,7 @@ async fn answer_as_agent( context: &str, tools: &[ToolDefinition], executor: &dyn crate::agent::llm::ToolExecutor, + effort: &'static str, ) -> AgentReply { let started = std::time::Instant::now(); let mut reply = AgentReply { @@ -1531,7 +1547,7 @@ async fn answer_as_agent( }, max_tokens: ASK_MAX_TOKENS, deadline: None, - effort: Some("medium"), + effort: Some(effort), }, None, None, @@ -1585,6 +1601,7 @@ pub async fn try_ask( // it's sent, as an agent that lists no tools always does. &[], &NoTools, + ASK_EFFORT, ) .await } @@ -2371,3 +2388,18 @@ mod tests { assert!(q.contains("'none'")); } } + +#[cfg(test)] +mod review_effort_tests { + use super::*; + + #[test] + fn a_plan_is_reviewed_at_low_effort_and_everything_else_as_before() { + assert_eq!(review_effort("plan"), "low"); + assert_eq!(review_effort("code"), "medium"); + assert_eq!(review_effort("pr_description"), "medium"); + // The plan's revision turn after the review runs at the same effort. + let src = include_str!("plan.rs"); + assert!(src.contains("effort: Some(super::skills::review_effort(\"plan\"))")); + } +}