From 357e332468e28743df772cfc0447aa51d23013fd Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 15 Nov 2026 13:37:18 -0500 Subject: [PATCH 1/3] Cut model spend: cache what reviews and feedback share, per-team review route Reviews and feedback rounds put per-PR text (recalled memories, examples, the prompt variant) inside their one system block, so no two ever shared a cached prefix. A marker now splits each system prompt at the boundary between what holds for the whole repository and what was picked for this pull request; the tools and the repository part are cached for an hour. The text the model reads is unchanged (tests check the joined blocks and the byte-identical prefixes). Reviews can be written on the measured lighter model per team (review_model_route: measured_light, critic stays on the strongest), off by default. route_review_real_live replays a team's own past reviews, exported outside the repository by scripts/export_real_review_cases.py, and scores accepted-finding recall, blocking recall, severity agreement and dismissed findings raised again. --- scripts/export_real_review_cases.py | 218 ++++++++++++ services/gateway/src/routes/api.rs | 103 ++++-- services/worker/src/agent/anthropic.rs | 112 +++++++ services/worker/src/agent/provider.rs | 75 ++++- services/worker/src/passes/feedback.rs | 68 ++-- .../worker/src/passes/model_route_eval.rs | 312 ++++++++++++++++++ .../worker/src/passes/review_cases/README.md | 24 ++ services/worker/src/passes/review_eval.rs | 21 +- services/worker/src/passes/review_pr.rs | 27 +- services/worker/src/passes/skills.rs | 1 + 10 files changed, 906 insertions(+), 55 deletions(-) create mode 100644 scripts/export_real_review_cases.py diff --git a/scripts/export_real_review_cases.py b/scripts/export_real_review_cases.py new file mode 100644 index 000000000..00bdbe99b --- /dev/null +++ b/scripts/export_real_review_cases.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python3 +"""Export a team's past reviews as replay cases for the reviewer route eval. + +Usage: + AWS_PROFILE= python3 scripts/export_real_review_cases.py \ + --team 'TEAM#...' --since 2026-11-01 --out /path/outside/the/repo [--limit 60] + +For each review CoderHelm posted since --since, it reads the REVIEW# record +(the findings, where they were anchored, whether they held the merge) from +the settings table, and from GitHub (the `gh` CLI, the operator's own login) +the pull request's diff at the reviewed head, the changed files at that head, +the repository's instruction files and the review threads CoderHelm opened. +Each finding whose fate is clear becomes the answer: + + accepted the thread went outdated (the code under it changed after the + comment) or a person replied agreeing; + dismissed the thread was resolved, or answered by a person, with the code + under it unchanged, and the pull request was merged or closed. + +Findings with no thread or an open, unanswered one are left out. A review +with no finding of known fate is skipped. + +The cases hold the team's code: they are written only to --out, which must +be outside this repository, and are never committed. Run the eval with +`EVAL_REAL_CASES= cargo test -p worker route_review_real_live -- --ignored` +once per reviewer model (EVAL_REVIEW_MODEL) and compare the summaries. +""" + +import argparse +import json +import os +import re +import subprocess +import sys + +import boto3 + +INSTRUCTION_FILES = ["AGENTS.md", "CLAUDE.md", ".github/copilot-instructions.md", "CODERHELM.md"] +AGREE = re.compile(r"\b(good catch|fixed|done|agreed|addressed|will fix|updated)\b", re.I) +NEAR = 6 +MAX_FILE_BYTES = 200_000 + + +def gh(args, ok_missing=False): + r = subprocess.run(["gh", "api", *args], capture_output=True, text=True) + if r.returncode != 0: + if ok_missing: + return None + raise SystemExit(f"gh api {' '.join(args)}: {r.stderr.strip()}") + return json.loads(r.stdout) if r.stdout.strip() else None + + +def threads(repo, pr): + owner, name = repo.split("/", 1) + q = """query($o:String!,$n:String!,$p:Int!,$c:String){repository(owner:$o,name:$n){ + pullRequest(number:$p){state merged reviewThreads(first:100,after:$c){ + pageInfo{hasNextPage endCursor} + nodes{isResolved isOutdated path line originalLine + comments(first:20){nodes{author{login} body createdAt + reactions(first:20){nodes{content}}}}}}}}}""" + out, cursor, state = [], None, None + while True: + args = ["graphql", "-f", f"query={q}", "-F", f"o={owner}", "-F", f"n={name}", "-F", f"p={pr}"] + if cursor: + args += ["-F", f"c={cursor}"] + d = gh(args)["data"]["repository"]["pullRequest"] + state = "MERGED" if d["merged"] else d["state"] + page = d["reviewThreads"] + out += page["nodes"] + if not page["pageInfo"]["hasNextPage"]: + return out, state + cursor = page["pageInfo"]["endCursor"] + + +def is_bot(login): + return login.endswith("[bot]") or "coderhelm" in login.lower() + + +def fate(thread, pr_state): + """accepted, dismissed or None for a CoderHelm thread.""" + comments = thread["comments"]["nodes"] + people = [c for c in comments[1:] if not is_bot((c.get("author") or {}).get("login", ""))] + reactions = [r["content"] for r in comments[0].get("reactions", {}).get("nodes", [])] if comments else [] + if thread["isOutdated"] or any(AGREE.search(c["body"]) for c in people) or "THUMBS_UP" in reactions: + return "accepted" + settled = pr_state in ("MERGED", "CLOSED") + if settled and (thread["isResolved"] or people or "THUMBS_DOWN" in reactions): + return "dismissed" + return None + + +def match(finding, thread_list): + for t in thread_list: + line = t.get("originalLine") or t.get("line") + if t["path"] == finding["file"] and line and abs(int(line) - int(finding["line"])) <= NEAR: + return t + return None + + +def case_for(repo, pr, record, findings, thread_list, pr_state): + head = record["head_sha"] + accepted, dismissed = [], [] + for f in findings: + if not f.get("file") or not f.get("line"): + continue + t = match(f, thread_list) + if not t: + continue + k = {"file": f["file"], "line": int(f["line"]), + "blocking": f.get("tier") == "blocking" or f.get("severity") == "blocking" or bool(f.get("blocks"))} + v = fate(t, pr_state) + if v == "accepted": + accepted.append(k) + elif v == "dismissed": + dismissed.append(k) + if not accepted and not dismissed: + return None + pull = gh(["repos/" + repo + "/pulls/" + str(pr)]) + compare = gh([f"repos/{repo}/compare/{pull['base']['ref']}...{head}"], ok_missing=True) + if not compare: + return None + diff, files, changed = "", {}, 0 + for f in compare.get("files", []): + path = f["filename"] + changed += f.get("additions", 0) + f.get("deletions", 0) + diff += f"\n### {path} ({f['status']}, +{f.get('additions', 0)}/-{f.get('deletions', 0)})\n{f.get('patch', '(no textual diff)')}\n" + if f["status"] != "removed": + body = raw(repo, path, head) + if body is not None: + files[path] = body + instructions = "" + for p in INSTRUCTION_FILES: + body = raw(repo, p, head) + if body: + instructions += f"\n\n# {p}\n{body}" + return { + "name": f"{repo.split('/')[1]}-{pr}-{head[:8]}", + "title": record.get("pr_title", ""), + "body": pull.get("body") or "", + "diff": diff, + "files": files, + "instructions": instructions.strip(), + "accepted": accepted, + "dismissed": dismissed, + "lines_changed": changed, + } + + +def raw(repo, path, ref): + r = subprocess.run( + ["gh", "api", "-H", "Accept: application/vnd.github.raw", f"repos/{repo}/contents/{path}?ref={ref}"], + capture_output=True, text=True) + if r.returncode != 0 or len(r.stdout) > MAX_FILE_BYTES: + return None + return r.stdout + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--team", required=True) + ap.add_argument("--since", required=True, help="YYYY-MM-DD") + ap.add_argument("--out", required=True) + ap.add_argument("--stage", default="prod") + ap.add_argument("--limit", type=int, default=60) + a = ap.parse_args() + + out = os.path.realpath(a.out) + repo_root = os.path.realpath(os.path.join(os.path.dirname(__file__), "..")) + if out == repo_root or out.startswith(repo_root + os.sep): + raise SystemExit("--out must be outside the repository: the cases hold the team's code") + os.makedirs(out, exist_ok=True) + + table = boto3.resource("dynamodb").Table(f"coderhelm-{a.stage}-settings") + items, kwargs = [], {} + while True: + r = table.query( + KeyConditionExpression="pk = :p AND begins_with(sk, :s)", + ExpressionAttributeValues={":p": a.team, ":s": "REVIEW#"}, + **kwargs, + ) + items += r["Items"] + if "LastEvaluatedKey" not in r: + break + kwargs = {"ExclusiveStartKey": r["LastEvaluatedKey"]} + + reviews = [] + for it in items: + when = it["sk"].rsplit("#", 1)[-1] + if when < a.since or it.get("record_type", "review") != "review" or not it.get("findings"): + continue + findings = json.loads(it["findings"]) + if findings: + reviews.append((when, it["repo"], int(it["pr_number"]), it, findings)) + reviews.sort(key=lambda r: r[0], reverse=True) + + written, seen_threads = 0, {} + for _, repo, pr, record, findings in reviews: + if written >= a.limit: + break + key = (repo, pr) + if key not in seen_threads: + t, state = threads(repo, pr) + seen_threads[key] = ([x for x in t if x["comments"]["nodes"] + and is_bot((x["comments"]["nodes"][0].get("author") or {}).get("login", ""))], state) + bot_threads, state = seen_threads[key] + case = case_for(repo, pr, record, findings, bot_threads, state) + if not case: + continue + with open(os.path.join(out, case["name"] + ".json"), "w") as fh: + json.dump(case, fh, indent=1) + written += 1 + print(f"{case['name']}: {len(case['accepted'])} accepted, {len(case['dismissed'])} dismissed", + file=sys.stderr) + print(f"{written} cases in {out}", file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index d49ec6915..89019ba1c 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -6035,11 +6035,67 @@ pub async fn get_model_provider( "api_key_masked": api_key_masked, "primary_model": current(&primary_saved), "heavy_model": current(&heavy_saved), + "review_model_route": review_model_route(saved("review_model_route").as_deref()), "retired_models": retired, "deployment_provider": deployment_provider(), }))) } +/// Which model writes the team's reviews: "strongest" (the default) or +/// "measured_light" (the review written on the lighter measured model, its +/// critic on the strongest; see the worker's `ReviewRoute`). Anything else +/// reads as the default. +fn review_model_route(v: Option<&str>) -> &'static str { + match v.map(str::trim) { + Some("measured_light") => "measured_light", + _ => "strongest", + } +} + +/// The route a save keeps: the one in the request when it names one (an +/// unknown name is refused), else the one saved before, so a client that +/// doesn't know the field never resets it. +fn review_route_to_save(body: &Value, saved: Option<&str>) -> Result<&'static str, StatusCode> { + match body.get("review_model_route").and_then(|v| v.as_str()) { + Some("strongest") => Ok("strongest"), + Some("measured_light") => Ok("measured_light"), + Some(_) => Err(StatusCode::BAD_REQUEST), + None => Ok(review_model_route(saved)), + } +} + +#[cfg(test)] +mod review_route_tests { + use super::*; + + #[test] + fn the_review_route_is_strongest_until_a_team_picks_the_measured_one() { + assert_eq!(review_model_route(None), "strongest"); + assert_eq!(review_model_route(Some("sonnet")), "strongest"); + assert_eq!(review_model_route(Some("measured_light")), "measured_light"); + // A save without the field keeps what was saved. + let none = json!({"primary_model": "claude-sonnet-5-5"}); + assert_eq!(review_route_to_save(&none, None), Ok("strongest")); + assert_eq!( + review_route_to_save(&none, Some("measured_light")), + Ok("measured_light") + ); + // A save with it sets it; an unknown name is refused. + let light = json!({"review_model_route": "measured_light"}); + assert_eq!(review_route_to_save(&light, None), Ok("measured_light")); + let back = json!({"review_model_route": "strongest"}); + assert_eq!( + review_route_to_save(&back, Some("measured_light")), + Ok("strongest") + ); + let bad = json!({"review_model_route": "haiku"}); + assert_eq!( + review_route_to_save(&bad, None), + Err(StatusCode::BAD_REQUEST) + ); + } +} + /// How this deployment calls Claude: "bedrock" (its own AWS account, no team /// key needed) or "anthropic" (each team's key). fn deployment_provider() -> &'static str { @@ -6074,6 +6130,27 @@ pub async fn update_model_provider( return Err(StatusCode::BAD_REQUEST); } + let existing = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(&claims.team_id)) + .key("sk", attr_s("SETTINGS#MODEL_PROVIDER")) + .send() + .await + .map_err(|e| { + error!("Failed to fetch existing model provider: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + let saved = |k: &str| { + existing + .item() + .and_then(|item| item.get(k)) + .and_then(|v| v.as_s().ok()) + .cloned() + }; + let review_route = review_route_to_save(&body, saved("review_model_route").as_deref())?; + // On Bedrock the install's own role calls the model: only the model // choices are saved, with no key to check. if common::model_provider::is_bedrock() { @@ -6087,6 +6164,7 @@ pub async fn update_model_provider( .item("provider", attr_s(provider)) .item("primary_model", attr_s(primary_model)) .item("heavy_model", attr_s(heavy_model)) + .item("review_model_route", attr_s(review_route)) .item("updated_at", attr_s(&now)) .send() .await @@ -6098,27 +6176,9 @@ pub async fn update_model_provider( } // If no new key provided, try to reuse existing one - let api_key = if let Some(key) = api_key_from_body { - key - } else { - let existing = state - .dynamo - .get_item() - .table_name(&state.config.settings_table_name) - .key("pk", attr_s(&claims.team_id)) - .key("sk", attr_s("SETTINGS#MODEL_PROVIDER")) - .send() - .await - .map_err(|e| { - error!("Failed to fetch existing model provider: {e}"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - existing - .item() - .and_then(|item| item.get("api_key")) - .and_then(|v| v.as_s().ok()) - .cloned() - .ok_or(StatusCode::BAD_REQUEST)? + let api_key = match api_key_from_body { + Some(key) => key, + None => saved("api_key").ok_or(StatusCode::BAD_REQUEST)?, }; // Validate the key (and its access to the chosen model) via the Models API @@ -6166,6 +6226,7 @@ pub async fn update_model_provider( .item("api_key", attr_s(&api_key)) .item("primary_model", attr_s(primary_model)) .item("heavy_model", attr_s(heavy_model)) + .item("review_model_route", attr_s(review_route)) .item("updated_at", attr_s(&now)) .send() .await diff --git a/services/worker/src/agent/anthropic.rs b/services/worker/src/agent/anthropic.rs index 73d057b79..93f8b1cac 100644 --- a/services/worker/src/agent/anthropic.rs +++ b/services/worker/src/agent/anthropic.rs @@ -2838,6 +2838,118 @@ mod shared_prefix_tests { assert_eq!(v["tools"][1]["cache_control"], json!({"type": "ephemeral"})); } + /// The texts of the system blocks a prompt is sent as. + fn system_texts(system_prompt: &str) -> Vec { + system_blocks(system_prompt) + .into_iter() + .map(|SystemBlock::Text { text, .. }| text) + .collect() + } + + /// Two reviews of different pull requests in one repository: the tools + /// and the system prompt up to the per-PR part (examples, prompt variant, + /// recalled memories) are the same bytes, so the second review reads them + /// from the cache. The model still reads the same text as before: the + /// blocks joined are the prompt without the marker. + #[test] + fn two_reviews_in_a_repository_share_their_prefix() { + use crate::passes::{review_agent, review_pr}; + let repo_wide = "\n\n## Repository instructions\n- Handlers stay small\n\ + ## Team rules\n- Every migration is reversible"; + let pr_a = + "\n## Examples\n- Good: names the caller\n## Memory\n- PR #12: retries are idempotent"; + let pr_b = + "\n## Prompt variant\nBe brief.\n## Memory\n- PR #40: the cache key has the tenant"; + let tools = review_agent::review_tools(); + let prompt = |this_pr: &str| { + review_agent::review_system_prompt( + "acme", + "web", + &review_pr::review_instructions_block(repo_wide, this_pr), + true, + ) + }; + let (a, b) = (prompt(pr_a), prompt(pr_b)); + let pa = shared_prefix_bytes( + "claude-opus-5-5", + &a, + "PR: Fix the cursor\n(diff a)", + &tools, + ); + let pb = shared_prefix_bytes("claude-opus-5-5", &b, "PR: Add a cache\n(diff b)", &tools); + assert_eq!(pa, pb, "tools and the repository's prompt are identical"); + assert!( + pa.0.contains("\"ttl\":\"1h\""), + "the tools are cached for an hour" + ); + assert!(pa.1.contains("\"ttl\":\"1h\"")); + assert!(pa.1.contains("Every migration is reversible")); + for part in [pr_a, pr_b, "When done exploring"] { + assert!( + !pa.1.contains(part.trim()), + "{part} is after the shared prefix" + ); + } + assert!(!pa.1.contains(SHARED_PREFIX_END)); + // The text the model reads is what it read before the split. + for this_pr in [pr_a, pr_b] { + let before = review_agent::review_system_prompt( + "acme", + "web", + &format!("{repo_wide}{this_pr}"), + true, + ); + assert_eq!(system_texts(&prompt(this_pr)).concat(), before); + } + } + + /// Two feedback rounds whose recalled memories differ share the tools + /// and the role, voice, team and rules part of the system prompt. + #[test] + fn two_feedback_rounds_share_their_prefix() { + use crate::passes::feedback::feedback_system_prompt; + let tools = vec![tool("read_file"), tool("edit_file"), tool("reply")]; + let round = |memory: &str| { + feedback_system_prompt( + "acme", + "web", + " Match the team's voice: short.", + "\n## Team rules\n- Reversible migrations", + "", + memory, + ) + "\n\n## Web\nhosts: shop.acme.test" + }; + let a = round("\n## Memory\n- tests run with make test"); + let b = round("\n## Memory\n- the API retries twice"); + let pa = shared_prefix_bytes( + "claude-sonnet-5-5", + &a, + "A reviewer left comments on PR #3", + &tools, + ); + let pb = shared_prefix_bytes( + "claude-sonnet-5-5", + &b, + "A reviewer left comments on PR #9", + &tools, + ); + assert_eq!(pa, pb); + assert!(pa.1.contains("Reversible migrations") && !pa.1.contains("Memory")); + // Joined, the blocks are the prompt as it was before the marker. + assert_eq!(system_texts(&a).concat(), a.replace(SHARED_PREFIX_END, ""),); + assert_eq!(a.matches(SHARED_PREFIX_END).count(), 1); + } + + /// The review and feedback passes build their prompts through the + /// functions the tests above check. + #[test] + fn reviews_and_feedback_mark_their_shared_prefix() { + let review = include_str!("../passes/review_pr.rs"); + assert!(review.contains("let instructions_block = review_instructions_block(")); + let feedback = include_str!("../passes/feedback.rs"); + assert!(feedback.contains("let system = feedback_system_prompt(")); + } + #[test] fn server_side_clearing_is_rare_and_large() { let edit = clear_tool_uses_edit(); diff --git a/services/worker/src/agent/provider.rs b/services/worker/src/agent/provider.rs index 3f196a386..005f84b48 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -19,6 +19,10 @@ pub struct ModelProvider { /// runs on it; otherwise the routes measured to hold their quality on a /// lighter model (`MEASURED_LIGHT_MODEL`) run there. pub heavy_model_chosen: bool, + /// Which model writes the team's pull request reviews (Settings, Model + /// Provider, `review_model_route`). The strongest model unless the team + /// switched to the measured route. + pub review_route: ReviewRoute, /// Counts this team's model calls (set by `load_for_team`). Required: /// there is no provider, so no client, whose calls go uncounted. pub meter: common::usage::UsageMeter, @@ -83,6 +87,11 @@ impl ModelProvider { .filter(|m| !m.trim().is_empty()) .map(|m| common::model_ids::current(m).to_string()) .unwrap_or_else(|| "claude-opus-5-5".to_string()); + let review_route = ReviewRoute::parse( + item.get("review_model_route") + .and_then(|v| v.as_s().ok()) + .map(String::as_str), + ); info!(team_id, "Loaded Anthropic provider"); let analytics_table = std::env::var("ANALYTICS_TABLE_NAME").unwrap_or_default(); @@ -97,6 +106,7 @@ impl ModelProvider { primary_model, heavy_model, heavy_model_chosen, + review_route, meter: common::usage::UsageMeter::dynamo(dynamo.clone(), &analytics_table, team_id), scope: super::policy::PolicyScope { team: team_id.to_string(), @@ -141,9 +151,14 @@ impl ModelProvider { /// The reviewer's reading and writing of a review (`generate_review`). /// It decides what the findings are and so what a review holds the merge - /// on: a judgment step, on [`Self::judgment_model_id`]. + /// on: a judgment step, on [`Self::judgment_model_id`], unless the team + /// chose the measured route. The critic that decides which findings are + /// kept, and so what blocks, stays on the judgment model either way. pub fn review_model_id(&self) -> &str { - self.judgment_model_id() + match self.review_route { + ReviewRoute::Strongest => self.judgment_model_id(), + ReviewRoute::MeasuredLight => MEASURED_LIGHT_MODEL, + } } /// Every judgment step: the stop judge, planner decisions, the reviewer's @@ -209,6 +224,29 @@ impl ModelProvider { /// a review holds the merge on); it is back on the strongest model. pub const MEASURED_LIGHT_MODEL: &str = "claude-sonnet-5-5"; +/// Which model writes a team's reviews. `Strongest` (the default, and what +/// any value but `measured_light` reads as) keeps them on the judgment model. +/// `MeasuredLight` writes them on [`MEASURED_LIGHT_MODEL`] with the critic on +/// the judgment model, the configuration the synthetic measurement +/// (`passes/model_route_eval.rs`, `route_review_live`) scored at the same +/// recall at about half the cost. A team turns it on only after the replay of +/// its own past reviews (`route_review_real_live`) holds. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum ReviewRoute { + #[default] + Strongest, + MeasuredLight, +} + +impl ReviewRoute { + pub fn parse(v: Option<&str>) -> Self { + match v.map(str::trim) { + Some("measured_light") => ReviewRoute::MeasuredLight, + _ => ReviewRoute::Strongest, + } + } +} + /// A heavy route that may run on [`MEASURED_LIGHT_MODEL`]: writing code for /// a medium ticket (an edit, not a judgment). #[derive(Debug, Clone, Copy)] @@ -326,6 +364,7 @@ mod client_tests { primary_model: "claude-haiku-4-5".into(), heavy_model: heavy.into(), heavy_model_chosen: chosen, + review_route: ReviewRoute::Strongest, meter: common::usage::UsageMeter::memory("t").0, scope: Default::default(), } @@ -353,4 +392,36 @@ mod client_tests { // The measured model is one this release calls. assert!(common::model_ids::is_selectable(MEASURED_LIGHT_MODEL)); } + + #[test] + fn reviews_stay_on_the_strongest_model_unless_the_team_switches() { + // Nothing saved, or anything but the measured route's name: strongest. + for saved in [ + None, + Some(""), + Some("strongest"), + Some("sonnet"), + Some("Measured_Light"), + ] { + assert_eq!( + ReviewRoute::parse(saved), + ReviewRoute::Strongest, + "{saved:?}" + ); + } + assert_eq!( + ReviewRoute::parse(Some("measured_light")), + ReviewRoute::MeasuredLight + ); + let mut p = provider("claude-opus-5-5", false); + assert_eq!(p.review_model_id(), "claude-opus-5-5"); + p.review_route = ReviewRoute::MeasuredLight; + // The review is written on the measured model; every judgment step, + // the critic's included (it runs on the heavy model), stays. + assert_eq!(p.review_model_id(), MEASURED_LIGHT_MODEL); + assert_eq!(p.judgment_model_id(), "claude-opus-5-5"); + assert_eq!(p.heavy_model_id(), "claude-opus-5-5"); + let src = include_str!("../passes/review_agent.rs"); + assert!(src.contains("provider::converse_simple(\n state,\n provider,\n provider.heavy_model_id(),")); + } } diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index ba224d0ce..5c0501b35 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -650,29 +650,13 @@ pub async fn run( &format!("PR #{}", msg.pr_number), ) .await; - let system = format!( - "You are the engineer answering reviewer comments on a pull request in the \ - {owner}/{repo} repository, by reading and writing files directly to the PR branch. \ - {stance}Every change a comment asks for is made, checked and working when you \ - finish; a reply says what you did and what you checked. \ - If a comment requests a code change, commit it — use edit_file for targeted edits \ - (the default, and the ONLY safe option for a few lines in a large file), and write_file \ - or batch_write only for new files or whole-file rewrites — then confirm briefly. \ - If a comment asks a question, read the code and answer clearly. \ - If a comment asks to change the pull request's description (its text, a section, a \ - banner, a name in it), call update_pr_description with exactly what to change; never \ - edit files for that. CoderHelm rewrites the description and adds what changed to your \ - reply. \ - Change only what each comment asks for: code next to it that looks alike but that the \ - comment did not name stays exactly as it is. \ - Your changes land on the pull request as one commit in one push when you finish, after \ - CoderHelm checks them (scope, logs, the full test suite). \ - Your output is posted directly as a GitHub comment — write natural replies, no meta-commentary.{voice_block}{team_block}{tests_block}{logs_block}{memory_block}", - logs_block = super::review_fix::logs::GUIDANCE, - memory_block = repo_memory.text, - stance = super::ownership::coder_stance(), - owner = msg.repo_owner, - repo = msg.repo_name, + let system = feedback_system_prompt( + &msg.repo_owner, + &msg.repo_name, + &voice_block, + &team_block, + tests_block, + &repo_memory.text, ); // The team's commit convention and the run's ticket: every commit this @@ -4231,6 +4215,44 @@ async fn ensure_pr_open( true } +/// The feedback round's system prompt. The marker sits before the memories +/// recalled for this round's comments: what comes before it (the role, the +/// team's voice, instructions and rules) is the same for every round in the +/// repository, so it is cached with the tools and read by the next round +/// instead of written again. The text is unchanged; only the cache point is +/// new (`crate::agent::anthropic::SHARED_PREFIX_END`). +pub(crate) fn feedback_system_prompt( + owner: &str, + repo: &str, + voice_block: &str, + team_block: &str, + tests_block: &str, + memory_block: &str, +) -> String { + format!( + "You are the engineer answering reviewer comments on a pull request in the \ + {owner}/{repo} repository, by reading and writing files directly to the PR branch. \ + {stance}Every change a comment asks for is made, checked and working when you \ + finish; a reply says what you did and what you checked. \ + If a comment requests a code change, commit it — use edit_file for targeted edits \ + (the default, and the ONLY safe option for a few lines in a large file), and write_file \ + or batch_write only for new files or whole-file rewrites — then confirm briefly. \ + If a comment asks a question, read the code and answer clearly. \ + If a comment asks to change the pull request's description (its text, a section, a \ + banner, a name in it), call update_pr_description with exactly what to change; never \ + edit files for that. CoderHelm rewrites the description and adds what changed to your \ + reply. \ + Change only what each comment asks for: code next to it that looks alike but that the \ + comment did not name stays exactly as it is. \ + Your changes land on the pull request as one commit in one push when you finish, after \ + CoderHelm checks them (scope, logs, the full test suite). \ + Your output is posted directly as a GitHub comment — write natural replies, no meta-commentary.{voice_block}{team_block}{tests_block}{logs_block}{shared}{memory_block}", + logs_block = super::review_fix::logs::GUIDANCE, + shared = crate::agent::anthropic::SHARED_PREFIX_END, + stance = super::ownership::coder_stance(), + ) +} + #[cfg(test)] mod review_request_tests { use super::*; diff --git a/services/worker/src/passes/model_route_eval.rs b/services/worker/src/passes/model_route_eval.rs index 2a60bcfba..c5978454b 100644 --- a/services/worker/src/passes/model_route_eval.rs +++ b/services/worker/src/passes/model_route_eval.rs @@ -269,6 +269,318 @@ async fn route_review_live() { ); } +// ── Real reviews ───────────────────────────────────────────────────────── +// +// The team's own past reviews replayed on the same inputs: the PR's diff, +// its files at the reviewed head and the repository's instruction files, +// with what people did with each finding as the answer. Cases are exported +// by `scripts/export_real_review_cases.py` into a directory OUTSIDE the +// repository (they hold the team's code) and read from `EVAL_REAL_CASES`. +// Never committed; nothing here names them. + +/// One replayed review. +#[derive(Deserialize)] +struct RealCase { + name: String, + title: String, + #[serde(default)] + body: String, + diff: String, + files: BTreeMap, + /// The repository's instruction files at the reviewed head. + #[serde(default)] + instructions: String, + /// Findings people acted on: the code at the line changed after the + /// comment, or a person agreed with it. + #[serde(default)] + accepted: Vec, + /// Findings people rejected: resolved or answered with no change, or + /// rated down. + #[serde(default)] + dismissed: Vec, + /// Lines the diff adds and removes, for the per-size buckets. + #[serde(default)] + lines_changed: u64, +} + +/// A finding whose fate is known, where it was anchored. +#[derive(Deserialize, Clone)] +struct Known { + file: String, + line: u64, + /// Whether the original finding held the merge. + #[serde(default)] + blocking: bool, +} + +impl Known { + fn as_defect(&self) -> Defect { + Defect { + file: self.file.clone(), + line: self.line, + what: String::new(), + } + } +} + +/// What one replay of a real review scored. +#[derive(Debug, Default, PartialEq, serde::Serialize)] +struct RealScore { + accepted: usize, + /// Accepted findings raised again. + found: usize, + /// ...with the same say on the merge (holds it, or doesn't) as before. + same_severity: usize, + /// Blocking accepted findings raised again as blocking. + accepted_blocking: usize, + found_blocking: usize, + dismissed: usize, + /// Dismissed findings raised again (the false positives people saw). + dismissed_raised: usize, + dismissed_raised_blocking: usize, + /// Findings about neither: unknown, not counted against either model. + other: usize, +} + +fn score_real(case: &RealCase, findings: &[Finding]) -> RealScore { + // The findings about `k`, and whether any of them holds the merge. + let hit = |k: &Known| -> (bool, bool) { + let d = k.as_defect(); + let on: Vec<&Finding> = findings.iter().filter(|f| finding_hits(f, &d)).collect(); + (!on.is_empty(), on.iter().any(|f| f.holds_merge())) + }; + let mut s = RealScore { + accepted: case.accepted.len(), + accepted_blocking: case.accepted.iter().filter(|k| k.blocking).count(), + dismissed: case.dismissed.len(), + ..Default::default() + }; + for k in &case.accepted { + let (found, blocks) = hit(k); + if !found { + continue; + } + s.found += 1; + if blocks == k.blocking { + s.same_severity += 1; + } + if k.blocking && blocks { + s.found_blocking += 1; + } + } + for k in &case.dismissed { + let (found, blocks) = hit(k); + if found { + s.dismissed_raised += 1; + if blocks { + s.dismissed_raised_blocking += 1; + } + } + } + s.other = findings + .iter() + .filter(|f| { + !case + .accepted + .iter() + .chain(&case.dismissed) + .any(|k| finding_hits(f, &k.as_defect())) + }) + .count(); + s +} + +/// The size bucket a case is reported in: the route can move only the +/// sizes where the lighter model holds. +fn size_bucket(lines_changed: u64) -> &'static str { + match lines_changed { + 0..=80 => "small", + 81..=400 => "medium", + _ => "large", + } +} + +fn real_cases(dir: &std::path::Path) -> Vec { + let mut out: Vec = std::fs::read_dir(dir) + .unwrap_or_else(|e| panic!("{}: {e}", dir.display())) + .map(|e| e.unwrap().path()) + .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("json")) + .map(|p| { + let text = std::fs::read_to_string(&p).unwrap(); + serde_json::from_str(&text).unwrap_or_else(|e| panic!("{}: {e}", p.display())) + }) + .collect(); + out.sort_by(|a, b| a.name.cmp(&b.name)); + out +} + +#[test] +fn a_real_review_scores_what_people_kept_and_what_they_rejected() { + let f = |file: &str, line: u64, severity: &str, evidence: &str| -> Finding { + serde_json::from_value(json!({ + "file": file, "line": line, "severity": severity, "category": "bug", + "title": "t", "body": "b", "evidence": evidence, + })) + .unwrap() + }; + let case = RealCase { + name: "c".into(), + title: "t".into(), + body: String::new(), + diff: String::new(), + files: BTreeMap::new(), + instructions: String::new(), + accepted: vec![ + Known { + file: "a.rs".into(), + line: 10, + blocking: true, + }, + Known { + file: "b.rs".into(), + line: 50, + blocking: false, + }, + Known { + file: "c.rs".into(), + line: 5, + blocking: false, + }, + ], + dismissed: vec![Known { + file: "d.rs".into(), + line: 7, + blocking: false, + }], + lines_changed: 40, + }; + let blocking = f("a.rs", 12, "blocking", "verified-defect"); + assert!( + blocking.holds_merge(), + "the fixture's blocking finding holds the merge" + ); + let got = vec![ + blocking, + f("b.rs", 51, "low", "unverified-concern"), + f("d.rs", 7, "medium", "unverified-concern"), + f("e.rs", 1, "low", "unverified-concern"), + ]; + let s = score_real(&case, &got); + assert_eq!( + s, + RealScore { + accepted: 3, + found: 2, + same_severity: 2, + accepted_blocking: 1, + found_blocking: 1, + dismissed: 1, + dismissed_raised: 1, + dismissed_raised_blocking: 0, + other: 1, + } + ); + assert_eq!(size_bucket(40), "small"); + assert_eq!(size_bucket(300), "medium"); + assert_eq!(size_bucket(2000), "large"); +} + +/// Live, on demand: the exported real reviews in `EVAL_REAL_CASES`, each +/// reviewed with the chosen reviewer and critic, `EVAL_REPEAT` times. Prints +/// one `ROUTE_EVAL` line per case and a `ROUTE_EVAL_SUMMARY` line per size +/// bucket and overall. Run it once per reviewer model on the same cases and +/// compare: the measured route is safe only where the lighter reviewer finds +/// as many accepted findings, with the same say on the merge, and raises no +/// more dismissed ones. +#[tokio::test] +#[ignore] +async fn route_review_real_live() { + let Ok(dir) = std::env::var("EVAL_REAL_CASES") else { + panic!("set EVAL_REAL_CASES to the directory export_real_review_cases.py wrote"); + }; + let (client, model) = eval_client().await; + let model = std::env::var("EVAL_REVIEW_MODEL").unwrap_or(model); + let critic = std::env::var("EVAL_CRITIC_MODEL").unwrap_or_else(|_| model.clone()); + let cases = real_cases(std::path::Path::new(&dir)); + assert!(!cases.is_empty(), "no cases in {dir}"); + let mut errors = vec![]; + for rep in 0..repeats() { + // Per bucket and "all": the summed score, cases, cost. + let mut sums: BTreeMap<&str, (RealScore, usize, f64)> = BTreeMap::new(); + for c in &cases { + let lr = LiveReview { + title: c.title.clone(), + body: c.body.clone(), + diff: c.diff.clone(), + files: c.files.clone(), + expect: LiveExpect::default(), + after_reply: None, + }; + let mut usage = crate::models::TokenUsage::default(); + let got = match super::review_eval::live_review_in_repo( + &client, + &model, + &critic, + &lr, + "", + &c.instructions, + &mut usage, + ) + .await + { + Ok(got) => got, + Err(e) => { + errors.push(format!("{}: {e}", c.name)); + continue; + } + }; + let s = score_real(c, &got.findings); + println!( + "ROUTE_EVAL {}", + json!({ + "suite": "review-real", "rep": rep, "case": c.name, "model": model, + "critic": critic, "bucket": size_bucket(c.lines_changed), "score": s, + "verdict": got.verdict, "cost_usd": usage.cost_usd, + }) + ); + for key in ["all", size_bucket(c.lines_changed)] { + let e = sums.entry(key).or_default(); + e.0.accepted += s.accepted; + e.0.found += s.found; + e.0.same_severity += s.same_severity; + e.0.accepted_blocking += s.accepted_blocking; + e.0.found_blocking += s.found_blocking; + e.0.dismissed += s.dismissed; + e.0.dismissed_raised += s.dismissed_raised; + e.0.dismissed_raised_blocking += s.dismissed_raised_blocking; + e.0.other += s.other; + e.1 += 1; + e.2 += usage.cost_usd; + } + } + let ratio = |a: usize, b: usize| if b == 0 { 0.0 } else { a as f64 / b as f64 }; + for (bucket, (s, n, cost)) in &sums { + println!( + "ROUTE_EVAL_SUMMARY {}", + json!({ + "suite": "review-real", "rep": rep, "bucket": bucket, "model": model, + "critic": critic, "cases": n, "score": s, + "accepted_recall": ratio(s.found, s.accepted), + "blocking_recall": ratio(s.found_blocking, s.accepted_blocking), + "severity_agreement": ratio(s.same_severity, s.found), + "dismissed_raised_rate": ratio(s.dismissed_raised, s.dismissed), + "cost_usd": cost, "cost_per_review": cost / (*n).max(1) as f64, + }) + ); + } + } + assert!( + errors.is_empty(), + "review calls failed:\n{}", + errors.join("\n") + ); +} + // ── Implement ──────────────────────────────────────────────────────────── #[derive(Deserialize)] diff --git a/services/worker/src/passes/review_cases/README.md b/services/worker/src/passes/review_cases/README.md index a304457b1..3550ecbac 100644 --- a/services/worker/src/passes/review_cases/README.md +++ b/services/worker/src/passes/review_cases/README.md @@ -97,6 +97,30 @@ findings, whether the verdict blocked as it should, and the tokens and cost. They run only on demand (`reviewer-evals.yml`, `suite: route-review`, with the reviewer and critic models as inputs), never nightly. +## Replaying the team's own reviews (`route_review_real_live`) + +Before a team's reviews move to the measured route (Settings, Model Provider, +`review_model_route: measured_light`), its own past reviews are replayed on +both reviewer models. `scripts/export_real_review_cases.py` writes one case +per past review to a directory outside the repository (the cases hold the +team's code and are never committed): the diff and files at the reviewed +head, the repository's instruction files, and each finding whose fate is +known from its GitHub thread, `accepted` (the code under it changed, or a +person agreed) or `dismissed` (resolved or answered with no change on a +settled PR). Then, once per reviewer model, with the critic on the strongest: + +```sh +EVAL_REAL_CASES= ANTHROPIC_API_KEY= \ + EVAL_REVIEW_MODEL=claude-sonnet-5-5 EVAL_CRITIC_MODEL=claude-opus-5-5 \ + cargo test -p worker route_review_real_live -- --ignored --nocapture +``` + +Each `ROUTE_EVAL_SUMMARY` line (overall and per diff size) gives the recall +on accepted findings, the recall on accepted blocking ones, how often a +re-found finding has the same say on the merge, and how many dismissed +findings come back. The route moves only where the lighter reviewer matches +the strongest on the first three and raises no more dismissed findings. + ## Add a case from a real PR (one step) ```sh diff --git a/services/worker/src/passes/review_eval.rs b/services/worker/src/passes/review_eval.rs index a131589ae..c1710b597 100644 --- a/services/worker/src/passes/review_eval.rs +++ b/services/worker/src/passes/review_eval.rs @@ -1064,12 +1064,27 @@ pub(super) async fn live_review( prior: &str, usage: &mut crate::models::TokenUsage, ) -> Result { - // Built as production builds it (`review_pr::run_once`); the cases carry - // no repo or team instructions, so both blocks are empty. + live_review_in_repo(client, model, critic_model, lr, prior, "", usage).await +} + +/// [`live_review`] of a pull request whose repository has its own +/// instruction files (`repo_instructions`, as `load_repo_instructions_at_ref` +/// reads them): a replayed real review is held to the rules it was held to. +pub(super) async fn live_review_in_repo( + client: &crate::agent::anthropic::AnthropicClient, + model: &str, + critic_model: &str, + lr: &LiveReview, + prior: &str, + repo_instructions: &str, + usage: &mut crate::models::TokenUsage, +) -> Result { + // Built as production builds it (`review_pr::run_once`); the synthetic + // cases carry no repo or team instructions, so both blocks are empty. let team_instructions = ""; let instructions_block = format!( "{}{}", - super::format_instructions_block(""), + super::format_instructions_block(repo_instructions), review_agent::team_rules_block(team_instructions) ); let system = review_agent::review_system_prompt("acme", "app", &instructions_block, false); diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index f1e61cca4..220073690 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -2742,12 +2742,12 @@ async fn run_once( &format!("PR #{}: {title}", msg.pr_number), ) .await; - let instructions_block = format!( - "{}{org_block}{extra}{learning}{team_lessons}{}{}{}", - super::format_instructions_block(&repo_instructions), - reward.context, - reward.addendum, - repo_memory.text, + let instructions_block = review_instructions_block( + &format!( + "{}{org_block}{extra}{learning}{team_lessons}", + super::format_instructions_block(&repo_instructions) + ), + &format!("{}{}{}", reward.context, reward.addendum, repo_memory.text), ); let critic_lessons = format!("{team_lessons}{}", reward.context); let changed = review_agent::changed_right_lines(&compare); @@ -4993,6 +4993,21 @@ async fn feed_review_back_to_run(state: &WorkerState, msg: &ReviewMessage, revie } } +/// The review's instructions block: what holds for every pull request in the +/// repository (its instruction files, the org's and team's rules, the +/// lessons), then what was chosen for this one (examples by its files, the +/// prompt variant, the memories recalled for it). The text is the two joined, +/// unchanged; the marker between them lets the reviewer's system prompt be +/// sent as two blocks, so the repository's part (with the tools before it) is +/// cached once and read by the next review of any pull request in the +/// repository instead of written again with every review. +pub(crate) fn review_instructions_block(repo_wide: &str, this_pr: &str) -> String { + format!( + "{repo_wide}{}{this_pr}", + crate::agent::anthropic::SHARED_PREFIX_END + ) +} + /// Build a "past feedback to learn from" block from this repo's recent review /// records — the 👎 ratings and human notes the team left. Reused so the reviewer /// stops repeating comment styles the team rejected. Best-effort, capped, empty diff --git a/services/worker/src/passes/skills.rs b/services/worker/src/passes/skills.rs index 1af9b9209..86980d9d6 100644 --- a/services/worker/src/passes/skills.rs +++ b/services/worker/src/passes/skills.rs @@ -2228,6 +2228,7 @@ mod tests { primary_model: "team-primary".into(), heavy_model: "team-heavy".into(), heavy_model_chosen: true, + review_route: Default::default(), meter: common::usage::UsageMeter::memory("t").0, scope: Default::default(), }; From 0b3ab37253372f8325021af67a152acaefde48ba Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 15 Nov 2026 14:42:24 -0500 Subject: [PATCH 2/3] Feedback prefix test uses a registered tool name --- services/worker/src/agent/anthropic.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/worker/src/agent/anthropic.rs b/services/worker/src/agent/anthropic.rs index 93f8b1cac..363664f44 100644 --- a/services/worker/src/agent/anthropic.rs +++ b/services/worker/src/agent/anthropic.rs @@ -2908,7 +2908,7 @@ mod shared_prefix_tests { #[test] fn two_feedback_rounds_share_their_prefix() { use crate::passes::feedback::feedback_system_prompt; - let tools = vec![tool("read_file"), tool("edit_file"), tool("reply")]; + let tools = vec![tool("read_file"), tool("edit_file"), tool("write_file")]; let round = |memory: &str| { feedback_system_prompt( "acme", From 9dc05607ca9be720b036f5812dded6a474fef80e Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 15 Nov 2026 15:31:35 -0500 Subject: [PATCH 3/3] Reviews are written on the measured model by default; a team can keep the strongest --- services/gateway/src/routes/api.rs | 23 +++++++++--------- services/worker/src/agent/provider.rs | 34 +++++++++++++-------------- 2 files changed, 29 insertions(+), 28 deletions(-) diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 449928031..8bddd4fe2 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -6044,14 +6044,15 @@ pub async fn get_model_provider( }))) } -/// Which model writes the team's reviews: "strongest" (the default) or -/// "measured_light" (the review written on the lighter measured model, its -/// critic on the strongest; see the worker's `ReviewRoute`). Anything else -/// reads as the default. +/// Which model writes the team's reviews: "measured_light" (the default: +/// the review written on the lighter measured model, its critic on the +/// strongest; see the worker's `ReviewRoute`) or "strongest" (a team that +/// keeps every review on the strongest model). Anything else reads as the +/// default. fn review_model_route(v: Option<&str>) -> &'static str { match v.map(str::trim) { - Some("measured_light") => "measured_light", - _ => "strongest", + Some("strongest") => "strongest", + _ => "measured_light", } } @@ -6072,13 +6073,13 @@ mod review_route_tests { use super::*; #[test] - fn the_review_route_is_strongest_until_a_team_picks_the_measured_one() { - assert_eq!(review_model_route(None), "strongest"); - assert_eq!(review_model_route(Some("sonnet")), "strongest"); - assert_eq!(review_model_route(Some("measured_light")), "measured_light"); + fn the_review_route_is_measured_light_unless_a_team_picks_the_strongest() { + assert_eq!(review_model_route(None), "measured_light"); + assert_eq!(review_model_route(Some("sonnet")), "measured_light"); + assert_eq!(review_model_route(Some("strongest")), "strongest"); // A save without the field keeps what was saved. let none = json!({"primary_model": "claude-sonnet-5-5"}); - assert_eq!(review_route_to_save(&none, None), Ok("strongest")); + assert_eq!(review_route_to_save(&none, None), Ok("measured_light")); assert_eq!( review_route_to_save(&none, Some("measured_light")), Ok("measured_light") diff --git a/services/worker/src/agent/provider.rs b/services/worker/src/agent/provider.rs index 005f84b48..95b7e46bc 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -224,25 +224,25 @@ impl ModelProvider { /// a review holds the merge on); it is back on the strongest model. pub const MEASURED_LIGHT_MODEL: &str = "claude-sonnet-5-5"; -/// Which model writes a team's reviews. `Strongest` (the default, and what -/// any value but `measured_light` reads as) keeps them on the judgment model. -/// `MeasuredLight` writes them on [`MEASURED_LIGHT_MODEL`] with the critic on -/// the judgment model, the configuration the synthetic measurement -/// (`passes/model_route_eval.rs`, `route_review_live`) scored at the same -/// recall at about half the cost. A team turns it on only after the replay of -/// its own past reviews (`route_review_real_live`) holds. +/// Which model writes a team's reviews. `MeasuredLight` (the default, and +/// what any value but `strongest` reads as) writes them on +/// [`MEASURED_LIGHT_MODEL`] with the critic on the judgment model, the +/// configuration the synthetic measurement (`passes/model_route_eval.rs`, +/// `route_review_live`) scored at the same recall at about half the cost. +/// `Strongest` keeps them on the judgment model for a team that sets it. +/// `route_review_real_live` replays a team's own past reviews to check it. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum ReviewRoute { - #[default] Strongest, + #[default] MeasuredLight, } impl ReviewRoute { pub fn parse(v: Option<&str>) -> Self { match v.map(str::trim) { - Some("measured_light") => ReviewRoute::MeasuredLight, - _ => ReviewRoute::Strongest, + Some("strongest") => ReviewRoute::Strongest, + _ => ReviewRoute::MeasuredLight, } } } @@ -394,24 +394,24 @@ mod client_tests { } #[test] - fn reviews_stay_on_the_strongest_model_unless_the_team_switches() { - // Nothing saved, or anything but the measured route's name: strongest. + fn reviews_use_the_measured_model_unless_the_team_keeps_the_strongest() { + // Nothing saved, or anything but the strongest route's name: measured. for saved in [ None, Some(""), - Some("strongest"), + Some("measured_light"), Some("sonnet"), - Some("Measured_Light"), + Some("Strongest"), ] { assert_eq!( ReviewRoute::parse(saved), - ReviewRoute::Strongest, + ReviewRoute::MeasuredLight, "{saved:?}" ); } assert_eq!( - ReviewRoute::parse(Some("measured_light")), - ReviewRoute::MeasuredLight + ReviewRoute::parse(Some("strongest")), + ReviewRoute::Strongest ); let mut p = provider("claude-opus-5-5", false); assert_eq!(p.review_model_id(), "claude-opus-5-5");