diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ca7c645b4..f13a1484e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -90,11 +90,17 @@ jobs: # alone resolves features differently and compiles everything again). - name: Incident regressions run: cargo test --workspace -- 'incidents::' + # Stops, asks, blocks and loops replayed through the real decision + # functions and graded on the decision, with the stop judge's recorded + # answers k = 3 times each (pass^k; passes/replay/README.md). It gates + # any prompt, model or effort change to a judgment step. + - name: Replay suite + run: cargo test --workspace -- 'replay::' # Includes the reviewer evals (worker passes::review_eval): recorded # review histories replayed through the real decision code, no model. - # The incident suite already ran above, on the same build. + # The incident and replay suites already ran above, on the same build. - name: Workspace tests - run: cargo test --workspace -- --skip 'incidents::' + run: cargo test --workspace -- --skip 'incidents::' --skip 'replay::' rust: name: Rust (workspace) diff --git a/lambda/stuck-run-cleanup/handler.py b/lambda/stuck-run-cleanup/handler.py index df6de033a..44f4c7b2e 100644 --- a/lambda/stuck-run-cleanup/handler.py +++ b/lambda/stuck-run-cleanup/handler.py @@ -211,12 +211,47 @@ def _send_waiting(run, why): return False +def deadline_passed(run, now): + """A question the stop judge let the run ask carries a default and a + deadline (worker passes::stop_judge::keep_ask_deadline). Once it passes + with no answer, reversible work goes ahead with the default.""" + if not str(run.get("ask_default", "")).strip(): + return False + due = _parse_time(run.get("ask_deadline")) + return due is not None and now >= due + + +def take_default(runs_table, run, now): + """Claims the deadline once (the worker restarts the ticket with the + default as its answer). Returns True when this sweep claimed it.""" + key = {"team_id": run["team_id"], "run_id": run["run_id"]} + try: + runs_table.update_item( + Key=key, + UpdateExpression="SET ask_default_taken_at = :now", + ExpressionAttributeNames={"#s": "status"}, + ExpressionAttributeValues={":now": now.isoformat(), ":ni": NEEDS_INPUT}, + ConditionExpression="#s = :ni AND attribute_not_exists(ask_default_taken_at)", + ) + except _db().meta.client.exceptions.ConditionalCheckFailedException: + return False + except Exception as e: + logger.error(f"Could not claim the deadline of {run['run_id']}: {e}") + return False + return _send_waiting(run, "deadline") + + def settle_waiting(runs_table, run, now): - """A needs_input run: name its wait when it names none, or remind once. - Returns "named", "reminded" or "".""" + """A needs_input run: take a passed question deadline's default, name + its wait when it names none, or remind once. Returns "defaulted", + "named", "reminded" or "".""" run_id = run["run_id"] key = {"team_id": run["team_id"], "run_id": run_id} now_iso = now.isoformat() + if deadline_passed(run, now) and not run.get("ask_default_taken_at"): + if take_default(runs_table, run, now): + logger.info(f"Run {run_id}: question deadline passed, going ahead with the default") + return "defaulted" try: if not asks_something(run): wait = named_wait(run, now_iso) @@ -539,7 +574,7 @@ def handler(event, context): # before, so awaiting_ci runs sat forever. stuck_runs = [] over_count = 0 - waiting = {"named": 0, "reminded": 0} + waiting = {"named": 0, "reminded": 0, "defaulted": 0} scan_kwargs = { "FilterExpression": "#s = :running OR #s = :awaiting OR #s = :ni", "ExpressionAttributeNames": {"#s": "status"}, @@ -599,6 +634,7 @@ def handler(event, context): "over_ceiling": over_count, "waiting_named": waiting["named"], "waiting_reminded": waiting["reminded"], + "waiting_defaulted": waiting["defaulted"], } logger.info(f"Found {len(stuck_runs)} stuck runs") @@ -690,4 +726,5 @@ def handler(event, context): "over_ceiling": over_count, "waiting_named": waiting["named"], "waiting_reminded": waiting["reminded"], + "waiting_defaulted": waiting["defaulted"], } diff --git a/lambda/tests/test_stuck_run_cleanup.py b/lambda/tests/test_stuck_run_cleanup.py index cd9fe8d68..049ab300a 100644 --- a/lambda/tests/test_stuck_run_cleanup.py +++ b/lambda/tests/test_stuck_run_cleanup.py @@ -283,6 +283,29 @@ def test_a_stalled_run_with_its_pull_request_is_found_and_handed_to_review(self) # Never failed or completed: still waiting, now for something named. self.assertNotIn(":new", updates[0]["ExpressionAttributeValues"]) + def test_a_passed_question_deadline_goes_ahead_with_the_default_once(self): + run = { + "team_id": "T", + "run_id": "R", + "status": "needs_input", + "updated_at": self.NOW.isoformat(), + "questions": '{"questions":[{"id":"q1","question":"Monthly or yearly?"}]}', + "ask_default": "Monthly", + "ask_deadline": (self.NOW - sweep.timedelta(hours=1)).isoformat(), + } + self.assertTrue(sweep.deadline_passed(run, self.NOW)) + out, updates, sent = self._sweep([run]) + self.assertEqual(out["waiting_defaulted"], 1) + self.assertIn("attribute_not_exists(ask_default_taken_at)", updates[0]["ConditionExpression"]) + self.assertEqual(sent, [{"type": "run_waiting", "team_id": "T", "run_id": "R", "why": "deadline"}]) + # Before the deadline, or already taken, or with no default: nothing. + early = dict(run, ask_deadline=(self.NOW + sweep.timedelta(hours=1)).isoformat()) + self.assertFalse(sweep.deadline_passed(early, self.NOW)) + self.assertFalse(sweep.deadline_passed(dict(run, ask_default=""), self.NOW)) + out, _, sent = self._sweep([dict(run, ask_default_taken_at=self.NOW.isoformat())]) + self.assertEqual(out["waiting_defaulted"], 0) + self.assertNotIn("deadline", [m["why"] for m in sent]) + def test_without_a_pull_request_it_waits_for_a_retry(self): wait = sweep.named_wait({"error_message": "stopped"}, "now") self.assertIn("Retry", wait["action"]) diff --git a/selfhost/versions.json b/selfhost/versions.json index 8eb5ea764..db73b6e84 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": "88285390aff81267992458e5e450a9a011c88fd6" + "dashboardRef": "8434a36b91d88b770f7757bee913f683e08b93f2" } diff --git a/services/common/src/decision_log.rs b/services/common/src/decision_log.rs new file mode 100644 index 000000000..ac97af8ae --- /dev/null +++ b/services/common/src/decision_log.rs @@ -0,0 +1,966 @@ +//! What the stop judge decided, and what people did afterwards. +//! +//! Every judged decision ([`crate::stop_judge::Judged`]) is kept on the +//! settings table under the team, with the picture it saw and the model's +//! answers, so a wrong one can be replayed. When a person acts on it the +//! outcome is added ([`Outcome`]): answered with the default or otherwise, +//! dismissed the review, merged with the flagged lines unchanged, cancelled +//! the run, retried it, overrode the stop, or fixed what was flagged. +//! +//! Analytics reads them as two rates ([`summarize`]): unnecessary stops (a +//! question answered with the default, a stop overridden or retried as it +//! was) and nuisance blocks (a review dismissed, overridden, or merged with +//! the lines it flagged unchanged). A confirmed-wrong decision exports as a +//! replay fixture ([`fixture`]), so it becomes a case the suite holds. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use crate::stop_judge::{Group, Judged, Kind, Picture, Verdict}; + +/// The record type on the settings table. +pub const RECORD_TYPE: &str = "decision"; +/// Every decision's sort key starts with this. +pub const SK_PREFIX: &str = "DECISION#"; + +/// Longest stored picture and replies, so an item stays far under 400 KB. +const MAX_PICTURE_BYTES: usize = 60_000; +const MAX_REPLIES_BYTES: usize = 12_000; + +/// What a decision was about. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Subject { + Run { run_id: String }, + Pr { repo: String, number: u64 }, +} + +impl Subject { + /// The sort-key prefix of this subject's decisions. + pub fn prefix(&self) -> String { + match self { + Subject::Run { run_id } => format!("{SK_PREFIX}RUN#{run_id}#"), + Subject::Pr { repo, number } => format!("{SK_PREFIX}PR#{repo}#{number:0>6}#"), + } + } + + pub fn sk(&self, at: &str) -> String { + format!("{}{at}", self.prefix()) + } +} + +/// What a person did after a decision. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Outcome { + /// Answered the question with the recommended default. + AnsweredDefault, + /// Answered with something else. + AnsweredOther, + /// Dismissed CoderHelm's request for changes. + DismissedReview, + /// Merged with the flagged lines unchanged since the block. + MergedFlaggedUnchanged, + /// Changed the flagged lines, then merged or pushed. + Fixed, + /// Cancelled or closed the run. + CancelledRun, + /// Retried the run without changing anything. + Retried, + /// Went ahead over the stop or block (merged over it, told the run to + /// continue without answering). + Overrode, +} + +impl Outcome { + pub fn as_str(self) -> &'static str { + match self { + Outcome::AnsweredDefault => "answered_default", + Outcome::AnsweredOther => "answered_other", + Outcome::DismissedReview => "dismissed_review", + Outcome::MergedFlaggedUnchanged => "merged_flagged_unchanged", + Outcome::Fixed => "fixed", + Outcome::CancelledRun => "cancelled_run", + Outcome::Retried => "retried", + Outcome::Overrode => "overrode", + } + } + + pub fn parse(s: &str) -> Option { + serde_json::from_value(Value::String(s.to_string())).ok() + } + + /// Whether this outcome shows the decision was wrong (`Some(true)`), + /// right (`Some(false)`), or says nothing about it (`None`). + pub fn confirms_wrong(self, group: Group) -> Option { + match (group, self) { + (Group::Stop, Outcome::AnsweredDefault | Outcome::Retried | Outcome::Overrode) => { + Some(true) + } + (Group::Stop, Outcome::AnsweredOther) => Some(false), + ( + Group::Block, + Outcome::DismissedReview | Outcome::MergedFlaggedUnchanged | Outcome::Overrode, + ) => Some(true), + (Group::Block, Outcome::Fixed) => Some(false), + _ => None, + } + } +} + +/// One decision as stored. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Record { + pub sk: String, + pub kind: String, + pub step: String, + pub verdict: String, + /// `model`, `model_reasked`, `rule:...`, `fallback:...`. + pub source: String, + /// The category analytics groups by: the block's category, the kind of + /// fact a question asks for, or the step for a stop. + pub category: String, + /// The step's reason for proposing it. + pub reason: String, + /// The blocker, the question, or the assumption. + pub detail: String, + /// The default answer of a question. + #[serde(default)] + pub default_answer: String, + /// The location a block flagged. + #[serde(default)] + pub location: String, + /// The pull request head the decision was made on. + #[serde(default)] + pub head_sha: String, + #[serde(default)] + pub run_id: String, + #[serde(default)] + pub repo: String, + #[serde(default)] + pub pr_number: u64, + pub created_at: String, + #[serde(default)] + pub outcome: Option, + #[serde(default)] + pub outcome_at: String, + /// The picture the judge saw (JSON, bounded). + #[serde(default)] + pub picture: String, + /// The model's answers (JSON array, bounded). + #[serde(default)] + pub replies: String, +} + +impl Record { + /// Built from a judged decision and the picture it saw. + pub fn new(subject: &Subject, judged: &Judged, picture: &Picture, head_sha: &str) -> Self { + let created_at = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); + let (category, detail, default_answer, location) = match judged.verdict() { + Verdict::Proceed { assumption } => ( + judged.step().to_string(), + assumption.clone(), + "".into(), + "".into(), + ), + Verdict::Ask(q) => ( + serde_json::to_value(q.person_only) + .ok() + .and_then(|v| v.as_str().map(str::to_string)) + .unwrap_or_default(), + q.question.clone(), + q.default.clone(), + String::new(), + ), + Verdict::Hold(h) => ( + h.category + .map(|c| c.as_str().to_string()) + .unwrap_or_else(|| judged.step().to_string()), + h.blocker.clone(), + String::new(), + h.location.clone(), + ), + }; + let source = match judged.source() { + crate::stop_judge::Source::Model => "model".to_string(), + crate::stop_judge::Source::ModelReasked => "model_reasked".to_string(), + crate::stop_judge::Source::Rule(r) => format!("rule:{r}"), + crate::stop_judge::Source::Fallback(r) => { + format!("fallback:{}", crate::truncate_str(r, 400)) + } + }; + let (run_id, repo, pr_number) = match subject { + Subject::Run { run_id } => (run_id.clone(), String::new(), 0), + Subject::Pr { repo, number } => (String::new(), repo.clone(), *number), + }; + Record { + sk: subject.sk(&created_at), + kind: judged.kind().as_str().to_string(), + step: judged.step().to_string(), + verdict: judged.verdict().as_str().to_string(), + source, + category, + reason: crate::truncate_str(&picture.reason, 2_000).to_string(), + detail: crate::truncate_str(&detail, 2_000).to_string(), + default_answer, + location, + head_sha: head_sha.to_string(), + run_id, + repo, + pr_number, + created_at, + outcome: None, + outcome_at: String::new(), + picture: crate::head_tail_str( + &serde_json::to_string(picture).unwrap_or_default(), + MAX_PICTURE_BYTES, + ), + replies: crate::head_tail_str( + &serde_json::to_string(judged.replies()).unwrap_or_default(), + MAX_REPLIES_BYTES, + ), + } + } + + fn kind(&self) -> Option { + serde_json::from_value(Value::String(self.kind.clone())).ok() + } + + pub fn group(&self) -> Group { + self.kind().map(Kind::group).unwrap_or(Group::Stop) + } + + /// A stop or a block actually happened (the judge asked or held). A + /// proceed costs no one anything, so it is never a nuisance. + pub fn stopped(&self) -> bool { + self.verdict == "ask" || self.verdict == "hold" + } + + /// The outcome shows this decision was wrong. + pub fn confirmed_wrong(&self) -> bool { + self.stopped() + && self + .outcome + .and_then(|o| o.confirms_wrong(self.group())) + .unwrap_or(false) + } + + pub fn to_item(&self, team_id: &str) -> HashMap { + let s = |v: &str| AttributeValue::S(v.to_string()); + let mut item = HashMap::new(); + item.insert("pk".into(), s(team_id)); + item.insert("sk".into(), s(&self.sk)); + item.insert("record_type".into(), s(RECORD_TYPE)); + for (k, v) in [ + ("kind", &self.kind), + ("step", &self.step), + ("verdict", &self.verdict), + ("source", &self.source), + ("category", &self.category), + ("reason", &self.reason), + ("detail", &self.detail), + ("default_answer", &self.default_answer), + ("location", &self.location), + ("head_sha", &self.head_sha), + ("run_id", &self.run_id), + ("repo", &self.repo), + ("created_at", &self.created_at), + ("picture", &self.picture), + ("replies", &self.replies), + ] { + if !v.is_empty() { + item.insert(k.into(), s(v)); + } + } + if self.pr_number > 0 { + item.insert( + "pr_number".into(), + AttributeValue::N(self.pr_number.to_string()), + ); + } + if let Some(o) = self.outcome { + item.insert("outcome".into(), s(o.as_str())); + item.insert("outcome_at".into(), s(&self.outcome_at)); + } + item + } + + pub fn from_item(item: &HashMap) -> Self { + let s = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + Record { + sk: s("sk"), + kind: s("kind"), + step: s("step"), + verdict: s("verdict"), + source: s("source"), + category: s("category"), + reason: s("reason"), + detail: s("detail"), + default_answer: s("default_answer"), + location: s("location"), + head_sha: s("head_sha"), + run_id: s("run_id"), + repo: s("repo"), + pr_number: item + .get("pr_number") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0), + created_at: s("created_at"), + outcome: Outcome::parse(&s("outcome")), + outcome_at: s("outcome_at"), + picture: s("picture"), + replies: s("replies"), + } + } +} + +/// Keeps a decision. Best effort: a failed write never changes the decision. +pub async fn record( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + rec: &Record, +) -> bool { + if table.is_empty() { + return false; + } + match dynamo + .put_item() + .table_name(table) + .set_item(Some(rec.to_item(team_id))) + .send() + .await + { + Ok(_) => true, + Err(e) => { + tracing::warn!(team_id, sk = %rec.sk, error = %e, "Could not keep the stop judge's decision"); + false + } + } +} + +/// A subject's decisions, oldest first. +pub async fn for_subject( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + subject: &Subject, +) -> Vec { + query_prefix(dynamo, table, team_id, &subject.prefix(), None, 5).await +} + +/// Decisions under a sort-key prefix, oldest first, newer than `since` +/// when given. +pub async fn query_prefix( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + prefix: &str, + since: Option<&str>, + max_pages: usize, +) -> Vec { + let mut out = Vec::new(); + if table.is_empty() { + return out; + } + let mut start: Option> = None; + for _ in 0..max_pages { + let mut q = dynamo + .query() + .table_name(table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", AttributeValue::S(team_id.into())) + .expression_attribute_values(":p", AttributeValue::S(prefix.into())) + .set_exclusive_start_key(start.take()); + if let Some(since) = since { + q = q + .filter_expression("created_at >= :since") + .expression_attribute_values(":since", AttributeValue::S(since.into())); + } + let Ok(page) = q.send().await else { + break; + }; + out.extend(page.items().iter().map(Record::from_item)); + match page.last_evaluated_key() { + Some(k) if !k.is_empty() => start = Some(k.clone()), + _ => break, + } + } + out +} + +/// Which open decisions an outcome lands on: the subject's stops and blocks +/// that have no outcome yet. `pick` narrows them (by kind, by head). +pub fn pending(records: &[Record], group: Group) -> Vec<&Record> { + records + .iter() + .filter(|r| r.stopped() && r.outcome.is_none() && r.group() == group) + .collect() +} + +/// Sets an outcome on one decision, only if it has none (a later act never +/// rewrites the first one). +pub async fn set_outcome( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + sk: &str, + outcome: Outcome, +) -> bool { + if table.is_empty() { + return false; + } + dynamo + .update_item() + .table_name(table) + .key("pk", AttributeValue::S(team_id.into())) + .key("sk", AttributeValue::S(sk.into())) + .update_expression("SET outcome = :o, outcome_at = :t") + .condition_expression("attribute_exists(sk) AND attribute_not_exists(outcome)") + .expression_attribute_values(":o", AttributeValue::S(outcome.as_str().into())) + .expression_attribute_values(":t", AttributeValue::S(chrono::Utc::now().to_rfc3339())) + .send() + .await + .is_ok() +} + +/// Lands one outcome on a subject's open decisions of `group`; returns how +/// many it set. `choose` picks the outcome per decision (a merge is +/// "unchanged" for one block and "fixed" for another). +pub async fn land( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + subject: &Subject, + group: Group, + choose: impl Fn(&Record) -> Option, +) -> usize { + let records = for_subject(dynamo, table, team_id, subject).await; + let mut n = 0; + for r in pending(&records, group) { + if let Some(o) = choose(r) { + if set_outcome(dynamo, table, team_id, &r.sk, o).await { + n += 1; + } + } + } + n +} + +/// Whether a person's answer took the recommended default. +pub fn answered_default(default: &str, answer: &str) -> bool { + let norm = |s: &str| { + s.to_ascii_lowercase() + .split(|c: char| !c.is_alphanumeric()) + .filter(|w| !w.is_empty()) + .collect::>() + .join(" ") + }; + let (d, a) = (norm(default), norm(answer)); + !d.is_empty() + && (a == d + || a.starts_with(&d) + || matches!( + a.as_str(), + "yes" | "ok" | "default" | "go ahead" | "sounds good" | "recommended" + )) +} + +/// The outcome of a merge for a block: unchanged when the flagged file was +/// not touched after the block's head (or the head is the same), else fixed. +/// `changed_since` is the files changed between the block's head and the +/// merge, when known. +pub fn merge_outcome(rec: &Record, merge_head: &str, changed_since: Option<&[String]>) -> Outcome { + if !rec.head_sha.is_empty() && rec.head_sha == merge_head { + return Outcome::MergedFlaggedUnchanged; + } + let path = rec + .location + .split([':', '#', ' ']) + .next() + .unwrap_or("") + .trim(); + match changed_since { + Some(files) if !path.is_empty() => { + if files.iter().any(|f| f == path) { + Outcome::Fixed + } else { + Outcome::MergedFlaggedUnchanged + } + } + // New commits and nothing to compare: the change was looked at. + _ => Outcome::Fixed, + } +} + +// ── Where people's acts land ─────────────────────────────────────────────── + +/// A person answered a run's questions: each open ask on the run is answered +/// with its default or otherwise; an open hold was answered (the person gave +/// what it named). +pub async fn on_answers( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + run_id: &str, + answers: &[String], +) -> usize { + let subject = Subject::Run { + run_id: run_id.to_string(), + }; + land(dynamo, table, team_id, &subject, Group::Stop, |r| { + Some(if r.verdict == "ask" { + if answers + .iter() + .any(|a| answered_default(&r.default_answer, a)) + { + Outcome::AnsweredDefault + } else { + Outcome::AnsweredOther + } + } else { + Outcome::AnsweredOther + }) + }) + .await +} + +/// A person ended or restarted a run: its open stops get that outcome. +pub async fn on_run_acted( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + run_id: &str, + outcome: Outcome, +) -> usize { + let subject = Subject::Run { + run_id: run_id.to_string(), + }; + land(dynamo, table, team_id, &subject, Group::Stop, |_| { + Some(outcome) + }) + .await +} + +/// A person dismissed CoderHelm's request for changes on a pull request. +pub async fn on_review_dismissed( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + repo: &str, + pr: u64, +) -> usize { + let subject = Subject::Pr { + repo: repo.to_string(), + number: pr, + }; + land(dynamo, table, team_id, &subject, Group::Block, |_| { + Some(Outcome::DismissedReview) + }) + .await +} + +/// A pull request merged: each open block on it was either left as it was +/// (merged with the flagged lines unchanged) or acted on (fixed). +pub async fn on_merged( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + repo: &str, + pr: u64, + merge_head: &str, + changed_since: Option<&[String]>, +) -> usize { + let subject = Subject::Pr { + repo: repo.to_string(), + number: pr, + }; + land(dynamo, table, team_id, &subject, Group::Block, |r| { + Some(merge_outcome(r, merge_head, changed_since)) + }) + .await +} + +/// Decisions newer than `since` (RFC 3339), across the team. +pub async fn since( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + since: &str, +) -> Vec { + query_prefix(dynamo, table, team_id, SK_PREFIX, Some(since), 20).await +} + +// ── Analytics ────────────────────────────────────────────────────────────── + +/// One example of a confirmed-wrong decision, for the view. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Example { + pub sk: String, + pub kind: String, + pub step: String, + pub category: String, + pub detail: String, + pub outcome: String, + pub created_at: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub run_id: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub repo: String, + #[serde(default, skip_serializing_if = "is_zero")] + pub pr_number: u64, +} + +fn is_zero(n: &u64) -> bool { + *n == 0 +} + +/// A rate of wrong stops or blocks. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Rate { + /// Stops (or blocks) the judge let happen. + pub total: u64, + /// Of those, the ones a person's act settled either way. + pub with_outcome: u64, + /// Of those, confirmed wrong. + pub wrong: u64, + /// `wrong / with_outcome` (0 when nothing has an outcome yet). + pub rate: f64, + /// Wrong ones by category. + pub by_category: Vec<(String, u64)>, + /// The newest wrong ones. + pub examples: Vec, +} + +/// Both views and the decisions the judge turned around. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Summary { + pub unnecessary_stops: Rate, + pub nuisance_blocks: Rate, + /// Decisions the judge made in the window, stops and proceeds alike. + pub decisions: u64, + /// Of those, proceeds (the step proposed a stop, the work went on). + pub proceeded: u64, +} + +const MAX_EXAMPLES: usize = 10; + +fn rate(records: &[&Record]) -> Rate { + let total = records.len() as u64; + let with_outcome: Vec<&&Record> = records + .iter() + .filter(|r| { + r.outcome + .and_then(|o| o.confirms_wrong(r.group())) + .is_some() + }) + .collect(); + let mut wrong: Vec<&&Record> = with_outcome + .iter() + .copied() + .filter(|r| r.confirmed_wrong()) + .collect(); + wrong.sort_by(|a, b| b.created_at.cmp(&a.created_at)); + let mut cats: HashMap = HashMap::new(); + for r in &wrong { + *cats.entry(r.category.clone()).or_default() += 1; + } + let mut by_category: Vec<(String, u64)> = cats.into_iter().collect(); + by_category.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + let w = wrong.len() as u64; + let n = with_outcome.len() as u64; + Rate { + total, + with_outcome: n, + wrong: w, + rate: if n == 0 { 0.0 } else { w as f64 / n as f64 }, + by_category, + examples: wrong + .iter() + .take(MAX_EXAMPLES) + .map(|r| Example { + sk: r.sk.clone(), + kind: r.kind.clone(), + step: r.step.clone(), + category: r.category.clone(), + detail: crate::truncate_str(&r.detail, 300).to_string(), + outcome: r + .outcome + .map(|o| o.as_str().to_string()) + .unwrap_or_default(), + created_at: r.created_at.clone(), + run_id: r.run_id.clone(), + repo: r.repo.clone(), + pr_number: r.pr_number, + }) + .collect(), + } +} + +/// The two views over a window's decisions. +pub fn summarize(records: &[Record]) -> Summary { + let stops: Vec<&Record> = records + .iter() + .filter(|r| r.stopped() && r.group() == Group::Stop) + .collect(); + let blocks: Vec<&Record> = records + .iter() + .filter(|r| r.stopped() && r.group() == Group::Block) + .collect(); + Summary { + unnecessary_stops: rate(&stops), + nuisance_blocks: rate(&blocks), + decisions: records.len() as u64, + proceeded: records.iter().filter(|r| r.verdict == "proceed").count() as u64, + } +} + +/// The weekly email's line, or `None` when there was nothing to judge. +pub fn weekly_line(s: &Summary) -> Option { + let st = &s.unnecessary_stops; + let bl = &s.nuisance_blocks; + if st.total == 0 && bl.total == 0 { + return None; + } + let pct = |r: &Rate| { + if r.with_outcome == 0 { + "no outcomes yet".to_string() + } else { + format!( + "{:.0}% ({} of {} with an outcome)", + r.rate * 100.0, + r.wrong, + r.with_outcome + ) + } + }; + Some(format!( + "Stops and blocks: {} stops, unnecessary {}; {} blocks, nuisance {}.", + st.total, + pct(st), + bl.total, + pct(bl) + )) +} + +// ── Replay fixtures ──────────────────────────────────────────────────────── + +/// A confirmed-wrong decision as a replay fixture: the picture it saw, the +/// model's recorded answers, and the decision people's act says was right. +/// Names are the team's own; scrub them before committing the file. +pub fn fixture(rec: &Record) -> Value { + let picture: Value = serde_json::from_str(&rec.picture).unwrap_or(Value::Null); + let replies: Value = serde_json::from_str(&rec.replies).unwrap_or(json!([])); + let expect = match rec.group() { + Group::Block => "proceed", + Group::Stop => "proceed", + }; + json!({ + "name": format!("{}-{}", rec.step, rec.created_at.replace([':', '.'], "-")), + "about": format!( + "Exported: the judge chose {} on {}; the outcome was {} ({}). Scrub names, then \ + record three trials (REPLAY_RECORD=1) once the decision is right.", + rec.verdict, + rec.kind, + rec.outcome.map(|o| o.as_str()).unwrap_or("none"), + crate::truncate_str(&rec.detail, 200) + ), + "case": "stop_judge", + "k": 1, + "input": { "picture": picture }, + "replies": [replies], + "expect": { "verdict": expect, "never_ask": true } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::stop_judge::{self, Evidence, JudgeModel}; + + struct One(Value); + impl JudgeModel for One { + async fn answer(&self, _: &str, _: &str, _: &Value) -> Result { + Ok(self.0.clone()) + } + } + + fn judged(kind: Kind, reply: Value) -> (Judged, Picture) { + let mut p = Picture::new(kind, "review", "a finding"); + p.evidence = vec![Evidence { + source: "ci".into(), + finding: "fails".into(), + location: "src/a.rs:3".into(), + checked: true, + ..Default::default() + }]; + let j = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(stop_judge::judge(&One(reply), p.clone())); + (j, p) + } + + fn hold() -> Value { + json!({"verdict":"hold","assumption":"","question":"","person_only":"","tried":[], + "options":[],"default":"","deadline_hours":0,"blocker":"tests fail", + "evidence":["E1"],"category":"correctness","location":"src/a.rs:3"}) + } + + #[test] + fn a_record_round_trips_through_the_item() { + let (j, p) = judged(Kind::Block, hold()); + let subject = Subject::Pr { + repo: "acme/site".into(), + number: 7, + }; + let mut r = Record::new(&subject, &j, &p, "abc123"); + r.outcome = Some(Outcome::DismissedReview); + r.outcome_at = "2026-11-06T00:00:00Z".into(); + let back = Record::from_item(&r.to_item("TEAM#1")); + assert_eq!(back, r); + assert!(back.sk.starts_with("DECISION#PR#acme/site#000007#")); + assert_eq!(back.category, "correctness"); + assert!(back.confirmed_wrong()); + } + + #[test] + fn outcomes_say_wrong_right_or_nothing() { + use Outcome::*; + assert_eq!(AnsweredDefault.confirms_wrong(Group::Stop), Some(true)); + assert_eq!(AnsweredOther.confirms_wrong(Group::Stop), Some(false)); + assert_eq!(CancelledRun.confirms_wrong(Group::Stop), None); + assert_eq!(DismissedReview.confirms_wrong(Group::Block), Some(true)); + assert_eq!( + MergedFlaggedUnchanged.confirms_wrong(Group::Block), + Some(true) + ); + assert_eq!(Fixed.confirms_wrong(Group::Block), Some(false)); + for o in [ + AnsweredDefault, + AnsweredOther, + DismissedReview, + MergedFlaggedUnchanged, + Fixed, + CancelledRun, + Retried, + Overrode, + ] { + assert_eq!(Outcome::parse(o.as_str()), Some(o)); + } + } + + #[test] + fn the_summary_counts_rates_categories_and_examples() { + let (j, p) = judged(Kind::Block, hold()); + let pr = Subject::Pr { + repo: "acme/site".into(), + number: 1, + }; + let mut a = Record::new(&pr, &j, &p, "h"); + a.outcome = Some(Outcome::MergedFlaggedUnchanged); + let mut b = Record::new(&pr, &j, &p, "h"); + b.outcome = Some(Outcome::Fixed); + let c = Record::new(&pr, &j, &p, "h"); + let s = summarize(&[a, b, c]); + assert_eq!(s.nuisance_blocks.total, 3); + assert_eq!(s.nuisance_blocks.with_outcome, 2); + assert_eq!(s.nuisance_blocks.wrong, 1); + assert!((s.nuisance_blocks.rate - 0.5).abs() < 1e-9); + assert_eq!( + s.nuisance_blocks.by_category, + vec![("correctness".into(), 1)] + ); + assert_eq!(s.nuisance_blocks.examples.len(), 1); + assert_eq!(s.unnecessary_stops.total, 0); + assert!(weekly_line(&s).unwrap().contains("nuisance 50% (1 of 2")); + assert!(weekly_line(&Summary::default()).is_none()); + } + + #[test] + fn a_proceed_is_never_a_nuisance() { + let (j, p) = judged( + Kind::Ask, + json!({"verdict":"proceed","assumption":"monthly","question":"","person_only":"", + "tried":[],"options":[],"default":"","deadline_hours":0,"blocker":"", + "evidence":[],"category":"","location":""}), + ); + let mut r = Record::new( + &Subject::Run { + run_id: "r1".into(), + }, + &j, + &p, + "", + ); + r.outcome = Some(Outcome::Overrode); + assert!(!r.confirmed_wrong()); + let s = summarize(&[r]); + assert_eq!(s.unnecessary_stops.total, 0); + assert_eq!(s.proceeded, 1); + } + + #[test] + fn a_merge_is_unchanged_or_fixed_by_the_flagged_file() { + let (j, p) = judged(Kind::Block, hold()); + let r = Record::new( + &Subject::Pr { + repo: "a/b".into(), + number: 1, + }, + &j, + &p, + "h1", + ); + assert_eq!( + merge_outcome(&r, "h1", None), + Outcome::MergedFlaggedUnchanged + ); + let other = vec!["README.md".to_string()]; + assert_eq!( + merge_outcome(&r, "h2", Some(&other)), + Outcome::MergedFlaggedUnchanged + ); + let touched = vec!["src/a.rs".to_string()]; + assert_eq!(merge_outcome(&r, "h2", Some(&touched)), Outcome::Fixed); + } + + #[test] + fn answers_that_take_the_default() { + assert!(answered_default("Monthly totals", "monthly totals")); + assert!(answered_default("Monthly totals", "Monthly totals, please")); + assert!(answered_default("Monthly totals", "yes")); + assert!(!answered_default("Monthly totals", "Yearly")); + assert!(!answered_default("", "yes")); + } + + #[test] + fn a_wrong_decision_exports_as_a_fixture_the_suite_reads() { + let (j, p) = judged(Kind::Block, hold()); + let mut r = Record::new( + &Subject::Pr { + repo: "a/b".into(), + number: 1, + }, + &j, + &p, + "h", + ); + r.outcome = Some(Outcome::DismissedReview); + let f = fixture(&r); + assert_eq!(f["case"], "stop_judge"); + assert_eq!(f["expect"]["verdict"], "proceed"); + assert_eq!(f["input"]["picture"]["step"], "review"); + assert_eq!(f["replies"][0][0]["verdict"], "hold"); + let back: Picture = serde_json::from_value(f["input"]["picture"].clone()).unwrap(); + assert_eq!(back.kind, Some(Kind::Block)); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 9c1aaf57f..9975e72a3 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -100,6 +100,7 @@ pub mod paged; pub mod pr_outcome; pub mod run_prs; // review_stats: time-ordered review records for analytics +pub mod decision_log; pub mod deploy_stats; /// Work CoderHelm started on its own pull request and hasn't landed, and /// what a person's mention there does about it. @@ -144,6 +145,7 @@ pub mod skill_compat; pub mod skills; /// Who may ask CoderHelm for work from a GitHub comment or review. pub mod standing; +pub mod stop_judge; pub mod stop_rules; /// A team's run and PR-reviewed counts, each added exactly once. pub mod team_counts; diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index d98fbe433..119e56924 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -688,6 +688,8 @@ pub struct RunWaitingMessage { pub run_id: String, /// `reminder`: still waiting after `run_wait::REMIND_AFTER_HOURS`. /// `named`: it waited for nothing, and the sweep just named what for. + /// `deadline`: a judged question went unanswered past its deadline; the + /// worker goes ahead with its recommended default. #[serde(default)] pub why: String, } diff --git a/services/common/src/stop_judge.rs b/services/common/src/stop_judge.rs new file mode 100644 index 000000000..aca4c2512 --- /dev/null +++ b/services/common/src/stop_judge.rs @@ -0,0 +1,1163 @@ +//! The stop judge: the one place a costly decision is made. +//! +//! A costly decision is one that spends a person's attention or holds the +//! work up: asking a person, stopping a run or making it wait, blocking a +//! pull request (or keeping "changes requested"), starting another fix cycle +//! beyond the first, and handing a run off. Each used to be decided by the +//! narrow step that hit it, and each picked the costly outcome when unsure. +//! Now every one is put to this judge, with the whole picture: the ticket and +//! its acceptance criteria, related tickets and their pull requests, the plan, +//! the diff, CI and plan results, what the proof checks and rules found (as +//! evidence, not as verdicts), the review threads, the run's budget, and the +//! decision the step proposes with its reason. +//! +//! The judge answers one of three ways ([`Verdict`]): +//! +//! - **Proceed**: the work moves on, on a written assumption that becomes an +//! open item in the pull request description. For a proposed extra cycle it +//! means "deliver what exists"; for a proposed block it means "approve, with +//! notes". +//! - **Ask**: only for a fact a person alone has (a product choice, access or +//! credentials, or readings of the ticket that lead to different code). The +//! question carries what was tried, 2 to 4 options, a recommended default +//! and a deadline after which reversible work goes ahead with the default. +//! - **Hold**: only with a named blocker that cites checked evidence from the +//! picture. For a proposed extra cycle it means "this blocker is worth +//! another cycle"; for a proposed block it means "request changes", which +//! further needs a correctness, security or data-loss problem with a +//! location. +//! +//! One call on the strongest configured model at high effort, structured +//! output ([`judge`]). An answer that breaks the rules above is asked again +//! once, with the schema and what was wrong; a second bad answer falls back +//! deterministically ([`fallback`]): proceed for reversible work, never to +//! asking a person. +//! +//! The only way to get a [`Judged`] is from [`judge`], and the code that asks +//! a person, sets `needs_input`, requests changes or starts another loop takes +//! one, so none of it can run without the judge. A source test in the worker +//! (`passes::stop_judge`) fails when a path does it any other way. + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +/// The costly decisions. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + /// Ask a person a question and wait for the answer. + Ask, + /// Stop the run, or make it wait on something. + Stop, + /// Post "changes requested" on a pull request, or keep it standing. + Block, + /// Start another fix cycle beyond the first. + ExtraCycle, + /// Hand the run to a person. + Handoff, +} + +impl Kind { + pub fn as_str(self) -> &'static str { + match self { + Kind::Ask => "ask", + Kind::Stop => "stop", + Kind::Block => "block", + Kind::ExtraCycle => "extra_cycle", + Kind::Handoff => "handoff", + } + } + + /// Analytics groups decisions as stops (a run waited or a person was + /// asked) or blocks (a pull request was held). + pub fn group(self) -> Group { + match self { + Kind::Block => Group::Block, + _ => Group::Stop, + } + } + + /// The judge may ask a person for this decision. A review never asks: + /// what it wants to know is a note on the approval. + fn may_ask(self) -> bool { + !matches!(self, Kind::Block) + } +} + +/// How analytics groups a decision. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Group { + Stop, + Block, +} + +/// The facts only a person has. Anything else, the run finds out or assumes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PersonOnly { + /// A product choice: what the thing should do, when the ticket doesn't say + /// and the options differ for the people using it. + ProductChoice, + /// Access or credentials the run doesn't have. + Access, + /// Readings of the ticket that lead to different code. + DivergentReadings, +} + +impl PersonOnly { + fn parse(s: &str) -> Option { + match s.trim() { + "product_choice" => Some(Self::ProductChoice), + "access" | "access_or_credentials" | "credentials" => Some(Self::Access), + "divergent_readings" => Some(Self::DivergentReadings), + _ => None, + } + } +} + +/// What a request for changes may rest on. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum BlockCategory { + Correctness, + Security, + DataLoss, +} + +impl BlockCategory { + pub fn parse(s: &str) -> Option { + match s + .trim() + .to_ascii_lowercase() + .replace(['-', ' '], "_") + .as_str() + { + "correctness" | "bug" | "defect" => Some(Self::Correctness), + "security" => Some(Self::Security), + "data_loss" | "data" | "dataloss" => Some(Self::DataLoss), + _ => None, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Self::Correctness => "correctness", + Self::Security => "security", + Self::DataLoss => "data_loss", + } + } +} + +// ── The picture ──────────────────────────────────────────────────────────── + +/// A ticket related to this one (a sibling, the parent, a duplicate) and +/// the pull request that does its work, if any. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Related { + pub ticket: String, + pub summary: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub pr: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub pr_state: String, +} + +/// One piece of evidence: what a check, a rule, CI or a person's thread +/// found. Each has an id the judge cites. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Evidence { + /// `E1`, `E2`, ... (assigned by [`Picture::with_ids`] when empty). + #[serde(default)] + pub id: String, + /// Where it came from: `proof`, `rules`, `ci`, `tests`, `review`, ... + pub source: String, + /// What it says, in plain words. + pub finding: String, + /// `path:line`, a check name or a lookup, when it has one. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub location: String, + /// Confirmed by running something or reading the code, not inferred. + #[serde(default)] + pub checked: bool, +} + +/// One review or comment thread and where it stands. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Thread { + /// `T1`, `T2`, ... (assigned by [`Picture::with_ids`] when empty). + #[serde(default)] + pub id: String, + pub summary: String, + /// Still open (not resolved, not answered). + #[serde(default)] + pub open: bool, + /// The last word in it is a person's. + #[serde(default)] + pub person_last: bool, +} + +/// What the run has spent and may spend. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Budget { + #[serde(default)] + pub spend_usd: f64, + #[serde(default)] + pub spend_cap_usd: f64, + #[serde(default)] + pub continuations: u32, + #[serde(default)] + pub continuation_cap: u32, + /// Fix cycles of the step asking, so far. + #[serde(default)] + pub cycles: u32, + #[serde(default)] + pub cycle_cap: u32, +} + +impl Budget { + /// No room for another cycle of the step asking. + pub fn cycles_spent(&self) -> bool { + self.cycle_cap > 0 && self.cycles >= self.cycle_cap + } + + fn line(&self) -> String { + format!( + "spent ${:.2} of ${:.2}; continuations {} of {}; fix cycles of this step {} of {}", + self.spend_usd, + self.spend_cap_usd, + self.continuations, + self.continuation_cap, + self.cycles, + self.cycle_cap + ) + } +} + +/// The question a step would ask, if the judge lets it. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct ProposedQuestion { + pub question: String, + #[serde(default)] + pub tried: Vec, + #[serde(default)] + pub options: Vec, +} + +/// Everything the judge sees. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Picture { + /// The decision proposed. + pub kind: Option, + /// The step that proposes it (`plan`, `fix_location`, `run_guard`, + /// `review`, `own_review`, ...). + pub step: String, + /// Why the step proposes it. + pub reason: String, + /// Undoing what proceeding does costs nothing more than a commit or a + /// comment (a branch, a draft, a review). Nearly everything is. + pub reversible: bool, + pub ticket_title: String, + pub ticket_body: String, + #[serde(default)] + pub acceptance: Vec, + #[serde(default)] + pub related: Vec, + #[serde(default)] + pub plan: String, + #[serde(default)] + pub diff_summary: String, + /// CI and plan results, one line each. + #[serde(default)] + pub results: Vec, + #[serde(default)] + pub evidence: Vec, + #[serde(default)] + pub threads: Vec, + #[serde(default)] + pub budget: Budget, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub question: Option, + /// Set when going on is impossible, not a judgment: the repository isn't + /// connected, a person ended the run, the run's hard ceiling is spent. + /// The decision is still recorded here, without a model call. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub cannot_proceed: String, +} + +/// Longest text of one field in the prompt and the stored record. +const MAX_FIELD: usize = 6_000; +const MAX_ITEMS: usize = 40; + +impl Picture { + pub fn new(kind: Kind, step: &str, reason: &str) -> Self { + Self { + kind: Some(kind), + step: step.to_string(), + reason: reason.to_string(), + reversible: true, + ..Default::default() + } + } + + /// Ids on every evidence item and thread that has none, and the lists + /// bounded. + pub fn with_ids(mut self) -> Self { + self.evidence.truncate(MAX_ITEMS); + self.threads.truncate(MAX_ITEMS); + self.related.truncate(MAX_ITEMS); + self.results.truncate(MAX_ITEMS); + for (i, e) in self.evidence.iter_mut().enumerate() { + if e.id.trim().is_empty() { + e.id = format!("E{}", i + 1); + } + } + for (i, t) in self.threads.iter_mut().enumerate() { + if t.id.trim().is_empty() { + t.id = format!("T{}", i + 1); + } + } + self + } + + fn kind(&self) -> Kind { + self.kind.unwrap_or(Kind::Stop) + } + + /// Evidence or a thread by the id the judge cites. + fn cited(&self, id: &str) -> Option> { + let id = id.trim().trim_matches(|c| c == '[' || c == ']'); + if let Some(e) = self.evidence.iter().find(|e| e.id.eq_ignore_ascii_case(id)) { + return Some(Cited::Evidence(e)); + } + self.threads + .iter() + .find(|t| t.id.eq_ignore_ascii_case(id)) + .map(Cited::Thread) + } +} + +enum Cited<'a> { + Evidence(&'a Evidence), + Thread(&'a Thread), +} + +impl Cited<'_> { + /// Evidence counts when it was checked; a thread when a person's + /// words in it are still open. + fn checked(&self) -> bool { + match self { + Cited::Evidence(e) => e.checked, + Cited::Thread(t) => t.open && t.person_last, + } + } +} + +fn clip(s: &str) -> String { + crate::head_tail_str(s.trim(), MAX_FIELD) +} + +// ── The answer ───────────────────────────────────────────────────────────── + +/// A question the judge lets the run ask. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Question { + pub question: String, + pub person_only: PersonOnly, + /// What the run already tried or read. + pub tried: Vec, + /// 2 to 4 options. + pub options: Vec, + /// One of `options`. + pub default: String, + /// After this many hours reversible work goes ahead with the default. + pub deadline_hours: u32, +} + +/// A named blocker, on checked evidence. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Hold { + pub blocker: String, + /// Ids from the picture (`E1`, `T2`), each checked. + pub evidence: Vec, + /// For a block: what kind of problem, and where. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub category: Option, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub location: String, +} + +/// The judge's answer. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "verdict", rename_all = "snake_case")] +pub enum Verdict { + Proceed { assumption: String }, + Ask(Question), + Hold(Hold), +} + +impl Verdict { + pub fn as_str(&self) -> &'static str { + match self { + Verdict::Proceed { .. } => "proceed", + Verdict::Ask(_) => "ask", + Verdict::Hold(_) => "hold", + } + } +} + +/// Where the answer came from. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Source { + /// The model's first answer. + Model, + /// The model's second answer, after the first broke a rule. + ModelReasked, + /// A rule settled it before any model call (no budget for another cycle). + Rule(String), + /// Two bad answers (or no answer): the deterministic fallback. + Fallback(String), +} + +/// A judged decision. Only [`judge`] makes one. +#[derive(Debug, Clone, PartialEq)] +pub struct Judged { + kind: Kind, + step: String, + verdict: Verdict, + source: Source, + /// The model's answers, as they came (for the record and replay). + replies: Vec, + _sealed: (), +} + +impl Judged { + pub fn kind(&self) -> Kind { + self.kind + } + pub fn step(&self) -> &str { + &self.step + } + pub fn verdict(&self) -> &Verdict { + &self.verdict + } + pub fn source(&self) -> &Source { + &self.source + } + pub fn replies(&self) -> &[Value] { + &self.replies + } + + /// The work moves on. + pub fn proceeds(&self) -> bool { + matches!(self.verdict, Verdict::Proceed { .. }) + } + + pub fn question(&self) -> Option<&Question> { + match &self.verdict { + Verdict::Ask(q) => Some(q), + _ => None, + } + } + + pub fn hold(&self) -> Option<&Hold> { + match &self.verdict { + Verdict::Hold(h) => Some(h), + _ => None, + } + } + + /// The assumption a proceed rests on. + pub fn assumption(&self) -> Option<&str> { + match &self.verdict { + Verdict::Proceed { assumption } => Some(assumption), + _ => None, + } + } + + /// The line the pull request description lists under Open items for a + /// proceed: the assumption, so a person sees what was decided for them. + pub fn open_item(&self) -> Option { + self.assumption() + .map(|a| format!("Assumed ({}): {}", self.step_words(), a.trim())) + } + + fn step_words(&self) -> String { + self.step.replace('_', " ") + } + + /// A question as a person reads it: what was tried, the options with the + /// default marked, and when the default is taken. + pub fn question_markdown(&self) -> Option { + let q = self.question()?; + let mut s = format!("**{}**\n\n", q.question.trim()); + if !q.tried.is_empty() { + s.push_str("What I checked first:\n"); + for t in &q.tried { + s.push_str(&format!("- {}\n", t.trim())); + } + s.push('\n'); + } + s.push_str("Options:\n"); + for (i, o) in q.options.iter().enumerate() { + let mark = if o == &q.default { + " (recommended)" + } else { + "" + }; + s.push_str(&format!("{}. {}{}\n", i + 1, o.trim(), mark)); + } + s.push_str(&format!( + "\nIf there is no answer within {} hours, I go ahead with the recommended option.", + q.deadline_hours + )); + Some(s) + } + + /// The question as the run's question list stores it. + pub fn run_question(&self) -> Option { + let q = self.question()?; + Some(crate::run_questions::Question { + id: "q1".into(), + question: q.question.clone(), + why: format!( + "Default if unanswered in {} hours: {}", + q.deadline_hours, q.default + ), + suggestions: q.options.clone(), + checked: q.tried.clone(), + ..Default::default() + }) + } + + /// What the run page and the notification say for a hold. + pub fn hold_words(&self) -> Option { + let h = self.hold()?; + let mut s = h.blocker.trim().to_string(); + if !h.location.is_empty() { + s.push_str(&format!(" ({})", h.location.trim())); + } + Some(s) + } +} + +// ── The model call ───────────────────────────────────────────────────────── + +/// What the judge asks a model. The worker's implementation calls the +/// strongest configured model at high effort; the replay suite plays back +/// recorded answers. +#[allow(async_fn_in_trait)] +pub trait JudgeModel { + /// One structured answer, or why there is none. + async fn answer(&self, system: &str, prompt: &str, schema: &Value) -> Result; +} + +/// The effort every judgment step runs at: high, not max. +pub const JUDGMENT_EFFORT: &str = "high"; + +/// The longest a person is given before reversible work takes the default. +pub const MAX_DEADLINE_HOURS: u32 = 168; +/// The deadline when the model gives none. +pub const DEFAULT_DEADLINE_HOURS: u32 = 24; + +pub const SYSTEM: &str = "You are CoderHelm's stop judge. A step of an automated coding run \ +proposes a costly decision: asking a person, stopping or waiting, blocking a pull request, \ +starting another fix cycle, or handing the run off. You see the whole run and decide.\n\n\ +Default to proceed. Decide the most reasonable assumption, proceed with it, and state it in one \ +sentence: it is listed as an open item on the pull request, where a person can correct it. \ +Uncertainty alone is never a reason to stop. A parse failure, a missing field, a rule that \ +matched, or a check that reports something are evidence to weigh, not verdicts.\n\n\ +Ask only for a fact only a person has: a product choice the ticket leaves open, access or \ +credentials the run lacks, or readings of the ticket that lead to different code. A question \ +must say what was tried, give 2 to 4 options and recommend one; reversible work goes ahead \ +with the recommendation after the deadline.\n\n\ +Hold only with a named blocker that cites checked evidence ids from the picture (E1, T2). For a \ +proposed block (request changes) a hold also needs a correctness, security or data-loss problem \ +and its location; style, naming, suggestions and unconfirmed concerns are notes on an approval. \ +For a proposed extra fix cycle, hold means the named blocker is worth one more cycle; proceed \ +means deliver what exists with open items. For a run that reached its budget, proceed means \ +deliver the draft with open items; hold means a person must act on the named blocker."; + +/// The structured answer's schema. +pub fn schema() -> Value { + json!({ + "type": "object", + "additionalProperties": false, + "required": ["verdict", "assumption", "question", "person_only", "tried", "options", + "default", "deadline_hours", "blocker", "evidence", "category", "location"], + "properties": { + "verdict": { "type": "string", "enum": ["proceed", "ask", "hold"] }, + "assumption": { "type": "string" }, + "question": { "type": "string" }, + "person_only": { "type": "string", + "enum": ["", "product_choice", "access", "divergent_readings"] }, + "tried": { "type": "array", "items": { "type": "string" } }, + "options": { "type": "array", "items": { "type": "string" } }, + "default": { "type": "string" }, + "deadline_hours": { "type": "integer" }, + "blocker": { "type": "string" }, + "evidence": { "type": "array", "items": { "type": "string" } }, + "category": { "type": "string", + "enum": ["", "correctness", "security", "data_loss", "other"] }, + "location": { "type": "string" } + } + }) +} + +/// The picture, as the judge reads it. +pub fn prompt(p: &Picture) -> String { + let mut s = String::new(); + let kind = p.kind(); + s.push_str(&format!( + "## Proposed decision\n{} by the {} step: {}\nReversible: {}\n\n", + kind.as_str(), + p.step, + clip(&p.reason), + if p.reversible { "yes" } else { "no" } + )); + if let Some(q) = &p.question { + s.push_str(&format!( + "## The question it would ask\n{}\n", + clip(&q.question) + )); + for t in &q.tried { + s.push_str(&format!("- tried: {}\n", clip(t))); + } + for o in &q.options { + s.push_str(&format!("- option: {}\n", clip(o))); + } + s.push('\n'); + } + s.push_str(&format!( + "## Ticket\n{}\n\n{}\n\n", + clip(&p.ticket_title), + clip(&p.ticket_body) + )); + if !p.acceptance.is_empty() { + s.push_str("## Acceptance criteria\n"); + for a in &p.acceptance { + s.push_str(&format!("- {}\n", clip(a))); + } + s.push('\n'); + } + if !p.related.is_empty() { + s.push_str("## Related tickets\n"); + for r in &p.related { + let pr = if r.pr.is_empty() { + String::new() + } else { + format!(" (PR {} {})", r.pr, r.pr_state) + }; + s.push_str(&format!("- {}: {}{}\n", r.ticket, clip(&r.summary), pr)); + } + s.push('\n'); + } + for (head, body) in [("Plan", &p.plan), ("Diff summary", &p.diff_summary)] { + if !body.trim().is_empty() { + s.push_str(&format!("## {head}\n{}\n\n", clip(body))); + } + } + if !p.results.is_empty() { + s.push_str("## CI and plan results\n"); + for r in &p.results { + s.push_str(&format!("- {}\n", clip(r))); + } + s.push('\n'); + } + if !p.evidence.is_empty() { + s.push_str("## Evidence (cite by id)\n"); + for e in &p.evidence { + s.push_str(&format!( + "- [{}] {} ({}{}): {}\n", + e.id, + e.source, + if e.checked { "checked" } else { "not checked" }, + if e.location.is_empty() { + String::new() + } else { + format!(", {}", e.location) + }, + clip(&e.finding) + )); + } + s.push('\n'); + } + if !p.threads.is_empty() { + s.push_str("## Threads (cite by id)\n"); + for t in &p.threads { + s.push_str(&format!( + "- [{}] {}{}: {}\n", + t.id, + if t.open { "open" } else { "settled" }, + if t.person_last { + ", a person spoke last" + } else { + "" + }, + clip(&t.summary) + )); + } + s.push('\n'); + } + s.push_str(&format!("## Budget\n{}\n", p.budget.line())); + s +} + +/// Reads and checks an answer against the rules. `Err` says what was wrong, +/// in words the re-ask passes on. +pub fn validate(p: &Picture, v: &Value) -> Result { + let s = |k: &str| v[k].as_str().unwrap_or("").trim().to_string(); + let list = |k: &str| -> Vec { + v[k].as_array() + .map(|a| { + a.iter() + .filter_map(|x| x.as_str()) + .map(|x| x.trim().to_string()) + .filter(|x| !x.is_empty()) + .collect() + }) + .unwrap_or_default() + }; + let kind = p.kind(); + match s("verdict").as_str() { + "proceed" => { + let assumption = s("assumption"); + if assumption.is_empty() { + return Err("a proceed must state its assumption in `assumption`".into()); + } + Ok(Verdict::Proceed { assumption }) + } + "ask" => { + if !kind.may_ask() { + return Err( + "a review never asks a person: proceed (approve with notes) or hold".into(), + ); + } + let question = s("question"); + if question.is_empty() { + return Err("an ask needs `question`".into()); + } + let Some(person_only) = PersonOnly::parse(&s("person_only")) else { + return Err( + "an ask must name what only a person has in `person_only`: product_choice, \ + access or divergent_readings; anything else, proceed on an assumption" + .into(), + ); + }; + let tried = list("tried"); + if tried.is_empty() { + return Err("an ask must list what was tried in `tried`".into()); + } + let options = list("options"); + if !(2..=4).contains(&options.len()) { + return Err(format!( + "an ask needs 2 to 4 `options`, not {}", + options.len() + )); + } + let default = s("default"); + let Some(default) = options + .iter() + .find(|o| o.eq_ignore_ascii_case(&default)) + .cloned() + else { + return Err("`default` must be one of `options`, word for word".into()); + }; + let hours = v["deadline_hours"].as_u64().unwrap_or(0) as u32; + let deadline_hours = if hours == 0 { + DEFAULT_DEADLINE_HOURS + } else { + hours.min(MAX_DEADLINE_HOURS) + }; + Ok(Verdict::Ask(Question { + question, + person_only, + tried, + options, + default, + deadline_hours, + })) + } + "hold" => { + let blocker = s("blocker"); + if blocker.is_empty() { + return Err("a hold must name its blocker in `blocker`".into()); + } + let evidence = list("evidence"); + if evidence.is_empty() { + return Err("a hold must cite evidence ids from the picture in `evidence`".into()); + } + for id in &evidence { + match p.cited(id) { + None => return Err(format!("`{id}` is not an evidence or thread id")), + Some(c) if !c.checked() => { + return Err(format!( + "`{id}` was not checked; a hold rests only on checked evidence or a \ + person's open thread" + )) + } + Some(_) => {} + } + } + let category = BlockCategory::parse(&s("category")); + let location = s("location"); + if kind == Kind::Block { + if category.is_none() { + return Err( + "changes are requested only for a correctness, security or data-loss \ + problem; anything else is a note on an approval (proceed)" + .into(), + ); + } + if location.is_empty() { + return Err("a request for changes must give the problem's location".into()); + } + } + Ok(Verdict::Hold(Hold { + blocker, + evidence, + category, + location, + })) + } + other => Err(format!( + "`verdict` must be proceed, ask or hold, not `{other}`" + )), + } +} + +/// The answer when the model gave none that keeps the rules. Never an ask: +/// reversible work proceeds; work that can't be undone holds on the step's +/// own reason. +pub fn fallback(p: &Picture, why: &str) -> Verdict { + if p.reversible { + Verdict::Proceed { + assumption: format!( + "the stop judge had no usable answer ({}), so the work went ahead as planned \ + instead of stopping on: {}", + crate::truncate_str(why.trim(), 200), + crate::truncate_str(p.reason.trim(), 300) + ), + } + } else { + Verdict::Hold(Hold { + blocker: format!( + "{} (the step can't be undone and the stop judge had no usable answer)", + crate::truncate_str(p.reason.trim(), 300) + ), + evidence: Vec::new(), + category: None, + location: String::new(), + }) + } +} + +/// A rule that settles the decision before any model call, if one does: +/// going on is impossible (no access the run could get, a hard ceiling), or +/// another cycle with no cycles left (the run's hard limits are not the +/// judge's to lift). +fn settled_by_rule(p: &Picture) -> Option<(Verdict, String)> { + if !p.cannot_proceed.trim().is_empty() { + return Some(( + Verdict::Hold(Hold { + blocker: p.cannot_proceed.trim().to_string(), + evidence: Vec::new(), + category: None, + location: String::new(), + }), + "cannot proceed".into(), + )); + } + if p.kind() == Kind::ExtraCycle && p.budget.cycles_spent() { + return Some(( + Verdict::Proceed { + assumption: format!( + "the {} step used its {} fix cycles; the work is delivered with what is \ + still open listed", + p.step.replace('_', " "), + p.budget.cycle_cap + ), + }, + "cycle budget".into(), + )); + } + None +} + +/// The decision. One model call; a rule-breaking answer is asked again once +/// with what was wrong; then the deterministic fallback. +pub async fn judge(model: &M, picture: Picture) -> Judged { + let picture = picture.with_ids(); + let kind = picture.kind(); + let step = picture.step.clone(); + let make = |verdict, source, replies| Judged { + kind, + step: step.clone(), + verdict, + source, + replies, + _sealed: (), + }; + if let Some((verdict, rule)) = settled_by_rule(&picture) { + return make(verdict, Source::Rule(rule), Vec::new()); + } + let schema = schema(); + let first_prompt = prompt(&picture); + let mut replies = Vec::new(); + let first = model.answer(SYSTEM, &first_prompt, &schema).await; + let problem = match first { + Ok(v) => { + let checked = validate(&picture, &v); + replies.push(v); + match checked { + Ok(verdict) => return make(verdict, Source::Model, replies), + Err(e) => e, + } + } + Err(e) => format!("no answer: {e}"), + }; + let again = format!( + "{first_prompt}\n## Your earlier answer broke a rule\n{problem}\n\nAnswer again with \ + one JSON object matching this schema exactly:\n{schema}" + ); + match model.answer(SYSTEM, &again, &schema).await { + Ok(v) => { + let checked = validate(&picture, &v); + replies.push(v); + match checked { + Ok(verdict) => make(verdict, Source::ModelReasked, replies), + Err(e) => make( + fallback(&picture, &e), + Source::Fallback(format!("{problem}; then {e}")), + replies, + ), + } + } + Err(e) => make( + fallback(&picture, &e), + Source::Fallback(format!("{problem}; then no answer: {e}")), + replies, + ), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + + /// Plays back answers in order; `Err` once they run out. + struct Recorded(Mutex>>); + + impl Recorded { + fn new(v: Vec>) -> Self { + Self(Mutex::new(v.into_iter().rev().collect())) + } + } + + impl JudgeModel for Recorded { + async fn answer(&self, _: &str, _: &str, _: &Value) -> Result { + self.0 + .lock() + .unwrap() + .pop() + .unwrap_or_else(|| Err("no more".into())) + } + } + + fn block(blocker: &str, evidence: &[&str], category: &str, location: &str) -> Value { + json!({"verdict":"hold","assumption":"","question":"","person_only":"","tried":[], + "options":[],"default":"","deadline_hours":0,"blocker":blocker, + "evidence":evidence,"category":category,"location":location}) + } + + fn proceed(a: &str) -> Value { + json!({"verdict":"proceed","assumption":a,"question":"","person_only":"","tried":[], + "options":[],"default":"","deadline_hours":0,"blocker":"","evidence":[], + "category":"","location":""}) + } + + fn picture(kind: Kind) -> Picture { + let mut p = Picture::new(kind, "test", "a step wants to stop"); + p.evidence = vec![ + Evidence { + source: "ci".into(), + finding: "unit tests fail".into(), + location: "src/a.rs:10".into(), + checked: true, + ..Default::default() + }, + Evidence { + source: "review".into(), + finding: "might be slow".into(), + checked: false, + ..Default::default() + }, + ]; + p + } + + fn run(f: F) -> F::Output { + tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(f) + } + + #[test] + fn a_good_answer_is_taken_as_it_is() { + let m = Recorded::new(vec![Ok(proceed("the button goes on the settings page"))]); + let j = run(judge(&m, picture(Kind::Ask))); + assert!(j.proceeds()); + assert_eq!(j.source(), &Source::Model); + assert!(j.open_item().unwrap().contains("settings page")); + } + + #[test] + fn a_hold_needs_checked_evidence_and_a_block_needs_category_and_location() { + let p = picture(Kind::Block).with_ids(); + assert!(validate( + &p, + &block("tests fail", &["E1"], "correctness", "src/a.rs:10") + ) + .is_ok()); + // Unchecked evidence. + assert!(validate(&p, &block("slow", &["E2"], "correctness", "src/a.rs:1")).is_err()); + // Unknown id. + assert!(validate(&p, &block("x", &["E9"], "correctness", "a")).is_err()); + // A style point is never a block. + assert!(validate(&p, &block("naming", &["E1"], "other", "src/a.rs:10")).is_err()); + // No location. + assert!(validate(&p, &block("tests fail", &["E1"], "correctness", "")).is_err()); + // A stop needs no category. + let p = picture(Kind::Stop).with_ids(); + assert!(validate(&p, &block("tests fail", &["E1"], "", "")).is_ok()); + } + + #[test] + fn an_ask_needs_a_person_only_fact_options_a_default_and_what_was_tried() { + let p = picture(Kind::Ask).with_ids(); + let ask = |person: &str, opts: Vec<&str>, default: &str, tried: Vec<&str>| { + json!({"verdict":"ask","assumption":"","question":"Which page?","person_only":person, + "tried":tried,"options":opts,"default":default,"deadline_hours":12, + "blocker":"","evidence":[],"category":"","location":""}) + }; + let ok = validate( + &p, + &ask("product_choice", vec!["a", "b"], "a", vec!["read it"]), + ); + assert!(matches!(ok, Ok(Verdict::Ask(ref q)) if q.deadline_hours == 12)); + assert!(validate(&p, &ask("", vec!["a", "b"], "a", vec!["r"])).is_err()); + assert!(validate(&p, &ask("access", vec!["a"], "a", vec!["r"])).is_err()); + assert!(validate( + &p, + &ask("access", vec!["a", "b", "c", "d", "e"], "a", vec!["r"]) + ) + .is_err()); + assert!(validate(&p, &ask("access", vec!["a", "b"], "c", vec!["r"])).is_err()); + assert!(validate(&p, &ask("access", vec!["a", "b"], "a", vec![])).is_err()); + // A review never asks. + let p = picture(Kind::Block).with_ids(); + assert!(validate(&p, &ask("access", vec!["a", "b"], "a", vec!["r"])).is_err()); + } + + #[test] + fn a_bad_answer_is_asked_again_once_then_falls_back_to_proceed_never_to_asking() { + let bad = json!({"verdict":"maybe"}); + let m = Recorded::new(vec![Ok(bad.clone()), Ok(proceed("ok"))]); + let j = run(judge(&m, picture(Kind::Ask))); + assert_eq!(j.source(), &Source::ModelReasked); + assert_eq!(j.replies().len(), 2); + + let m = Recorded::new(vec![Ok(bad.clone()), Ok(bad)]); + let j = run(judge(&m, picture(Kind::Ask))); + assert!(j.proceeds()); + assert!(matches!(j.source(), Source::Fallback(_))); + assert!(j.question().is_none()); + + let m = Recorded::new(vec![Err("timeout".into()), Err("timeout".into())]); + let j = run(judge(&m, picture(Kind::Handoff))); + assert!(j.proceeds()); + } + + #[test] + fn irreversible_work_without_an_answer_holds_on_its_own_reason() { + let mut p = picture(Kind::Stop); + p.reversible = false; + let m = Recorded::new(vec![]); + let j = run(judge(&m, p)); + assert!(j.hold().is_some()); + assert!(j.question().is_none()); + } + + #[test] + fn no_cycle_is_started_past_the_budget_and_no_model_is_called() { + let mut p = picture(Kind::ExtraCycle); + p.budget.cycles = 2; + p.budget.cycle_cap = 2; + let m = Recorded::new(vec![Ok(block("tests fail", &["E1"], "", ""))]); + let j = run(judge(&m, p)); + assert!(j.proceeds()); + assert_eq!(j.source(), &Source::Rule("cycle budget".into())); + assert!(j.replies().is_empty()); + } + + #[test] + fn what_cannot_go_on_holds_without_a_model_call() { + let mut p = picture(Kind::Stop); + p.cannot_proceed = "the repository is not connected".into(); + let m = Recorded::new(vec![Ok(proceed("go"))]); + let j = run(judge(&m, p)); + assert_eq!(j.hold_words().unwrap(), "the repository is not connected"); + assert_eq!(j.source(), &Source::Rule("cannot proceed".into())); + } + + #[test] + fn the_question_reads_with_options_default_and_deadline() { + let p = picture(Kind::Ask); + let m = Recorded::new(vec![Ok(json!({"verdict":"ask","assumption":"", + "question":"Monthly or yearly totals?","person_only":"product_choice", + "tried":["read the ticket","read the report code"],"options":["Monthly","Yearly"], + "default":"monthly","deadline_hours":0,"blocker":"","evidence":[],"category":"", + "location":""}))]); + let j = run(judge(&m, p)); + let md = j.question_markdown().unwrap(); + assert!(md.contains("1. Monthly (recommended)")); + assert!(md.contains("24 hours")); + assert!(md.contains("read the report code")); + let rq = j.run_question().unwrap(); + assert_eq!(rq.suggestions, vec!["Monthly", "Yearly"]); + } + + #[test] + fn the_prompt_carries_the_whole_picture() { + let mut p = picture(Kind::Stop); + p.ticket_title = "Add export".into(); + p.acceptance = vec!["CSV download".into()]; + p.related = vec![Related { + ticket: "SIB-2".into(), + summary: "the sibling".into(), + pr: "#9".into(), + pr_state: "open".into(), + }]; + p.threads = vec![Thread { + summary: "why this?".into(), + open: true, + person_last: true, + ..Default::default() + }]; + p.budget.cycle_cap = 2; + let text = prompt(&p.with_ids()); + for want in [ + "Add export", + "CSV download", + "SIB-2", + "[E1]", + "[T1]", + "of 2", + ] { + assert!(text.contains(want), "{want} missing:\n{text}"); + } + } +} diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index d91259891..1d78ae1cb 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -461,6 +461,14 @@ async fn main() -> Result<(), Error> { .route("/stats", get(routes::api::get_stats)) .route("/stats/history", get(routes::api::get_stats_history)) .route("/analytics", get(routes::analytics::get_analytics)) + .route( + "/analytics/decisions", + get(routes::decisions::get_decisions), + ) + .route( + "/analytics/decisions/export", + get(routes::decisions::export_decisions), + ) // Reviewer agent — per-repo config, reviews list/detail, ratings .route( "/reviewer/org-config", diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index eba492e7e..acab1cedd 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -108,6 +108,7 @@ pub const CAPABILITIES: &[Capability] = &[ "api::list_repos", "api::get_stats", "analytics::get_analytics", + "decisions::get_decisions", "plans::list_plans", "plans::get_plan", "reviewer::list_reviews", @@ -245,6 +246,7 @@ pub const CAPABILITIES: &[Capability] = &[ min_role: "member", handlers: &[ "api::retry_run", + "decisions::export_decisions", "run_answer::answer_run", "api::reset_and_rerun", "api::re_review_run", diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index e0526db53..15716207b 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -2116,6 +2116,15 @@ pub async fn retry_run( .await; info!(run_id, "Run retried — dispatched to SQS"); + // A retry as it was says the stop wasn't needed (the outcome log). + common::decision_log::on_run_acted( + &state.dynamo, + &state.config.settings_table_name, + &claims.team_id, + &run_id, + common::decision_log::Outcome::Retried, + ) + .await; Ok(Json(RunActionResult { status: "retrying".into(), @@ -2804,6 +2813,14 @@ pub async fn cancel_run( })?; info!(run_id, "Run cancelled by user"); + common::decision_log::on_run_acted( + &state.dynamo, + &state.config.settings_table_name, + &claims.team_id, + &run_id, + common::decision_log::Outcome::CancelledRun, + ) + .await; Ok(Json(RunActionResult { status: "cancelled".into(), })) diff --git a/services/gateway/src/routes/decisions.rs b/services/gateway/src/routes/decisions.rs new file mode 100644 index 000000000..4cd6833a9 --- /dev/null +++ b/services/gateway/src/routes/decisions.rs @@ -0,0 +1,87 @@ +//! Analytics of the stop judge's decisions: "Unnecessary stops" and +//! "Nuisance blocks" (rate, count, examples), and the confirmed-wrong +//! decisions as replay cases to add to the suite +//! (`common::decision_log`, `services/worker/src/passes/replay`). + +use std::sync::Arc; + +use axum::extract::{Query, State}; +use axum::http::StatusCode; +use axum::{Extension, Json}; +use chrono::{Duration, Utc}; +use serde_json::{json, Value}; + +use crate::models::Claims; +use crate::AppState; + +#[derive(serde::Deserialize)] +pub struct DecisionsQuery { + days: Option, +} + +fn window(days: Option) -> Result<(i64, String), StatusCode> { + let days = match days.unwrap_or(30) { + d @ (7 | 30 | 90) => d, + _ => return Err(StatusCode::BAD_REQUEST), + }; + Ok((days, (Utc::now() - Duration::days(days)).to_rfc3339())) +} + +/// GET /api/analytics/decisions?days=30 +pub async fn get_decisions( + State(state): State>, + Extension(claims): Extension, + Query(q): Query, +) -> Result, StatusCode> { + let (days, since) = window(q.days)?; + let records = common::decision_log::since( + &state.dynamo, + &state.config.settings_table_name, + &claims.team_id, + &since, + ) + .await; + let summary = common::decision_log::summarize(&records); + Ok(Json(json!({ + "days": days, + "summary": summary, + }))) +} + +/// GET /api/analytics/decisions/export?days=90: every confirmed-wrong +/// decision as a replay case (names as the team wrote them: scrub before +/// committing one). +pub async fn export_decisions( + State(state): State>, + Extension(claims): Extension, + Query(q): Query, +) -> Result, StatusCode> { + claims.require_role(1)?; + let (_, since) = window(q.days.or(Some(90)))?; + let records = common::decision_log::since( + &state.dynamo, + &state.config.settings_table_name, + &claims.team_id, + &since, + ) + .await; + let cases: Vec = records + .iter() + .filter(|r| r.confirmed_wrong()) + .map(common::decision_log::fixture) + .collect(); + Ok(Json(json!({ "cases": cases }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_three_windows() { + assert_eq!(window(None).unwrap().0, 30); + assert_eq!(window(Some(7)).unwrap().0, 7); + assert_eq!(window(Some(90)).unwrap().0, 90); + assert!(window(Some(12)).is_err()); + } +} diff --git a/services/gateway/src/routes/description_review.rs b/services/gateway/src/routes/description_review.rs index 3314e8630..76aa0d275 100644 --- a/services/gateway/src/routes/description_review.rs +++ b/services/gateway/src/routes/description_review.rs @@ -99,6 +99,9 @@ pub(crate) fn standing_review_awaits_answer(records: &[StoredReview]) -> bool { standing.verdict == "REQUEST_CHANGES" || standing.posted_as == "REQUEST_CHANGES" || standing.body.contains("Confirm before merge") + // The reviewer's FYI list of facts worth confirming (its wording + // since changes are requested only for named problems). + || standing.body.contains("FYI: facts worth confirming") } /// What the two claims say about queueing a review for this edit. @@ -430,6 +433,12 @@ mod tests { #[test] fn only_a_review_that_waits_on_an_answer_is_rerun() { let confirm = "Changes requested\n\n#### Confirm before merge\n- Not run against a restore of real data."; + // The approval's FYI list asks the same, without holding the merge. + assert!(standing_review_awaits_answer(&[review( + "COMMENT", + "COMMENT", + "Approved with notes\n\n#### FYI: facts worth confirming\n- The vendor's field." + )])); assert!(standing_review_awaits_answer(&[review( "REQUEST_CHANGES", "REQUEST_CHANGES", diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index b9de6490b..6c8863b44 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -1874,6 +1874,26 @@ async fn handle_pull_request( { warn!(pr_number, error = %e, "Could not record a stopped auto-merge's PR as closed"); } + // Merged with CoderHelm's request for changes on it: the flagged + // lines left as they were, or fixed first (the outcome log). + if merged { + common::decision_log::on_merged( + &state.dynamo, + &state.config.settings_table_name, + team_id, + &format!( + "{}/{}", + repo["owner"]["login"].as_str().unwrap_or(""), + repo["name"].as_str().unwrap_or("") + ), + pr_number, + payload["pull_request"]["head"]["sha"] + .as_str() + .unwrap_or(""), + None, + ) + .await; + } } } @@ -2281,6 +2301,21 @@ async fn handle_pr_review( // key. Re-evaluate the gate at once, so it never merges on a withdrawn // key and its status comment says so (fail closed). if action == "dismissed" { + // A person dismissing CoderHelm's request for changes says the block + // wasn't needed (the outcome log). + let reviewer = &payload["review"]["user"]; + if reviewer["type"].as_str() == Some("Bot") + && payload["sender"]["type"].as_str() != Some("Bot") + { + common::decision_log::on_review_dismissed( + &state.dynamo, + &state.config.settings_table_name, + team_id, + &format!("{owner}/{name}"), + pr_number, + ) + .await; + } rearm_gate( state, team_id, diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index de3f95628..800e0256b 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -15,6 +15,7 @@ pub mod chat_eval; pub mod chat_policy; pub mod connectors; pub mod data_sources; +pub mod decisions; pub mod deliveries; pub mod deliveries_analytics; pub mod description_review; diff --git a/services/gateway/src/routes/run_answer.rs b/services/gateway/src/routes/run_answer.rs index 61f9d3451..65ef79780 100644 --- a/services/gateway/src/routes/run_answer.rs +++ b/services/gateway/src/routes/run_answer.rs @@ -258,6 +258,17 @@ pub async fn answer( )); } + // What the person answered lands on the stop judge's decisions for this + // run: the default taken, or another answer (the outcome log). + let given: Vec = answers.iter().map(|a| a.answer.clone()).collect(); + common::decision_log::on_answers( + &state.dynamo, + &state.config.settings_table_name, + &claims.team_id, + run_id, + &given, + ) + .await; let asked_at = asked.and_then(|a| a.comment_url); let comment_url = post_reply(state, &item, &person.public, &answers, asked_at.as_deref()).await; let posted = comment_url.is_some(); diff --git a/services/gateway/src/routes/run_close.rs b/services/gateway/src/routes/run_close.rs index d9b79e59f..b5550b338 100644 --- a/services/gateway/src/routes/run_close.rs +++ b/services/gateway/src/routes/run_close.rs @@ -556,6 +556,14 @@ impl Ctx<'_> { async fn after_close(&self, run_id: &str, steps: &CloseSteps) -> CloseResult { info!(run_id, from = %steps.from, close_pr = self.close_pr, "Run closed by a person"); + common::decision_log::on_run_acted( + &self.state.dynamo, + &self.state.config.settings_table_name, + self.team_id, + run_id, + common::decision_log::Outcome::CancelledRun, + ) + .await; let mut out = CloseResult::new(run_id, Outcome::Closed, "Closed."); if let Some(ticket) = &steps.ticket_lock { super::api::delete_ticket_lock(self.state, self.team_id, ticket).await; diff --git a/services/worker/src/agent/policy.rs b/services/worker/src/agent/policy.rs index 4ea43e849..d46f5d258 100644 --- a/services/worker/src/agent/policy.rs +++ b/services/worker/src/agent/policy.rs @@ -431,6 +431,33 @@ pub fn claim_stop(run_id: &str) -> Option { /// pause ends) or waiting for input (an approval nobody answered), with the /// note on the run. Never overwrites a run a person cancelled or closed. pub async fn end_run_for_stop(state: &WorkerState, team_id: &str, run_id: &str, stop: &Stop) { + // An approval the team's policy requires is not the run's to skip: the + // stop is recorded as the judge's decision, without a model call. + let judged = match stop { + Stop::TimedOut { .. } => Some( + crate::passes::stop_judge::cannot_proceed( + state, + team_id, + &crate::passes::stop_judge::run_subject(run_id), + crate::passes::stop_judge::Kind::Ask, + "agent_policy", + &stop.note(), + ) + .await, + ), + Stop::Paused { .. } => None, + }; + write_run_stop(state, team_id, run_id, stop, judged.as_ref()).await; +} + +/// Writes the stop [`end_run_for_stop`] decided. +async fn write_run_stop( + state: &WorkerState, + team_id: &str, + run_id: &str, + stop: &Stop, + _judged: Option<&crate::passes::stop_judge::Judged>, +) { use aws_sdk_dynamodb::types::AttributeValue; use common::run_status::EndedValues; let status = match stop { diff --git a/services/worker/src/agent/provider.rs b/services/worker/src/agent/provider.rs index 75f37b32f..662047ba4 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -140,10 +140,20 @@ impl ModelProvider { } /// The reviewer's reading and writing of a review (`generate_review`). - /// The critic, which decides which findings are kept and so what blocks, - /// stays on [`Self::heavy_model_id`]. + /// It decides what the findings are and so what a review holds the merge + /// on: a judgment step, on [`Self::judgment_model_id`]. pub fn review_model_id(&self) -> &str { - self.heavy_route(Route::ReviewWriting) + self.judgment_model_id() + } + + /// Every judgment step: the stop judge, planner decisions, the reviewer's + /// verdicts and its severity check, done checks and question screening. + /// The strongest configured model, always (run at + /// `common::stop_judge::JUDGMENT_EFFORT`). Extraction, formatting and + /// edits stay on the cheaper models. The replay suite + /// (`passes::replay`) gates any change here. + pub fn judgment_model_id(&self) -> &str { + self.heavy_model_id() } /// The coder's model for a ticket of this complexity: simple tickets on @@ -163,7 +173,7 @@ impl ModelProvider { return self.heavy_model_id(); } match route { - Route::ReviewWriting | Route::MediumImplement => MEASURED_LIGHT_MODEL, + Route::MediumImplement => MEASURED_LIGHT_MODEL, } } @@ -193,17 +203,16 @@ impl ModelProvider { } } -/// The model the routes below were measured on and held their quality -/// (`passes/model_route_eval.rs`, `reviewer-evals.yml` route suites): -/// review writing with the heavy critic kept 40/40 planted defects and -/// blocked 55/56 cases right against 40/40 and 53/56 on the heavy model; -/// medium tickets passed 20/20 on both. +/// The model the route below was measured on and held its quality +/// (`passes/model_route_eval.rs`): medium tickets passed 20/20 on both. Review +/// writing ran here too until it was counted a judgment step (it decides what +/// a review holds the merge on); it is back on the strongest model. pub const MEASURED_LIGHT_MODEL: &str = "claude-sonnet-5-5"; -/// A heavy route that may run on [`MEASURED_LIGHT_MODEL`]. +/// 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)] enum Route { - ReviewWriting, MediumImplement, } @@ -309,7 +318,9 @@ mod client_tests { #[test] fn measured_routes_run_light_unless_the_team_chose_its_heavy_model() { let default = provider("claude-opus-5-5", false); - assert_eq!(default.review_model_id(), MEASURED_LIGHT_MODEL); + // Judgment steps are on the strongest configured model always. + assert_eq!(default.review_model_id(), "claude-opus-5-5"); + assert_eq!(default.judgment_model_id(), "claude-opus-5-5"); assert_eq!(default.implement_model_id("medium"), MEASURED_LIGHT_MODEL); // Unmeasured routes keep their models: the critic and complex // tickets on heavy, simple tickets on primary. diff --git a/services/worker/src/passes/branch_update.rs b/services/worker/src/passes/branch_update.rs index 10ed4cbe8..d2e518a86 100644 --- a/services/worker/src/passes/branch_update.rs +++ b/services/worker/src/passes/branch_update.rs @@ -123,13 +123,13 @@ pub(crate) async fn asked( super::load_team_instructions(state, &msg.team_id, &msg.repo_owner, &msg.repo_name).await; match crate::agent::anthropic::converse_json( &provider.client(), - &state.config.light_model_id, + provider.judgment_model_id(), SYSTEM, &prompt(&comments, &team), &schema(), true, - "low", - 512, + common::stop_judge::JUDGMENT_EFFORT, + 4096, usage, ) .await diff --git a/services/worker/src/passes/feature/mod.rs b/services/worker/src/passes/feature/mod.rs index 2b6e6de3a..759a1d1d2 100644 --- a/services/worker/src/passes/feature/mod.rs +++ b/services/worker/src/passes/feature/mod.rs @@ -1068,7 +1068,25 @@ async fn check_and_fix( + sandbox_failed.len(); w.report_findings("rules", open).await; w.ledger.update(|l| l.rules.checked(&head, open)); - if clean || !w.ledger.update(|l| l.rules.may_fix(MAX_FIX_ROUNDS)) || !has_time() { + let licence = + if !clean && w.ledger.update(|l| l.rules.may_fix(MAX_FIX_ROUNDS)) && has_time() { + super::stop_judge::cycle_licence( + w.state, + w.msg, + w.run_id, + "new_feature_rules", + w.ledger.update(|l| l.rules.rounds), + MAX_FIX_ROUNDS, + &super::stop_judge::evidence_lines( + "new-feature rules", + &[format!("{open} open item(s) of the new-feature rules")], + ), + ) + .await + } else { + None + }; + if clean || licence.is_none() { if !release_gaps.is_empty() { return Err(format!( "the migration can't be released safely yet: {}", @@ -1141,7 +1159,10 @@ async fn check_and_fix( .await; return Ok((!facts.is_empty()).then_some(facts)); } - w.ledger.update(|l| l.rules.start_fix()); + let Some(licence) = licence else { + return Ok(None); + }; + w.ledger.update(|l| l.rules.start_fix(licence)); w.save_ledger().await; let mut feedback = String::new(); if !release_gaps.is_empty() { diff --git a/services/worker/src/passes/feature/reuse.rs b/services/worker/src/passes/feature/reuse.rs index fe558d114..ac5302160 100644 --- a/services/worker/src/passes/feature/reuse.rs +++ b/services/worker/src/passes/feature/reuse.rs @@ -368,7 +368,7 @@ pub async fn judge( match provider::converse_simple( state, provider, - provider.primary_model_id(), + provider.judgment_model_id(), SYSTEM, &prompt(pairs), usage, 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 765cdbdc1..daf5d61b1 100644 --- a/services/worker/src/passes/incidents/k_own_review_findings.rs +++ b/services/worker/src/passes/incidents/k_own_review_findings.rs @@ -51,8 +51,15 @@ fn the_own_review_requests_changes_and_lists_every_non_optional_finding() { let mut findings = the_three_findings(); review_severity::ground(&mut findings, ""); review_severity::finalize(&mut findings); - // Every one blocks under the rubric, so the verdict can't be APPROVE. - assert!(findings.iter().all(Finding::holds_merge)); + // The two correctness and data-loss problems block; the skipped-records + // finding (a written team rule, category convention, no defect class) is + // a Suggestion. The verdict still can't be APPROVE. + assert!(findings[0].holds_merge() && findings[1].holds_merge()); + assert!(!findings[2].holds_merge()); + assert_eq!( + review_severity::label(&findings[2]), + Some(review_severity::Label::Suggestion) + ); let verdict = review_agent::decide_verdict(&findings, 0, &[], false); assert_eq!(verdict, "REQUEST_CHANGES"); assert_eq!( diff --git a/services/worker/src/passes/incidents/p_finished_work_loop.rs b/services/worker/src/passes/incidents/p_finished_work_loop.rs index ff5999289..772c5019e 100644 --- a/services/worker/src/passes/incidents/p_finished_work_loop.rs +++ b/services/worker/src/passes/incidents/p_finished_work_loop.rs @@ -157,7 +157,8 @@ fn a_continuation_does_not_reset_the_rounds_or_recheck_a_head() { l.proof.checked(&at, open); } if l.proof.may_fix(MAX_PROOF_FIX_ROUNDS) && l.proof.open > 0 { - l.proof.start_fix(); + l.proof + .start_fix(crate::passes::stop_judge::CycleLicence::for_test()); rounds_run += 1; head += 1; l.proof.end_fix(); @@ -176,7 +177,7 @@ fn no_progress_between_rounds_stops_the_fixing_at_once() { let mut r = CheckRecord::default(); r.checked("a", 2); assert!(r.may_fix(MAX_PROOF_FIX_ROUNDS)); - r.start_fix(); + r.start_fix(crate::passes::stop_judge::CycleLicence::for_test()); r.end_fix(); r.checked("b", 4); assert!(!r.may_fix(MAX_PROOF_FIX_ROUNDS)); @@ -203,7 +204,8 @@ fn time_running_out_during_fixes_leaves_only_the_description_to_do() { ..Default::default() }; l.rules.checked("a", 1); - l.rules.start_fix(); + l.rules + .start_fix(crate::passes::stop_judge::CycleLicence::for_test()); let mut next: Ledger = serde_json::from_str(&l.to_json_bounded()).unwrap(); next.on_step_start(); assert_eq!(next.opened.as_ref().unwrap().number, 7, "no second PR"); @@ -279,14 +281,17 @@ fn every_check_runs_once_on_a_head_and_stops_at_the_deadline() { let gate = fn_of(src, "\npub async fn gate(", "\nasync fn check_and_fix("); assert!(gate.contains(".unchanged(&head)"), "{name}"); assert!(gate.contains("return standing;"), "{name}"); - assert!(src.contains("start_fix()"), "{name}"); + // A round beyond the first starts only with the stop judge's licence. + assert!(src.contains("start_fix(licence)"), "{name}"); + assert!(src.contains("stop_judge::cycle_licence("), "{name}"); assert!(src.contains("w.deadline,"), "{name}"); assert!(src.contains("end_fix()"), "{name}"); } let proof_src = include_str!("../proof.rs"); let prove = fn_of(proof_src, "\npub async fn prove(", "\n#[cfg(test)]"); assert!(prove.contains("l.proof.unchanged(&head)")); - assert!(prove.contains("start_fix()")); + assert!(prove.contains("start_fix(lic)")); + assert!(prove.contains("stop_judge::cycle_licence(")); // Nothing counts rounds in a local any more. for (name, src) in [ ("proof", proof_src), diff --git a/services/worker/src/passes/jira_comment.rs b/services/worker/src/passes/jira_comment.rs index aa67b8701..9c46fc167 100644 --- a/services/worker/src/passes/jira_comment.rs +++ b/services/worker/src/passes/jira_comment.rs @@ -154,20 +154,20 @@ pub fn prompt(msg: &JiraCommentMessage) -> String { /// The model's reading of the comment; `None` when it couldn't be read. async fn classify( - state: &WorkerState, + _state: &WorkerState, provider: &ModelProvider, msg: &JiraCommentMessage, usage: &mut TokenUsage, ) -> Option { match crate::agent::anthropic::converse_json( &provider.client(), - &state.config.light_model_id, + provider.judgment_model_id(), SYSTEM, &prompt(msg), &schema(), true, - "low", - 512, + common::stop_judge::JUDGMENT_EFFORT, + 4096, usage, ) .await diff --git a/services/worker/src/passes/link_checks.rs b/services/worker/src/passes/link_checks.rs index c63fb0454..26eef918d 100644 --- a/services/worker/src/passes/link_checks.rs +++ b/services/worker/src/passes/link_checks.rs @@ -1322,11 +1322,25 @@ async fn check_and_fix( w.report_findings("links", blocking.len()).await; let head = w.head().await; w.ledger.update(|l| l.links.checked(&head, blocking.len())); - if !w.ledger.update(|l| l.links.may_fix(MAX_FIX_ROUNDS)) || !has_time() { + let licence = if w.ledger.update(|l| l.links.may_fix(MAX_FIX_ROUNDS)) && has_time() { + super::stop_judge::cycle_licence( + w.state, + w.msg, + w.run_id, + "link_check", + w.ledger.update(|l| l.links.rounds), + MAX_FIX_ROUNDS, + &super::stop_judge::evidence_lines("link and redirect check", &blocking), + ) + .await + } else { + None + }; + let Some(licence) = licence else { w.save_ledger().await; return Err(blocking.join("; ")); - } - w.ledger.update(|l| l.links.start_fix()); + }; + w.ledger.update(|l| l.links.start_fix(licence)); w.save_ledger().await; super::add_progress_note( w.state, diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index c6debf002..700796427 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -857,6 +857,8 @@ pub mod release_notes; pub mod release_plan; pub mod release_run; pub mod remote_mcp; +#[cfg(test)] +mod replay; pub(crate) mod repo_pick; mod resolve; mod resolved; @@ -899,6 +901,7 @@ pub mod skills; pub mod stack; pub(crate) mod steps; pub(crate) mod stop_gate; +pub mod stop_judge; pub mod stop_pr; pub mod support_sync; pub mod syntax_check; @@ -2535,21 +2538,42 @@ async fn run_passes( ), ..Default::default() }; - finish_without_code( + let proposed = unknown_fix_questions(&decision, &msg.answers, &plan_result.tasks); + let mut picture = + stop_judge::ask_picture("plan_files", &decision.cause, msg, &proposed); + picture.plan = plan_result.tasks.clone(); + let judged = stop_judge::decide( state, - msg, - run_id, - &github, - &decision, - fix_location::Route::Ask, - &plan_result.tasks, + &provider, usage, - start, - &used_mcp_ids, + &msg.team_id, + &stop_judge::run_subject(run_id), + "", + picture, ) .await; - close_memory(state, agent_memory.take()).await; - return Ok(()); + if !judged.proceeds() { + finish_without_code( + state, + msg, + run_id, + &github, + &decision, + fix_location::Route::Ask, + &plan_result.tasks, + usage, + start, + &used_mcp_ids, + Some(&judged), + ) + .await; + close_memory(state, agent_memory.take()).await; + return Ok(()); + } + info!( + run_id, + "Stop judge: code the plan's files on an assumption instead of asking" + ); } early_validation = Some(v); } @@ -2614,6 +2638,54 @@ async fn run_passes( ); } + // Not knowing where the fix belongs is a question only when a person + // alone can answer it: the stop judge decides first, on the whole + // picture. A proceed codes what the plan's tasks name, on a written + // assumption; with nothing to code it reports what was found. + let mut fix_judged: Option = None; + if fix_route == fix_location::Route::Ask + && !plan_result.tasks.starts_with("NO_CHANGES_NEEDED:") + && !plan_result.tasks.starts_with("CLARIFICATION_NEEDED:") + { + if let Some(decision) = plan_result.fix.as_ref() { + let proposed = unknown_fix_questions(decision, &msg.answers, &plan_result.tasks); + let mut picture = stop_judge::ask_picture( + "fix_location", + &format!( + "the plan doesn't settle where the fix belongs: {}", + decision.cause.trim() + ), + msg, + &proposed, + ); + picture.plan = plan_result.tasks.clone(); + let judged = stop_judge::decide( + state, + &provider, + usage, + &msg.team_id, + &stop_judge::run_subject(run_id), + "", + picture, + ) + .await; + if judged.proceeds() { + let codes = !plan_result.tasks.trim().is_empty() + && !plan_result + .tasks + .trim_start() + .starts_with(fix_location::NO_CODE_CHANGE); + fix_route = if codes { + fix_location::Route::Code + } else { + fix_location::Route::OutsideOnly + }; + info!(run_id, route = ?fix_route, "Stop judge: proceed instead of asking where the fix belongs"); + } + fix_judged = Some(judged); + } + } + // --- Check: is the fix outside the code? --- // The code works as designed and the outcome comes from data or settings // in another system: report the change to make there, open no PR. Not @@ -2662,6 +2734,7 @@ async fn run_passes( usage, start, &used_mcp_ids, + fix_judged.as_ref(), ) .await; close_memory(state, agent_memory.take()).await; @@ -2838,7 +2911,93 @@ async fn run_passes( } // --- Check: clarification needed? --- + // The planner's questions go to the stop judge first: it proceeds on a + // written assumption unless only a person has the answer. A proceed + // plans again once with the assumption as the answer; a plan that still + // asks after that is a planner failure, never a question. + if plan_result.tasks.starts_with("CLARIFICATION_NEEDED:") { + let detail = plan_result + .tasks + .strip_prefix("CLARIFICATION_NEEDED:") + .unwrap_or("") + .trim() + .to_string(); + let proposed = clarification_questions(&detail, &msg.answers); + let mut picture = stop_judge::ask_picture( + "plan", + &format!("the planner asks before it can plan: {detail}"), + msg, + &proposed, + ); + picture.plan = plan_result.design.clone(); + let judged = stop_judge::decide( + state, + &provider, + usage, + &msg.team_id, + &stop_judge::run_subject(run_id), + "", + picture, + ) + .await; + if judged.proceeds() { + let assumed = stop_judge::assumed_answers(&judged, &proposed); + info!( + run_id, + "Stop judge: plan on an assumption instead of asking" + ); + add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "Planning on an assumption instead of asking: {}", + judged.assumption().unwrap_or("") + ), + ) + .await; + common::run_questions::merge(&mut msg.answers, &assumed); + plan_result = plan::run( + state, + msg, + &github, + &triage_result, + &repo_instructions, + &provider, + usage, + run_id, + &history, + true, + ) + .await?; + if plan_result.tasks.starts_with("CLARIFICATION_NEEDED:") { + close_memory(state, agent_memory.take()).await; + return Err(format!( + "Planner failure: the plan asked again after planning on the assumption \"{}\". \ + Nothing was asked of a person; retry the run.", + judged.assumption().unwrap_or("") + ) + .into()); + } + } + } if plan_result.tasks.starts_with("CLARIFICATION_NEEDED:") { + let judged = stop_judge::decide( + state, + &provider, + usage, + &msg.team_id, + &stop_judge::run_subject(run_id), + "", + stop_judge::ask_picture( + "plan", + "the planner still asks after an assumption", + msg, + &[], + ), + ) + .await; + let detail = plan_result .tasks .strip_prefix("CLARIFICATION_NEEDED:") @@ -2849,10 +3008,11 @@ async fn run_passes( detail, "Plan needs clarification from the ticket author" ); - // The questions, one by one: on the ticket, and kept on the run so - // its page lists them and takes answers. Questions people answered - // already in CoderHelm are not asked again. - let questions = clarification_questions(detail, &msg.answers); + // The judge's question (options, a default and a deadline), else + // the planner's, one by one: on the ticket, and kept on the run so + // its page lists them and takes answers. + let questions = + stop_judge::questions_for(&judged, &clarification_questions(detail, &msg.answers)); // Stop rule 1, at the point the questions would be asked: one that // quotes the run's own tooling failing is never a question. if let Some(f) = questions.iter().find_map(|q| { @@ -2861,8 +3021,8 @@ async fn run_passes( close_memory(state, agent_memory.take()).await; return Err(f.reason().into()); } - let list_md = common::run_questions::markdown(&questions); - let list_plain = common::run_questions::plain(&questions); + let list_md = stop_judge::stop_text(&judged, &common::run_questions::markdown(&questions)); + let list_plain = stop_judge::stop_text(&judged, &common::run_questions::plain(&questions)); let raw_github = format!( "❓ **Clarification needed**\n\n{list_md}\n\nReply here, or answer on the run page in \ CoderHelm, and I'll continue." @@ -2883,12 +3043,27 @@ async fn run_passes( &github_comment, &jira_comment, "Clarification needed", + &judged, ) .await; // Mark the run as needs_input so a comment can re-trigger it - let wait = wait_on_ticket(msg, &questions, detail); - mark_run_needs_input(state, msg, run_id, usage, start, &used_mcp_ids, &wait).await; + let wait = if judged.hold().is_some() { + stop_judge::wait_for(&judged, &questions, None, &ticket_url(msg)) + } else { + wait_on_ticket(msg, &questions, detail) + }; + mark_run_needs_input( + state, + msg, + run_id, + usage, + start, + &used_mcp_ids, + &wait, + &judged, + ) + .await; close_memory(state, agent_memory.take()).await; return Ok(()); @@ -3180,9 +3355,10 @@ async fn run_passes( // about it: don't open a second one; ask (once). if existing_pr.is_none() && !open_pr_settled { if let Some(other) = other_open_pr.as_ref() { - stop_for_open_pr(state, msg, &github, run_id, usage, start, other).await; - close_memory(state, agent_memory.take()).await; - return Ok(()); + if stop_for_open_pr(state, msg, &github, run_id, usage, start, other).await { + close_memory(state, agent_memory.take()).await; + return Ok(()); + } } } @@ -3950,7 +4126,11 @@ async fn run_passes( if choice == open_pr_choice::Choice::Own { continue; } - stop_for_open_pr(state, msg, &github, run_id, usage, start, &other).await; + if !stop_for_open_pr(state, msg, &github, run_id, usage, start, &other) + .await + { + continue; + } close_memory(state, agent_memory.take()).await; return Ok(()); } @@ -4517,14 +4697,45 @@ async fn run_passes( result.files_modified = files; } run_end::Empty::Ask(qs) => { + let proposed = run_end::questions_from(&qs); + let judged = stop_judge::decide( + state, + &provider, + usage, + &msg.team_id, + &stop_judge::run_subject(run_id), + "", + stop_judge::ask_picture( + "implement", + "the coder built what it could and asks for a decision", + msg, + &proposed, + ), + ) + .await; + if judged.proceeds() { + // Nothing to commit and nothing to ask: a failure the + // run page names (Retry carries the assumption on). + close_memory(state, agent_memory.take()).await; + return Err(format!( + "The coder made no change and asked for a decision; the stop judge \ + found it isn't one only a person has. Assumed: {}. Retry to build \ + on that.", + judged.assumption().unwrap_or("") + ) + .into()); + } + let asked = stop_judge::questions_for(&judged, &proposed); let text = format!( - "I built what I could and need a decision before I go on:\n{}", - qs.iter() - .map(|q| format!("- {q}")) - .collect::>() - .join("\n") + "I built what I could and need a decision before I go on:\n\n{}", + stop_judge::stop_text( + &judged, + &qs.iter() + .map(|q| format!("- {q}")) + .collect::>() + .join("\n") + ) ); - let asked = run_end::questions_from(&qs); ask_on_ticket( state, msg, @@ -4534,11 +4745,21 @@ async fn run_passes( &text, &text, "A decision is needed", + &judged, + ) + .await; + let wait = stop_judge::wait_for(&judged, &asked, None, &ticket_url(msg)); + mark_run_needs_input( + state, + msg, + run_id, + usage, + start, + &used_mcp_ids, + &wait, + &judged, ) .await; - let wait = wait_on_ticket(msg, &asked, &text); - mark_run_needs_input(state, msg, run_id, usage, start, &used_mcp_ids, &wait) - .await; close_memory(state, agent_memory.take()).await; return Ok(()); } @@ -4584,6 +4805,49 @@ async fn run_passes( } else { empty_change_questions() }; + // A repository the team hasn't turned on is access only a person + // can give; anything else goes to the stop judge, and a proceed + // is a failure to retry, never generic questions. + let judged = match elsewhere_note.as_deref() { + Some(note) => { + stop_judge::cannot_proceed( + state, + &msg.team_id, + &stop_judge::run_subject(run_id), + stop_judge::Kind::Ask, + "implement", + note, + ) + .await + } + None => { + stop_judge::decide( + state, + &provider, + usage, + &msg.team_id, + &stop_judge::run_subject(run_id), + "", + stop_judge::ask_picture( + "implement", + "the coder produced no file changes", + msg, + &questions, + ), + ) + .await + } + }; + if judged.proceeds() { + close_memory(state, agent_memory.take()).await; + return Err(format!( + "The coder produced no file changes. Nothing was asked of a person: the stop \ + judge found the ticket answers it. Assumed: {}. Retry the run.", + judged.assumption().unwrap_or("") + ) + .into()); + } + let questions = stop_judge::questions_for(&judged, &questions); ask_on_ticket( state, msg, @@ -4593,38 +4857,26 @@ async fn run_passes( &clarification, &clarification, "More detail needed", + &judged, ) .await; - let duration = start.elapsed().as_secs(); - let delta = usage.unrecorded(); - let now = chrono::Utc::now().to_rfc3339(); - let wait = wait_on_ticket(msg, &questions, raw_clarification); - let usage_res = state - .dynamo - .update_item() - .table_name(&state.config.runs_table_name) - .key("team_id", attr_s(&msg.team_id)) - .key("run_id", attr_s(run_id)) - .update_expression( - "SET #status = :s, status_run_id = :sri, waiting_on = :wo, error_message = :em, \ - tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ - cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ - cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t, current_pass = :cp", - ) - .expression_attribute_names("#status", "status") - .needs_input(run_id, &wait) - .expression_attribute_values(":em", attr_s(raw_clarification)) - .usage_values(&delta) - .expression_attribute_values(":d", attr_n(duration)) - .expression_attribute_values(":t", attr_s(&now)) - .expression_attribute_values(":cp", attr_s("done")) - .send() - .await; - if usage_res.is_ok() { - usage.mark_recorded(&delta); - } - self::webhooks::emit_run(state, &msg.team_id, run_id, "needs_input").await; + let wait = if judged.hold().is_some() { + stop_judge::wait_for(&judged, &questions, None, &ticket_url(msg)) + } else { + wait_on_ticket(msg, &questions, raw_clarification) + }; + mark_unbuilt_needs_input( + state, + msg, + run_id, + usage, + start, + &wait, + raw_clarification, + &judged, + ) + .await; close_memory(state, agent_memory.take()).await; return Ok(()); } @@ -5606,6 +5858,9 @@ async fn run_passes( if let Some(f) = &feature_pr { gaps.extend(feature::open_findings(f)); } + // What the stop judge assumed instead of asking: an Open item a person + // corrects if it's wrong. + gaps.extend(stop_judge::assumptions(state, &msg.team_id, run_id).await); pr::apply_checks( state, msg, @@ -6600,6 +6855,7 @@ async fn run_repo_pipeline( None } }; + gaps.extend(stop_judge::assumptions(state, &msg.team_id, run_id).await); pr::apply_checks( state, msg, @@ -7037,8 +7293,12 @@ async fn finish_without_code( usage: &TokenUsage, start: &std::time::Instant, mcp_ids: &[String], + judged: Option<&stop_judge::Judged>, ) { - let outside = route == fix_location::Route::OutsideOnly; + // Asking needs a judged ask or hold; without one the run reports what it + // found and asks nothing. + let judged = judged.filter(|j| !j.proceeds()); + let outside = route == fix_location::Route::OutsideOnly || judged.is_none(); let (report, jira_title, jira_type) = if outside { ( fix_location::outside_report(decision, false), @@ -7089,10 +7349,15 @@ async fn finish_without_code( warn!(run_id, error = %e, "Could not post the outside-the-code report on the ticket"); } } - } else { - // Not knowing where the fix belongs is a question for a person: the - // run page lists the decision's questions and takes the answers. - let questions = unknown_fix_questions(decision, &msg.answers, tasks); + } else if let Some(judged) = judged { + // The judge let it ask (a fact only a person has) or named what + // blocks: the run page lists the question and takes the answer. + let questions = stop_judge::questions_for( + judged, + &unknown_fix_questions(decision, &msg.answers, tasks), + ); + let github_body = format!("{github_body}\n\n{}", stop_judge::stop_text(judged, "")); + let jira_body = format!("{jira_body}\n\n{}", stop_judge::stop_text(judged, "")); ask_on_ticket( state, msg, @@ -7102,10 +7367,15 @@ async fn finish_without_code( &github_body, &jira_body, jira_title, + judged, ) .await; - let wait = wait_on_ticket(msg, &questions, &report); - mark_run_needs_input(state, msg, run_id, usage, start, mcp_ids, &wait).await; + let wait = if judged.hold().is_some() { + stop_judge::wait_for(judged, &questions, None, &ticket_url(msg)) + } else { + wait_on_ticket(msg, &questions, &report) + }; + mark_run_needs_input(state, msg, run_id, usage, start, mcp_ids, &wait, judged).await; } let status = if outside { fix_location::STATUS_OUTSIDE @@ -7556,19 +7826,67 @@ async fn report_questions( /// What a run that asked on its ticket waits for: the questions it asked, /// else the missing detail on the ticket (`what`: what it said there). -fn wait_on_ticket( +/// A run that built nothing waits on the judged question or blocker, with +/// what it found as its error message. +#[allow(clippy::too_many_arguments)] +async fn mark_unbuilt_needs_input( + state: &WorkerState, msg: &TicketMessage, - questions: &[common::run_questions::Question], - what: &str, -) -> WaitingOn { - let ticket = if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { + run_id: &str, + usage: &TokenUsage, + start: &std::time::Instant, + wait: &WaitingOn, + error: &str, + _judged: &stop_judge::Judged, +) { + let duration = start.elapsed().as_secs(); + let delta = usage.unrecorded(); + let now = chrono::Utc::now().to_rfc3339(); + let usage_res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("run_id", attr_s(run_id)) + .update_expression( + "SET #status = :s, status_run_id = :sri, waiting_on = :wo, error_message = :em, \ + tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t, current_pass = :cp", + ) + .expression_attribute_names("#status", "status") + .needs_input(run_id, wait) + .expression_attribute_values(":em", attr_s(error)) + .usage_values(&delta) + .expression_attribute_values(":d", attr_n(duration)) + .expression_attribute_values(":t", attr_s(&now)) + .expression_attribute_values(":cp", attr_s("done")) + .send() + .await; + if usage_res.is_ok() { + usage.mark_recorded(&delta); + } + self::webhooks::emit_run(state, &msg.team_id, run_id, "needs_input").await; +} + +/// The ticket's address, when it is a GitHub issue (empty otherwise). +fn ticket_url(msg: &TicketMessage) -> String { + if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { format!( "https://github.com/{}/{}/issues/{}", msg.repo_owner, msg.repo_name, msg.issue_number ) } else { String::new() - }; + } +} + +fn wait_on_ticket( + msg: &TicketMessage, + questions: &[common::run_questions::Question], + what: &str, +) -> WaitingOn { + let ticket = ticket_url(msg); WaitingOn::answer_or( questions, None, @@ -7582,6 +7900,7 @@ fn wait_on_ticket( /// Mark a run `needs_input` (a comment or re-run can pick it up again) and /// count it in the analytics, the way every needs_input stop is recorded. +#[allow(clippy::too_many_arguments)] async fn mark_run_needs_input( state: &WorkerState, msg: &TicketMessage, @@ -7590,6 +7909,7 @@ async fn mark_run_needs_input( start: &std::time::Instant, mcp_ids: &[String], wait: &WaitingOn, + _judged: &stop_judge::Judged, ) { let duration = start.elapsed().as_secs(); let delta = usage.unrecorded(); @@ -7647,6 +7967,7 @@ pub(crate) async fn mark_run_stopped_by_guard( msg: &TicketMessage, run_id: &str, reason: &str, + _judged: &stop_judge::Judged, ) { if let Err(e) = state .dynamo @@ -7715,7 +8036,18 @@ async fn stop_run_repo_not_enabled( message, "", ); - mark_run_needs_input(state, msg, run_id, usage, start, &[], &wait).await; + // Access only a person can give: recorded as the judge's decision, no + // model call. + let judged = stop_judge::cannot_proceed( + state, + &msg.team_id, + &stop_judge::run_subject(run_id), + stop_judge::Kind::Stop, + "repo_access", + message, + ) + .await; + mark_run_needs_input(state, msg, run_id, usage, start, &[], &wait, &judged).await; } /// Append a timestamped progress note to the run record for live activity display. @@ -8529,10 +8861,10 @@ async fn stop_for_open_pr( msg: &TicketMessage, github: &GitHubClient, run_id: &str, - usage: &TokenUsage, + usage: &mut TokenUsage, start: &std::time::Instant, pr: &open_pr_choice::OtherPr, -) { +) -> bool { let note = open_pr_choice::notice_text(&msg.ticket_id, pr); info!( run_id, @@ -8542,6 +8874,44 @@ async fn stop_for_open_pr( ); add_progress_note(state, &msg.team_id, run_id, ¬e).await; let question = open_pr_choice::notice_question(pr); + // Opening CoderHelm's own draft beside it is reversible and leaves the + // other pull request as it is: the stop judge decides whether this is a + // question only a person can answer. + let mut picture = + stop_judge::ask_picture("open_pr", ¬e, msg, std::slice::from_ref(&question)); + picture.related = vec![stop_judge::Related { + ticket: msg.ticket_id.clone(), + summary: pr.title.clone(), + pr: format!("{}#{}", pr.repo, pr.number), + pr_state: "open".into(), + }]; + let judged = stop_judge::decide_for_team( + state, + usage, + &msg.team_id, + &stop_judge::run_subject(run_id), + "", + picture, + ) + .await; + if judged.proceeds() { + add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "Opening my own pull request beside #{} instead of asking: {}", + pr.number, + judged.assumption().unwrap_or("") + ), + ) + .await; + return false; + } + let question = stop_judge::questions_for(&judged, std::slice::from_ref(&question)) + .into_iter() + .next() + .unwrap_or(question); ask_on_ticket_keyed( state, msg, @@ -8552,10 +8922,12 @@ async fn stop_for_open_pr( ¬e, "A pull request is already open", &pr.key(), + &judged, ) .await; let wait = wait_on_ticket(msg, std::slice::from_ref(&question), ¬e); - mark_run_needs_input(state, msg, run_id, usage, start, &[], &wait).await; + mark_run_needs_input(state, msg, run_id, usage, start, &[], &wait, &judged).await; + true } async fn post_jira_comment( @@ -8666,6 +9038,7 @@ async fn ask_on_ticket( github_body: &str, jira_body: &str, jira_title: &str, + judged: &stop_judge::Judged, ) { ask_on_ticket_keyed( state, @@ -8677,6 +9050,7 @@ async fn ask_on_ticket( jira_body, jira_title, "", + judged, ) .await } @@ -8695,7 +9069,9 @@ async fn ask_on_ticket_keyed( jira_body: &str, jira_title: &str, key: &str, + judged: &stop_judge::Judged, ) { + stop_judge::keep_ask_deadline(state, &msg.team_id, run_id, judged).await; let text_hash = common::sha256_hex(&[ &questions .iter() @@ -8728,7 +9104,7 @@ async fn ask_on_ticket_keyed( ) .await; let url = (!earlier.url.is_empty()).then(|| earlier.url.clone()); - record_questions(state, &msg.team_id, run_id, questions, url).await; + record_questions(state, &msg.team_id, run_id, questions, url, judged).await; return; } let mut comment_url = None; @@ -8785,7 +9161,7 @@ async fn ask_on_ticket_keyed( ) .await; } - record_questions(state, &msg.team_id, run_id, questions, comment_url).await; + record_questions(state, &msg.team_id, run_id, questions, comment_url, judged).await; } /// What a run asks when it wrote no change and the ticket names no other @@ -8836,6 +9212,7 @@ async fn record_questions( run_id: &str, questions: &[common::run_questions::Question], comment_url: Option, + _judged: &stop_judge::Judged, ) { if questions.is_empty() { return; @@ -10231,7 +10608,7 @@ Respond with ONLY one line: either "CORRECT" or "SWITCH owner/name"."#, state, provider, common::agent_policy::Agent::Planner, - provider.primary_model_id(), + provider.judgment_model_id(), system, &mut messages, &[], @@ -10239,9 +10616,9 @@ Respond with ONLY one line: either "CORRECT" or "SWITCH owner/name"."#, usage, llm::ConverseOptions { max_turns: 1, - max_tokens: 128, + max_tokens: 4096, deadline: None, - effort: Some("low"), + effort: Some(common::stop_judge::JUDGMENT_EFFORT), }, None, None, diff --git a/services/worker/src/passes/open_pr_choice.rs b/services/worker/src/passes/open_pr_choice.rs index 2af56c6d4..5654ff682 100644 --- a/services/worker/src/passes/open_pr_choice.rs +++ b/services/worker/src/passes/open_pr_choice.rs @@ -212,7 +212,7 @@ pub fn prompt(notice: &str, reply: &Reply) -> String { /// The model's reading of one reply; `Unclear` when it couldn't be read. async fn classify( - state: &WorkerState, + _state: &WorkerState, provider: &ModelProvider, notice: &str, reply: &Reply, @@ -220,13 +220,13 @@ async fn classify( ) -> Choice { match crate::agent::anthropic::converse_json( &provider.client(), - &state.config.light_model_id, + provider.judgment_model_id(), SYSTEM, &prompt(notice, reply), &schema(), true, - "low", - 512, + common::stop_judge::JUDGMENT_EFFORT, + 4096, usage, ) .await diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 84b5fed04..0f58a5d2a 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -736,7 +736,7 @@ Then the ```fix_location.json block described above."#, effort: None, }; - let model_id = provider.primary_model_id(); + let model_id = provider.judgment_model_id(); let can_look_up = live.as_ref().is_some_and(|l| !l.tools().is_empty()); let lookups = || live.as_ref().map_or(0, |l| l.lookups_made()); let mut response = provider::converse( @@ -1248,8 +1248,8 @@ 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. + // The revision answers the advice in one turn, at the + // review's effort (high: a judgment step). let one_turn = llm::ConverseOptions { max_turns: 1, effort: Some(super::skills::review_effort("plan")), @@ -1522,7 +1522,7 @@ async fn reask_decision( state, provider, common::agent_policy::Agent::Planner, - provider.primary_model_id(), + provider.judgment_model_id(), "You write one JSON block for a plan that already exists. Return only the block.", &mut messages, &[], @@ -1530,9 +1530,9 @@ async fn reask_decision( usage, llm::ConverseOptions { max_turns: 1, - max_tokens: 4096, + max_tokens: 8192, deadline: None, - effort: Some("low"), + effort: Some(common::stop_judge::JUDGMENT_EFFORT), }, None, None, diff --git a/services/worker/src/passes/plan_judge.rs b/services/worker/src/passes/plan_judge.rs index d72298879..15158beeb 100644 --- a/services/worker/src/passes/plan_judge.rs +++ b/services/worker/src/passes/plan_judge.rs @@ -325,7 +325,7 @@ pub async fn judge( match provider::converse_simple( state, provider, - provider.primary_model_id(), + provider.judgment_model_id(), SYSTEM, prompt, usage, diff --git a/services/worker/src/passes/proof.rs b/services/worker/src/passes/proof.rs index 808ff744f..5b4db93d5 100644 --- a/services/worker/src/passes/proof.rs +++ b/services/worker/src/passes/proof.rs @@ -403,7 +403,8 @@ impl Finding { match self.point.trim() { "ci_pending" => Settler::Ci, "manual_check" => Settler::Person, - "end_to_end" | "optional_task" | "check_blocked" | "rule_failing" => Settler::Owner, + "end_to_end" | "optional_task" | "check_blocked" | "rule_failing" + | JUDGE_ASSUMPTION => Settler::Owner, _ => Settler::Proof, } } @@ -412,6 +413,7 @@ impl Finding { match self.point.trim() { "ci_pending" => "Waiting on CI", "check_blocked" => "Check not passed", + JUDGE_ASSUMPTION => "Assumed instead of asking", "rule_failing" => "New-feature rule failing", "manual_check" => "Check by hand", "unrun_check" => "Check not run", @@ -1259,6 +1261,10 @@ fn is_security(f: &Finding) -> bool { /// An Open item for a check the change didn't pass. The pull request is /// already open, so a check can't stop it: it holds the draft instead, until a /// person deals with it. +/// The point of an Open item the stop judge proceeded on +/// (`passes::stop_judge::assumptions`): a person corrects it if it's wrong. +pub const JUDGE_ASSUMPTION: &str = "judge_assumption"; + pub fn blocked_item(check: &str, why: &str) -> Finding { Finding { point: "check_blocked".to_string(), @@ -1718,8 +1724,32 @@ pub async fn prove( .ledger .update(|l| (l.proof.rounds, l.proof.may_fix(MAX_FIX_ROUNDS))); // Only a round that could run asks about time: a "no" for one that - // couldn't would send the run to a fresh step for nothing. - let fix_ok = may_fix && has_time(); + // couldn't would send the run to a fresh step for nothing. A round + // beyond the first is the stop judge's call. + let wants_round = may_fix + && has_time() + && matches!(next(findings.as_deref(), rounds, true), Next::FixRound); + let mut licence = if wants_round { + let open: Vec = findings + .as_deref() + .unwrap_or_default() + .iter() + .map(|f| f.detail.clone()) + .collect(); + super::stop_judge::cycle_licence( + w.state, + w.msg, + w.run_id, + "proof_check", + rounds, + MAX_FIX_ROUNDS, + &super::stop_judge::evidence_lines("proof check", &open), + ) + .await + } else { + None + }; + let fix_ok = licence.is_some(); match next(findings.as_deref(), rounds, fix_ok) { Next::Open => { if findings.is_some() { @@ -1764,7 +1794,10 @@ pub async fn prove( } Next::FixRound => { let gaps = findings.unwrap_or_default(); - w.ledger.update(|l| l.proof.start_fix()); + let Some(lic) = licence.take() else { + return gaps; + }; + w.ledger.update(|l| l.proof.start_fix(lic)); w.save_ledger().await; super::add_progress_note( w.state, diff --git a/services/worker/src/passes/replay/README.md b/services/worker/src/passes/replay/README.md new file mode 100644 index 000000000..1bdd63761 --- /dev/null +++ b/services/worker/src/passes/replay/README.md @@ -0,0 +1,52 @@ +# Replay suite + +Incidents where CoderHelm stopped, asked, blocked or looped when it should +have gone on, replayed through the real decision code and graded on the +decision. CI runs it with the incident suite (`cargo test -p worker +replay::`); a prompt, model or effort change that breaks a case fails CI. + +## Add an incident + +Add one file to `cases/`, named `NN_what_happened.json`. Use made-up names +only (no company, customer, repository, ticket or person names). + +```json +{ + "name": "one line: what must hold", + "about": "what happened, and why the decision below is right", + "case": "stop_judge", + "input": { "picture": { "kind": "ask", "step": "plan", "reason": "...", "reversible": true } }, + "replies": [[ {"verdict": "proceed", "assumption": "..."} ], [ ... ], [ ... ]], + "expect": { "verdict": "proceed", "never_ask": true } +} +``` + +- `case` picks the decision path (see `mod.rs`): `stop_judge`, + `ticket_route`, `registration`, `run_loop`, `review_settled`, + `blocker_comment`, `deploy_count`. Each reads its own `input` and + `expect`; the existing cases show both. +- `replies`: where the stop judge is called, the model's recorded answers, + one list per trial, in call order (a rule-breaking first answer followed by + the re-asked one is two entries). Three trials (`k` = 3), and every trial + must pass (pass^k). Cases with no model call leave `replies` out. +- Record real answers with `REPLAY_RECORD=1 ANTHROPIC_API_KEY=... cargo test + -p worker replay::replay_record -- --ignored` and review the diff. +- Run the real model on every case without writing anything with + `REPLAY_LIVE=1 ANTHROPIC_API_KEY=... cargo test -p worker + replay::replay_live -- --ignored` (optional, not in CI). + +## From the outcome log + +A decision people confirmed wrong (a question answered with the default, a +review dismissed or merged unchanged) exports as a case from Analytics +("Unnecessary stops" and "Nuisance blocks", export) or from +`common::decision_log::fixture`. It arrives as a `stop_judge` case with the +picture and the answers that were wrong, so it fails until the decision is +right. Scrub names, fix the decision path, record three trials, commit. + +## Model and effort + +Judgment steps run on the strongest configured model at high effort +(`ModelProvider::judgment_model_id`, `common::stop_judge::JUDGMENT_EFFORT`), +and `passes::stop_judge`'s tests list every one. A downgrade to a cheaper +model or a lower effort clears this suite in live mode first. diff --git a/services/worker/src/passes/replay/cases/01_feature_complaint_missing_planner_field.json b/services/worker/src/passes/replay/cases/01_feature_complaint_missing_planner_field.json new file mode 100644 index 000000000..c8ed24a43 --- /dev/null +++ b/services/worker/src/passes/replay/cases/01_feature_complaint_missing_planner_field.json @@ -0,0 +1,17 @@ +{ + "name": "a feature phrased as a complaint, with the planner's decision block missing, goes to code", + "about": "A ticket filed as a bug complains that a page lacks a filter; the planner's answer lost its fix_location block. The run asked a person where the fix belongs after spending its budget. The plan's tasks name this repository's files, so the run codes them and asks nothing.", + "case": "ticket_route", + "input": { + "title": "The class schedule page has no way to filter by coach", + "body": "Members keep complaining that they can't find a coach's classes on the schedule page.\n\n## Acceptance criteria\n- A coach filter on the schedule page\n- The filter keeps the chosen coach when the week changes", + "ticket_type": "Bug", + "model_intent": "bug", + "planner_answer": "## Design\nAdd a coach filter to the schedule page and pass it to the classes query.\n\n## Tasks\n- [ ] apps/web/src/app/schedule/page.tsx: [modify] Add the coach filter\n- [ ] apps/web/src/lib/classes.ts: [modify] Filter the query by coach\n", + "tasks": "- [ ] apps/web/src/app/schedule/page.tsx: [modify] Add the coach filter\n- [ ] apps/web/src/lib/classes.ts: [modify] Filter the query by coach" + }, + "expect": { + "route": "code", + "asked": false + } +} diff --git a/services/worker/src/passes/replay/cases/02_helper_beside_registered_schema_files.json b/services/worker/src/passes/replay/cases/02_helper_beside_registered_schema_files.json new file mode 100644 index 000000000..89bd3417a --- /dev/null +++ b/services/worker/src/passes/replay/cases/02_helper_beside_registered_schema_files.json @@ -0,0 +1,26 @@ +{ + "name": "a validation helper beside registered schema documents is not a new item", + "about": "The new-feature rule counted any new file in a folder of registered schema documents as a sibling that must be registered, so a module of validation helpers blocked the pull request. Judged by structure (no default export, no schema), it is another kind of file and nothing blocks.", + "case": "registration", + "input": { + "tree": [ + "studio/schemaTypes/documents/author.ts", + "studio/schemaTypes/documents/blog.ts", + "studio/schemaTypes/documents/blog-index.ts", + "studio/schemaTypes/documents/index.ts", + "studio/structure.ts" + ], + "files": { + "studio/schemaTypes/documents/author.ts": "import {defineField, defineType} from 'cms-kit'\n\nexport default defineType({\n name: 'author',\n type: 'document',\n fields: [defineField({name: 'title', type: 'string'})],\n})\n", + "studio/schemaTypes/documents/blog.ts": "import {defineField, defineType} from 'cms-kit'\n\nexport default defineType({\n name: 'blog',\n type: 'document',\n fields: [defineField({name: 'title', type: 'string'})],\n})\n", + "studio/schemaTypes/documents/blog-index.ts": "import {defineField, defineType} from 'cms-kit'\n\nexport default defineType({\n name: 'blog-index',\n type: 'document',\n fields: [defineField({name: 'title', type: 'string'})],\n})\n", + "studio/schemaTypes/documents/index.ts": "import author from './author'\nimport blog from './blog'\nimport blogIndex from './blog-index'\n\nexport const documents = [author, blog, blogIndex]\n", + "studio/structure.ts": "export const structure = (S) =>\n S.list().items([\n S.documentTypeListItem('author'),\n S.documentTypeListItem('blog'),\n S.documentTypeListItem('blog-index'),\n ])\n" + }, + "added": "studio/schemaTypes/documents/promotion-validation.ts", + "added_text": "import type {ValidationContext} from 'cms-kit'\n\nexport function endsAfterStart(value: unknown, context: ValidationContext) {\n return true\n}\n\nexport const requireCode = (rule: any) => rule.custom((v: string) => !!v)\n" + }, + "expect": { + "blocking": 0 + } +} diff --git a/services/worker/src/passes/replay/cases/03_plan_implement_review_loop_gaps.json b/services/worker/src/passes/replay/cases/03_plan_implement_review_loop_gaps.json new file mode 100644 index 000000000..10e7e1cb1 --- /dev/null +++ b/services/worker/src/passes/replay/cases/03_plan_implement_review_loop_gaps.json @@ -0,0 +1,22 @@ +{ + "name": "a finished run whose checks report 2, 4, 3, 1 gaps across 11 continuations ends with a draft pull request within budget", + "about": "A small ticket finished its tasks, then spent 2.5 hours and about $42 over 11 continuations with no pull request: every step re-ran the checks (2, 4, 3, 1 gaps) and started fresh fix rounds. The draft opens first, a round that doesn't shrink the gaps ends fixing, and the run stops after its continuations allowance.", + "case": "run_loop", + "input": { + "gaps": [ + 2, + 4, + 3, + 1 + ], + "continuations": 11, + "usd_per_step": 4.0 + }, + "expect": { + "draft_pr": true, + "stops": true, + "max_continuations": 4, + "max_spend_usd": 16.0, + "max_fix_rounds": 2 + } +} diff --git a/services/worker/src/passes/replay/cases/04_same_commit_every_thread_settled.json b/services/worker/src/passes/replay/cases/04_same_commit_every_thread_settled.json new file mode 100644 index 000000000..d549ec301 --- /dev/null +++ b/services/worker/src/passes/replay/cases/04_same_commit_every_thread_settled.json @@ -0,0 +1,26 @@ +{ + "name": "the same commit with every thread settled is approved", + "about": "A request for changes stood on a commit whose every thread had since been resolved or answered; nothing named held the merge, yet it kept blocking. A verdict lives only while its named reasons do: the review approves, replacing the stale request.", + "case": "review_settled", + "input": { + "head": "c0ffee1d2e3f", + "standing": "REQUEST_CHANGES", + "threads": [ + { + "path": "src/queue.rs", + "line": 40, + "body": "🔴 **Blocking (correctness): Retry loop never ends** (correctness)\n\nThe loop retries forever on an empty queue.", + "settled": true + }, + { + "path": "src/api.rs", + "line": 12, + "body": "🔴 **Blocking (security): Token logged** (security)\n\nThe bearer token is written to the log.", + "settled": true + } + ] + }, + "expect": { + "event": "APPROVE" + } +} diff --git a/services/worker/src/passes/replay/cases/05_blocker_comment_unchanged_commit.json b/services/worker/src/passes/replay/cases/05_blocker_comment_unchanged_commit.json new file mode 100644 index 000000000..b9c680948 --- /dev/null +++ b/services/worker/src/passes/replay/cases/05_blocker_comment_unchanged_commit.json @@ -0,0 +1,20 @@ +{ + "name": "a comment that names a blocker on an unchanged commit gets an answer, no second review and no spliced text", + "about": "A person commented that a finding still blocked, on a commit nothing had changed since the review. CoderHelm ran a second paid review and posted a reply that spliced the comment into a template. The standing verdict is the answer, in its own whole words.", + "case": "blocker_comment", + "input": { + "trigger": "reply", + "head": "a1b2c3d4e5f6", + "standing": "REQUEST_CHANGES", + "comment": "This still blocks: the retry loop never ends when the queue is empty.", + "reply_reads": "block", + "holding": [ + "`src/queue.rs:40` Retry loop never ends" + ] + }, + "expect": { + "answered": true, + "second_review": false, + "no_spliced_text": true + } +} diff --git a/services/worker/src/passes/replay/cases/06_deploys_coderhelm_started_by_cause.json b/services/worker/src/passes/replay/cases/06_deploys_coderhelm_started_by_cause.json new file mode 100644 index 000000000..2434acb45 --- /dev/null +++ b/services/worker/src/passes/replay/cases/06_deploys_coderhelm_started_by_cause.json @@ -0,0 +1,62 @@ +{ + "name": "deploys CoderHelm started are counted by cause from the runs that really deployed", + "about": "Analytics showed 0 production deploys: it counted only CoderHelm's own deploy labels. Deploys are the completed deploy runs CoderHelm's app triggered (a merge it made, a push to its PR), never a person's run and never a test workflow.", + "case": "deploy_count", + "input": { + "bot_login": "helper-app[bot]", + "default_branch": "main", + "deploy_workflows": "", + "runs": [ + { + "triggering_actor": { + "login": "helper-app[bot]", + "type": "Bot" + }, + "event": "push", + "head_branch": "main", + "name": "Deploy production", + "path": ".github/workflows/deploy.yml", + "conclusion": "success" + }, + { + "triggering_actor": { + "login": "helper-app[bot]", + "type": "Bot" + }, + "event": "pull_request", + "head_branch": "helper/gh-7-filter", + "name": "Deploy preview", + "path": ".github/workflows/preview.yml", + "conclusion": "success" + }, + { + "triggering_actor": { + "login": "helper-app[bot]", + "type": "Bot" + }, + "event": "push", + "head_branch": "main", + "name": "Tests", + "path": ".github/workflows/test.yml", + "conclusion": "success" + }, + { + "triggering_actor": { + "login": "pat", + "type": "User" + }, + "event": "push", + "head_branch": "main", + "name": "Deploy production", + "path": ".github/workflows/deploy.yml", + "conclusion": "success" + } + ] + }, + "expect": { + "by_cause": { + "merge": 1, + "pull_request": 1 + } + } +} diff --git a/services/worker/src/passes/replay/cases/07_extra_fix_cycle_without_a_blocker_delivers.json b/services/worker/src/passes/replay/cases/07_extra_fix_cycle_without_a_blocker_delivers.json new file mode 100644 index 000000000..8ef141122 --- /dev/null +++ b/services/worker/src/passes/replay/cases/07_extra_fix_cycle_without_a_blocker_delivers.json @@ -0,0 +1,68 @@ +{ + "name": "a second fix cycle with no named blocker worth it delivers the draft instead", + "about": "The proof check's gaps shrank after the first round (3, then 2), so the old rule started a second round. The stop judge sees the whole run and finds no named blocker worth another cycle: the draft goes out with the gaps under Open items.", + "case": "run_loop", + "input": { + "gaps": [ + 3, + 2, + 2 + ], + "continuations": 3, + "usd_per_step": 4.0 + }, + "replies": [ + [ + { + "verdict": "proceed", + "assumption": "the remaining 2 gaps are unproven details a reviewer can confirm; deliver the draft with them listed", + "question": "", + "person_only": "", + "tried": [], + "options": [], + "default": "", + "deadline_hours": 0, + "blocker": "", + "evidence": [], + "category": "", + "location": "" + } + ], + [ + { + "verdict": "proceed", + "assumption": "deliver the draft; the gaps are listed under Open items for a person to confirm", + "question": "", + "person_only": "", + "tried": [], + "options": [], + "default": "", + "deadline_hours": 0, + "blocker": "", + "evidence": [], + "category": "", + "location": "" + } + ], + [ + { + "verdict": "proceed", + "assumption": "no gap names a defect; the draft goes out with the gaps as open items", + "question": "", + "person_only": "", + "tried": [], + "options": [], + "default": "", + "deadline_hours": 0, + "blocker": "", + "evidence": [], + "category": "", + "location": "" + } + ] + ], + "expect": { + "draft_pr": true, + "max_fix_rounds": 1 + } +} diff --git a/services/worker/src/passes/replay/cases/08_stop_judge_nit_is_not_a_block.json b/services/worker/src/passes/replay/cases/08_stop_judge_nit_is_not_a_block.json new file mode 100644 index 000000000..e863b8abc --- /dev/null +++ b/services/worker/src/passes/replay/cases/08_stop_judge_nit_is_not_a_block.json @@ -0,0 +1,110 @@ +{ + "name": "a naming nit never requests changes, even when the model first answers hold", + "about": "Exported from the decision log shape: the step proposed requesting changes over a helper's name. A hold on a block needs a correctness, security or data-loss category and a location; the first answer gave neither and is asked again; the second proceeds.", + "case": "stop_judge", + "input": { + "picture": { + "kind": "block", + "step": "review", + "reason": "the review would request changes on: `src/util.ts:3` Rename parse to parse_rows", + "reversible": true, + "ticket_title": "Parse the import rows", + "ticket_body": "Reads the CSV rows into records.", + "evidence": [ + { + "id": "E1", + "source": "review finding (a preference the reviewer inferred)", + "finding": "Rename parse to parse_rows: helper names start with a verb", + "location": "src/util.ts:3", + "checked": false + } + ] + } + }, + "replies": [ + [ + { + "verdict": "hold", + "assumption": "", + "question": "", + "person_only": "", + "tried": [], + "options": [], + "default": "", + "deadline_hours": 0, + "blocker": "helper name", + "evidence": [ + "E1" + ], + "category": "other", + "location": "src/util.ts:3" + }, + { + "verdict": "proceed", + "assumption": "the name is a preference; approve with a Nit", + "question": "", + "person_only": "", + "tried": [], + "options": [], + "default": "", + "deadline_hours": 0, + "blocker": "", + "evidence": [], + "category": "", + "location": "" + } + ], + [ + { + "verdict": "proceed", + "assumption": "a naming preference is a Nit on the approval", + "question": "", + "person_only": "", + "tried": [], + "options": [], + "default": "", + "deadline_hours": 0, + "blocker": "", + "evidence": [], + "category": "", + "location": "" + } + ], + [ + { + "verdict": "hold", + "assumption": "", + "question": "", + "person_only": "", + "tried": [], + "options": [], + "default": "", + "deadline_hours": 0, + "blocker": "rename the helper", + "evidence": [ + "E1" + ], + "category": "", + "location": "" + }, + { + "verdict": "proceed", + "assumption": "approve; the rename is a Nit", + "question": "", + "person_only": "", + "tried": [], + "options": [], + "default": "", + "deadline_hours": 0, + "blocker": "", + "evidence": [], + "category": "", + "location": "" + } + ] + ], + "expect": { + "verdict": "proceed", + "never_ask": true + } +} diff --git a/services/worker/src/passes/replay/cases/09_stop_judge_access_question_has_options.json b/services/worker/src/passes/replay/cases/09_stop_judge_access_question_has_options.json new file mode 100644 index 000000000..1baf85328 --- /dev/null +++ b/services/worker/src/passes/replay/cases/09_stop_judge_access_question_has_options.json @@ -0,0 +1,93 @@ +{ + "name": "a question for access only a person has is asked with options, a default and a deadline", + "about": "The run needed read access to a vendor's sandbox to confirm a payload shape. That is a fact only a person can give, so the judge asks, with what was tried, options and a recommended default.", + "case": "stop_judge", + "input": { + "picture": { + "kind": "ask", + "step": "plan", + "reason": "the planner asks for sandbox credentials to read a real payload", + "reversible": true, + "ticket_title": "Sync refunds from the payments vendor", + "ticket_body": "Refunds should appear in the daily totals.", + "question": { + "question": "Can CoderHelm get read access to the vendor sandbox?", + "tried": [ + "searched the repository for fixtures", + "read the vendor's public docs" + ], + "options": [] + } + } + }, + "replies": [ + [ + { + "verdict": "ask", + "assumption": "", + "question": "How should the refund payload shape be confirmed?", + "person_only": "access", + "tried": [ + "searched the repository for fixtures", + "read the vendor's public docs" + ], + "options": [ + "Add a sandbox API key to the team's secrets", + "Build from the public docs and confirm on review" + ], + "default": "Build from the public docs and confirm on review", + "deadline_hours": 24, + "blocker": "", + "evidence": [], + "category": "", + "location": "" + } + ], + [ + { + "verdict": "ask", + "assumption": "", + "question": "Can the run get read access to the vendor sandbox?", + "person_only": "access", + "tried": [ + "read the public docs", + "searched for fixtures" + ], + "options": [ + "Add read-only sandbox credentials", + "Proceed from the public docs" + ], + "default": "Proceed from the public docs", + "deadline_hours": 24, + "blocker": "", + "evidence": [], + "category": "", + "location": "" + } + ], + [ + { + "verdict": "ask", + "assumption": "", + "question": "Confirm the refund payload: sandbox access, or the docs?", + "person_only": "access", + "tried": [ + "read the docs" + ], + "options": [ + "Sandbox access", + "The docs" + ], + "default": "The docs", + "deadline_hours": 24, + "blocker": "", + "evidence": [], + "category": "", + "location": "" + } + ] + ], + "expect": { + "verdict": "ask" + } +} diff --git a/services/worker/src/passes/replay/mod.rs b/services/worker/src/passes/replay/mod.rs new file mode 100644 index 000000000..fc5bda8df --- /dev/null +++ b/services/worker/src/passes/replay/mod.rs @@ -0,0 +1,738 @@ +//! The replay suite: incidents where CoderHelm stopped, asked, blocked or +//! looped when it should have gone on, replayed through the real decision +//! code and graded on the decision, not on wording. +//! +//! Each case is one JSON file in `cases/` (see `README.md` beside this +//! file). Its `case` names the decision path it replays: +//! +//! - `stop_judge`: a picture straight to `common::stop_judge::judge`. +//! - `ticket_route`: triage's intent, the planner's answer, the fix-location +//! fallback and route, then the stop judge when the route would ask. +//! - `registration`: the new-feature registration rule, from the files. +//! - `run_loop`: a run's continuations through the run guard, the checks' +//! ledger, the ceiling and the stop judge's licence for each extra cycle. +//! - `review_settled`: a review of a commit whose earlier threads are all +//! settled, through `named_holding` and `review_verdict::decide`. +//! - `blocker_comment`: a person's comment naming a blocker on an unchanged +//! commit, through `review_policy` and `review_verdict::decide`. +//! - `deploy_count`: workflow runs through `common::deploy_stats`. +//! +//! Where the stop judge is involved the case carries the model's recorded +//! answers for `k` trials (pass^k: every trial must pass, k = 3), so CI is +//! deterministic. `replay_live` (ignored by default) puts the same pictures +//! to the real model `k` times: `REPLAY_LIVE=1 ANTHROPIC_API_KEY=... +//! cargo test -p worker replay::replay_live -- --ignored`. + +use std::path::{Path, PathBuf}; + +use common::stop_judge::{self as judge, JudgeModel, Picture}; +use serde::Deserialize; +use serde_json::{json, Value}; + +use crate::passes::stop_judge::Recorded; + +/// One case file. +#[derive(Debug, Clone, Deserialize)] +struct Case { + name: String, + #[allow(dead_code)] + about: String, + case: String, + /// Trials; each must pass (pass^k). + #[serde(default)] + k: Option, + /// The model's recorded answers, one list per trial, in call order. + #[serde(default)] + replies: Vec>, + #[serde(default)] + input: Value, + expect: Value, +} + +impl Case { + fn trials(&self) -> usize { + self.k + .unwrap_or(if self.replies.is_empty() { 1 } else { 3 }) + } +} + +fn cases_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("src/passes/replay/cases") +} + +fn load() -> Vec<(String, Case)> { + let mut out = Vec::new(); + let mut paths: Vec = std::fs::read_dir(cases_dir()) + .expect("the replay cases folder") + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|x| x == "json")) + .collect(); + paths.sort(); + for p in paths { + let file = p.file_name().unwrap().to_string_lossy().to_string(); + let text = std::fs::read_to_string(&p).unwrap(); + let case: Case = + serde_json::from_str(&text).unwrap_or_else(|e| panic!("{file} doesn't read: {e}")); + out.push((file, case)); + } + out +} + +fn block_on(f: F) -> F::Output { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(f) +} + +fn s<'a>(v: &'a Value, k: &str) -> &'a str { + v[k].as_str().unwrap_or("") +} + +fn strings(v: &Value) -> Vec { + v.as_array() + .map(|a| { + a.iter() + .filter_map(|x| x.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default() +} + +/// The model a trial uses: its recorded answers, or (live) the real model. +enum Model { + Recorded(Vec), + #[allow(dead_code)] + Live(LiveModel), +} + +/// Runs the judge on a picture with this trial's model. +fn judged(model: &Model, picture: Picture) -> judge::Judged { + match model { + Model::Recorded(answers) => { + block_on(judge::judge(&Recorded::new(answers.clone()), picture)) + } + Model::Live(live) => block_on(judge::judge(live, picture)), + } +} + +// ── The cases ────────────────────────────────────────────────────────────── + +fn want_verdict(expect: &Value, j: &judge::Judged) -> Result<(), String> { + if let Some(v) = expect["verdict"].as_str() { + if j.verdict().as_str() != v { + return Err(format!( + "verdict {} ({:?}), want {v}", + j.verdict().as_str(), + j.verdict() + )); + } + } + if expect["never_ask"].as_bool() == Some(true) && j.question().is_some() { + return Err("asked a person".into()); + } + Ok(()) +} + +fn run_stop_judge(c: &Case, model: &Model) -> Result<(), String> { + let picture: Picture = + serde_json::from_value(c.input["picture"].clone()).map_err(|e| format!("picture: {e}"))?; + let j = judged(model, picture); + want_verdict(&c.expect, &j) +} + +fn run_ticket_route(c: &Case, model: &Model) -> Result<(), String> { + use crate::passes::fix_location::{self, Route}; + use crate::passes::triage::{self, TicketIntent}; + let i = &c.input; + let ticket_type = i["ticket_type"].as_str(); + let intent = triage::settle_intent( + TicketIntent::parse(s(i, "model_intent")), + s(i, "title"), + s(i, "body"), + ticket_type, + ); + let tasks = s(i, "tasks"); + let decision = match fix_location::parse_detailed(s(i, "planner_answer")) { + Ok(d) => Some(d), + Err(problem) => fix_location::fallback(intent, tasks, &format!("{problem:?}")), + }; + let mut route = fix_location::route_for_plan(decision.as_ref(), tasks); + let mut asked = false; + if route == Route::Ask { + let mut p = Picture::new( + judge::Kind::Ask, + "fix_location", + &format!( + "the plan doesn't settle where the fix belongs: {}", + decision.as_ref().map(|d| d.cause.as_str()).unwrap_or("") + ), + ); + p.ticket_title = s(i, "title").into(); + p.ticket_body = s(i, "body").into(); + p.plan = tasks.into(); + let j = judged(model, p); + if j.proceeds() { + route = Route::Code; + } else { + asked = true; + } + } + let want_route = s(&c.expect, "route"); + let got = match route { + Route::Code => "code", + Route::CodeAndOutside => "code_and_outside", + Route::OutsideOnly => "outside_only", + Route::Ask => "ask", + }; + if got != want_route { + return Err(format!( + "route {got}, want {want_route} (intent {})", + intent.as_str() + )); + } + if c.expect["asked"].as_bool() == Some(false) && asked { + return Err("asked a person".into()); + } + if let Some(want) = c.expect["intent"].as_str() { + if intent.as_str() != want { + return Err(format!("intent {}, want {want}", intent.as_str())); + } + } + Ok(()) +} + +fn run_registration(c: &Case, _: &Model) -> Result<(), String> { + use crate::passes::feature::registration::*; + let i = &c.input; + let tree = strings(&i["tree"]); + let files: Vec<(String, String)> = i["files"] + .as_object() + .map(|o| { + o.iter() + .map(|(k, v)| (k.clone(), v.as_str().unwrap_or("").to_string())) + .collect() + }) + .unwrap_or_default(); + let added = s(i, "added"); + let added_text = s(i, "added_text"); + let items = new_items(&[added.to_string()], &tree); + let Some(item) = items.first() else { + // Not even a candidate item: nothing to register. + return check_blocking(&c.expect, 0); + }; + let sibs = siblings(item, &tree, None); + let parent = added.rsplit_once('/').map(|(p, _)| p).unwrap_or(""); + let sib_files: Vec<(String, String)> = sibs + .iter() + .filter_map(|sib| { + files + .iter() + .find(|(p, _)| { + p.rsplit_once('/').is_some_and(|(dir, name)| { + dir == parent && name.split('.').next() == Some(sib.as_str()) + }) + }) + .cloned() + }) + .collect(); + let registry_files: Vec<(String, String)> = files + .iter() + .filter(|(p, _)| !sib_files.iter().any(|(q, _)| q == p)) + .cloned() + .collect(); + let keep = registration_places(item, &sibs, ®istry_files); + let places: Vec<(String, String, bool)> = registry_files + .iter() + .filter_map(|(p, t)| { + keep.iter() + .find(|(k, _)| k == p) + .map(|(_, r)| (p.clone(), t.clone(), *r)) + }) + .collect(); + let registries: Vec<&str> = places + .iter() + .filter(|(_, _, r)| *r) + .map(|(_, t, _)| t.as_str()) + .collect(); + let kind = kind_of(Some((added, added_text)), &sib_files, ®istries, &sibs); + let lookup = |p: &str| { + registry_files + .iter() + .find(|(q, _)| q == p) + .map(|(_, t)| t.clone()) + }; + let missing = judge(item, &sibs, &kind, &places, &lookup); + check_blocking(&c.expect, blocking(&missing).len()) +} + +fn check_blocking(expect: &Value, n: usize) -> Result<(), String> { + let want = expect["blocking"].as_u64().unwrap_or(0) as usize; + if n != want { + return Err(format!("{n} blocking registration item(s), want {want}")); + } + Ok(()) +} + +fn run_loop(c: &Case, model: &Model) -> Result<(), String> { + use crate::passes::run_ceiling::Totals; + use crate::passes::run_guard::{GuardState, Ledger, Progress, MAX_PROOF_FIX_ROUNDS}; + use crate::passes::stop_judge::CycleLicence; + let i = &c.input; + let gaps: Vec = i["gaps"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|x| x.as_u64()) + .map(|n| n as usize) + .collect() + }) + .unwrap_or_default(); + let continuations = i["continuations"].as_u64().unwrap_or(11) as usize; + let usd = i["usd_per_step"].as_f64().unwrap_or(4.0); + let mut answers = match model { + Model::Recorded(a) => a.clone().into_iter(), + Model::Live(_) => Vec::new().into_iter(), + }; + let mut guard = GuardState::default(); + let mut totals = Totals::default(); + let mut ledger = Ledger::default(); + guard.apply(&Progress::WorkDone); + let mut pr_open_at: Option = None; + let mut stopped_at: Option = None; + let mut fix_rounds = 0u32; + for step in 0..continuations { + ledger.on_step_start(); + // Finished work opens its draft first; the checks run on it. + if pr_open_at.is_none() { + pr_open_at = Some(step); + guard.apply(&Progress::PrOpen); + } + let open = gaps.get(step % gaps.len().max(1)).copied().unwrap_or(0); + let head = format!("h{step}"); + if !ledger.proof.unchanged(&head) { + ledger.proof.checked(&head, open); + guard.apply(&Progress::Findings("proof", open)); + } + if open > 0 && ledger.proof.may_fix(MAX_PROOF_FIX_ROUNDS) { + let licence = match CycleLicence::first(ledger.proof.rounds) { + Some(l) => Some(l), + None => { + let mut p = Picture::new( + judge::Kind::ExtraCycle, + "proof_check", + &format!( + "the proof check still reports {open} gap(s) after {} cycle(s)", + ledger.proof.rounds + ), + ); + p.evidence = (0..open) + .map(|n| judge::Evidence { + source: "proof check".into(), + finding: format!("gap {}", n + 1), + checked: true, + ..Default::default() + }) + .collect(); + p.budget.cycles = ledger.proof.rounds; + p.budget.cycle_cap = MAX_PROOF_FIX_ROUNDS; + let j = match model { + Model::Recorded(_) => { + let a: Vec = answers.next().into_iter().collect(); + block_on(judge::judge(&Recorded::new(a), p)) + } + Model::Live(live) => block_on(judge::judge(live, p)), + }; + CycleLicence::judged(&j) + } + }; + if let Some(l) = licence { + ledger.proof.start_fix(l); + ledger.proof.end_fix(); + fix_rounds += 1; + } + } + guard.on_continuation(usd); + totals.continuations += 1; + totals.spend_usd += usd; + if guard.trip().is_some() || totals.over().is_some() { + stopped_at = Some(step); + break; + } + } + let e = &c.expect; + if e["draft_pr"].as_bool() == Some(true) && pr_open_at.is_none() { + return Err("no draft pull request".into()); + } + if let Some(max) = e["max_continuations"].as_u64() { + let used = stopped_at.map(|s| s + 1).unwrap_or(continuations) as u64; + if used > max { + return Err(format!("{used} continuations, want at most {max}")); + } + } + if let Some(max) = e["max_spend_usd"].as_f64() { + if totals.spend_usd > max { + return Err(format!( + "spent ${:.2}, want at most ${max:.2}", + totals.spend_usd + )); + } + } + if let Some(max) = e["max_fix_rounds"].as_u64() { + if u64::from(fix_rounds) > max { + return Err(format!("{fix_rounds} fix rounds, want at most {max}")); + } + } + if e["stops"].as_bool() == Some(true) && stopped_at.is_none() { + return Err("the run never stopped".into()); + } + Ok(()) +} + +fn run_review_settled(c: &Case, _: &Model) -> Result<(), String> { + use crate::passes::review_agent::thread_holds_merge; + use crate::passes::review_policy::named_holding; + use crate::passes::review_verdict::{self as rv, Context, Decision, Input, StandingReview}; + let i = &c.input; + let head = s(i, "head"); + let open: Vec<(String, u64, String)> = i["threads"] + .as_array() + .into_iter() + .flatten() + .filter(|t| t["settled"].as_bool() != Some(true)) + .filter(|t| thread_holds_merge(s(t, "body"))) + .map(|t| { + ( + s(t, "path").to_string(), + t["line"].as_u64().unwrap_or(0), + s(t, "body").to_string(), + ) + }) + .collect(); + let verdict = rv::Verdict::from_holding(named_holding(&[], &open, &[], false, &[], &[])); + let ctx = Context { + standing: Some(StandingReview { + verdict: s(i, "standing").to_string(), + failed: false, + head_sha: head.to_string(), + }), + self_authored: false, + }; + let d = rv::decide( + Input::Review { + verdict: verdict.event(), + has_news: false, + explicit: false, + already_answered: false, + }, + &ctx, + ); + let want = s(&c.expect, "event"); + match d { + Decision::Post { event, .. } if event == want => {} + other => return Err(format!("{other:?}, want a posted {want}")), + } + if !rv::may_post(want, &verdict, None) { + return Err(format!("the chokepoint refuses {want}")); + } + Ok(()) +} + +fn run_blocker_comment(c: &Case, _: &Model) -> Result<(), String> { + use crate::passes::review_agent::VerdictChange; + use crate::passes::review_policy::{ + answers_from_standing, standing_answer, verdict_stands_note, + }; + use crate::passes::review_verdict::{self as rv, Context, Decision, Input, StandingReview}; + let i = &c.input; + let head = s(i, "head"); + let standing = s(i, "standing"); + let comment = s(i, "comment"); + let holding = strings(&i["holding"]); + // Nothing the verdict rests on changed: only words. + let changed: Vec = Vec::new(); + let from_standing = answers_from_standing(s(i, "trigger"), &changed, true); + let ctx = Context { + standing: Some(StandingReview { + verdict: standing.to_string(), + failed: false, + head_sha: head.to_string(), + }), + self_authored: false, + }; + let change = match s(i, "reply_reads") { + "block" => VerdictChange::Block, + "clear" => VerdictChange::Clear, + _ => VerdictChange::None, + }; + let d = rv::decide( + Input::Reply { + change, + more_than_words: false, + }, + &ctx, + ); + let e = &c.expect; + if e["second_review"].as_bool() == Some(false) && matches!(d, Decision::Review) { + return Err("a second paid review".into()); + } + if e["answered"].as_bool() == Some(true) && !from_standing && s(i, "trigger") != "reply" { + return Err("no answer".into()); + } + // The answer is whole: fixed words from facts, never a person's words + // spliced into a template. + let answer = if from_standing { + standing_answer(head, standing, &holding) + } else { + verdict_stands_note(head, standing) + }; + if e["no_spliced_text"].as_bool() == Some(true) { + let snippet: String = comment.chars().take(24).collect(); + if !snippet.trim().is_empty() && answer.contains(snippet.trim()) { + return Err(format!("the answer splices the comment: {answer}")); + } + if answer.trim().is_empty() { + return Err("an empty answer".into()); + } + } + Ok(()) +} + +fn run_deploy_count(c: &Case, _: &Model) -> Result<(), String> { + use common::deploy_stats::*; + let i = &c.input; + let bot = s(i, "bot_login"); + let default_branch = s(i, "default_branch"); + let setting = parse_deploy_workflows(s(i, "deploy_workflows")); + let mut by_cause: std::collections::BTreeMap = Default::default(); + for run in i["runs"].as_array().into_iter().flatten() { + if !started_by_coderhelm(run, bot) { + continue; + } + let is_tag = run["is_tag"].as_bool().unwrap_or(false); + let targets = run_targets(run, None, None, &setting); + if targets.is_empty() { + continue; + } + *by_cause + .entry(cause_of(run, default_branch, is_tag).as_str().to_string()) + .or_default() += targets.len() as u64; + } + let want: std::collections::BTreeMap = + serde_json::from_value(c.expect["by_cause"].clone()).map_err(|e| e.to_string())?; + if by_cause != want { + return Err(format!("deploys by cause {by_cause:?}, want {want:?}")); + } + Ok(()) +} + +fn run_one(c: &Case, model: &Model) -> Result<(), String> { + match c.case.as_str() { + "stop_judge" => run_stop_judge(c, model), + "ticket_route" => run_ticket_route(c, model), + "registration" => run_registration(c, model), + "run_loop" => run_loop(c, model), + "review_settled" => run_review_settled(c, model), + "blocker_comment" => run_blocker_comment(c, model), + "deploy_count" => run_deploy_count(c, model), + other => Err(format!("unknown case kind `{other}`")), + } +} + +/// Every case, every trial (pass^k). +pub(crate) fn replay_all(live: Option<&LiveModel>) -> (usize, Vec) { + let mut failures = Vec::new(); + let mut trials = 0; + for (file, c) in load() { + let k = c.trials(); + for t in 0..k { + trials += 1; + let model = match live { + Some(l) => Model::Live(l.clone()), + None => Model::Recorded(c.replies.get(t).cloned().unwrap_or_default()), + }; + if let Err(e) = run_one(&c, &model) { + failures.push(format!("{file} ({}) trial {}/{k}: {e}", c.name, t + 1)); + } + } + } + (trials, failures) +} + +/// The real model, for the live mode. +#[derive(Clone)] +pub(crate) struct LiveModel { + key: String, + model: String, +} + +impl JudgeModel for LiveModel { + async fn answer(&self, system: &str, prompt: &str, schema: &Value) -> Result { + let client = crate::agent::anthropic::AnthropicClient::new( + self.key.clone(), + common::usage::UsageMeter::memory("replay").0, + ); + let mut usage = crate::models::TokenUsage::default(); + crate::agent::anthropic::converse_json( + &client, + &self.model, + system, + prompt, + schema, + true, + judge::JUDGMENT_EFFORT, + 8_000, + &mut usage, + ) + .await + .map_err(|e| e.to_string()) + } +} + +#[test] +fn replay_every_incident_pass_k() { + let (trials, failures) = replay_all(None); + assert!(trials >= 6, "found the cases ({trials} trials)"); + assert!( + failures.is_empty(), + "replay failures:\n{}", + failures.join("\n") + ); +} + +#[test] +fn every_case_with_a_model_call_has_k_recorded_trials() { + for (file, c) in load() { + if !c.replies.is_empty() { + assert!(c.trials() >= 3, "{file}: pass^k needs k >= 3"); + assert_eq!( + c.replies.len(), + c.trials(), + "{file}: one recorded answer list per trial" + ); + } + assert!(!c.name.trim().is_empty(), "{file}: a name"); + } +} + +#[test] +fn the_seed_incidents_are_all_here() { + let kinds: Vec = load().into_iter().map(|(_, c)| c.case).collect(); + for k in [ + "ticket_route", + "registration", + "run_loop", + "review_settled", + "blocker_comment", + "deploy_count", + ] { + assert!(kinds.iter().any(|x| x == k), "no `{k}` case"); + } +} + +/// A case that would pass whatever the code did is no case: a wrong +/// expectation fails. +#[test] +fn a_wrong_expectation_fails() { + for (file, mut c) in load() { + if c.case != "ticket_route" { + continue; + } + c.expect = json!({"route": "ask"}); + let model = Model::Recorded(c.replies.first().cloned().unwrap_or_default()); + assert!(run_one(&c, &model).is_err(), "{file}"); + return; + } + panic!("no ticket_route case"); +} + +/// The live mode: the real model on every picture, `k` times. +#[test] +#[ignore] +fn replay_live() { + if std::env::var("REPLAY_LIVE").ok().as_deref() != Some("1") { + return; + } + let key = std::env::var("ANTHROPIC_API_KEY").expect("ANTHROPIC_API_KEY"); + let model = std::env::var("REPLAY_MODEL").unwrap_or_else(|_| "claude-opus-5-5".into()); + let (trials, failures) = replay_all(Some(&LiveModel { key, model })); + assert!(trials > 0); + assert!( + failures.is_empty(), + "live replay failures:\n{}", + failures.join("\n") + ); +} + +/// An exported decision (`common::decision_log::fixture`) reads as a case, +/// and the suite tells a wrong one apart: its recorded answer held where +/// people's act says it should have gone on. +#[test] +fn an_exported_decision_reads_as_a_case() { + let mut p = Picture::new(judge::Kind::Block, "review", "a nit"); + p.evidence = vec![judge::Evidence { + id: "E1".into(), + source: "review".into(), + finding: "tests fail".into(), + location: "src/a.rs:1".into(), + checked: true, + }]; + let hold = json!({"verdict":"hold","assumption":"","question":"","person_only":"", + "tried":[],"options":[],"default":"","deadline_hours":0,"blocker":"tests fail", + "evidence":["E1"],"category":"correctness","location":"src/a.rs:1"}); + let usage_free = vec![hold.clone()]; + let j = block_on(judge::judge(&Recorded::new(usage_free), p.clone())); + let mut rec = common::decision_log::Record::new( + &common::decision_log::Subject::Pr { + repo: "acme/site".into(), + number: 3, + }, + &j, + &p, + "h1", + ); + rec.outcome = Some(common::decision_log::Outcome::DismissedReview); + let c: Case = serde_json::from_value(common::decision_log::fixture(&rec)).expect("reads"); + assert_eq!(c.case, "stop_judge"); + assert_eq!(c.trials(), 1); + let model = Model::Recorded(c.replies[0].clone()); + // The recorded answer held: the exported case fails until the judge + // decides it right and three trials are recorded. + assert!(run_one(&c, &model).is_err()); +} + +/// Records the real model's answers for every case with a model call: +/// `REPLAY_RECORD=1 ANTHROPIC_API_KEY=... cargo test -p worker +/// replay::replay_record -- --ignored`. Each case's `replies` becomes `k` +/// fresh trials; review the diff before committing it. +#[test] +#[ignore] +fn replay_record() { + if std::env::var("REPLAY_RECORD").ok().as_deref() != Some("1") { + return; + } + let key = std::env::var("ANTHROPIC_API_KEY").expect("ANTHROPIC_API_KEY"); + let model = std::env::var("REPLAY_MODEL").unwrap_or_else(|_| "claude-opus-5-5".into()); + let live = LiveModel { key, model }; + for entry in std::fs::read_dir(cases_dir()).unwrap().flatten() { + let path = entry.path(); + let text = std::fs::read_to_string(&path).unwrap(); + let mut v: Value = serde_json::from_str(&text).unwrap(); + if v["case"] != "stop_judge" { + continue; + } + let c: Case = serde_json::from_value(v.clone()).unwrap(); + let picture: Picture = serde_json::from_value(c.input["picture"].clone()).unwrap(); + let k = c.trials().max(3); + let mut trials = Vec::new(); + for _ in 0..k { + let j = block_on(judge::judge(&live, picture.clone())); + trials.push(Value::Array(j.replies().to_vec())); + } + v["replies"] = Value::Array(trials); + v["k"] = json!(k); + std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap() + "\n").unwrap(); + } +} diff --git a/services/worker/src/passes/resolved.rs b/services/worker/src/passes/resolved.rs index 2e305c2b8..6ea33bea5 100644 --- a/services/worker/src/passes/resolved.rs +++ b/services/worker/src/passes/resolved.rs @@ -199,7 +199,7 @@ pub fn by_words(questions: &[Question], settled: &[Answer]) -> Vec { /// One verdict per question. Nothing settled: every question is open. pub async fn judge( - state: &WorkerState, + _state: &WorkerState, provider: &ModelProvider, questions: &[Question], settled: &[Answer], @@ -210,13 +210,13 @@ pub async fn judge( } match crate::agent::anthropic::converse_json( &provider.client(), - &state.config.light_model_id, + provider.judgment_model_id(), SYSTEM, &prompt(questions, settled), &schema(), true, - "low", - 2048, + common::stop_judge::JUDGMENT_EFFORT, + 8192, usage, ) .await diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 468ef937c..5d1fdd359 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -2617,6 +2617,40 @@ pub async fn run( mark_events_processed(state, &msg.run_id, &events).await; return Ok(()); } + super::own_review::Next::Fix { .. } + if progress.rounds > 0 + && super::stop_judge::cycle_licence( + state, + &ticket_msg, + &msg.run_id, + "own_review", + progress.rounds, + super::own_review::MAX_FIX_ROUNDS, + &super::stop_judge::evidence_lines( + "CoderHelm's own review", + &own_open, + ), + ) + .await + .is_none() => + { + // The stop judge found no named blocker worth another + // round: the draft goes to a person with what is open. + stop_on_own_findings( + state, + &ticket_msg, + &msg.run_id, + &super::own_review::cap_reason(&own_open), + &pr_url, + pr_number, + &branch, + &usage, + wall_clock_secs(created_at, &start), + ) + .await?; + mark_events_processed(state, &msg.run_id, &events).await; + return Ok(()); + } super::own_review::Next::Fix { stalled } => { record_own_review_progress( state, @@ -4904,7 +4938,45 @@ async fn wait_for_review( usage: &TokenUsage, duration: u64, ) -> Result<(), Box> { - let wait = super::stop_pr::review_wait(pr_number, pr_url, reason); + // Handing the run to a person is the stop judge's call: a named blocker + // for the person, or the draft carries the assumption it went on. + let mut judge_usage = TokenUsage::default(); + let judged = super::stop_judge::decide_for_team( + state, + &mut judge_usage, + &msg.team_id, + &super::stop_judge::run_subject(run_id), + "", + super::stop_judge::handoff_picture(msg, "fix_rounds", reason, &[]), + ) + .await; + wait_on_person( + state, msg, run_id, reason, pr_url, pr_number, branch, usage, duration, &judged, + ) + .await +} + +/// The run waits on its pull request's review, with the judge's blocker or +/// assumption beside what is open. +#[allow(clippy::too_many_arguments)] +async fn wait_on_person( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + reason: &str, + pr_url: &str, + pr_number: u64, + branch: &str, + usage: &TokenUsage, + duration: u64, + judged: &super::stop_judge::Judged, +) -> Result<(), Box> { + let detail = match (judged.hold_words(), judged.assumption()) { + (Some(h), _) => format!("{reason}\nBlocked on: {h}"), + (None, Some(a)) => format!("{reason}\nAssumed: {a}"), + _ => reason.to_string(), + }; + let wait = super::stop_pr::review_wait(pr_number, pr_url, &detail); end_run( state, msg, @@ -4914,6 +4986,7 @@ async fn wait_for_review( (pr_url, pr_number, branch), usage, duration, + Some(judged), ) .await } @@ -4932,11 +5005,7 @@ async fn complete_run_with_status( usage: &TokenUsage, duration: u64, ) -> Result<(), Box> { - debug_assert_ne!( - status, - common::run_status::NEEDS_INPUT, - "use wait_for_review" - ); + debug_assert_ne!(status, "needs_input", "use wait_for_review"); end_run( state, msg, @@ -4946,6 +5015,7 @@ async fn complete_run_with_status( (pr_url, pr_number, branch), usage, duration, + None, ) .await } @@ -4960,11 +5030,13 @@ async fn end_run( (pr_url, pr_number, branch): (&str, u64, &str), usage: &TokenUsage, duration: u64, + judged: Option<&super::stop_judge::Judged>, ) -> Result<(), Box> { let now = chrono::Utc::now().to_rfc3339(); let delta = usage.unrecorded(); - // Waiting on a person is always for something named. - let wait = (status == common::run_status::NEEDS_INPUT).then(|| { + // Waiting on a person is always for something named, and only after + // the stop judge decided it. + let wait = (status == common::run_status::NEEDS_INPUT && judged.is_some()).then(|| { wait.cloned() .unwrap_or_else(|| super::stop_pr::review_wait(pr_number, pr_url, "")) }); diff --git a/services/worker/src/passes/review_agent.rs b/services/worker/src/passes/review_agent.rs index 7dcf43e7c..5a056215a 100644 --- a/services/worker/src/passes/review_agent.rs +++ b/services/worker/src/passes/review_agent.rs @@ -210,7 +210,12 @@ pub fn thread_holds_merge(body: &str) -> bool { return false; } let first = body.lines().next().unwrap_or(""); - !first.trim_end().ends_with("(question)") + if first.contains("**Nit: ") || first.contains("**FYI: ") || first.contains("**Suggestion: ") { + return false; + } + // Older comments: a question never holds the merge, blocking or not. + let first = first.trim_end(); + !(first.ends_with("(question)") || first.ends_with("(question, blocks the merge)")) } /// The model's structured review output. @@ -328,7 +333,7 @@ pub const REQUIRE_TESTS_SECTION: &str = "\n## Tests are required in this repo\n\ code so they assert the new behavior (a bug fix needs a test that would have caught it). \ Use your tools: find where this code is already tested (search for the changed symbols / \ files in test directories) and check the diff touches those tests. If tests are missing or \ - stale, add ONE finding with category \"tests\" and severity \"blocking\", anchored on the \ + stale, add ONE finding with category \"tests\" and severity \"medium\", anchored on the \ main changed line, saying exactly what behavior needs a test and which existing test file \ to add it to or update (or where similar tests live). Ask for a test at the level the repo \ already tests that behavior: when a function is covered through the flow, mapper or screen \ @@ -598,14 +603,20 @@ pub fn format_discussion(comments: &[(String, String)]) -> String { s } -/// "Require tests": every `tests` finding is blocking, and holds the merge -/// as a policy the repo set. +/// "Require tests": a `tests` finding is always posted (the critic never +/// drops it) as a Suggestion on the approval. A missing test is not a +/// correctness, security or data-loss problem, so it never requests changes +/// on its own; CoderHelm's own coding passes still write the tests. +pub const REQUIRED_TESTS_NOTE: &str = "This repository asks for tests with behavior changes."; + pub fn enforce_required_tests(findings: &mut [Finding]) { for f in findings.iter_mut() { if f.category.eq_ignore_ascii_case("tests") { - f.severity = "blocking".to_string(); - f.optional = Some(false); - f.evidence = Some(Evidence::VerifiedDefect.as_str().to_string()); + f.severity = "medium".to_string(); + f.optional = Some(true); + if !f.body.contains(REQUIRED_TESTS_NOTE) { + f.body = format!("{}\n\n_{REQUIRED_TESTS_NOTE}_", f.body.trim_end()); + } } } } @@ -769,9 +780,9 @@ fn one_line(s: &str) -> String { s.split_whitespace().collect::>().join(" ") } -/// The unconfirmed facts in a review body: those the change rests on, as the -/// ask that clears them, and the rest under "Notes" (they don't hold the -/// merge). +/// The unconfirmed facts in a review body, as FYI notes: an unconfirmed +/// fact names no problem the review showed, so it never holds the merge. +/// Those the change rests on come first, with how to confirm them. pub fn unconfirmed_markdown(unconfirmed: &[UnconfirmedFact]) -> String { let line = |f: &UnconfirmedFact| { if f.why.trim().is_empty() { @@ -781,24 +792,22 @@ pub fn unconfirmed_markdown(unconfirmed: &[UnconfirmedFact]) -> String { } }; let mut s = String::new(); - let blocking: Vec<&UnconfirmedFact> = unconfirmed.iter().filter(|f| f.blocks).collect(); - if !blocking.is_empty() { + let rests: Vec<&UnconfirmedFact> = unconfirmed.iter().filter(|f| f.blocks).collect(); + if !rests.is_empty() { s.push_str( - "\n\n#### Confirm before merge\nThe change relies on these facts about another \ - system, and the PR's evidence says they weren't confirmed. Confirm each from the \ - real system (a payload or a row) and add what came back to the description. \ - Updating the description starts a re-review on its own, so there's no need to \ - push a commit or ask for one:\n", + "\n\n#### FYI: facts worth confirming\nThe change relies on these facts about \ + another system, and the PR's evidence doesn't confirm them. They don't hold the \ + merge; confirming each from the real system (a payload or a row) in the \ + description makes the change safer to ship:\n", ); - for f in blocking { + for f in rests { s.push_str(&line(f)); } } let notes: Vec<&UnconfirmedFact> = unconfirmed.iter().filter(|f| !f.blocks).collect(); if !notes.is_empty() { s.push_str( - "\n\n#### Notes\nUnconfirmed in the PR's evidence, but the change doesn't rest on \ - them, so they don't hold the merge:\n", + "\n\n#### FYI\nUnconfirmed in the PR's evidence; the change doesn't rest on them:\n", ); for f in notes { s.push_str(&line(f)); @@ -812,23 +821,23 @@ pub fn unconfirmed_markdown(unconfirmed: &[UnconfirmedFact]) -> String { /// `APPROVE` or `REQUEST_CHANGES`: a formal review never leaves the author /// guessing with a bare comment. /// -/// `REQUEST_CHANGES` for anything that holds the merge: a verified defect -/// (or a policy like required tests), a question or an unconfirmed fact the -/// change's correctness rests on, an earlier requested change still open, or -/// a failed verification. Otherwise `APPROVE`: notes, suggestions, concerns -/// the reviewer couldn't verify, questions the change doesn't rest on and -/// environment notes are posted with the approval. +/// `REQUEST_CHANGES` only for a named correctness, security or data-loss +/// problem with its location and evidence (a finding that holds the merge, +/// [`super::review_severity::classify`]), an earlier such request still +/// open, or a failed verification run (the change's own tests failing). +/// Otherwise `APPROVE`, with every other finding as a labeled note: Nit, +/// Suggestion or FYI (questions, unconfirmed facts, concerns the reviewer +/// couldn't show). The stop judge sees a request for changes before it is +/// posted (`passes::stop_judge`). pub fn decide_verdict( findings: &[Finding], prior_open_holding: usize, - unconfirmed: &[UnconfirmedFact], + _unconfirmed: &[UnconfirmedFact], verify_failed: bool, ) -> &'static str { - if verify_failed - || prior_open_holding > 0 - || findings.iter().any(Finding::holds_merge) - || unconfirmed.iter().any(|f| f.blocks) - { + // An unconfirmed fact is an FYI note: it names no problem the review + // showed, so it never requests changes on its own. + if verify_failed || prior_open_holding > 0 || findings.iter().any(Finding::holds_merge) { "REQUEST_CHANGES" } else { "APPROVE" @@ -1992,6 +2001,15 @@ pub fn to_postable( } else { "💬" }; + // Notes carry their label first (Nit, Suggestion, FYI); a blocker + // names its kind. + let label = match super::review_severity::label(f) { + Some(l) => format!("{}: ", l.as_str()), + None => match super::review_severity::blocking_kind(f) { + Some(k) => format!("Blocking ({}): ", k.as_str().replace('_', " ")), + None => "Blocking: ".to_string(), + }, + }; let kind = match f.evidence() { Evidence::VerifiedDefect if f.basis() == Some(Basis::Documented) => { format!("{}, documented", f.category) @@ -2003,7 +2021,7 @@ pub fn to_postable( Evidence::Question => "question".to_string(), Evidence::UnverifiedConcern => format!("{}, not verified", f.category), }; - let mut body = format!("{emoji} **{}** ({kind})\n\n{}", f.title, f.body); + let mut body = format!("{emoji} **{label}{}** ({kind})\n\n{}", f.title, f.body); if let Some(src) = f.source.as_deref().map(str::trim).filter(|s| !s.is_empty()) { if !f.body.contains(src) { body.push_str(&format!("\n\nSource: {src}")); @@ -2803,7 +2821,7 @@ mod required_tests_tests { } #[test] - fn tests_findings_become_blocking_others_untouched() { + fn tests_findings_become_suggestions_others_untouched() { let mut v = vec![ f("tests", "medium"), f("Tests", "low"), @@ -2811,7 +2829,8 @@ mod required_tests_tests { f("convention", "nit"), ]; enforce_required_tests(&mut v); - assert!(v[0].is_blocking() && v[1].is_blocking()); + assert!(v[0].optional == Some(true) && v[1].optional == Some(true)); + assert!(!v[0].is_blocking() && !v[0].holds_merge() && !v[1].holds_merge()); assert_eq!(v[2].severity, "medium"); assert_eq!(v[3].severity, "nit"); } @@ -2947,10 +2966,15 @@ mod evidence_tests { } #[test] - fn required_tests_are_a_policy_that_holds_the_merge() { - let mut v = vec![f("tests", Some("question"))]; + fn required_tests_are_a_suggestion_on_the_approval() { + let mut v = vec![f("tests", Some("verified-defect"))]; enforce_required_tests(&mut v); - assert!(v[0].holds_merge()); + assert!(!v[0].holds_merge()); + assert_eq!( + crate::passes::review_severity::label(&v[0]), + Some(crate::passes::review_severity::Label::Suggestion) + ); + assert!(v[0].body.contains(REQUIRED_TESTS_NOTE)); } fn lookup( @@ -3068,11 +3092,12 @@ mod evidence_tests { )], ); assert_eq!(rests_on.len(), 1, "{rests_on:?}"); - assert_eq!(decide_verdict(&[], 0, &rests_on, false), "REQUEST_CHANGES"); + // An unconfirmed fact is an FYI note, even one the change rests on. + assert_eq!(decide_verdict(&[], 0, &rests_on, false), "APPROVE"); let md = unconfirmed_markdown(&rests_on); - assert!(md.contains("#### Confirm before merge"), "{md}"); + assert!(md.contains("#### FYI: facts worth confirming"), "{md}"); assert!(md.contains("confirm `line_type` from a real refund payload")); - assert!(!md.contains("#### Notes")); + assert!(!md.contains("Confirm before merge")); let env_only = unconfirmed_external_facts( body, @@ -3084,10 +3109,10 @@ mod evidence_tests { ); assert_eq!(decide_verdict(&[], 0, &env_only, false), "APPROVE"); - // A description line no triage covers holds the merge until one does. + // A description line no triage covers is listed first, as an FYI. let untriaged = unconfirmed_external_facts(body, &[]); assert!(untriaged[0].blocks); - assert_eq!(decide_verdict(&[], 0, &untriaged, false), "REQUEST_CHANGES"); + assert_eq!(decide_verdict(&[], 0, &untriaged, false), "APPROVE"); // A human PR that says so in words: the reviewer's triage counts. let read = unconfirmed_external_facts( @@ -3098,7 +3123,8 @@ mod evidence_tests { "the code branches on it", )], ); - assert_eq!(decide_verdict(&[], 0, &read, false), "REQUEST_CHANGES"); + assert_eq!(read.len(), 1); + assert_eq!(decide_verdict(&[], 0, &read, false), "APPROVE"); assert_eq!(decide_verdict(&[], 0, &[], false), "APPROVE"); assert_eq!(unconfirmed_markdown(&[]), ""); } @@ -3141,7 +3167,7 @@ mod evidence_tests { ); assert!(!heading.contains("Questions")); let md = unconfirmed_markdown(&facts); - assert!(md.contains("#### Notes"), "{md}"); + assert!(md.contains("#### FYI"), "{md}"); assert!(md.contains("a vendor sandbox outage, not the change")); assert!(!md.contains("Confirm before merge")); assert!(!md.contains("isn't approved")); @@ -3182,16 +3208,21 @@ mod evidence_tests { let p = to_postable(std::slice::from_ref(¬e), &changed, &HashMap::new()); assert!(!thread_holds_merge(&p.inline[0].body)); } + // The owner's policy: a question is an FYI note even when the change + // rests on it; reviews never hold the merge on a question. let rests_on = q(Some(true)); - assert!(rests_on.holds_merge()); + assert!(!rests_on.holds_merge()); assert_eq!( decide_verdict(std::slice::from_ref(&rests_on), 0, &[], false), - "REQUEST_CHANGES" + "APPROVE" ); let p = to_postable(std::slice::from_ref(&rests_on), &changed, &HashMap::new()); - assert!(p.inline[0].body.contains("(question, blocks the merge)")); - // A later review counts the open thread as a requested change. - assert!(thread_holds_merge(&p.inline[0].body)); + assert!(p.inline[0].body.contains("**FYI: "), "{}", p.inline[0].body); + assert!(!thread_holds_merge(&p.inline[0].body)); + // An older blocking question thread no longer holds either. + assert!(!thread_holds_merge( + "🔴 **Is it idempotent?** (question, blocks the merge)\n\nx" + )); } /// Whatever the inputs, a finished review's verdict is one of two. @@ -3275,9 +3306,16 @@ mod evidence_tests { use crate::passes::review_verdict::{may_post, HoldKind as K, Holding, Verdict}; let nothing = Verdict::from_holding(vec![]); assert_eq!(nothing.event(), "APPROVE"); - assert!(!may_post("REQUEST_CHANGES", ¬hing)); - assert!(may_post("APPROVE", ¬hing)); - assert!(may_post("COMMENT", ¬hing)); + let hold = crate::passes::stop_judge::test_hold(crate::passes::stop_judge::Kind::Block); + assert!(!may_post("REQUEST_CHANGES", ¬hing, Some(&hold))); + assert!(may_post("APPROVE", ¬hing, None)); + assert!(may_post("COMMENT", ¬hing, None)); + // Something named, but no judged hold: refused. + let named = Verdict::from_holding(vec![Holding::new(K::Defect, "`a.rs:1` crash")]); + assert!(!may_post("REQUEST_CHANGES", &named, None)); + assert!(may_post("REQUEST_CHANGES", &named, Some(&hold))); + let other = crate::passes::stop_judge::test_hold(crate::passes::stop_judge::Kind::Stop); + assert!(!may_post("REQUEST_CHANGES", &named, Some(&other))); // A blank name names nothing. let blank = Verdict::from_holding(vec![Holding::new(K::Defect, " ")]); assert_eq!(blank.event(), "APPROVE"); diff --git a/services/worker/src/passes/review_cases/README.md b/services/worker/src/passes/review_cases/README.md index 8f5d8ea40..535d2f0e6 100644 --- a/services/worker/src/passes/review_cases/README.md +++ b/services/worker/src/passes/review_cases/README.md @@ -176,9 +176,11 @@ completes while its PR reviewer's verdict blocks. `passes/review_policy_eval.rs` replays the review sequences behind the verdict rules in `passes/review_policy.rs` and the severity rubric in `passes/review_severity.rs` (one review per head commit, no flip on an -unchanged commit without new information, blocking by default with notes -only for inferred preferences, optional improvements and unchecked external -state, blockers raised up front). Each case is a list of steps (`push`, +unchanged commit without new information, changes requested only for a +named correctness, security or data-loss problem with its location and +evidence, every other finding a labeled note (Nit, Suggestion, FYI) on the +approval, blockers raised up front). A request for changes is also put to the +stop judge before it is posted (`passes/stop_judge.rs`). Each case is a list of steps (`push`, `comment`, `base_failing`, `team_rules`, `claims_expire`, `review`, and `together` for jobs that start before any of them finishes) with the model output each review got (and the severity second pass's answer, `judge`, when diff --git a/services/worker/src/passes/review_cases/policy/team_rule_violation_blocks.json b/services/worker/src/passes/review_cases/policy/team_rule_violation_blocks.json deleted file mode 100644 index b53b046ca..000000000 --- a/services/worker/src/passes/review_cases/policy/team_rule_violation_blocks.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "description": "The code skips missing or invalid records silently, while the team's written rules require a WARNING with the record id and a count in the run summary. The reviewer posted it as a convention note. Breaking a written team rule blocks when the finding quotes it; a rule the finding cites that the team never wrote is dropped, and the finding is then a preference note.", - "steps": [ - {"team_rules": "## Data jobs\n- When a record is skipped because it is missing or invalid, log a WARNING with the record id and report the count of skipped records in the run summary.\n- Use the shared HTTP client."}, - {"push": {"head": "d1d2d3d"}}, - {"review": {"trigger": "synchronize", "dedup_key": "head#d1d2d3d", - "model": {"verdict": "APPROVE", "summary": "x", "findings": [ - {"file": "jobs/import.py", "line": 30, "severity": "medium", "category": "convention", "evidence": "verified-defect", "team_rule": "log a WARNING with the record id and report the count of skipped records in the run summary", "title": "Invalid records are skipped silently", "body": "`continue` on a missing price drops the record with no log and no count."}, - {"file": "jobs/import.py", "line": 50, "severity": "medium", "category": "convention", "evidence": "verified-defect", "team_rule": "Name every helper with a verb first", "title": "Rename parse to parse_rows", "body": "Helper names should start with a verb."} - ]}}} - ], - "expect": { - "formal": [["d1d2d3d", "REQUEST_CHANGES"]], - "last_notes": 1, - "body_contains": [[0, "[high] Invalid records are skipped silently"], [0, "[medium] Rename parse to parse_rows"]] - } -} diff --git a/services/worker/src/passes/review_cases/policy/team_rule_violation_is_a_suggestion.json b/services/worker/src/passes/review_cases/policy/team_rule_violation_is_a_suggestion.json new file mode 100644 index 000000000..4c873253c --- /dev/null +++ b/services/worker/src/passes/review_cases/policy/team_rule_violation_is_a_suggestion.json @@ -0,0 +1,64 @@ +{ + "description": "The code skips missing or invalid records, while the team's written rules require a WARNING with the record id and a count in the run summary. The reviewer filed it as a convention finding that quotes the rule. Under the owner's policy a written team rule not followed, with no correctness, security or data-loss defect shown, is a Suggestion on the approval; a rule the finding cites that the team never wrote is dropped, and the finding is then a preference note.", + "steps": [ + { + "team_rules": "## Data jobs\n- When a record is skipped because it is missing or invalid, log a WARNING with the record id and report the count of skipped records in the run summary.\n- Use the shared HTTP client." + }, + { + "push": { + "head": "d1d2d3d" + } + }, + { + "review": { + "trigger": "synchronize", + "dedup_key": "head#d1d2d3d", + "model": { + "verdict": "APPROVE", + "summary": "x", + "findings": [ + { + "file": "jobs/import.py", + "line": 30, + "severity": "medium", + "category": "convention", + "evidence": "verified-defect", + "team_rule": "log a WARNING with the record id and report the count of skipped records in the run summary", + "title": "Invalid records are skipped silently", + "body": "`continue` on a missing price drops the record with no log and no count." + }, + { + "file": "jobs/import.py", + "line": 50, + "severity": "medium", + "category": "convention", + "evidence": "verified-defect", + "team_rule": "Name every helper with a verb first", + "title": "Rename parse to parse_rows", + "body": "Helper names should start with a verb." + } + ] + } + } + } + ], + "expect": { + "formal": [ + [ + "d1d2d3d", + "APPROVE" + ] + ], + "last_notes": 2, + "body_contains": [ + [ + 0, + "Invalid records are skipped silently" + ], + [ + 0, + "Rename parse to parse_rows" + ] + ] + } +} diff --git a/services/worker/src/passes/review_cases/unconfirmed_vendor_field_is_fyi.json b/services/worker/src/passes/review_cases/unconfirmed_vendor_field_is_fyi.json new file mode 100644 index 000000000..dd701f847 --- /dev/null +++ b/services/worker/src/passes/review_cases/unconfirmed_vendor_field_is_fyi.json @@ -0,0 +1,67 @@ +{ + "name": "an unconfirmed field the code reads is an FYI on the approval", + "description": "The change sums a refund field of another system that the PR's own evidence says nobody read from a real payload, next to a staging note that doesn't matter. Under the owner's policy an unconfirmed fact names no problem the review showed, so it is listed first as an FYI worth confirming and the review approves; once the author confirms the field, the next review approves again without it.", + "steps": [ + { + "push": "h1" + }, + { + "review": { + "head": "h1", + "model_output": { + "verdict": "APPROVE", + "summary": "Adds refunds to the daily totals.", + "findings": [], + "unconfirmed_facts": [ + { + "fact": "refund lines carry `refund_total`", + "blocks": true, + "why": "the totals sum it; confirm `refund_total` from a real refund payload" + }, + { + "fact": "the staging ledger has no refunds", + "blocks": false, + "why": "staging data, not the change" + } + ] + } + } + }, + { + "push": "h2" + }, + { + "review": { + "head": "h2", + "model_output": { + "verdict": "APPROVE", + "summary": "The description now shows `refund_total` in a real refund payload.", + "findings": [], + "unconfirmed_facts": [ + { + "fact": "the staging ledger has no refunds", + "blocks": false, + "why": "staging data, not the change" + } + ] + } + } + } + ], + "expect": { + "final_formal": { + "head": "h2", + "event": "APPROVE" + }, + "formal_events": [ + [ + "h1", + "APPROVE" + ], + [ + "h2", + "APPROVE" + ] + ] + } +} diff --git a/services/worker/src/passes/review_cases/unconfirmed_vendor_field_requests_changes.json b/services/worker/src/passes/review_cases/unconfirmed_vendor_field_requests_changes.json deleted file mode 100644 index fb95c6077..000000000 --- a/services/worker/src/passes/review_cases/unconfirmed_vendor_field_requests_changes.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "an unconfirmed field the code reads requests changes with the ask", - "description": "The change sums a refund field of another system that the PR's own evidence says nobody read from a real payload, next to a staging note that doesn't matter. The field holds the merge as a request for changes (never a bare comment); the staging note rides along. Once the author confirms the field from a real payload, the review approves.", - "steps": [ - {"push": "h1"}, - {"review": {"head": "h1", "model_output": { - "verdict": "APPROVE", - "summary": "Adds refunds to the daily totals.", - "findings": [], - "unconfirmed_facts": [ - {"fact": "refund lines carry `refund_total`", "blocks": true, "why": "the totals sum it; confirm `refund_total` from a real refund payload"}, - {"fact": "the staging ledger has no refunds", "blocks": false, "why": "staging data, not the change"} - ] - }}}, - {"push": "h2"}, - {"review": {"head": "h2", "model_output": { - "verdict": "APPROVE", - "summary": "The description now shows `refund_total` in a real refund payload.", - "findings": [], - "unconfirmed_facts": [ - {"fact": "the staging ledger has no refunds", "blocks": false, "why": "staging data, not the change"} - ] - }}} - ], - "expect": { - "final_formal": {"head": "h2", "event": "APPROVE"}, - "formal_events": [["h1", "REQUEST_CHANGES"], ["h2", "APPROVE"]] - } -} diff --git a/services/worker/src/passes/review_policy.rs b/services/worker/src/passes/review_policy.rs index e7919e2e4..7e7ee44d4 100644 --- a/services/worker/src/passes/review_policy.rs +++ b/services/worker/src/passes/review_policy.rs @@ -560,9 +560,8 @@ pub fn named_holding( super::own_review::thread_line(path, *line, body), )); } - for fact in unconfirmed.iter().filter(|f| f.blocks) { - out.push(Holding::new(HoldKind::Fact, fact.fact.clone())); - } + // Unconfirmed facts are FYI notes on the approval, never a hold. + let _ = unconfirmed; if verify_failed { out.push(Holding::new( HoldKind::Verification, @@ -887,7 +886,7 @@ mod tests { }, Finding { title: "integration-tests job fails".into(), - ..defect("a.rs", 6, "high", "tests") + ..defect("a.rs", 6, "high", "bug") }, defect("a.rs", 7, "high", "bug"), ]; @@ -1641,9 +1640,11 @@ mod tests { assert!(heading.contains(&h.name), "{heading}"); } } + // An unconfirmed fact never holds: it is an + // FYI note on the approval. + let _ = u; let empty = !f.is_empty() || !t.is_empty() - || u.iter().any(|x| x.blocks) || v || !o.is_empty() || !k.is_empty(); diff --git a/services/worker/src/passes/review_policy_eval.rs b/services/worker/src/passes/review_policy_eval.rs index 4155a52e8..e1ff019e1 100644 --- a/services/worker/src/passes/review_policy_eval.rs +++ b/services/worker/src/passes/review_policy_eval.rs @@ -631,11 +631,18 @@ mod misgraded_findings { Optional, /// Negative: depends on external state nobody can check here. ExternalUnknown, + /// Negative (the owner's policy): a written team rule not followed, + /// with no correctness, security or data-loss defect shown, is a + /// Suggestion on the approval. + TeamRuleOnly, } impl Rule { fn blocks(self) -> bool { - !matches!(self, Rule::Style | Rule::Optional | Rule::ExternalUnknown) + !matches!( + self, + Rule::Style | Rule::Optional | Rule::ExternalUnknown | Rule::TeamRuleOnly + ) } } @@ -892,18 +899,6 @@ mod misgraded_findings { to end yet, so this is the most likely way it fails.", ), }, - Graded { - name: "a shipped agent instruction contradicts the repository's written test rule", - rule: Rule::BrokenTeamRules, - finding: finding( - "e2e/agents/test-healer.md", 1, "low", "docs", "verified-defect", - "Healer agent is told to fixme failing tests, which the repo's rules forbid for payment tests", - "This agent file says that when an error persists it should mark the test \ - `test.fixme()` and do whatever passes the test. The repository's own rules \ - (e2e/RULES.md) say payment tests are never skipped, fixme'd or loosened. An \ - agent invoked directly just follows its own prompt.", - ), - }, Graded { name: "a one-shot batch script marks every remaining batch terminal on one lasting rejection", rule: Rule::OneShot, @@ -937,6 +932,18 @@ mod misgraded_findings { fn true_notes() -> Vec { vec![ + Graded { + name: "a shipped agent instruction contradicts the repository's written test rule", + rule: Rule::TeamRuleOnly, + finding: finding( + "e2e/agents/test-healer.md", 1, "low", "docs", "verified-defect", + "Healer agent is told to fixme failing tests, which the repo's rules forbid for payment tests", + "This agent file says that when an error persists it should mark the test \ + `test.fixme()` and do whatever passes the test. The repository's own rules \ + (e2e/RULES.md) say payment tests are never skipped, fixme'd or loosened. An \ + agent invoked directly just follows its own prompt.", + ), + }, Graded { name: "a comment that went stale", rule: Rule::Style, diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 308e40637..780fc51ef 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -3061,7 +3061,7 @@ async fn run_once( .filter(|t| review_agent::thread_holds_merge(&t.body)) .map(|t| (t.path.clone(), t.line, t.body.clone())) .collect(); - let final_verdict = + let mut final_verdict = super::review_verdict::Verdict::from_holding(super::review_policy::named_holding( &findings, &open_holding, @@ -3070,6 +3070,51 @@ async fn run_once( &own_open, &stable.kept, )); + // A request for changes on someone's PR is a costly decision: the stop + // judge sees the whole picture and either holds on a named correctness, + // security or data-loss problem, or the review approves with the + // holdings as notes and its assumption written down. + let mut review_judged: Option = None; + let mut judge_note = String::new(); + if !self_authored && final_verdict.event() == "REQUEST_CHANGES" { + let picture = block_picture( + title, + pr_body, + &compare, + &findings, + &final_verdict, + &prior_threads, + &fixed_threads, + verify_failed, + &verify_md, + ); + let judged = super::stop_judge::decide( + state, + &provider, + &mut usage, + &msg.team_id, + &super::stop_judge::pr_subject(&msg.repo_owner, &msg.repo_name, msg.pr_number), + &head_sha, + picture, + ) + .await; + if let Some(a) = judged.assumption() { + info!(pr = msg.pr_number, head = %head_sha, "Stop judge: approve with notes instead of requesting changes"); + for f in findings.iter_mut().filter(|f| f.holds_merge()) { + super::review_policy::demote( + f, + "FYI, not a block: on the whole picture this is not a named correctness, \ + security or data-loss problem to hold the merge on.", + ); + } + judge_note = format!( + "\n\n**FYI:** on the whole picture nothing here holds the merge. Assumed: {}", + a.trim() + ); + final_verdict = super::review_verdict::Verdict::approve(); + } + review_judged = Some(judged); + } let verdict = final_verdict.event(); // 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) { @@ -3187,6 +3232,7 @@ async fn run_once( ), None => format!("{verdict_line}\n\n{summary}\n\n{}", risk_report.markdown()), }; + full_body.push_str(&judge_note); full_body.push_str(&review_agent::unconfirmed_markdown(&unconfirmed)); if !verify_md.is_empty() { full_body.push_str(&format!("\n\n{verify_md}")); @@ -3364,6 +3410,7 @@ async fn run_once( &full_body, &postable.inline, &final_verdict, + review_judged.as_ref(), ) .await { @@ -3716,6 +3763,7 @@ async fn carry_approval( &body, &[], &super::review_verdict::Verdict::approve(), + None, ) .await { @@ -4746,7 +4794,7 @@ pub(crate) fn reconcile_message(msg: &ReviewMessage, head: &str, reason: &str) - /// check is read as a question: the person gets an answer, and nothing about /// the formal review changes. async fn classify_ask( - state: &WorkerState, + _state: &WorkerState, provider: &ModelProvider, comment: &str, standing: Option<&super::review_verdict::StandingReview>, @@ -4768,13 +4816,13 @@ async fn classify_ask( }; match crate::agent::anthropic::converse_json( &provider.client(), - &state.config.light_model_id, + provider.judgment_model_id(), review_agent::ASK_SYSTEM, &review_agent::ask_prompt(comment, &standing_line, last_reply, outstanding), &review_agent::ask_schema(), true, - "low", - 512, + common::stop_judge::JUDGMENT_EFFORT, + 4096, usage, ) .await @@ -4799,13 +4847,13 @@ async fn reply_conclusion( ) -> Option { match crate::agent::anthropic::converse_json( &provider.client(), - provider.primary_model_id(), + provider.judgment_model_id(), review_agent::REPLY_CONCLUSION_SYSTEM, &review_agent::reply_conclusion_prompt(earlier_replies, question, answer), &review_agent::reply_conclusion_schema(), true, - "low", - 4096, + common::stop_judge::JUDGMENT_EFFORT, + 8192, usage, ) .await @@ -4856,6 +4904,94 @@ fn settled_prior_threads<'a>( .collect() } +/// What the stop judge sees for a proposed request for changes: the PR's +/// title and description, the files it changes, every finding as evidence +/// (checked when it blocks and traces its mechanism), the verification run, +/// and the earlier threads with where each stands. +#[allow(clippy::too_many_arguments)] +fn block_picture( + title: &str, + pr_body: &str, + compare: &serde_json::Value, + findings: &[review_agent::Finding], + verdict: &super::review_verdict::Verdict, + prior_threads: &[&crate::clients::github::BotReviewThread], + fixed_threads: &[&crate::clients::github::BotReviewThread], + verify_failed: bool, + verify_md: &str, +) -> super::stop_judge::Picture { + use super::stop_judge::{Evidence, Kind, Picture, Thread}; + let mut p = Picture::new( + Kind::Block, + "review", + &format!( + "the review would request changes on: {}", + verdict.names().join("; ") + ), + ); + p.ticket_title = title.to_string(); + p.ticket_body = pr_body.to_string(); + p.acceptance = super::stop_judge::acceptance(pr_body); + p.diff_summary = compare["files"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|f| { + Some(format!( + "{} ({}, +{} -{})", + f["filename"].as_str()?, + f["status"].as_str().unwrap_or(""), + f["additions"].as_u64().unwrap_or(0), + f["deletions"].as_u64().unwrap_or(0) + )) + }) + .collect::>() + .join("\n") + }) + .unwrap_or_default(); + for f in findings { + let class = super::review_severity::classify(f); + p.evidence.push(Evidence { + source: format!("review finding ({})", class.reason()), + finding: format!("{}: {}", f.title, common::truncate_str(&f.body, 1_500)), + location: if f.line > 0 { + format!("{}:{}", f.file, f.line) + } else { + f.file.clone() + }, + checked: class.blocks() && super::review_severity::traces_mechanism(f), + ..Default::default() + }); + } + if verify_failed { + p.evidence.push(Evidence { + source: "verification run".into(), + finding: format!( + "the change's affected tests or build failed in the sandbox: {}", + common::truncate_str(verify_md, 1_500) + ), + location: "the verification run".into(), + checked: true, + ..Default::default() + }); + } + for t in prior_threads { + let fixed = fixed_threads.iter().any(|f| f.id == t.id); + p.threads.push(Thread { + summary: format!( + "{}:{} {}", + t.path, + t.line, + common::truncate_str(&t.body, 600) + ), + open: !fixed && !t.resolved, + person_last: t.replies.last().is_some_and(|r| !r.by_bot), + ..Default::default() + }); + } + p +} + #[cfg(test)] mod review_usage_tests { use super::*; @@ -5244,7 +5380,8 @@ mod verdict_tests { assert_eq!(a[1]["kind"], "concern"); assert_eq!(a[1]["blocks"], false); assert_eq!(a[2]["kind"], "question"); - assert_eq!(a[2]["blocks"], true); + // A question is an FYI note, even one the change rests on. + assert_eq!(a[2]["blocks"], false); assert_eq!(super::findings_record(&[]), "[]"); } @@ -5348,16 +5485,14 @@ mod verdict_tests { decide_verdict(std::slice::from_ref(&nit), 0, &[], false), "APPROVE" ); - // A required test or a failed check still blocks. + // A required test is a Suggestion on the approval; a failed + // verification run (the change's own tests failing) still blocks. let mut tests = Finding { category: "tests".into(), ..Default::default() }; super::review_agent::enforce_required_tests(std::slice::from_mut(&mut tests)); - assert_eq!( - decide_verdict(&[nit, tests], 0, &[], false), - "REQUEST_CHANGES" - ); + assert_eq!(decide_verdict(&[nit, tests], 0, &[], false), "APPROVE"); assert_eq!(decide_verdict(&[], 0, &[], true), "REQUEST_CHANGES"); } diff --git a/services/worker/src/passes/review_severity.rs b/services/worker/src/passes/review_severity.rs index f44b2ce0a..9fddeba76 100644 --- a/services/worker/src/passes/review_severity.rs +++ b/services/worker/src/passes/review_severity.rs @@ -1,33 +1,29 @@ -//! Whether a review finding holds the merge. +//! Whether a review finding holds the merge, and how a note is labeled. //! -//! Blocking is the default. A finding is a note only when it is one of: +//! The owner's policy: changes are requested only for a named correctness, +//! security or data-loss problem, with its location and evidence. Every +//! other finding is posted on an approval as a labeled note ([`Label`]): //! -//! 1. a style or naming preference the reviewer inferred itself (not a -//! written team or repository rule); -//! 2. an optional suggestion or improvement where the current code is -//! correct; -//! 3. a concern that rests on unknown external state the reviewer couldn't -//! check, on a path that doesn't run once in production. -//! -//! Everything else blocks: defects verified by the code, tests or CI, a data -//! query or documentation; correctness and data issues; a PR that misses its -//! own stated goal; a broken team rule; security issues. Policies on top -//! (a follow-up the PR tracks, a problem it didn't cause, a late blocker) -//! still make a finding a note ([`super::review_policy`]). +//! - **Nit**: a style, naming or layout preference; +//! - **Suggestion**: an optional improvement, hardening, a refactor, or a +//! written team rule the change doesn't follow (no defect shown); +//! - **FYI**: a question, a concern resting on state nobody could check, an +//! unconfirmed fact, or a problem without a location or evidence. //! //! [`classify`] decides from the finding's structured fields (basis, -//! category, path kind, stated-goal miss, cited rule); the model's own -//! severity is only an input. [`ground`] fills those fields from what the -//! finding shows (a code path it traces, a documented exit or status code -//! the code gets backwards, a team rule it quotes), and [`second_pass`] -//! has an independent judge check every note against the same rubric. +//! category, location, stated-goal miss); the model's own severity is only +//! an input. [`ground`] fills those fields from what the finding shows (a +//! code path it traces, a documented exit or status code the code gets +//! backwards, a team rule it quotes), and [`second_pass`] has an independent +//! judge check every note against the same rubric. A finding that blocks is +//! still put to the stop judge before "changes requested" is posted +//! (`passes::stop_judge`). //! -//! The miss behind it: a provisioning script that threw on an installer's -//! documented "success, reboot required" code, a write that hid rows from -//! two incremental cursors (traced line by line, posted "not verified"), a -//! sort-key tie the PR set out to remove that a data query confirmed -//! (posted as a note because "the impact is likely small"), and a silent -//! skip the team's written rules forbid, all posted as non-blocking. +//! The misses behind the evidence rules: a provisioning script that threw on +//! an installer's documented "success, reboot required" code, a write that +//! hid rows from two incremental cursors (traced line by line), and a +//! sort-key tie a data query confirmed: each a correctness or data-loss +//! problem shown by evidence, so each blocks. use super::review_agent::{Basis, Evidence, Finding}; use crate::agent::provider::{self, ModelProvider}; @@ -165,6 +161,46 @@ fn category_in(category: &str, list: &[&str]) -> bool { pub const PREFERENCE: &str = "a preference the reviewer inferred"; /// Why a note is an optional improvement. pub const OPTIONAL: &str = "an optional suggestion; the current code is correct"; +/// Why a question is a note. +pub const QUESTION: &str = "a question; reviews ask in notes and never hold the merge on one"; +/// Why a team-rule finding with no defect shown is a note. +pub const TEAM_RULE: &str = "a written team rule the change doesn't follow, with no defect shown"; +/// Why a finding outside the three blocking kinds is a note. +pub const NOT_BLOCKING_KIND: &str = "not a correctness, security or data-loss problem"; +/// Why a finding with no file is a note. +pub const NO_LOCATION: &str = "no location in the change"; +/// Why an unshown concern is a note. +pub const UNSHOWN: &str = "a concern the review couldn't show with evidence"; + +/// How a note is labeled on the approval. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Label { + Nit, + Suggestion, + Fyi, +} + +impl Label { + pub fn as_str(self) -> &'static str { + match self { + Label::Nit => "Nit", + Label::Suggestion => "Suggestion", + Label::Fyi => "FYI", + } + } +} + +/// The label a note carries (`None`: it blocks). +pub fn label(f: &Finding) -> Option