From a1267b33c35dafc1f4a06ec86a2428d1767d79a1 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Thu, 12 Nov 2026 07:30:26 -0500 Subject: [PATCH] Runs finish or hand back only for a listed reason: one supervisor for every ending Runs kept ending by handing unfinished work to a person: two steps that changed nothing stopped the run with a held draft, a CI fix that met the same failure set needs_input, own-review rounds at their cap asked a person, an error after the work became a held draft. Each loop had its own stall rule and its own hand-back ending, and every earlier fix changed one of them. needs_input is now written only with a HandBack (common::handback), which exists only for a reason on the human-only list: a credential, missing access, a product decision, an ambiguous ticket, someone else holding the work, the usage limit, an approval, or a person's own action. The type that writes the status takes one, and the reason is kept on the wait. supervisor::hand_back_for is the one reading of a stop. Every former hand-back ending now finishes through supervisor::end: - a stop after the work ships: tasks left are deferred with why on the checklist, the pull request gets a Deferred section, and the run goes on to CI and the ready decision; - CI give-ups revert to the last green head, else take out the last planned task, defer it and let CI decide again; only when nothing can come out does the run end failed with what fails; - own-review, planned-work and guard stops finish on their pull request (failed when its CI is red); held drafts on finished runs stay recorded without turning the run into a wait. A step that changed nothing climbs a ladder instead of stopping: one task, fresh context with edits in place, a re-split, the strongest model, defer the task (non-core after three), then ship; near 85% of the spend ceiling it ships. Own-review rounds extend while they fix things, up to twice the cap. Errors after the work get one fresh step, the step-limit continuation covers every pass after the work, and a reply that spent its whole output thinking is taken again with less thinking instead of read as the answer. Tests: the supervisor's rules over every combination, a replay of 217 historical stuck-run shapes (invented names) asserting no run waits unless its blocker is on the list, and a source scan that fails when an ending goes around the supervisor. --- services/common/src/agent_log.rs | 3 + services/common/src/handback.rs | 258 ++ services/common/src/lib.rs | 3 +- services/common/src/run_wait.rs | 25 +- services/gateway/src/routes/run_close.rs | 6 +- services/worker/src/agent/anthropic.rs | 217 +- services/worker/src/agent/policy.rs | 1 + .../passes/incidents/ac_partial_and_red_ci.rs | 10 +- services/worker/src/passes/mod.rs | 331 ++- services/worker/src/passes/own_review.rs | 34 +- services/worker/src/passes/plan_coverage.rs | 59 +- services/worker/src/passes/ready.rs | 27 +- services/worker/src/passes/resume.rs | 316 ++- services/worker/src/passes/run_ceiling.rs | 2 +- services/worker/src/passes/run_guard.rs | 77 +- services/worker/src/passes/steps.rs | 2 + services/worker/src/passes/stop_pr.rs | 237 +- services/worker/src/passes/supervisor.rs | 862 ++++++ .../worker/src/passes/supervisor_replays.rs | 2413 +++++++++++++++++ 19 files changed, 4690 insertions(+), 193 deletions(-) create mode 100644 services/common/src/handback.rs create mode 100644 services/worker/src/passes/supervisor.rs create mode 100644 services/worker/src/passes/supervisor_replays.rs diff --git a/services/common/src/agent_log.rs b/services/common/src/agent_log.rs index cbf790a17..7e7a1904b 100644 --- a/services/common/src/agent_log.rs +++ b/services/common/src/agent_log.rs @@ -143,6 +143,8 @@ pub enum NoteKind { WrapUp, /// Every tool step is used: tools are off, answer now. ToolsOff, + /// A turn reached the output limit before any tool call: act now. + OutputLimit, } impl NoteKind { @@ -151,6 +153,7 @@ impl NoteKind { NoteKind::TurnBudget => "turn_budget", NoteKind::WrapUp => "wrap_up", NoteKind::ToolsOff => "tools_off", + NoteKind::OutputLimit => "output_limit", } } } diff --git a/services/common/src/handback.rs b/services/common/src/handback.rs new file mode 100644 index 000000000..cc54edf65 --- /dev/null +++ b/services/common/src/handback.rs @@ -0,0 +1,258 @@ +//! The only reasons a run hands its work to a person. +//! +//! A run that stalled, met a red check it couldn't fix, ran out of a budget, +//! or had a check error after its work used to end `needs_input` with "a +//! person should look". None of those need a person: CoderHelm changes its +//! approach, defers what resists with the reason, and ships what is done +//! (the worker's `passes::supervisor`). A person is needed only for what +//! only a person has, and this module is that list. +//! +//! [`HandBack`] is the permission to wait on a person: its fields are +//! private, so it exists only for a reason on [`HUMAN_ONLY`], and +//! `run_wait::NeedsInput::needs_input` (the one way to write the status) +//! takes one. The reason is kept on the run's wait (`handback`), so the run +//! page, analytics and the stuck-run sweep can all tell why. + +use std::fmt; + +/// The only reasons a run waits on a person. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum HumanOnly { + /// A secret, token or sign-in only a person can provide. + Credential, + /// Access CoderHelm lacks: a repository not turned on, a permission the + /// app wasn't granted, a system no connection reaches. + MissingAccess, + /// A product or business choice the ticket leaves open. + ProductDecision, + /// The ticket reads two ways and the readings lead to different code. + AmbiguousTicket, + /// Another run or person already works on the same pull request or + /// ticket. + HeldByAnother, + /// The team's usage limit stops runs. + UsageLimit, + /// The team's agent policy waits for a person's approval. + Approval, + /// A person stopped, reopened, redirected the run, or put its pull + /// request back to draft. + PersonAction, +} + +/// Every reason on the list. +pub const HUMAN_ONLY: &[HumanOnly] = &[ + HumanOnly::Credential, + HumanOnly::MissingAccess, + HumanOnly::ProductDecision, + HumanOnly::AmbiguousTicket, + HumanOnly::HeldByAnother, + HumanOnly::UsageLimit, + HumanOnly::Approval, + HumanOnly::PersonAction, +]; + +impl HumanOnly { + /// The code kept on the run's wait. + pub fn code(self) -> &'static str { + match self { + HumanOnly::Credential => "credential", + HumanOnly::MissingAccess => "missing_access", + HumanOnly::ProductDecision => "product_decision", + HumanOnly::AmbiguousTicket => "ambiguous_ticket", + HumanOnly::HeldByAnother => "held_by_another", + HumanOnly::UsageLimit => "usage_limit", + HumanOnly::Approval => "approval", + HumanOnly::PersonAction => "person_action", + } + } + + pub fn from_code(code: &str) -> Option { + HUMAN_ONLY.iter().copied().find(|h| h.code() == code.trim()) + } + + /// What a person reads. + pub fn label(self) -> &'static str { + match self { + HumanOnly::Credential => "a credential only a person can provide", + HumanOnly::MissingAccess => "access CoderHelm doesn't have", + HumanOnly::ProductDecision => "a product decision", + HumanOnly::AmbiguousTicket => "the ticket reads two ways", + HumanOnly::HeldByAnother => "someone else is working on it", + HumanOnly::UsageLimit => "the team's usage limit", + HumanOnly::Approval => "an approval", + HumanOnly::PersonAction => "a person's action on the run", + } + } +} + +impl fmt::Display for HumanOnly { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.code()) + } +} + +/// Permission to wait on a person: a reason on the list and the one thing +/// the person does. Made only by [`HandBack::new`] and [`HandBack::of`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HandBack { + why: HumanOnly, + need: String, +} + +impl HandBack { + /// `None` without a need: a hand-back says exactly what is needed. + pub fn new(why: HumanOnly, need: &str) -> Option { + let n = need.split_whitespace().collect::>().join(" "); + (!n.is_empty()).then(|| HandBack { + why, + need: crate::truncate_str(&n, 600).to_string(), + }) + } + + /// For a wait whose need is written in the wait itself (its action). + pub fn of(why: HumanOnly) -> HandBack { + HandBack { + why, + need: why.label().to_string(), + } + } + + pub fn why(&self) -> HumanOnly { + self.why + } + + pub fn need(&self) -> &str { + &self.need + } + + /// From what the stop judge found only a person has. + pub fn of_person_only(p: crate::stop_judge::PersonOnly, question: &str) -> Option { + use crate::stop_judge::PersonOnly as P; + let why = match p { + P::ProductChoice => HumanOnly::ProductDecision, + P::Access => { + if human_only_in(question) == Some(HumanOnly::Credential) { + HumanOnly::Credential + } else { + HumanOnly::MissingAccess + } + } + P::DivergentReadings => HumanOnly::AmbiguousTicket, + }; + HandBack::new(why, question) + } + + /// From the stop judge's decision: its question (always about what only + /// a person has), or a hold whose blocker names something on the list. + /// `None` for a proceed, and for a hold on anything else (a stall, a red + /// check, a budget, a tool error): those are CoderHelm's to finish. + pub fn of_judged(j: &crate::stop_judge::Judged) -> Option { + use crate::stop_judge::Verdict; + match j.verdict() { + Verdict::Ask(q) => HandBack::of_person_only(q.person_only, &q.question), + Verdict::Hold(h) => { + human_only_in(&h.blocker).and_then(|why| HandBack::new(why, &h.blocker)) + } + Verdict::Proceed { .. } => None, + } + } +} + +/// Reads a reason on the list from words a run, a check or the judge wrote. +/// `None` when they name none, which is the case for every stall, red +/// check, tool error, time limit or budget. +pub fn human_only_in(text: &str) -> Option { + let t = text.to_lowercase(); + let any = |marks: &[&str]| marks.iter().any(|m| t.contains(m)); + if any(&[ + "api key", + "secret value", + "a secret only", + "credentials for", + "credential for", + "a token for", + "password for", + "sign in to", + "log in to", + ]) { + return Some(HumanOnly::Credential); + } + if any(&[ + "turn the repository on", + "not turned on", + "the app wasn't granted", + "the app lacks", + "app isn't installed", + "no access to", + "access coderhelm doesn't have", + "access coderhelm lacks", + "grant access", + "resource not accessible by integration", + "outside the code", + "no connection reaches", + ]) { + return Some(HumanOnly::MissingAccess); + } + if any(&[ + "product decision", + "product choice", + "business decision", + "which behavior you want", + "which behaviour you want", + ]) { + return Some(HumanOnly::ProductDecision); + } + if any(&[ + "ticket is ambiguous", + "reads two ways", + "divergent readings", + ]) { + return Some(HumanOnly::AmbiguousTicket); + } + if any(&["approval", "approve the"]) && any(&["policy", "agent permission", "paused"]) { + return Some(HumanOnly::Approval); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_hand_back_needs_a_listed_reason_and_what_is_needed() { + assert!(HandBack::new(HumanOnly::Credential, " ").is_none()); + let h = HandBack::new(HumanOnly::Credential, "Add the PAYMENTS_KEY secret").unwrap(); + assert_eq!(h.need(), "Add the PAYMENTS_KEY secret"); + for r in HUMAN_ONLY { + assert_eq!(HumanOnly::from_code(r.code()), Some(*r)); + } + } + + #[test] + fn stalls_red_checks_budgets_and_errors_are_not_on_the_list() { + for words in [ + "Stopped: steps 2 and 3 made no progress. The branch stayed at a8c8814", + "CI fixes stalled on the same failure", + "A person looks at the failing check: CoderHelm's fixes keep meeting the same failure.", + "The step reached its time limit and the run couldn't continue in a fresh step", + "A check after the work errored: the link check.", + "CoderHelm's fix budget for this run is spent", + "Validation Failed: body is too long (maximum is 65536 characters)", + "Handed to a person: CoderHelm took 2 fix rounds on its own review's findings", + "7 checks are failing on this head", + "The coder used this step's turns with work left", + "Stopped before opening a pull request: 2 of 9 planned tasks are not done", + ] { + assert_eq!(human_only_in(words), None, "{words}"); + } + assert_eq!( + human_only_in("Turn the repository on for runs in CoderHelm, then press Retry"), + Some(HumanOnly::MissingAccess) + ); + assert_eq!( + human_only_in("It needs the API key for the payments sandbox"), + Some(HumanOnly::Credential) + ); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 0c1f2477d..549a6c875 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -149,6 +149,8 @@ pub mod run_prs; // review_stats: time-ordered review records for analytics pub mod decision_log; pub mod deploy_stats; +/// Run statuses; which ones a person set; closing and reopening a run. +pub mod handback; /// Work CoderHelm started on its own pull request and hasn't landed, and /// what a person's mention there does about it. pub mod held_work; @@ -188,7 +190,6 @@ pub mod run_questions; /// Fix rounds on an open pull request: each with its own time budget, /// resumable, and never a failed run when one doesn't finish. pub mod run_round; -/// Run statuses; which ones a person set; closing and reopening a run. pub mod run_status; /// What a run waiting on a person is waiting for: never nothing. pub mod run_wait; diff --git a/services/common/src/run_wait.rs b/services/common/src/run_wait.rs index b628a738e..26a3e5aa0 100644 --- a/services/common/src/run_wait.rs +++ b/services/common/src/run_wait.rs @@ -24,6 +24,7 @@ use aws_sdk_dynamodb::operation::update_item::builders::UpdateItemFluentBuilder; use aws_sdk_dynamodb::types::AttributeValue; use serde::{Deserialize, Serialize}; +use crate::handback::HandBack; use crate::run_questions::{Asked, Question, FIELD_QUESTIONS}; use crate::run_status::NEEDS_INPUT; @@ -56,6 +57,10 @@ pub struct WaitingOn { /// When the wait started (RFC 3339): the reminder counts from here. #[serde(default)] pub since: String, + /// Why only a person can do it: a code on the human-only list + /// (`handback::HumanOnly::code`), set by [`NeedsInput::needs_input`]. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub handback: String, } fn is_zero(n: &usize) -> bool { @@ -86,6 +91,7 @@ impl WaitingOn { url: url.trim().to_string(), questions: 0, since: now(), + handback: String::new(), }) } @@ -98,6 +104,7 @@ impl WaitingOn { url: url.trim().to_string(), questions: 0, since: now(), + handback: String::new(), } } @@ -190,16 +197,24 @@ pub fn asks_something(item: &HashMap) -> bool { asked || WaitingOn::of_item(item).is_some() } -/// The one way to write `needs_input`: with what the run waits for. +/// The one way to write `needs_input`: with what the run waits for, and +/// why only a person can do it ([`HandBack`]: a reason on the human-only +/// list). A stall, a red check, a budget or an error has no `HandBack`, so +/// it can't end a run this way. pub trait NeedsInput { /// Sets `:s` to `needs_input`, `:sri` to its `status_run_id` and `:wo` - /// to `wait`. The update expression names them: - /// `#s = :s, status_run_id = :sri, waiting_on = :wo`. - fn needs_input(self, run_id: &str, wait: &WaitingOn) -> Self; + /// to `wait` with the hand-back's reason. The update expression names + /// them: `#s = :s, status_run_id = :sri, waiting_on = :wo`. + fn needs_input(self, run_id: &str, wait: &WaitingOn, why: &HandBack) -> Self; } impl NeedsInput for UpdateItemFluentBuilder { - fn needs_input(self, run_id: &str, wait: &WaitingOn) -> Self { + fn needs_input(self, run_id: &str, wait: &WaitingOn, why: &HandBack) -> Self { + let mut wait = wait.clone(); + wait.handback = why.why().code().to_string(); + if wait.detail.trim().is_empty() { + wait.detail = bounded(why.need(), MAX_DETAIL_CHARS); + } self.expression_attribute_values(":s", AttributeValue::S(NEEDS_INPUT.into())) .expression_attribute_values( ":sri", diff --git a/services/gateway/src/routes/run_close.rs b/services/gateway/src/routes/run_close.rs index b5550b338..edc3d3a1b 100644 --- a/services/gateway/src/routes/run_close.rs +++ b/services/gateway/src/routes/run_close.rs @@ -994,7 +994,11 @@ pub async fn reopen_run( reopened_at = :t, reopened_by = :by \ REMOVE closed_at, closed_by, closed_by_name, closed_from, close_reason", ) - .needs_input(&run_id, &reopened_wait(item.as_ref())) + .needs_input( + &run_id, + &reopened_wait(item.as_ref()), + &common::handback::HandBack::of(common::handback::HumanOnly::PersonAction), + ) } else { update .update_expression( diff --git a/services/worker/src/agent/anthropic.rs b/services/worker/src/agent/anthropic.rs index 0c3ffcc3f..333c03b46 100644 --- a/services/worker/src/agent/anthropic.rs +++ b/services/worker/src/agent/anthropic.rs @@ -733,8 +733,14 @@ pub async fn converse_tool_loop( // which the agent must answer from what it already learned. Without it, // everything a planner read was thrown away the moment it ran out. let mut answer_now = false; - // Turns cut at the output limit before any tool call, nudged on. - let mut cut_nudges: u32 = 0; + // A turn cut at the output limit before any tool call is not an + // answer: one security run spent nine model calls and $11 thinking to the + // limit, each read as the coder's final word, and another coder did the + // same nine times on one README table. The turn is taken again with one + // step less thinking and a note to act in small steps, up to + // [`MAX_CUT_RETRIES`] times. + let mut effort = effort; + let mut cut_retries: u32 = 0; loop { turns += 1; @@ -880,35 +886,55 @@ pub async fn converse_tool_loop( }) .collect(); - if continue_after_cut( + if let Some(cut) = cut_before_acting( + &blocks, response.stop_reason.as_deref(), !tool_uses.is_empty(), - !tools.is_empty() && !answer_now, - cut_nudges, + !tools.is_empty(), + answer_now, + cut_retries, ) { - // A turn spent its whole output thinking and made no call: the - // coder once did that nine times on one README table and the run - // ended without the change. It is told to act in small steps. - cut_nudges += 1; + cut_retries += 1; + effort = Some(lower_effort(effort)); warn!( max_tokens, - nudge = cut_nudges, - "A turn reached the output limit before any tool call; asking for small steps" + retry = cut_retries, + output_tokens = response.usage.output_tokens, + effort = effort.unwrap_or(""), + kept = cut == CutTurn::SaidSomething, + "A turn reached the output limit before any tool call: taking it again with less thinking" ); - if let Some(ref mut log) = conversation_log { - log.push(json!({ - "turn": turns, - "call": call, - "role": "system_note", - "kind": "output_limit", - "content": OUTPUT_LIMIT_NOTE, - "stop_reason": response.stop_reason, - })); + log_note( + conversation_log.as_deref_mut(), + call, + turns, + common::agent_log::NoteKind::OutputLimit, + OUTPUT_LIMIT_NOTE, + ); + if cut == CutTurn::ThinkingOnly { + // A reply that only thought is dropped: its thinking was cut + // before it could be signed, and an assistant turn with no + // text or call can't be sent back. Dropping the last turn + // leaves the history before it untouched, so every earlier + // thinking block still round-trips. The note goes on the + // last user turn instead. + messages.pop(); + match messages.last_mut() { + Some((role, content)) if role == "user" => { + content.push(json!({"type": "text", "text": OUTPUT_LIMIT_NOTE})); + } + _ => messages.push(( + "user".to_string(), + vec![json!({"type": "text", "text": OUTPUT_LIMIT_NOTE})], + )), + } + } else { + // What it said stays in history: the model sees where it was cut. + messages.push(( + "user".to_string(), + vec![json!({"type": "text", "text": OUTPUT_LIMIT_NOTE})], + )); } - messages.push(( - "user".to_string(), - vec![json!({"type": "text", "text": OUTPUT_LIMIT_NOTE})], - )); continue; } @@ -1170,44 +1196,6 @@ fn call_index(log: &[Value]) -> usize { } /// Logs a message the loop put into the conversation itself. -/// Turns cut at the output limit before any tool call that are nudged on -/// before the loop takes the cut as the answer. -const MAX_CUT_NUDGES: u32 = 2; - -const OUTPUT_LIMIT_NOTE: &str = "Your last turn reached the output limit before you made any tool call, so nothing was done. Think briefly and act now: make the change in small edit_file calls (a few lines each), one call per turn if needed. If the task is not needed, say so in one sentence."; - -/// Whether a turn that made no tool call goes on with a nudge: it was cut -/// at the output limit, tools are on, and the nudges aren't used up. -fn continue_after_cut( - stop_reason: Option<&str>, - called_tools: bool, - tools_on: bool, - nudges: u32, -) -> bool { - stop_reason == Some("max_tokens") && !called_tools && tools_on && nudges < MAX_CUT_NUDGES -} - -#[cfg(test)] -mod cut_tests { - use super::*; - - #[test] - fn a_turn_cut_before_any_call_is_nudged_twice_then_ends() { - assert!(continue_after_cut(Some("max_tokens"), false, true, 0)); - assert!(continue_after_cut(Some("max_tokens"), false, true, 1)); - assert!(!continue_after_cut( - Some("max_tokens"), - false, - true, - MAX_CUT_NUDGES - )); - // A call was made, tools are off, or it simply ended: no nudge. - assert!(!continue_after_cut(Some("max_tokens"), true, true, 0)); - assert!(!continue_after_cut(Some("max_tokens"), false, false, 0)); - assert!(!continue_after_cut(Some("end_turn"), false, true, 0)); - } -} - fn log_note( log: Option<&mut Vec>, call: usize, @@ -1452,6 +1440,63 @@ fn read_message( }) } +/// Turns cut at the output limit before any tool call that are taken again +/// before the loop reads the cut as the answer. +const MAX_CUT_RETRIES: u32 = 3; + +/// What the model reads after a turn cut at the output limit before any +/// tool call. +const OUTPUT_LIMIT_NOTE: &str = "[SYSTEM NOTE] Your last turn reached the output limit before \ + you made any tool call, so nothing was done. Think briefly, then act now: make the next tool \ + call, and make a change in small edit_file calls (a few lines each), one call per turn if \ + needed. If the task is not needed, say so in one sentence; otherwise give your final answer."; + +/// A turn cut at the output limit before any tool call. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum CutTurn { + /// No text and no call: its whole output went on thinking. + ThinkingOnly, + /// It wrote text and was cut before its call. + SaidSomething, +} + +/// Whether a turn that made no tool call is taken again instead of read as +/// the answer: it was cut at the output limit, the loop isn't on its +/// tools-off answer turn, and the retries aren't used up. A cut that said +/// something is taken again only when tools are on (with none, its text is +/// the answer); one that only thought always is, as it says nothing at all. +fn cut_before_acting( + blocks: &[ContentBlock], + stop_reason: Option<&str>, + called_tools: bool, + tools_on: bool, + answer_now: bool, + retries: u32, +) -> Option { + if stop_reason != Some("max_tokens") || called_tools || answer_now || retries >= MAX_CUT_RETRIES + { + return None; + } + let said = blocks.iter().any(|b| match b { + ContentBlock::Text { text } => !text.trim().is_empty(), + _ => false, + }); + match (said, tools_on) { + (false, _) => Some(CutTurn::ThinkingOnly), + (true, true) => Some(CutTurn::SaidSomething), + (true, false) => None, + } +} + +/// One step less thinking. +fn lower_effort(effort: Option<&str>) -> &'static str { + match effort { + Some("max") | Some("xhigh") => "high", + Some("high") | None => "medium", + _ => "low", + } +} + fn extract_text( content: &[ContentBlock], ) -> Result> { @@ -1522,6 +1567,54 @@ mod tests { assert!(body.get("anthropic_beta").is_none()); } + /// A security run's coder spent nine replies thinking to the output + /// limit with no tool call, each read as its final answer; another coder + /// did the same nine times on one README table. + #[test] + fn a_turn_cut_before_any_call_is_taken_again_not_read_as_the_answer() { + let thought: Vec = vec![]; + let cut = |b: &[ContentBlock], stop, called, tools_on, answer_now, n| { + cut_before_acting(b, stop, called, tools_on, answer_now, n) + }; + let max = Some("max_tokens"); + assert_eq!( + cut(&thought, max, false, true, false, 0), + Some(CutTurn::ThinkingOnly) + ); + let blank = vec![ContentBlock::Text { text: " ".into() }]; + assert_eq!( + cut(&blank, max, false, true, false, 0), + Some(CutTurn::ThinkingOnly) + ); + let said = vec![ContentBlock::Text { + text: "Now the README table:".into(), + }]; + assert_eq!( + cut(&said, max, false, true, false, 0), + Some(CutTurn::SaidSomething) + ); + // Taken again up to the limit, then the cut is the answer. + assert!(cut(&thought, max, false, true, false, MAX_CUT_RETRIES - 1).is_some()); + assert_eq!( + cut(&thought, max, false, true, false, MAX_CUT_RETRIES), + None + ); + // A call was made, it simply ended, or it is the tools-off answer turn. + assert_eq!(cut(&thought, max, true, true, false, 0), None); + assert_eq!(cut(&thought, Some("end_turn"), false, true, false, 0), None); + assert_eq!(cut(&thought, max, false, true, true, 0), None); + // With no tools, text is the answer; a reply that only thought isn't. + assert_eq!(cut(&said, max, false, false, false, 0), None); + assert_eq!( + cut(&thought, max, false, false, false, 0), + Some(CutTurn::ThinkingOnly) + ); + assert_eq!(lower_effort(Some("high")), "medium"); + assert_eq!(lower_effort(Some("medium")), "low"); + assert_eq!(lower_effort(Some("low")), "low"); + assert_eq!(lower_effort(Some("max")), "high"); + } + use super::*; #[test] diff --git a/services/worker/src/agent/policy.rs b/services/worker/src/agent/policy.rs index d46f5d258..c5e7e6099 100644 --- a/services/worker/src/agent/policy.rs +++ b/services/worker/src/agent/policy.rs @@ -494,6 +494,7 @@ async fn write_run_stop( &stop.note(), "", ), + &common::handback::HandBack::of(common::handback::HumanOnly::Approval), ), Stop::Paused { .. } => update .update_expression( diff --git a/services/worker/src/passes/incidents/ac_partial_and_red_ci.rs b/services/worker/src/passes/incidents/ac_partial_and_red_ci.rs index b6c6f9c3e..baad2410b 100644 --- a/services/worker/src/passes/incidents/ac_partial_and_red_ci.rs +++ b/services/worker/src/passes/incidents/ac_partial_and_red_ci.rs @@ -267,13 +267,15 @@ fn the_step_after_one_that_changed_nothing_takes_a_different_approach() { plan_coverage::NO_CHANGE_LINE ); assert!(plan_coverage::declined_by_coder(&line, "web/src/hooks/useStickyScroll.ts").is_some()); - // The pipeline passes the stall count and uses the narrowed ask. + // The pipeline passes the supervisor's rung and uses the narrowed ask, + // with the rung's change of approach beside it. let src = include_str!("../mod.rs"); let cf = fn_src(src, "async fn continuation_feedback("); - assert!(cf.contains("stalled: u32")); - assert!(cf.contains("if stalled > 0 {")); + assert!(cf.contains("rung: supervisor::Rung")); + assert!(cf.contains("if rung != supervisor::Rung::Continue {")); assert!(cf.contains("plan_coverage::narrowed_feedback(&cov, &files)")); - assert!(src.contains("stalled_steps,")); + assert!(cf.contains("supervisor::rung_instruction(rung")); + assert!(src.contains("stall_rung,")); } fn red() -> Ci { diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 675853862..9559a7b32 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1193,6 +1193,7 @@ pub(crate) mod steps; pub(crate) mod stop_gate; pub mod stop_judge; pub mod stop_pr; +pub mod supervisor; pub mod support_sync; pub mod syntax_check; pub(crate) mod terraform; @@ -1410,12 +1411,36 @@ pub async fn orchestrate_ticket( &msg, &run_id, &checkpoint, - &["implement_started"], + // Any pass after the work started: a step limit in a + // late pass is the same "needs more turns". + &["implement", "implement_started", "security"], false, "The coder used this step's turns with work left", ) .await .continued(); + // An error after the work started that names nothing only a + // person has gets one fresh step first (`supervisor`): most + // are passing (a GitHub refusal, a check that errored once). + // A step after it that made no progress ships what is done. + let continued = continued + || !guard_ended + && paused.is_none() + && supervisor::human_only_in(&err_msg).is_none() + && e.downcast_ref::().is_none() + && crate::agent::policy::claim_stop(&run_id).is_none() + && steps::load(state, &msg.team_id, &run_id).await.stalled == 0 + && try_auto_continue( + state, + &msg, + &run_id, + &checkpoint, + &["implement", "implement_started", "security"], + false, + "A step after the work stopped on an error; the next one tries again", + ) + .await + .continued(); // A transient model failure (5xx incl. 520-524, 429, 529, no // response) that outlasted the client's own retries is not the // ticket's fault: the run is sent again later (same run_id), by @@ -3471,6 +3496,7 @@ async fn run_passes( &used_mcp_ids, &wait, &judged, + supervisor::HumanOnly::AmbiguousTicket, ) .await; @@ -3620,9 +3646,9 @@ async fn run_passes( } else { None }; - // Steps in a row that changed nothing, after this one started: the - // first such step changes approach (`continuation_feedback`). - let mut stalled_steps = step_state.stalled; + // Steps in a row that changed nothing, after this one started: each + // one climbs the supervisor's ladder (`continuation_feedback`). + let mut stall_rung = supervisor::Rung::Continue; if msg.continuation > 0 && step_state.mark_step != step { let at = resume_gate .map(|g| g.as_str().to_string()) @@ -3645,24 +3671,52 @@ async fn run_passes( steps::stalled_after(step_state.mark.as_deref(), &mark, step_state.stalled) }; steps::save_mark(state, &msg.team_id, run_id, &mark, stalled, step).await; - stalled_steps = stalled; - if steps::stops_for_stall(stalled) + // A security fix never ends by handing its unfinished work to a + // person, and it ships at the stall limit instead of climbing the + // ladder: its bumps are verified batch by batch, so a stalled coder + // step has nothing left a stronger approach would add. What is on + // the branch goes on to its checks and pull request (a draft naming + // the failing check when CI is red), the tasks left deferred with + // their reason. + let ship_now = steps::stops_for_stall(stalled) && common::security_fixes::is_ticket(&msg.ticket_id) - && at.starts_with("implement") - { - // A security fix never ends by handing its unfinished work to a - // person: what is on the branch goes on to its checks and pull - // request (a draft naming the failing check when CI is red), and - // the tasks left are named under Open items. - let task = current_plan_task(&github, msg, &plan_result, &branch_name).await; + && at.starts_with("implement"); + // A step that changed nothing changes approach; it never stops the + // run (`supervisor`): one task, then fresh context and edits in + // place, then a re-split, then the strongest model, then the stuck + // task is deferred with its reason, and finally what is done ships. + if stalled > 0 { + let (rung, settled) = supervise_stall( + state, + run_id, + &github, + msg, + &mut plan_result, + &branch_name, + stalled, + ship_now, + ) + .await; + stall_rung = rung; + if settled { + // A task deferred is a task settled: the next step starts + // from a clean count. + steps::save_mark(state, &msg.team_id, run_id, &mark, 0, step).await; + } + info!( + run_id, + step, + stalled, + rung = rung.as_str(), + "A step changed nothing: the supervisor changes approach" + ); + } + if ship_now { add_progress_note( state, &msg.team_id, run_id, - &format!( - "Two steps made no progress on {}: the run goes on with what the branch holds", - task.as_deref().unwrap_or("the planned tasks") - ), + "Two steps made no progress on the planned tasks: the run goes on with what the branch holds", ) .await; close_memory(state, agent_memory.take()).await; @@ -3679,14 +3733,6 @@ async fn run_passes( ) .await; } - if steps::stops_for_stall(stalled) { - let kept = - keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name).await; - // The stop names the planned task the steps were stuck on. - let task = current_plan_task(&github, msg, &plan_result, &branch_name).await; - close_memory(state, agent_memory.take()).await; - return Err(steps::stall_reason(step, &head, &at, &kept, task.as_deref()).into()); - } info!(run_id, step, stalled, at = %at, "Continuing the run in this step"); } let impl_result = if can_skip_implement { @@ -4926,12 +4972,18 @@ async fn run_passes( msg, &plan_result, &branch_name, - stalled_steps, + stall_rung, ) .await } else { None }; + // The strongest model for a core task that resisted the other rungs. + let effective_complexity = if stall_rung == supervisor::Rung::Escalate { + "complex".to_string() + } else { + effective_complexity.to_string() + }; let pass_start = std::time::Instant::now(); let usage_before = usage.clone(); let mut result = if let Some(run) = dep_run.take() { @@ -5386,6 +5438,7 @@ async fn run_passes( &used_mcp_ids, &wait, &judged, + supervisor::HumanOnly::ProductDecision, ) .await; close_memory(state, agent_memory.take()).await; @@ -6917,7 +6970,12 @@ fn wip_holds_other_work(compare: &serde_json::Value) -> bool { /// The plan's checklist with only the done tasks checked, written where the /// run page and a later attempt read it. -async fn save_checked_tasks(state: &WorkerState, msg: &TicketMessage, run_id: &str, md: &str) { +pub(crate) async fn save_checked_tasks( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + md: &str, +) { let tasks_key = format!( "{}/tasks.md", openspec_prefix( @@ -6941,29 +6999,78 @@ async fn save_checked_tasks(state: &WorkerState, msg: &TicketMessage, run_id: &s } } -/// The planned task the run is on (the first one its branch doesn't do), -/// as `task K of N (`path`: what)`; `None` without a checklist. -async fn current_plan_task( +/// The supervisor's answer to a step that changed nothing, carried out: +/// the rung for the stuck task (core or not, with the run's spend), and for +/// [`supervisor::Rung::Defer`] and [`supervisor::Rung::Ship`] the task (or +/// every task left) deferred on the run's checklist with its reason, so the +/// plan check and the pull request read them as settled. Returns the rung +/// and whether a task was settled. `ship_now` takes the last rung at once. +#[allow(clippy::too_many_arguments)] +async fn supervise_stall( + state: &WorkerState, + run_id: &str, github: &GitHubClient, msg: &TicketMessage, - plan: &plan::PlanResult, + plan: &mut plan::PlanResult, branch: &str, -) -> Option { + stalled: u32, + ship_now: bool, +) -> (supervisor::Rung, bool) { let tasks = plan_coverage::tasks_for(github, &msg.repo_owner, &msg.repo_name, branch, &plan.tasks) .await; - if tasks.is_empty() { - return None; - } - let changes = plan_coverage::plan_changes( + let Some(changes) = plan_coverage::plan_changes( github, &msg.repo_owner, &msg.repo_name, &msg.base_branch, branch, ) - .await?; - plan_coverage::current_task(&changes.coverage(&tasks)) + .await + else { + return (supervisor::next_rung(stalled, true), false); + }; + let cov = changes.coverage(&tasks); + let missing = cov.required_missing(); + let Some(first) = missing.first() else { + return (supervisor::Rung::Continue, false); + }; + let core = supervisor::is_core(&first.path, &first.task, first.optional); + let spent = run_ceiling::load(state, &msg.team_id, run_id) + .await + .map(|t| t.spend_usd) + .unwrap_or(0.0); + let rung = if ship_now { + supervisor::Rung::Ship + } else { + supervisor::rung_for(stalled, core, spent, run_ceiling::MAX_RUN_SPEND_USD) + }; + let defer: Vec<(String, String)> = match rung { + supervisor::Rung::Defer => vec![( + first.path.clone(), + supervisor::defer_reason(stalled, first.task.trim(), core), + )], + supervisor::Rung::Ship => missing + .iter() + .map(|t| { + ( + t.path.clone(), + supervisor::defer_reason( + stalled, + t.task.trim(), + supervisor::is_core(&t.path, &t.task, t.optional), + ), + ) + }) + .collect(), + _ => return (rung, false), + }; + plan.tasks = plan_coverage::with_deferred(&plan.tasks, &defer); + save_checked_tasks(state, msg, run_id, &plan.tasks).await; + for (path, why) in &defer { + add_progress_note(state, &msg.team_id, run_id, &format!("`{path}` {why}")).await; + } + (rung, true) } /// For a continuation: the planned tasks its branch doesn't do yet, as the @@ -6978,7 +7085,7 @@ async fn continuation_feedback( msg: &TicketMessage, plan: &plan::PlanResult, branch: &str, - stalled: u32, + rung: supervisor::Rung, ) -> Option { let tasks = plan_coverage::tasks_for(github, &msg.repo_owner, &msg.repo_name, branch, &plan.tasks) @@ -7010,7 +7117,7 @@ async fn continuation_feedback( if cov.required_missing().is_empty() { return None; } - if stalled > 0 { + if rung != supervisor::Rung::Continue { let files = plan_coverage::changed_files( github, &msg.repo_owner, @@ -7022,9 +7129,17 @@ async fn continuation_feedback( .unwrap_or_default(); info!( run_id, - stalled, "The last step changed nothing: this one takes one task, a different approach" + rung = rung.as_str(), + "The last step changed nothing: this one takes one task, a different approach" ); - return plan_coverage::narrowed_feedback(&cov, &files); + let narrowed = plan_coverage::narrowed_feedback(&cov, &files)?; + let first = cov.required_missing().into_iter().next()?; + let extra = supervisor::rung_instruction(rung, first.task.trim(), &first.path); + return Some(if extra.is_empty() || rung == supervisor::Rung::Narrow { + narrowed + } else { + format!("{narrowed}\n\n{extra}") + }); } Some(plan_coverage::round_feedback(&cov)) } @@ -8199,7 +8314,18 @@ async fn finish_without_code( } else { wait_on_ticket(msg, &questions, &report) }; - mark_run_needs_input(state, msg, run_id, usage, start, mcp_ids, &wait, judged).await; + mark_run_needs_input( + state, + msg, + run_id, + usage, + start, + mcp_ids, + &wait, + judged, + supervisor::HumanOnly::MissingAccess, + ) + .await; } let status = if outside { fix_location::STATUS_OUTSIDE @@ -8661,8 +8787,15 @@ async fn mark_unbuilt_needs_input( start: &std::time::Instant, wait: &WaitingOn, error: &str, - _judged: &stop_judge::Judged, + judged: &stop_judge::Judged, ) { + // A run that built nothing waits only for what only a person has: the + // judge's question or blocker, else the detail the ticket is missing. + let hand_back = supervisor::HandBack::of_judged(judged).unwrap_or_else(|| { + supervisor::HandBack::new(supervisor::HumanOnly::AmbiguousTicket, &wait.line()).unwrap_or( + supervisor::HandBack::of(supervisor::HumanOnly::AmbiguousTicket), + ) + }); let duration = start.elapsed().as_secs(); let delta = usage.unrecorded(); let now = chrono::Utc::now().to_rfc3339(); @@ -8679,7 +8812,7 @@ async fn mark_unbuilt_needs_input( 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) + .needs_input(run_id, wait, &hand_back) .expression_attribute_values(":em", attr_s(error)) .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) @@ -8734,8 +8867,17 @@ async fn mark_run_needs_input( start: &std::time::Instant, mcp_ids: &[String], wait: &WaitingOn, - _judged: &stop_judge::Judged, + judged: &stop_judge::Judged, + asked_for: supervisor::HumanOnly, ) { + // Waiting on a person is only for what only a person has: the judge's + // question or blocker when it names one, else what this stop asks for + // (a question about the ticket, a decision, access, a pull request + // someone else holds). + let hand_back = supervisor::HandBack::of_judged(judged).unwrap_or_else(|| { + supervisor::HandBack::new(asked_for, &wait.line()) + .unwrap_or(supervisor::HandBack::of(asked_for)) + }); let duration = start.elapsed().as_secs(); let delta = usage.unrecorded(); let now = chrono::Utc::now().to_rfc3339(); @@ -8753,7 +8895,7 @@ async fn mark_run_needs_input( status_run_id = :sri, mcp_servers = :mcp", ) .expression_attribute_names("#status", "status") - .needs_input(run_id, wait) + .needs_input(run_id, wait, &hand_back) .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&now)) @@ -8786,45 +8928,48 @@ async fn mark_run_needs_input( } } -/// A run the guard stopped with nothing to open a pull request from: it still -/// waits on a person, with the reason on the run page. +/// A run the guard stopped with nothing to open a pull request from: there +/// is no work to ship and nothing only a person has is missing, so the run +/// ends `failed` with the guard's reason (`common::run_fail`), never as a +/// wait on a person. A blocker on the human-only list waits as one. pub(crate) async fn mark_run_stopped_by_guard( state: &WorkerState, msg: &TicketMessage, run_id: &str, reason: &str, - _judged: &stop_judge::Judged, + judged: &stop_judge::Judged, ) { - if let Err(e) = 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 #s = :s, status_run_id = :sri, waiting_on = :wo, error_message = :em, \ - updated_at = :t, current_pass = :cp", - ) - .condition_expression(common::run_status::not_ended("#s")) - .ended_values() - .expression_attribute_names("#s", "status") - .needs_input( - run_id, - &WaitingOn::fixed( - "Read why CoderHelm stopped this run, then press Retry or close it", - reason, - "", - ), - ) - .expression_attribute_values(":em", attr_s(reason)) - .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) - .expression_attribute_values(":cp", attr_s("done")) - .send() - .await - { - warn!(run_id, error = %e, "Could not hand the stopped run to a person"); + if let Some(hand_back) = supervisor::hand_back_for(judged, reason) { + if let Err(e) = 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 #s = :s, status_run_id = :sri, waiting_on = :wo, error_message = :em, \ + updated_at = :t, current_pass = :cp", + ) + .condition_expression(common::run_status::not_ended("#s")) + .ended_values() + .expression_attribute_names("#s", "status") + .needs_input( + run_id, + &WaitingOn::fixed("Give CoderHelm what it needs, then press Retry", reason, ""), + &hand_back, + ) + .expression_attribute_values(":em", attr_s(reason)) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .expression_attribute_values(":cp", attr_s("done")) + .send() + .await + { + warn!(run_id, error = %e, "Could not record what the stopped run needs"); + } + self::webhooks::emit_run(state, &msg.team_id, run_id, "needs_input").await; + } else { + fail_run(state, msg, run_id, reason, &TokenUsage::default(), 0).await; } - self::webhooks::emit_run(state, &msg.team_id, run_id, "needs_input").await; release_blocked_pr(state, msg).await; } @@ -8874,7 +9019,18 @@ async fn stop_run_repo_not_enabled( message, ) .await; - mark_run_needs_input(state, msg, run_id, usage, start, &[], &wait, &judged).await; + mark_run_needs_input( + state, + msg, + run_id, + usage, + start, + &[], + &wait, + &judged, + supervisor::HumanOnly::MissingAccess, + ) + .await; } /// Append a timestamped progress note to the run record for live activity display. @@ -8987,7 +9143,7 @@ async fn release_blocked_pr(state: &WorkerState, msg: &TicketMessage) { } } -async fn fail_run( +pub(crate) async fn fail_run( state: &WorkerState, msg: &TicketMessage, run_id: &str, @@ -9630,7 +9786,18 @@ async fn stop_for_open_pr( ) .await; let wait = wait_on_ticket(msg, std::slice::from_ref(&question), ¬e); - mark_run_needs_input(state, msg, run_id, usage, start, &[], &wait, &judged).await; + mark_run_needs_input( + state, + msg, + run_id, + usage, + start, + &[], + &wait, + &judged, + supervisor::HumanOnly::HeldByAnother, + ) + .await; true } diff --git a/services/worker/src/passes/own_review.rs b/services/worker/src/passes/own_review.rs index 1e1881dc8..702ff0664 100644 --- a/services/worker/src/passes/own_review.rs +++ b/services/worker/src/passes/own_review.rs @@ -241,10 +241,12 @@ pub fn next( if after.is_empty() { return Next::Ready; } - if rounds >= MAX_FIX_ROUNDS { + let progress = before.is_none_or(|b| after.len() < b) || pushed_files > 0; + // A round that fixed something earns another past the cap, up to twice + // it (`supervisor::may_extend`): the budget follows progress. + if !super::supervisor::may_extend(rounds, MAX_FIX_ROUNDS, progress) { return Next::Stop(cap_reason(after)); } - let progress = before.is_none_or(|b| after.len() < b) || pushed_files > 0; if progress { return Next::Fix { stalled: 0 }; } @@ -271,10 +273,10 @@ pub fn stop_reason(items: &[String]) -> String { pub fn cap_reason(items: &[String]) -> String { let list: Vec = items.iter().map(|i| format!("- [ ] {i}")).collect(); format!( - "Handed to a person: CoderHelm took {MAX_FIX_ROUNDS} fix rounds on its own review's \ - findings and these are still open:\n{}\nThe pull request stays a draft with them listed \ - under \"Open review findings\". Fix them, or say on the pull request why one doesn't \ - apply, then mark it ready.", + "CoderHelm took its fix rounds on its own review's findings (up to {} while they made \ + progress) and these are still open, deferred and listed under \"Open review findings\" \ + on the pull request:\n{}", + MAX_FIX_ROUNDS * 2, list.join("\n") ) } @@ -428,16 +430,24 @@ mod tests { } #[test] - fn two_fix_rounds_at_most_then_a_person() { + fn rounds_go_on_past_the_cap_while_they_fix_things_then_defer_the_rest() { let open = vec!["a (`x.rs:1`)".to_string(), "b (`y.rs:2`)".to_string()]; - // Progress every round still stops at the cap: one fewer open each - // time, or a round that pushed changes. assert_eq!(next(Some(3), &open, 2, 0, 1), Next::Fix { stalled: 0 }); - match next(Some(3), &open, 2, 0, MAX_FIX_ROUNDS) { + // At the cap, a round that fixed something earns another + // (`supervisor::may_extend`), up to twice the cap. + assert_eq!( + next(Some(3), &open, 2, 0, MAX_FIX_ROUNDS), + Next::Fix { stalled: 0 } + ); + assert!(matches!( + next(Some(2), &open, 0, 0, MAX_FIX_ROUNDS), + Next::Stop(_) + )); + match next(Some(3), &open, 2, 0, MAX_FIX_ROUNDS * 2) { Next::Stop(why) => { - assert!(why.contains("2 fix rounds")); assert!(why.contains("- [ ] a (`x.rs:1`)\n- [ ] b (`y.rs:2`)")); - assert!(why.contains("stays a draft")); + assert!(why.contains("deferred")); + assert!(!why.contains("Handed to a person")); } other => panic!("{other:?}"), } diff --git a/services/worker/src/passes/plan_coverage.rs b/services/worker/src/passes/plan_coverage.rs index 3d9820343..c70fb9040 100644 --- a/services/worker/src/passes/plan_coverage.rs +++ b/services/worker/src/passes/plan_coverage.rs @@ -69,6 +69,8 @@ const OPTIONAL_MARKS: &[&str] = &[ "verify only", "read only", "read-only", + // A task the supervisor deferred with its reason (`with_deferred`). + "(deferred:", ]; /// What the coder says when it judged a planned file needs no change. @@ -511,19 +513,6 @@ pub fn narrowed_feedback(cov: &Coverage, diff_files: &[String]) -> Option Option { - let first = cov.required_missing().into_iter().next()?; - Some(format!( - "task {} of {} (`{}`: {})", - cov.done.len() + 1, - cov.total(), - first.path, - common::truncate_str(first.task.trim(), 160) - )) -} - /// Marks the tasks whose file the coder said needs no change (in `notes`) /// and the branch doesn't change: optional from now on, with the coder's /// line. Returns the paths it settled. @@ -574,6 +563,29 @@ pub fn with_declined(tasks_md: &str, tasks: &[PlanTask]) -> String { .join("\n") } +/// The plan's checklist with each deferred task's line carrying its reason +/// (`(deferred: ...)`), so every later check reads it as settled and the +/// pull request lists it with why. `defer` holds (path, reason) pairs; the +/// reason starts with `deferred:`. +pub fn with_deferred(tasks_md: &str, defer: &[(String, String)]) -> String { + tasks_md + .lines() + .map(|line| { + let Some(task) = plan_tasks(line).into_iter().next() else { + return line.to_string(); + }; + match defer.iter().find(|(p, _)| *p == task.path) { + Some((_, why)) if !task.optional => { + let why = why.trim().trim_start_matches("deferred:").trim(); + format!("{line} (deferred: {})", common::truncate_str(why, 300)) + } + _ => line.to_string(), + } + }) + .collect::>() + .join("\n") +} + /// The run's status when it stops with planned work not done: plain, and /// naming the tasks (the run record keeps up to 500 characters; the full /// list is in [`progress_note`]). @@ -1200,4 +1212,25 @@ mod tests { .starts_with("Not done by this run: 1. Replace the hero on production")); assert!(f[0].detail.contains("no production CMS write connection")); } + + #[test] + fn a_deferred_task_is_settled_and_listed_with_why() { + let md = "- [ ] `src/a.rs`: fix the parser\n- [ ] `README.md`: note the new flag"; + let out = with_deferred( + md, + &[( + "README.md".to_string(), + "deferred: this non-core task resisted 3 different approaches".to_string(), + )], + ); + let tasks = plan_tasks(&out); + assert!(!tasks[0].optional); + assert!(tasks[1].optional, "{out}"); + assert!(tasks[1].task.contains("resisted 3 different approaches")); + // Deferring twice doesn't stack the reason. + assert_eq!( + with_deferred(&out, &[("README.md".into(), "deferred: again".into())]), + out + ); + } } diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index 54534d845..f3c411253 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -1670,6 +1670,26 @@ async fn record_hold(state: &WorkerState, team_id: &str, run_id: &str, hold: Dra } } +/// Why a finished run's held draft may wait on a person: a person put it +/// back to draft, or a reason on the human-only list. `None` for every +/// other hold (red checks, open findings, planned work): those are +/// CoderHelm's, the hold stays recorded and named on the pull request, and +/// the run's status isn't turned into a wait. +fn draft_hand_back( + hold: &DraftHold, + judged: &super::stop_judge::Judged, +) -> Option { + use super::supervisor::{HandBack, HumanOnly}; + let summary = hold.summary(); + if summary.contains("put it back to draft") { + return Some( + HandBack::new(HumanOnly::PersonAction, &summary) + .unwrap_or(HandBack::of(HumanOnly::PersonAction)), + ); + } + super::supervisor::hand_back_for(judged, &summary) +} + /// Sets a finished run to `needs_input` on its draft hold, naming what to /// do. `false` when the run's status isn't one this changes. async fn wait_on_person( @@ -1678,8 +1698,11 @@ async fn wait_on_person( run_id: &str, hold: &DraftHold, was: &str, - _judged: &super::stop_judge::Judged, + judged: &super::stop_judge::Judged, ) -> bool { + let Some(hand_back) = draft_hand_back(hold, judged) else { + return false; + }; let now = chrono::Utc::now().to_rfc3339(); // `:held` is a condition value, never a status written here: the write // goes through `NeedsInput::needs_input`. @@ -1698,7 +1721,7 @@ async fn wait_on_person( "#s IN (:done, :old_done) OR (#s = :held AND attribute_exists(draft_hold))", ) .expression_attribute_names("#s", "status") - .needs_input(run_id, &hold.waiting_on()) + .needs_input(run_id, &hold.waiting_on(), &hand_back) .expression_attribute_values(":h", hold.to_attr()) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":done", attr_s(common::run_status::COMPLETED)) diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index e7b3c7157..358b33675 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -5513,6 +5513,33 @@ async fn hand_off_red_ci( tried: &[String], needed: &str, ) -> Result<(), Box> { + // The supervisor's last rungs before a run with red checks ends: take + // out what broke them (back to the last green head of this pull + // request, else the last planned task), defer it with why, and let CI + // decide again. Only when nothing can come out does the run end, failed + // with exactly what fails (`wait_on_person`), never as a wait. + if let Some(note) = revert_to_green(state, msg, ticket_msg, github, pr, excerpt).await { + mark_events_processed(state, &msg.run_id, events).await; + super::add_progress_note(state, &msg.team_id, &msg.run_id, ¬e).await; + if set_run_awaiting_ci( + state, + ticket_msg, + &msg.run_id, + pr.url, + pr.number, + pr.branch, + usage, + duration, + ) + .await? + { + info!( + run_id = msg.run_id, + "Reverted what broke the checks; waiting for CI on the result" + ); + } + return Ok(()); + } super::record_ci_outcome( state, &msg.team_id, @@ -5555,6 +5582,223 @@ async fn hand_off_red_ci( .await } +/// What a revert writes (each path with its content, or `None` to remove +/// it), the tasks it defers with why, and the note to record. +type Reverted = (Vec<(String, Option)>, Vec<(String, String)>, String); + +/// Takes out what broke the checks, per [`super::supervisor::revert_for`]: +/// one commit that puts every file changed since the last green head back +/// as it was there, or the last planned task's file back as the base branch +/// has it. The reverted work is deferred on the checklist and named on the +/// pull request. Returns the note to record, or `None` when nothing can +/// come out (no green head, one task or none, or the reverts are spent). +async fn revert_to_green( + state: &WorkerState, + msg: &ResumeMessage, + ticket_msg: &TicketMessage, + github: &GitHubClient, + pr: &PrRef<'_>, + excerpt: &str, +) -> Option { + use super::supervisor::{self as sup, Revert}; + use crate::clients::github::FileOp; + let reverts = run_number(state, &msg.team_id, &msg.run_id, "sup_reverts").await; + // Earlier heads of the pull request, newest first, and whether their + // checks passed (at most ten are read). + let commits = github + .list_pr_commits(pr.owner, pr.repo, pr.number) + .await + .unwrap_or_default(); + let shas: Vec = commits + .iter() + .filter_map(|c| c["sha"].as_str().map(str::to_string)) + .collect(); + let mut heads = Vec::new(); + for sha in shas.iter().rev().skip(1).take(10) { + let green = match github.list_ci_for_ref(pr.owner, pr.repo, sha).await { + Ok(c) => matches!(ci_verdict_from_checks(&c), CiVerdict::Green), + Err(_) => false, + }; + heads.push((sha.clone(), green)); + if green { + break; + } + } + // The planned tasks done, in plan order. + let mut done: Vec<(String, String)> = Vec::new(); + let plan = super::run_plan_files(state, ticket_msg).await; + if let Some(p) = &plan { + let tasks = + super::plan_coverage::tasks_for(github, pr.owner, pr.repo, pr.branch, &p.tasks).await; + if let Some(c) = super::plan_coverage::plan_changes( + github, + pr.owner, + pr.repo, + &ticket_msg.base_branch, + pr.branch, + ) + .await + { + done = c + .coverage(&tasks) + .done + .into_iter() + .filter(|t| !t.generated) + .map(|t| (t.path, t.task)) + .collect(); + } + } + let what = if excerpt.trim().is_empty() { + "the failing checks".to_string() + } else { + format!( + "the failing checks ({})", + common::truncate_str(excerpt.trim(), 200) + ) + }; + let (files, deferred, note): Reverted = match sup::revert_for(&heads, &done, reverts) { + Revert::Nothing => return None, + Revert::ToHead(sha) => { + let changed = github + .compare_changed_files(pr.owner, pr.repo, &sha, pr.branch) + .await + .ok()?; + let mut files = Vec::new(); + for path in &changed { + let was = github + .read_file_if_exists(pr.owner, pr.repo, path, &sha) + .await + .ok()?; + files.push((path.clone(), was)); + } + let deferred: Vec<(String, String)> = done + .iter() + .filter(|(p, _)| changed.contains(p)) + .map(|(p, _)| { + ( + p.clone(), + format!( + "deferred: its change broke {what}; reverted to the last green head" + ), + ) + }) + .collect(); + let short: String = sha.chars().take(7).collect(); + ( + files, + deferred, + format!( + "CI stayed red after the fix attempts: reverted {} file(s) to {short}, the \ + last head of this pull request whose checks passed, and deferred what \ + came after it. CI decides again.", + changed.len() + ), + ) + } + Revert::Task { path, task } => { + let was = github + .read_file_if_exists(pr.owner, pr.repo, &path, &ticket_msg.base_branch) + .await + .ok()?; + let deferred = vec![( + path.clone(), + format!( + "deferred: its change broke {what} and the fixes didn't repair it; reverted" + ), + )]; + ( + vec![(path.clone(), was)], + deferred, + format!( + "CI stayed red after the fix attempts: took out the last planned task \ + (`{path}`: {}) and deferred it. CI decides again.", + common::truncate_str(&task, 160) + ), + ) + } + }; + if files.is_empty() { + return None; + } + let ops: Vec = files + .into_iter() + .map(|(path, was)| match was { + Some(content) => FileOp::Write { path, content }, + None => FileOp::Delete { path }, + }) + .collect(); + if let Err(e) = github + .batch_write( + pr.owner, + pr.repo, + pr.branch, + "Revert the change that broke CI; it is deferred on the pull request", + &ops, + ) + .await + { + warn!(run_id = msg.run_id, error = %e, "Could not revert what broke the checks"); + return None; + } + add_run_number(state, &msg.team_id, &msg.run_id, "sup_reverts").await; + if let Some(mut p) = plan { + if !deferred.is_empty() { + p.tasks = super::plan_coverage::with_deferred(&p.tasks, &deferred); + super::save_checked_tasks(state, ticket_msg, &msg.run_id, &p.tasks).await; + } + } + if let Ok(p) = github.get_pull_request(pr.owner, pr.repo, pr.number).await { + let body = p["body"].as_str().unwrap_or(""); + let line = format!("- {note}"); + let now = if body.contains("## Deferred") { + format!("{}\n{line}", body.trim_end()) + } else { + format!("{}\n\n## Deferred\n{line}", body.trim_end()) + }; + let _ = github + .update_pr_body(pr.owner, pr.repo, pr.number, &now) + .await; + } + Some(note) +} + +/// A number kept on the run record (0 when absent). +async fn run_number(state: &WorkerState, team_id: &str, run_id: &str, field: &str) -> u32 { + state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("#f") + .expression_attribute_names("#f", field) + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| { + i.get(field) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + }) + .unwrap_or(0) +} + +/// Adds one to a number kept on the run record. +async fn add_run_number(state: &WorkerState, team_id: &str, run_id: &str, field: &str) { + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("ADD #f :one") + .expression_attribute_names("#f", field) + .expression_attribute_values(":one", attr_n(1)) + .send() + .await; +} + /// The run stops with its work on its pull request and something open on /// it: it waits on a person (`needs_input`), named as the pull request's /// review with `reason` as what is open (never a wait for nothing). @@ -5603,6 +5847,53 @@ async fn wait_on_person( duration: u64, judged: &super::stop_judge::Judged, ) -> Result<(), Box> { + // The supervisor's rule: only a need on the human-only list waits on a + // person. Everything else the run finishes: its pull request carries + // what is left, deferred and named, and the run is completed; or, when + // its own checks are still red after every fix and revert + // (`hand_off_red_ci`), it failed with exactly what fails. + let red = red_ci_blocks_completion(state, &msg.team_id, run_id).await; + let ending = super::supervisor::end(&super::supervisor::EndFacts { + blocker: super::supervisor::hand_back_for(judged, reason), + ci_failing: red.iter().cloned().collect(), + has_work: pr_number > 0, + ladder_spent: true, + ..Default::default() + }); + let super::supervisor::Ending::HandBack(hand_back) = ending else { + if let Some(red) = red { + let why = format!( + "{}; {red}. Every fix and revert CoderHelm tried is on pull request #{pr_number}.", + reason.trim().trim_end_matches('.') + ); + warn!(run_id, reason = %why, "CI stays red after the supervisor's ladder: the run failed"); + super::fail_run(state, msg, run_id, &why, usage, duration).await; + return Ok(()); + } + super::add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "Finished with what is left deferred and listed on pull request #{pr_number}: {}", + common::truncate_str(reason, 400) + ), + ) + .await; + return end_run( + state, + msg, + run_id, + common::run_status::COMPLETED, + None, + (pr_url, pr_number, branch), + usage, + duration, + None, + None, + ) + .await; + }; let detail = match (judged.hold_words(), judged.assumption()) { (Some(h), _) => format!("{reason}\nBlocked on: {h}"), (None, Some(a)) => format!("{reason}\nAssumed: {a}"), @@ -5619,6 +5910,7 @@ async fn wait_on_person( usage, duration, Some(judged), + Some(&hand_back), ) .await } @@ -5626,7 +5918,7 @@ async fn wait_on_person( /// The outcome rule over the run's CI record: `Some(why)` when its last CI /// result on the pull request is a failure that is this change's (not one the /// base branch has too, not an unrelated test fixed elsewhere). -async fn red_ci_blocks_completion( +pub(crate) async fn red_ci_blocks_completion( state: &WorkerState, team_id: &str, run_id: &str, @@ -5711,6 +6003,7 @@ async fn complete_run_with_status( usage, duration, None, + None, ) .await } @@ -5726,15 +6019,22 @@ async fn end_run( usage: &TokenUsage, duration: u64, judged: Option<&super::stop_judge::Judged>, + hand_back: Option<&super::supervisor::HandBack>, ) -> Result<(), Box> { let now = chrono::Utc::now().to_rfc3339(); let delta = usage.unrecorded(); - // 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, "")) - }); + // Waiting on a person is always for something named, only after the + // stop judge decided it, and only for a reason on the human-only list. + let wait = (status == common::run_status::NEEDS_INPUT && judged.is_some()) + .then_some(hand_back) + .flatten() + .map(|hb| { + ( + hb, + wait.cloned() + .unwrap_or_else(|| super::stop_pr::review_wait(pr_number, pr_url, "")), + ) + }); let set_status = if wait.is_some() { "#s = :s, status_run_id = :sri, waiting_on = :wo" } else { @@ -5756,7 +6056,7 @@ async fn end_run( .expression_attribute_names("#s", "status") .expression_attribute_names("#err", "error"); let update = match &wait { - Some(w) => update.needs_input(run_id, w), + Some((hb, w)) => update.needs_input(run_id, w, hb), None => update .expression_attribute_values(":s", attr_s(status)) .expression_attribute_values(":sri", attr_s(&format!("{status}#{run_id}"))), diff --git a/services/worker/src/passes/run_ceiling.rs b/services/worker/src/passes/run_ceiling.rs index 878072156..1c631ad4a 100644 --- a/services/worker/src/passes/run_ceiling.rs +++ b/services/worker/src/passes/run_ceiling.rs @@ -204,7 +204,7 @@ impl EntryGate for DynamoGate<'_> { } } -async fn load(state: &WorkerState, team_id: &str, run_id: &str) -> Option { +pub(crate) async fn load(state: &WorkerState, team_id: &str, run_id: &str) -> Option { match state .dynamo .get_item() diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index 7e20b08d6..df23c2193 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -794,6 +794,14 @@ async fn wait_on_open_pr( reason: &str, judged: &super::stop_judge::Judged, ) { + // The supervisor's rule: only a need on the human-only list waits on a + // person. A guard stop on a run that has its pull request otherwise + // finishes it: completed with the reason on the run page (the pull + // request lists what is open), or failed when its checks are red. + let Some(hand_back) = super::supervisor::hand_back_for(judged, reason) else { + finish_open_pr(state, team_id, run_id, reason).await; + return; + }; let reason = match (judged.hold_words(), judged.assumption()) { (Some(h), _) => format!("{reason} Blocked on: {h}"), (None, Some(a)) => format!("{reason} Assumed: {a}"), @@ -817,7 +825,7 @@ async fn wait_on_open_pr( .condition_expression(run_status::not_ended("#s")) .ended_values() .expression_attribute_names("#s", "status") - .needs_input(run_id, &wait) + .needs_input(run_id, &wait, &hand_back) .expression_attribute_values(":em", attr_s(reason)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("done")) @@ -831,6 +839,73 @@ async fn wait_on_open_pr( } } +/// A guard stop on a run with its pull request and nothing a person must +/// supply: `failed` with the reason when the run's checks are red by its +/// record (`common::run_fail`), else `completed` with the reason noted. +async fn finish_open_pr(state: &WorkerState, team_id: &str, run_id: &str, reason: &str) { + if let Some(red) = super::resume::red_ci_blocks_completion(state, team_id, run_id).await { + let why = format!("{}; {red}", reason.trim().trim_end_matches('.')); + let failure = common::run_fail::RunFailure { + reason: &why, + pass: None, + only_from: None, + extra: Vec::new(), + add: Vec::new(), + }; + match common::run_fail::fail_run( + &state.dynamo, + &state.config.runs_table_name, + team_id, + run_id, + &failure, + ) + .await + { + Ok(true) => super::webhooks::emit_run(state, team_id, run_id, "failed").await, + Ok(false) => {} + Err(e) => warn!(run_id, error = %e, "Run guard: could not end the run"), + } + return; + } + add_progress_note( + state, + team_id, + run_id, + &format!("Finished on its pull request; left open there: {reason}"), + ) + .await; + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression( + "SET #s = :s, status_run_id = :sri, deferred_reason = :dr, updated_at = :t, \ + current_pass = :cp", + ) + .condition_expression(run_status::not_ended("#s")) + .ended_values() + .expression_attribute_names("#s", "status") + .expression_attribute_values(":s", attr_s(run_status::COMPLETED)) + .expression_attribute_values( + ":sri", + attr_s(&format!("{}#{run_id}", run_status::COMPLETED)), + ) + .expression_attribute_values(":dr", attr_s(common::truncate_str(reason, 500))) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .expression_attribute_values(":cp", attr_s("done")) + .send() + .await; + match res { + Ok(_) => { + super::webhooks::emit_run(state, team_id, run_id, run_status::COMPLETED).await; + super::ready::after_completion(state, team_id, run_id).await; + } + Err(e) => warn!(run_id, error = %e, "Run guard: could not finish the run"), + } +} + /// The run's pull request (number, address), from its record. async fn run_pr(state: &WorkerState, team_id: &str, run_id: &str) -> (u64, String) { let item = state diff --git a/services/worker/src/passes/steps.rs b/services/worker/src/passes/steps.rs index c678d6850..f02b55b84 100644 --- a/services/worker/src/passes/steps.rs +++ b/services/worker/src/passes/steps.rs @@ -106,6 +106,7 @@ pub fn stops_for_stall(stalled: u32) -> bool { /// Why a stalled run stops, in a sentence, naming the planned task it was /// on when it knows (`task 8 of 8 (`path`: what)`). +#[cfg(test)] pub fn stall_reason(step: u32, head: &str, at: &str, kept: &str, task: Option<&str>) -> String { let short: String = head.chars().take(7).collect(); let on = match task { @@ -121,6 +122,7 @@ pub fn stall_reason(step: u32, head: &str, at: &str, kept: &str, task: Option<&s ) } +#[cfg(test)] fn where_label(at: &str) -> &str { match at { "verify" => "the test and security audit after the implement work", diff --git a/services/worker/src/passes/stop_pr.rs b/services/worker/src/passes/stop_pr.rs index 7289cda20..23c3a3ae0 100644 --- a/services/worker/src/passes/stop_pr.rs +++ b/services/worker/src/passes/stop_pr.rs @@ -267,6 +267,26 @@ pub async fn open_with( stop, super::outcome::Stop::NoProgress { .. } | super::outcome::Stop::OutOfTime(_) ); + // Only a need on the human-only list waits on a person + // (`supervisor::hand_back_for`). Anything else ships: the work on the + // branch goes on to CI and the ready decision like any finished run, + // with what is left deferred on the checklist and named on the pull + // request. + let ending = super::supervisor::end(&super::supervisor::EndFacts { + blocker: super::supervisor::hand_back_for(judged, reason), + has_work: true, + ladder_spent: true, + ..Default::default() + }); + let hand_back = match ending { + super::supervisor::Ending::HandBack(h) => Some(h), + _ => { + return ship( + state, msg, run_id, &github, branch, reason, &work, &open_text, &stop, &progress, + ) + .await + } + }; let unfinished = if mid_work { not_finished( &stop, @@ -365,7 +385,7 @@ pub async fn open_with( .ended_values() .expression_attribute_names("#s", "status") .expression_attribute_values(":cp", super::attr_s("done")) - .needs_input(run_id, &wait) + .needs_input(run_id, &wait, hand_back.as_ref().expect("checked above")) .expression_attribute_values(":pu", super::attr_s(&url)) .expression_attribute_values(":pn", super::attr_n(number)) .expression_attribute_values(":b", super::attr_s(branch)) @@ -393,6 +413,194 @@ pub async fn open_with( Ok(url) } +/// The "Deferred" section of a run that shipped with tasks left: what +/// the run did, what it deferred and why. It doesn't hold the pull request +/// as a draft; CI and the ready decision do that, as for every run. +pub fn deferred_section(stop: &super::outcome::Stop, progress: &Progress) -> String { + let total = progress.done.len() + progress.remaining.len(); + let mut lines = vec![format!( + "CoderHelm shipped the work that is done. What it couldn't land is deferred, with why: \ + {}.", + stop.words() + )]; + if total > 0 { + lines.push(format!("- **Done ({} of {total})**", progress.done.len())); + for (i, r) in progress.remaining.iter().take(15).enumerate() { + lines.push(format!( + "- Deferred, task {} of {total}: {}", + progress.done.len() + i + 1, + common::truncate_str(r, 300) + )); + } + } + format!("## Deferred\n{}", lines.join("\n")) +} + +/// A run stopped after its work for a reason that isn't on the human-only +/// list: the tasks left are deferred on the run's checklist, the pull +/// request opens (or is updated) with a "Deferred" section, and the run +/// goes on to CI like any finished run (`awaiting_ci`), so its CI fix loop +/// and ready decision take it from there. Never `needs_input`. +#[allow(clippy::too_many_arguments)] +async fn ship( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + github: &GitHubClient, + branch: &str, + reason: &str, + work: &[String], + open_text: &str, + stop: &super::outcome::Stop, + progress: &Progress, +) -> Result { + if let Some(mut plan) = super::run_plan_files(state, msg).await { + let defer: Vec<(String, String)> = progress + .remaining + .iter() + .filter_map(|r| { + let path = r.split('`').nth(1)?.to_string(); + Some((path, format!("deferred: {}", stop.words()))) + }) + .collect(); + if !defer.is_empty() { + plan.tasks = super::plan_coverage::with_deferred(&plan.tasks, &defer); + super::save_checked_tasks(state, msg, run_id, &plan.tasks).await; + } + } + let deferred = if progress.remaining.is_empty() { + format!("## Deferred\n{}.", stop.words()) + } else { + deferred_section(stop, progress) + }; + let existing = github + .find_open_pr_for_branch(&msg.repo_owner, &msg.repo_name, branch) + .await?; + let (number, url) = match existing { + Some(p) => { + let number = p["number"].as_u64().unwrap_or(0); + let body = p["body"].as_str().unwrap_or(""); + let now = if body.contains("## Deferred") { + body.to_string() + } else { + format!("{}\n\n{deferred}", body.trim_end()) + }; + if let Err(e) = github + .update_pr_body(&msg.repo_owner, &msg.repo_name, number, &now) + .await + { + tracing::warn!(run_id, error = %e, "Could not list what is deferred on the open pull request"); + } + (number, p["html_url"].as_str().unwrap_or("").to_string()) + } + None => { + let conventions = + super::load_git_conventions(state, &msg.team_id, &msg.ticket_id).await; + let title = super::pr::pr_title(&conventions, &super::ticket_tokens(msg), msg); + let body = shipped_body( + &super::outcome::ticket_line_for(msg), + work, + open_text, + &deferred, + ); + let p = github + .create_pull_request( + &msg.repo_owner, + &msg.repo_name, + common::truncate_str(&title, 72), + &body, + branch, + &msg.base_branch, + true, + ) + .await?; + ( + p["number"].as_u64().unwrap_or(0), + p["html_url"].as_str().unwrap_or("").to_string(), + ) + } + }; + let usage = crate::models::TokenUsage::default(); + super::save_checkpoint(state, &msg.team_id, run_id, "pr", branch, 0, &usage).await; + let now = chrono::Utc::now().to_rfc3339(); + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", super::attr_s(&msg.team_id)) + .key("run_id", super::attr_s(run_id)) + .update_expression( + "SET #s = :s, status_run_id = :sri, pr_url = :pu, pr_number = :pn, branch = :b, \ + updated_at = :t, current_pass = :cp, deferred_reason = :dr REMOVE error_message", + ) + .condition_expression(common::run_status::not_ended("#s")) + .ended_values() + .expression_attribute_names("#s", "status") + .expression_attribute_values(":s", super::attr_s(common::run_status::AWAITING_CI)) + .expression_attribute_values( + ":sri", + super::attr_s(&format!("{}#{run_id}", common::run_status::AWAITING_CI)), + ) + .expression_attribute_values(":pu", super::attr_s(&url)) + .expression_attribute_values(":pn", super::attr_n(number)) + .expression_attribute_values(":b", super::attr_s(branch)) + .expression_attribute_values(":t", super::attr_s(&now)) + .expression_attribute_values(":cp", super::attr_s("awaiting_ci")) + .expression_attribute_values(":dr", super::attr_s(common::truncate_str(reason, 500))) + .send() + .await; + if let Err(e) = res { + if !format!("{e:?}").contains("ConditionalCheckFailed") { + return Err(e.into()); + } + } + super::add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "Shipped what is done on pull request #{number}; deferred: {}. CI and the ready \ + decision take it from here.", + common::truncate_str(&stop.words(), 300) + ), + ) + .await; + super::run_guard::progress( + state, + &msg.team_id, + run_id, + super::run_guard::Progress::PrOpen, + ) + .await; + Ok(url) +} + +/// The body of a pull request a run shipped with work deferred: the ticket +/// line, Summary, Changes, Verification, what the checks left open, and the +/// "Deferred" section. +pub fn shipped_body(ticket: &str, files: &[String], open: &str, deferred: &str) -> String { + let shown: Vec = files.iter().take(20).map(|f| format!("- `{f}`")).collect(); + let more = files.len().saturating_sub(shown.len()); + let open = if open.trim().is_empty() { + String::new() + } else { + format!("\n\n{}", open.trim()) + }; + format!( + "{ticket}\n\n## Summary\n\nCoderHelm did the work below on this branch and shipped it; \ + what it deferred is listed at the end, with why.\n\n## Changes\n\n{}{}\n\n\ + ## Verification\n\nThe repository's CI runs on this pull request; CoderHelm fixes what \ + fails before it is marked ready.{open}\n\n{}", + shown.join("\n"), + if more > 0 { + format!("\n- and {more} more") + } else { + String::new() + }, + deferred.trim() + ) +} + /// What a stopped run with a pull request waits for: its review, with the /// reason as what is open on it. pub fn review_wait(number: u64, url: &str, reason: &str) -> WaitingOn { @@ -503,4 +711,31 @@ mod tests { assert_eq!(again.matches("## Not finished").count(), 1); assert!(again.contains("## Summary\nx")); } + + /// The stalled Jira run, shipped: seven of eight tasks done, the eighth + /// deferred with why. The body keeps the body rules and never holds the + /// pull request as unfinished work for a person. + #[test] + fn a_run_stopped_mid_work_ships_with_the_rest_deferred() { + let stop = super::super::outcome::Stop::from_recorded( + "Stopped: steps 2 and 3 made no progress. The branch stayed at a8c8814 and the run \ + was stuck at the implement work (planned tasks) while working on task 8 of 8 \ + (`web/hooks/useScroll.ts`: adapt the offset).", + ); + let progress = Progress { + done: (1..=7) + .map(|i| format!("`web/f{i}.tsx`: task {i}")) + .collect(), + remaining: vec!["`web/hooks/useScroll.ts`: adapt the offset".into()], + }; + let d = deferred_section(&stop, &progress); + let b = shipped_body("Source ticket: WEB-12", &["web/f1.tsx".into()], "", &d); + assert!( + super::super::outcome::body_problems(&b, "WEB-12").is_empty(), + "{b}" + ); + assert!(!super::super::proof::holds_unfinished(&b)); + assert!(b.contains("Deferred, task 8 of 8: `web/hooks/useScroll.ts`")); + assert!(!b.contains("What you can do")); + } } diff --git a/services/worker/src/passes/supervisor.rs b/services/worker/src/passes/supervisor.rs new file mode 100644 index 000000000..df8883879 --- /dev/null +++ b/services/worker/src/passes/supervisor.rs @@ -0,0 +1,862 @@ +//! One rule for how every run ends: it finishes, or it hands back only for +//! something on the human-only list. +//! +//! Runs too often ended by handing unfinished work to a person: two steps +//! that changed nothing stopped a ticket run with a held draft, a CI fix +//! that met the same failure twice set the run to `needs_input`, a review +//! fix loop at its round cap asked a person to finish, a check after the +//! work that errored became "a person should look". Each loop (the implement +//! steps, the CI fix, CoderHelm's own review, the planned-work rounds, the +//! progress guard, the ready decision) had its own stall rule ending in a +//! hand-back, and every earlier fix changed one loop's rule; the next loop, +//! or a new run type, kept its own and the class came back. +//! +//! Now the class is closed where every ending passes, and in the type that +//! writes the status: +//! +//! - **A hand-back needs a reason on the list.** `needs_input` is written +//! only by `run_wait::NeedsInput::needs_input`, which takes a +//! [`HandBack`]; a `HandBack` exists only for a [`HumanOnly`] reason (a +//! credential, missing access, a product decision, an ambiguous ticket, +//! someone else holding the work, the usage limit, an approval, a +//! person's own action). A stall, a red check, a budget or an error has +//! none, so it can't end a run as a wait. [`hand_back_for`] is the one +//! reading of a stop: the stop judge's question or blocker when it names +//! something on the list, else the stop's own words. +//! - **Every ending that used to hand back now finishes**: +//! - a stop after the work ships what is done (`stop_pr::ship`): the +//! tasks left are deferred with why, the pull request opens with a +//! "Deferred" section, and the run goes on to CI and the ready decision +//! like any finished run; +//! - red checks the fix attempts couldn't repair are taken out +//! (`resume::revert_to_green`, [`revert_for`]): back to the last green +//! head of the pull request, else the last planned task, deferred; CI +//! decides again. Only when nothing can come out does the run end, as +//! `failed` with exactly what fails, never as a wait; +//! - the own-review and guard stops finish on the pull request, with what +//! is open listed there (`resume::wait_on_person`, +//! `run_guard::finish_open_pr`); +//! - a held draft on a finished run stays recorded and named on the pull +//! request without turning the run into a wait (`ready::draft_hand_back`). +//! - **A stall changes approach** ([`next_rung`]): one task only, then a +//! fresh context with edits in place instead of whole-file writes, then +//! the task re-split, then the strongest model for a core task, then the +//! stuck task deferred with its reason, and finally what is done ships. A +//! non-core task (a readme line, a changelog) is deferred after three. +//! - **Budget follows progress** ([`may_extend`]): a loop at its round cap +//! that is still fixing things gets more rounds, up to twice the cap; a +//! run near its spend ceiling ships what is done ([`near_spend_cap`]). +//! +//! The tests at the bottom replay every historical stuck run's shape +//! ([`replay`], `supervisor_replays.rs`) and read the worker's sources so a +//! new ending can't go around these rules. + +// ── The human-only list ───────────────────────────────────────────────────── + +pub use common::handback::{human_only_in, HandBack, HumanOnly, HUMAN_ONLY}; + +/// The hand-back a stop may make, if any: the stop judge's question or a +/// hold on something only a person has, else the stop's own words naming +/// one. `None` for everything CoderHelm finishes itself. +pub fn hand_back_for(judged: &super::stop_judge::Judged, reason: &str) -> Option { + HandBack::of_judged(judged) + .or_else(|| human_only_in(reason).and_then(|h| HandBack::new(h, reason))) +} + +// ── The ladder ────────────────────────────────────────────────────────────── + +/// What the next attempt does differently. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Rung { + /// The same work continues: the last attempt made progress. + Continue, + /// One task only, the first one left. + Narrow, + /// A fresh context (the plan, the diff, the one task) and edits in place + /// instead of whole-file writes. + SwitchTools, + /// The task split into two or three smaller pieces, the first one now. + Resplit, + /// The strongest model, fresh context (core tasks). + Escalate, + /// The stuck task is deferred with its reason; the rest goes on. + Defer, + /// What is done ships; anything left is deferred and explained. + Ship, +} + +impl Rung { + pub fn as_str(self) -> &'static str { + match self { + Rung::Continue => "continue", + Rung::Narrow => "narrow", + Rung::SwitchTools => "switch_tools", + Rung::Resplit => "resplit", + Rung::Escalate => "escalate", + Rung::Defer => "defer", + Rung::Ship => "ship", + } + } +} + +/// Whether a planned task is core to the ticket. Documentation, changelog +/// and readme edits, and tasks the plan marks optional, are not: when they +/// stall they are deferred first. +pub fn is_core(path: &str, task: &str, optional: bool) -> bool { + if optional { + return false; + } + let p = path.to_lowercase(); + let name = p.rsplit('/').next().unwrap_or(&p); + let doc_file = name.starts_with("readme") + || name.starts_with("changelog") + || name.starts_with("contributing") + || name.ends_with(".md") + || name.ends_with(".mdx") + || name.ends_with(".rst") + || p.starts_with("docs/") + || p.contains("/docs/"); + let t = task.to_lowercase(); + let doc_task = [ + "document ", + "documentation", + "readme", + "changelog", + "release note", + ] + .iter() + .any(|m| t.contains(m)) + && !["implement", "fix ", "bump", "upgrade", "update the version"] + .iter() + .any(|m| t.contains(m)); + !(doc_file || doc_task) +} + +/// The rung after `stalled` attempts in a row without progress, on a task +/// that is core or not. Zero stalls continue as before. +pub fn next_rung(stalled: u32, core: bool) -> Rung { + match (stalled, core) { + (0, _) => Rung::Continue, + (1, _) => Rung::Narrow, + (2, _) => Rung::SwitchTools, + (3, true) => Rung::Resplit, + // A non-core task (a readme line, a changelog) that resisted three + // approaches isn't worth more: it is deferred with the reason. + (3, false) => Rung::Defer, + (4, true) => Rung::Escalate, + (5, true) => Rung::Defer, + _ => Rung::Ship, + } +} + +/// The share of the spend ceiling at which a run ships what is done. +pub const SHIP_AT_SPEND_SHARE: f64 = 0.85; + +/// Whether the run's spend is near its ceiling: ship, don't stop mid-way. +pub fn near_spend_cap(spent_usd: f64, cap_usd: f64) -> bool { + cap_usd > 0.0 && spent_usd >= cap_usd * SHIP_AT_SPEND_SHARE +} + +/// Whether a loop at `rounds` with cap `cap` may take another round: under +/// the cap always, past it only while the last round made progress, up to +/// twice the cap. +pub fn may_extend(rounds: u32, cap: u32, progressed: bool) -> bool { + rounds < cap || (progressed && rounds < cap.saturating_mul(2)) +} + +/// The rung for this attempt, with the spend ceiling: a run near its +/// ceiling ships. +pub fn rung_for(stalled: u32, core: bool, spent_usd: f64, cap_usd: f64) -> Rung { + if near_spend_cap(spent_usd, cap_usd) { + return Rung::Ship; + } + next_rung(stalled, core) +} + +/// What a rung tells the coder: the instruction that changes the approach. +/// Empty for [`Rung::Continue`], [`Rung::Defer`] and [`Rung::Ship`], which +/// the supervisor carries out itself. +pub fn rung_instruction(rung: Rung, task: &str, path: &str) -> String { + match rung { + Rung::Continue | Rung::Defer | Rung::Ship => String::new(), + Rung::Narrow => format!( + "The last attempt changed nothing. Take one task only: {task}. Make the change in \ + `{path}`, or, if the file already does what the task asks, write the line \ + `No change needed: {path}: ` in your final message." + ), + Rung::SwitchTools => format!( + "Two attempts changed nothing on this task: {task}. Start fresh from the plan and the \ + branch's diff; don't redo finished work. Change the tool approach: read `{path}` in \ + the parts you need and edit it in place with small edits, never rewrite the whole \ + file. If an edit is refused, read the exact current text around it and edit again. \ + Keep your thinking short and save the file before you stop." + ), + Rung::Resplit => format!( + "This task resisted three attempts: {task}. Split it into two or three smaller \ + changes in `{path}`, write the list as the first lines of your final message, and \ + make only the first change now, saved. The next step takes the next one." + ), + Rung::Escalate => format!( + "This core task resisted four attempts: {task}. Work from the plan and the branch \ + as it is now. Read the code around `{path}` and the tests that cover it, find why \ + earlier attempts didn't land (a refused edit, a wrong file, a failing build), and \ + make the change. Save the file before you stop." + ), + } +} + +/// The reason written beside a deferred task. +pub fn defer_reason(rung_count: u32, task: &str, core: bool) -> String { + let kind = if core { "task" } else { "non-core task" }; + format!( + "deferred: this {kind} resisted {rung_count} different approaches ({}); the rest of the \ + work ships without it and the pull request lists it", + common::truncate_str(task, 160) + ) +} + +// ── Red checks ────────────────────────────────────────────────────────────── + +/// How many reverts the supervisor makes on one pull request before the +/// run ends with what still fails. +pub const MAX_REVERTS: u32 = 3; + +/// What the supervisor takes out so what ships is green. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Revert { + /// Back to this earlier head of the pull request, whose checks passed. + ToHead(String), + /// The last planned task's file, back to the base branch's version. + Task { path: String, task: String }, + /// Nothing can come out without emptying the pull request. + Nothing, +} + +/// The revert for red checks after the fix attempts: the newest earlier +/// head whose checks passed (`heads`: older heads, newest first, with +/// whether their checks passed), else the last done task when more than one +/// is done (`done`: path and task, in plan order), else nothing. +pub fn revert_for(heads: &[(String, bool)], done: &[(String, String)], reverts: u32) -> Revert { + if reverts >= MAX_REVERTS { + return Revert::Nothing; + } + if let Some((sha, _)) = heads.iter().find(|(_, green)| *green) { + return Revert::ToHead(sha.clone()); + } + match done { + [_, .., (path, task)] => Revert::Task { + path: path.clone(), + task: task.clone(), + }, + _ => Revert::Nothing, + } +} + +// ── The ending ────────────────────────────────────────────────────────────── + +/// What a run's ending is decided from. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct EndFacts { + /// Planned tasks not done and not deferred. + pub open_tasks: Vec, + /// Tasks deferred, each with its reason. + pub deferred: Vec, + /// Checks of ours failing on the head. + pub ci_failing: Vec, + pub ci_running: bool, + /// A recorded human-only blocker, when one exists. + pub blocker: Option, + /// The branch has work (beyond the plan files). + pub has_work: bool, + /// The ladder is spent (the run reached [`Rung::Ship`]). + pub ladder_spent: bool, +} + +/// How a run ends. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Ending { + /// Keep working: tasks are open and the ladder isn't spent. + KeepGoing, + /// CI is still running. + Wait, + /// Finished: the pull request carries the work, with what was deferred + /// listed and why. + Finished { deferred: Vec }, + /// Nothing could ship (no work, or every change breaks the checks): the + /// run failed, with the exact cause. Not a question to a person. + Failed, + /// A human-only blocker: the one need, and a notification. + HandBack(HandBack), +} + +impl Ending { + /// The run status this ending writes. + pub fn status(&self) -> &'static str { + match self { + Ending::KeepGoing => common::run_status::RUNNING, + Ending::Wait => common::run_status::AWAITING_CI, + Ending::Finished { .. } => common::run_status::COMPLETED, + Ending::Failed => "failed", + Ending::HandBack(_) => common::run_status::NEEDS_INPUT, + } + } +} + +/// The one ending decision, as every ending site applies it. +pub fn decide_end(f: &EndFacts) -> Ending { + if let Some(h) = &f.blocker { + return Ending::HandBack(h.clone()); + } + if !f.open_tasks.is_empty() && !f.ladder_spent { + return Ending::KeepGoing; + } + if !f.has_work || !f.ci_failing.is_empty() { + return Ending::Failed; + } + if f.ci_running { + return Ending::Wait; + } + // The ladder is spent: what is still open is deferred with the rest. + let mut deferred = f.deferred.clone(); + deferred.extend( + f.open_tasks + .iter() + .map(|t| format!("{t} (deferred: the run's approaches are spent)")), + ); + Ending::Finished { deferred } +} + +/// [`decide_end`], with its rules checked: a slip is logged loudly (and +/// the tests drive every combination, so none ships). +pub fn end(f: &EndFacts) -> Ending { + let e = decide_end(f); + let b = broken(f, &e); + if !b.is_empty() { + tracing::error!(broken = ?b, "A run ending breaks the supervisor's rules"); + } + e +} + +/// The rules an ending keeps, as what it breaks (empty when it keeps them). +pub fn broken(f: &EndFacts, e: &Ending) -> Vec<&'static str> { + let mut out = Vec::new(); + match e { + Ending::HandBack(h) => { + if !HUMAN_ONLY.contains(&h.why()) { + out.push("hands back for a reason not on the human-only list"); + } + if h.need().trim().is_empty() { + out.push("hands back without saying what is needed"); + } + if f.blocker.is_none() { + out.push("hands back without a recorded blocker"); + } + } + Ending::Finished { deferred } => { + if !f.ci_failing.is_empty() { + out.push("finished with failing checks of ours"); + } + if deferred.len() < f.open_tasks.len() + f.deferred.len() { + out.push("finished with open tasks that aren't deferred"); + } + } + Ending::KeepGoing if f.ladder_spent => out.push("keeps going after the ladder is spent"), + _ => {} + } + if f.blocker.is_none() && e.status() == common::run_status::NEEDS_INPUT { + out.push("waits on a person without a human-only reason"); + } + out +} + +// ── Replays ──────────────────────────────────────────────────────────────── + +/// What stopped a historical run, as its shape. +#[cfg(test)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ReplayStop { + /// Steps or rounds that changed nothing on a planned task (plan + /// coverage, turn or step caps, replies that only thought). + Stall, + /// A step's time ran out and no fresh step took over. + OutOfTime, + /// A pass or check errored (a gate, GitHub refusing, the planner, the + /// coder writing nothing). + Errored, + /// Red checks of ours the fix attempts couldn't repair. + RedCi, + /// Red checks that fail on the base branch too. + RedOnBase, + /// CoderHelm's own review findings left open after its fix rounds. + OwnFindings, + /// A need only a person has. + Asked(HumanOnly), +} + +/// Replays a historical run's shape through the rules: the ending it would +/// reach now. Every attempt is assumed to change nothing (the worst case +/// the old run met), so a run finishes only on what it had already done. +/// `done` and `total` are its planned tasks. +#[cfg(test)] +pub fn replay(stop: ReplayStop, done: u32, total: u32) -> Ending { + let total = total.max(done); + let open: Vec = (done + 1..=total).map(|i| format!("task {i}")).collect(); + let mut f = EndFacts { + has_work: done > 0, + ..Default::default() + }; + match stop { + ReplayStop::Asked(why) => { + f.blocker = Some(HandBack::of(why)); + } + ReplayStop::Stall | ReplayStop::OutOfTime | ReplayStop::Errored => { + // An error first gets one fresh step; a stall climbs the ladder. + // Each open task climbs until it is deferred; none lands. + for t in &open { + let mut stalled = 0; + while !matches!(next_rung(stalled, true), Rung::Defer | Rung::Ship) { + stalled += 1; + } + f.deferred + .push(format!("{t} ({})", defer_reason(stalled, t, true))); + } + f.ladder_spent = true; + } + ReplayStop::RedCi => { + // The fix attempts didn't repair it: take out the last task + // while more than one is done (no green head is assumed). + let tasks: Vec<(String, String)> = (1..=done) + .map(|i| (format!("src/f{i}.rs"), format!("task {i}"))) + .collect(); + match revert_for(&[], &tasks, 0) { + Revert::Task { task, .. } => f + .deferred + .push(format!("{task} (deferred: its change broke the checks)")), + Revert::ToHead(_) => {} + Revert::Nothing => f.ci_failing = vec!["the checks".to_string()], + } + f.deferred + .extend(open.iter().map(|t| format!("{t} (deferred)"))); + f.ladder_spent = true; + } + ReplayStop::RedOnBase | ReplayStop::OwnFindings => { + f.deferred = open.iter().map(|t| format!("{t} (deferred)")).collect(); + f.has_work = true; + f.ladder_spent = true; + } + } + decide_end(&f) +} + +#[cfg(test)] +#[path = "supervisor_replays.rs"] +mod replays; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_stall_changes_approach_and_never_stops() { + let core: Vec = (0..7).map(|s| next_rung(s, true)).collect(); + assert_eq!( + core, + vec![ + Rung::Continue, + Rung::Narrow, + Rung::SwitchTools, + Rung::Resplit, + Rung::Escalate, + Rung::Defer, + Rung::Ship + ] + ); + assert_eq!(next_rung(3, false), Rung::Defer); + for s in 1..6 { + let r = next_rung(s, true); + if !matches!(r, Rung::Defer | Rung::Ship) { + assert!(!rung_instruction(r, "t", "p").is_empty(), "{r:?}"); + } + } + } + + #[test] + fn docs_tasks_are_not_core() { + assert!(!is_core("README.md", "note the new minimum version", false)); + assert!(!is_core("docs/setup.md", "document the flag", false)); + assert!(!is_core("CHANGELOG.md", "add the entry", false)); + assert!(is_core("web/package.json", "bump the framework", false)); + assert!(is_core( + "src/api/handler.rs", + "document the error path and fix the panic", + false + )); + assert!(!is_core("src/a.rs", "x", true)); + } + + #[test] + fn near_the_spend_cap_the_run_ships_and_progress_earns_rounds() { + assert_eq!(rung_for(1, true, 180.0, 200.0), Rung::Ship); + assert_eq!(rung_for(1, true, 20.0, 200.0), Rung::Narrow); + assert!(may_extend(3, 3, true)); + assert!(!may_extend(3, 3, false)); + assert!(!may_extend(6, 3, true)); + } + + #[test] + fn red_checks_revert_to_green_then_by_task_and_never_empty_the_pull_request() { + let heads = vec![("c3".to_string(), false), ("c2".to_string(), true)]; + let done = vec![ + ("src/a.rs".to_string(), "fix a".to_string()), + ("src/b.rs".to_string(), "fix b".to_string()), + ]; + assert_eq!(revert_for(&heads, &done, 0), Revert::ToHead("c2".into())); + let red = vec![("c1".to_string(), false)]; + assert_eq!( + revert_for(&red, &done, 1), + Revert::Task { + path: "src/b.rs".into(), + task: "fix b".into() + } + ); + assert_eq!(revert_for(&red, &done[..1], 0), Revert::Nothing); + assert_eq!(revert_for(&heads, &done, MAX_REVERTS), Revert::Nothing); + } + + #[test] + fn every_ending_keeps_the_rules() { + let blockers = [None, Some(HandBack::of(HumanOnly::Credential))]; + let mut n = 0; + for open in [vec![], vec!["`a.rs`: x".to_string()]] { + for failing in [vec![], vec!["build".to_string()]] { + for running in [false, true] { + for b in &blockers { + for has_work in [false, true] { + for spent in [false, true] { + let f = EndFacts { + open_tasks: open.clone(), + deferred: vec![], + ci_failing: failing.clone(), + ci_running: running, + blocker: b.clone(), + has_work, + ladder_spent: spent, + }; + let e = decide_end(&f); + assert!(broken(&f, &e).is_empty(), "{f:?} {e:?}"); + n += 1; + } + } + } + } + } + } + assert_eq!(n, 64); + } + + /// The four runs the investigation started from, by shape: a security + /// run stuck on its ninth task (a readme line); a finished security run + /// whose pull request GitHub refused; a run stuck after seven of eight + /// tasks; a CI fix that gave up after one try. None waits on a person. + #[test] + fn the_four_named_runs_finish_now() { + for (stop, done, total) in [ + (ReplayStop::Stall, 8, 9), + (ReplayStop::Errored, 24, 24), + (ReplayStop::Stall, 7, 8), + (ReplayStop::RedCi, 8, 8), + ] { + let e = replay(stop, done, total); + assert!( + matches!(e, Ending::Finished { .. }), + "{stop:?} {done}/{total}: {e:?}" + ); + } + } + + /// The invariant over the whole replay suite: no run ends waiting on a + /// person unless what blocked it is on the human-only list, every run + /// only a person could unblock still waits, and every replay ends. + #[test] + fn across_the_replays_only_human_only_blockers_wait() { + let (mut finished, mut failed, mut waits) = (0, 0, 0); + for c in replays::CASES { + let e = replay(c.stop, c.done, c.total); + match &e { + Ending::HandBack(h) => { + assert!(HUMAN_ONLY.contains(&h.why()), "{}: {e:?}", c.name); + assert!( + matches!(c.stop, ReplayStop::Asked(_)), + "{}: waits without a recorded need", + c.name + ); + waits += 1; + } + Ending::Finished { .. } => finished += 1, + Ending::Failed => failed += 1, + other => panic!("{}: a replay must end, got {other:?}", c.name), + } + if c.human_only && matches!(c.stop, ReplayStop::Asked(_)) { + assert!(matches!(e, Ending::HandBack(_)), "{}: {e:?}", c.name); + } + if c.human_only { + assert!(!matches!(e, Ending::Failed), "{}: {e:?}", c.name); + } + // A run that had work and stopped on something CoderHelm owns + // ships it now. + if !c.human_only && c.done > 1 && !matches!(c.stop, ReplayStop::Asked(_)) { + assert!(matches!(e, Ending::Finished { .. }), "{}: {e:?}", c.name); + } + } + assert_eq!(finished + failed + waits, replays::CASES.len()); + // Before: the same shapes through the old outcome rule + // (`outcome::decide`), where any stop, task left or red check + // needed a person. + let mut before_waits = 0; + for c in replays::CASES { + let open: Vec = (c.done + 1..=c.total.max(c.done)) + .map(|i| format!("task {i}")) + .collect(); + let stop = match c.stop { + ReplayStop::RedOnBase => None, + ReplayStop::OutOfTime => Some(super::super::outcome::Stop::OutOfTime( + "The step reached its time limit".into(), + )), + _ => Some(super::super::outcome::Stop::Other("stopped".into())), + }; + let ci = match c.stop { + ReplayStop::RedCi => super::super::outcome::CiState::Failing("ci".into()), + ReplayStop::RedOnBase => super::super::outcome::CiState::RedOnBase, + _ => super::super::outcome::CiState::NoChecks, + }; + let old = super::super::outcome::decide(&super::super::outcome::Facts { + tasks_remaining: open, + ci, + review: super::super::outcome::Review::Missing, + stop, + }); + if old.status == super::super::outcome::RunStatus::NeedsAttention { + before_waits += 1; + } + } + assert!(before_waits > waits, "{before_waits} then, {waits} now"); + // By group: runs, what they cost, how they ended then and now. + type Row<'a> = (u32, u32, Vec<&'a str>, Vec); + let mut groups: std::collections::BTreeMap<&str, Row> = Default::default(); + for c in replays::CASES { + let g = groups.entry(c.group).or_default(); + g.0 += 1; + g.1 += c.cost_cents; + g.2.push(c.old_status); + g.3.push(match replay(c.stop, c.done, c.total) { + Ending::HandBack(h) => format!("waits ({})", h.why()), + e => e.status().to_string(), + }); + assert!(c.date.len() == 10, "{}", c.name); + } + for (g, (n, cents, old, now)) in &groups { + let count = |v: &[String], s: &str| v.iter().filter(|x| x.starts_with(s)).count(); + println!( + "{g}: {n} runs, ${:.2}; then {} needs_input, {} failed, {} retried, {} completed; \ + now {} completed, {} failed, {} waiting", + *cents as f64 / 100.0, + old.iter().filter(|s| **s == "needs_input").count(), + old.iter().filter(|s| **s == "failed").count(), + old.iter().filter(|s| **s == "retried").count(), + old.iter().filter(|s| **s == "completed").count(), + count(now, "completed"), + count(now, "failed"), + count(now, "waits"), + ); + } + println!( + "replays: {} runs; before: {before_waits} waited on a person; now: finished \ + {finished}, failed with the cause {failed}, waiting on a human-only need {waits}", + replays::CASES.len() + ); + } + + // ── The source scan ──────────────────────────────────────────────── + + fn sources() -> Vec<(String, String)> { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut stack = vec![root.clone()]; + let mut out = Vec::new(); + while let Some(dir) = stack.pop() { + for e in std::fs::read_dir(&dir).unwrap().flatten() { + let p = e.path(); + if p.is_dir() { + stack.push(p); + } else if p.extension().is_some_and(|x| x == "rs") { + let rel = p + .strip_prefix(&root) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + out.push((rel, std::fs::read_to_string(&p).unwrap())); + } + } + } + assert!(out.len() > 50, "found the sources"); + out + } + + /// The body of `fn name` in `code` (to the next item at column zero). + fn body<'a>(code: &'a str, head: &str) -> &'a str { + let Some(i) = code.find(head) else { + return ""; + }; + let rest = &code[i..]; + let end = rest[1..].find("\n}\n").map(|j| j + 3).unwrap_or(rest.len()); + &rest[..end] + } + + /// No ending goes around the supervisor. Fails when: + /// - a file not on the list writes `needs_input` (each one on it takes + /// a `HandBack`, which the type requires); + /// - a `HandBack` is made from anything but a reason on the list + /// (a literal `HumanOnly::...`, the stop's own `asked_for`, or + /// `human_only_in`); + /// - a stop whose steps changed nothing returns as an error again, or + /// the CI give-up, the stop after the work, the guard and the ready + /// hold stop reading the supervisor first. + #[test] + fn no_ending_goes_around_the_supervisor() { + const WRITES_NEEDS_INPUT: &[&str] = &[ + "agent/policy.rs", + "passes/mod.rs", + "passes/ready.rs", + "passes/resume.rs", + "passes/run_guard.rs", + "passes/stop_pr.rs", + ]; + let mut bad = Vec::new(); + for (rel, code) in sources() { + // The incident cases and the scans' own test strings. + if rel.starts_with("passes/incidents/") + || rel.starts_with("passes/replay/") + || rel == "passes/stop_judge.rs" + || rel == "passes/supervisor.rs" + { + continue; + } + if code.contains(".needs_input(") && !WRITES_NEEDS_INPUT.contains(&rel.as_str()) { + bad.push(format!( + "{rel}: writes needs_input; only the supervisor's ending sites may" + )); + } + for make in ["HandBack::new(", "HandBack::of("] { + for (i, _) in code.match_indices(make) { + let arg = code[i + make.len()..] + .trim_start() + .split([',', ')']) + .next() + .unwrap_or("") + .trim() + .to_string(); + let listed = arg.contains("HumanOnly::") + || arg == "asked_for" + || arg == "why" + || arg == "h"; + if !listed { + bad.push(format!("{rel}: `{make}{arg}` isn't a reason on the list")); + } + } + } + if rel == "passes/mod.rs" { + if code.contains("steps::stall_reason(") { + bad.push(format!( + "{rel}: a stall stops the run again (steps::stall_reason)" + )); + } + for (i, _) in code.match_indices("mark_run_needs_input(") { + if code[..i].ends_with("async fn ") { + continue; + } + let call = &code[i..code[i..].find(".await").map_or(code.len(), |j| i + j)]; + if !call.contains("HumanOnly::") { + bad.push(format!( + "{rel}: a needs_input stop without its human-only reason" + )); + } + } + } + } + let find = |rel: &str| { + sources() + .into_iter() + .find(|(r, _)| r == rel) + .map(|(_, c)| c) + .unwrap_or_default() + }; + let resume = find("passes/resume.rs"); + let hand_off = body(&resume, "\nasync fn hand_off_red_ci("); + match ( + hand_off.find("revert_to_green("), + hand_off.find("record_ci_outcome("), + ) { + (Some(r), Some(o)) if r < o => {} + _ => bad.push("resume.rs: hand_off_red_ci gives up before reverting to green".into()), + } + for (rel, head, needle) in [ + ( + "passes/resume.rs", + "\nasync fn wait_on_person(", + "supervisor::end(", + ), + ( + "passes/stop_pr.rs", + "\npub async fn open_with(", + "supervisor::end(", + ), + ( + "passes/run_guard.rs", + "\nasync fn wait_on_open_pr(", + "hand_back_for(", + ), + ( + "passes/ready.rs", + "\nasync fn wait_on_person(", + "draft_hand_back(", + ), + ( + "passes/mod.rs", + "\npub(crate) async fn mark_run_stopped_by_guard(", + "hand_back_for(", + ), + ] { + let code = find(rel); + let b = body(&code, head); + if b.is_empty() || !b.contains(needle) { + bad.push(format!( + "{rel}: `{}` doesn't read the supervisor ({needle})", + head.trim() + )); + } + } + assert!( + bad.is_empty(), + "endings around the supervisor:\n{}", + bad.join("\n") + ); + } + + /// The scan catches what it guards: a made-up file that writes the + /// status, and a hand-back from a stall's words. + #[test] + fn the_scan_catches_an_ending_around_the_supervisor() { + let code = "fn stop() { u.needs_input(r, &w, &HandBack::new(kind_of(stall), \"x\")); }"; + let arg = code[code.find("HandBack::new(").unwrap() + 14..] + .split([',', ')']) + .next() + .unwrap() + .trim() + .to_string(); + assert_eq!(arg, "kind_of(stall"); + assert!(!arg.contains("HumanOnly::")); + let src = + "x\nasync fn hand_off_red_ci(\n record_ci_outcome(a);\n revert_to_green(b);\n}\n"; + let b = body(src, "\nasync fn hand_off_red_ci("); + assert!(b.find("record_ci_outcome(").unwrap() < b.find("revert_to_green(").unwrap()); + } +} diff --git a/services/worker/src/passes/supervisor_replays.rs b/services/worker/src/passes/supervisor_replays.rs new file mode 100644 index 000000000..fd71f4507 --- /dev/null +++ b/services/worker/src/passes/supervisor_replays.rs @@ -0,0 +1,2413 @@ +//! The replay suite's cases: every run on one install that ended without +//! a finished pull request and wasn't a person's own decision, as its shape +//! only (invented names; how many planned tasks it had done, what stopped +//! it, how it ended then). Generated from the run history; see +//! `supervisor::replay`. + +use super::{HumanOnly, ReplayStop}; + +pub struct Case { + pub name: &'static str, + /// The kind of stop, as the investigation grouped it. + pub group: &'static str, + pub date: &'static str, + pub cost_cents: u32, + /// Planned tasks done, and planned in all. + pub done: u32, + pub total: u32, + /// Only a person could have unblocked it. + pub human_only: bool, + /// How it ended with the code of its day. + pub old_status: &'static str, + pub stop: ReplayStop, +} + +pub const CASES: &[Case] = &[ + Case { + name: "case-001", + group: "setup", + date: "2026-04-16", + cost_cents: 0, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-002", + group: "setup", + date: "2026-04-17", + cost_cents: 0, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-003", + group: "setup", + date: "2026-04-17", + cost_cents: 0, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-004", + group: "setup", + date: "2026-04-17", + cost_cents: 21, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-005", + group: "setup", + date: "2026-04-17", + cost_cents: 21, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-006", + group: "setup", + date: "2026-04-17", + cost_cents: 20, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-007", + group: "setup", + date: "2026-04-17", + cost_cents: 21, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-008", + group: "github_api", + date: "2026-04-17", + cost_cents: 49, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-009", + group: "silent_end", + date: "2026-04-17", + cost_cents: 506, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-010", + group: "github_api", + date: "2026-04-18", + cost_cents: 2, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-011", + group: "github_api", + date: "2026-04-18", + cost_cents: 48, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-012", + group: "budget", + date: "2026-04-18", + cost_cents: 1324, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::OutOfTime, + }, + Case { + name: "case-013", + group: "no_change", + date: "2026-04-18", + cost_cents: 409, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-014", + group: "no_change", + date: "2026-04-18", + cost_cents: 694, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-015", + group: "budget", + date: "2026-04-19", + cost_cents: 822, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Stall, + }, + Case { + name: "case-016", + group: "setup", + date: "2026-04-19", + cost_cents: 0, + done: 0, + total: 0, + human_only: true, + old_status: "failed", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-017", + group: "setup", + date: "2026-04-19", + cost_cents: 0, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-018", + group: "ci_red", + date: "2026-04-20", + cost_cents: 84, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::RedCi, + }, + Case { + name: "case-019", + group: "failed", + date: "2026-04-20", + cost_cents: 6702, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-020", + group: "routing", + date: "2026-04-20", + cost_cents: 127, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-021", + group: "github_api", + date: "2026-04-20", + cost_cents: 2718, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-022", + group: "budget", + date: "2026-04-20", + cost_cents: 892, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Stall, + }, + Case { + name: "case-023", + group: "github_api", + date: "2026-04-20", + cost_cents: 650, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-024", + group: "budget", + date: "2026-04-20", + cost_cents: 2700, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::OutOfTime, + }, + Case { + name: "case-025", + group: "routing", + date: "2026-04-20", + cost_cents: 429, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-026", + group: "silent_end", + date: "2026-04-21", + cost_cents: 20, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-027", + group: "no_change", + date: "2026-04-21", + cost_cents: 736, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-028", + group: "budget", + date: "2026-04-21", + cost_cents: 1615, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::OutOfTime, + }, + Case { + name: "case-029", + group: "budget", + date: "2026-04-21", + cost_cents: 1810, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::OutOfTime, + }, + Case { + name: "case-030", + group: "budget", + date: "2026-04-22", + cost_cents: 39, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Stall, + }, + Case { + name: "case-031", + group: "routing", + date: "2026-04-22", + cost_cents: 70, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-032", + group: "budget", + date: "2026-04-22", + cost_cents: 0, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::OutOfTime, + }, + Case { + name: "case-033", + group: "ci_red", + date: "2026-04-22", + cost_cents: 7153, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::RedCi, + }, + Case { + name: "case-034", + group: "budget", + date: "2026-04-22", + cost_cents: 1381, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::OutOfTime, + }, + Case { + name: "case-035", + group: "silent_end", + date: "2026-04-23", + cost_cents: 36, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-036", + group: "routing", + date: "2026-04-24", + cost_cents: 54, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-037", + group: "routing", + date: "2026-04-24", + cost_cents: 81, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-038", + group: "no_change", + date: "2026-04-24", + cost_cents: 665, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-039", + group: "routing", + date: "2026-04-24", + cost_cents: 64, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-040", + group: "routing", + date: "2026-04-24", + cost_cents: 51, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-041", + group: "routing", + date: "2026-05-08", + cost_cents: 52, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-042", + group: "budget", + date: "2026-05-21", + cost_cents: 502, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::OutOfTime, + }, + Case { + name: "case-043", + group: "access", + date: "2026-05-22", + cost_cents: 372, + done: 0, + total: 0, + human_only: true, + old_status: "failed", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-044", + group: "silent_end", + date: "2026-05-25", + cost_cents: 21, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-045", + group: "routing", + date: "2026-06-04", + cost_cents: 142, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-046", + group: "routing", + date: "2026-06-04", + cost_cents: 37, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-047", + group: "routing", + date: "2026-06-04", + cost_cents: 39, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-048", + group: "routing", + date: "2026-06-05", + cost_cents: 40, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-049", + group: "budget", + date: "2026-06-05", + cost_cents: 2547, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::OutOfTime, + }, + Case { + name: "case-050", + group: "no_change", + date: "2026-06-05", + cost_cents: 54, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-051", + group: "routing", + date: "2026-06-07", + cost_cents: 39, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-052", + group: "access", + date: "2026-06-10", + cost_cents: 108, + done: 0, + total: 0, + human_only: true, + old_status: "failed", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-053", + group: "model_api", + date: "2026-06-16", + cost_cents: 53, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-054", + group: "budget", + date: "2026-06-17", + cost_cents: 147, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Stall, + }, + Case { + name: "case-055", + group: "budget", + date: "2026-06-17", + cost_cents: 1990, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Stall, + }, + Case { + name: "case-056", + group: "budget", + date: "2026-06-17", + cost_cents: 0, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::OutOfTime, + }, + Case { + name: "case-057", + group: "budget", + date: "2026-06-19", + cost_cents: 2874, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Stall, + }, + Case { + name: "case-058", + group: "budget", + date: "2026-06-19", + cost_cents: 1463, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Stall, + }, + Case { + name: "case-059", + group: "budget", + date: "2026-06-19", + cost_cents: 0, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::OutOfTime, + }, + Case { + name: "case-060", + group: "budget", + date: "2026-06-19", + cost_cents: 66, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Stall, + }, + Case { + name: "case-061", + group: "routing", + date: "2026-06-19", + cost_cents: 59, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-062", + group: "routing", + date: "2026-06-22", + cost_cents: 1517, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-063", + group: "silent_end", + date: "2026-06-23", + cost_cents: 18, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-064", + group: "routing", + date: "2026-07-01", + cost_cents: 173, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-065", + group: "routing", + date: "2026-07-01", + cost_cents: 226, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-066", + group: "routing", + date: "2026-07-02", + cost_cents: 63, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-067", + group: "silent_end", + date: "2026-07-02", + cost_cents: 18, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-068", + group: "routing", + date: "2026-07-02", + cost_cents: 151, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-069", + group: "routing", + date: "2026-07-02", + cost_cents: 64, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-070", + group: "routing", + date: "2026-07-02", + cost_cents: 78, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-071", + group: "routing", + date: "2026-07-02", + cost_cents: 188, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-072", + group: "budget", + date: "2026-07-05", + cost_cents: 35, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Stall, + }, + Case { + name: "case-073", + group: "operator_kill", + date: "2026-07-23", + cost_cents: 1586, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-074", + group: "operator_kill", + date: "2026-07-23", + cost_cents: 1174, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-075", + group: "operator_kill", + date: "2026-07-23", + cost_cents: 2347, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-076", + group: "ci_red", + date: "2026-07-23", + cost_cents: 1451, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::RedCi, + }, + Case { + name: "case-077", + group: "ci_red", + date: "2026-07-23", + cost_cents: 2225, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::RedCi, + }, + Case { + name: "case-078", + group: "budget", + date: "2026-07-24", + cost_cents: 635, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::OutOfTime, + }, + Case { + name: "case-079", + group: "failed", + date: "2026-08-05", + cost_cents: 185, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-080", + group: "silent_end", + date: "2026-08-07", + cost_cents: 34, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-081", + group: "no_change", + date: "2026-08-07", + cost_cents: 27, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-082", + group: "no_change", + date: "2026-08-07", + cost_cents: 19, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-083", + group: "no_change", + date: "2026-08-07", + cost_cents: 75, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-084", + group: "no_change", + date: "2026-08-07", + cost_cents: 13, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Errored, + }, + Case { + name: "case-085", + group: "no_change", + date: "2026-08-10", + cost_cents: 42, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Errored, + }, + Case { + name: "case-086", + group: "silent_end", + date: "2026-08-11", + cost_cents: 32, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Errored, + }, + Case { + name: "case-087", + group: "operator_kill", + date: "2026-08-11", + cost_cents: 133, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-088", + group: "budget", + date: "2026-08-11", + cost_cents: 139, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::OutOfTime, + }, + Case { + name: "case-089", + group: "budget", + date: "2026-08-17", + cost_cents: 79, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Stall, + }, + Case { + name: "case-090", + group: "ci_red", + date: "2026-08-17", + cost_cents: 1592, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::RedCi, + }, + Case { + name: "case-091", + group: "silent_end", + date: "2026-08-19", + cost_cents: 41, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-092", + group: "silent_end", + date: "2026-08-19", + cost_cents: 44, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-093", + group: "no_change", + date: "2026-08-21", + cost_cents: 357, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Errored, + }, + Case { + name: "case-094", + group: "budget", + date: "2026-08-26", + cost_cents: 72, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Stall, + }, + Case { + name: "case-095", + group: "budget", + date: "2026-08-26", + cost_cents: 60, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Stall, + }, + Case { + name: "case-096", + group: "no_change", + date: "2026-08-31", + cost_cents: 29, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-097", + group: "silent_end", + date: "2026-08-31", + cost_cents: 14, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-098", + group: "budget", + date: "2026-09-02", + cost_cents: 293, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Stall, + }, + Case { + name: "case-099", + group: "no_change", + date: "2026-09-04", + cost_cents: 424, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Errored, + }, + Case { + name: "case-100", + group: "no_change", + date: "2026-09-08", + cost_cents: 152, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Errored, + }, + Case { + name: "case-101", + group: "gate", + date: "2026-09-08", + cost_cents: 240, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-102", + group: "no_change", + date: "2026-09-08", + cost_cents: 105, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-103", + group: "access", + date: "2026-09-10", + cost_cents: 50, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-104", + group: "access", + date: "2026-09-10", + cost_cents: 81, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-105", + group: "access", + date: "2026-09-10", + cost_cents: 29, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-106", + group: "access", + date: "2026-09-10", + cost_cents: 52, + done: 0, + total: 0, + human_only: true, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-107", + group: "access", + date: "2026-09-10", + cost_cents: 142, + done: 0, + total: 0, + human_only: true, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-108", + group: "github_api", + date: "2026-09-11", + cost_cents: 1485, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-109", + group: "gate", + date: "2026-09-11", + cost_cents: 101, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-110", + group: "github_api", + date: "2026-09-11", + cost_cents: 2296, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-111", + group: "github_api", + date: "2026-09-11", + cost_cents: 52, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-112", + group: "github_api", + date: "2026-09-11", + cost_cents: 1521, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-113", + group: "ci_red", + date: "2026-09-12", + cost_cents: 1409, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::RedCi, + }, + Case { + name: "case-114", + group: "budget", + date: "2026-09-12", + cost_cents: 59, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Stall, + }, + Case { + name: "case-115", + group: "gate", + date: "2026-09-14", + cost_cents: 96, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-116", + group: "budget", + date: "2026-09-14", + cost_cents: 83, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Stall, + }, + Case { + name: "case-117", + group: "budget", + date: "2026-09-14", + cost_cents: 80, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Stall, + }, + Case { + name: "case-118", + group: "gate", + date: "2026-09-15", + cost_cents: 140, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-119", + group: "no_change", + date: "2026-09-15", + cost_cents: 258, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Errored, + }, + Case { + name: "case-120", + group: "no_change", + date: "2026-09-15", + cost_cents: 153, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-121", + group: "no_change", + date: "2026-09-15", + cost_cents: 68, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-122", + group: "no_change", + date: "2026-09-15", + cost_cents: 84, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Errored, + }, + Case { + name: "case-123", + group: "no_change", + date: "2026-09-15", + cost_cents: 198, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Errored, + }, + Case { + name: "case-124", + group: "no_change", + date: "2026-09-16", + cost_cents: 222, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-125", + group: "no_change", + date: "2026-09-16", + cost_cents: 89, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-126", + group: "silent_end", + date: "2026-09-16", + cost_cents: 80, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-127", + group: "budget", + date: "2026-09-17", + cost_cents: 66, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Stall, + }, + Case { + name: "case-128", + group: "budget", + date: "2026-09-17", + cost_cents: 48, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Stall, + }, + Case { + name: "case-129", + group: "budget", + date: "2026-09-17", + cost_cents: 57, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::Stall, + }, + Case { + name: "case-130", + group: "silent_end", + date: "2026-09-18", + cost_cents: 28, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-131", + group: "budget", + date: "2026-09-25", + cost_cents: 89, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Stall, + }, + Case { + name: "case-132", + group: "no_change", + date: "2026-09-25", + cost_cents: 155, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Errored, + }, + Case { + name: "case-133", + group: "silent_end", + date: "2026-09-25", + cost_cents: 56, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-134", + group: "silent_end", + date: "2026-09-25", + cost_cents: 21, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-135", + group: "silent_end", + date: "2026-10-05", + cost_cents: 30, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-136", + group: "silent_end", + date: "2026-10-05", + cost_cents: 45, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-137", + group: "silent_end", + date: "2026-10-07", + cost_cents: 71, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-138", + group: "silent_end", + date: "2026-10-12", + cost_cents: 22, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Errored, + }, + Case { + name: "case-139", + group: "routing", + date: "2026-10-12", + cost_cents: 54, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-140", + group: "silent_end", + date: "2026-10-13", + cost_cents: 32, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-141", + group: "silent_end", + date: "2026-10-14", + cost_cents: 28, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Errored, + }, + Case { + name: "case-142", + group: "silent_end", + date: "2026-10-14", + cost_cents: 39, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-143", + group: "budget", + date: "2026-10-16", + cost_cents: 65, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Stall, + }, + Case { + name: "case-144", + group: "routing", + date: "2026-10-19", + cost_cents: 186, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-145", + group: "silent_end", + date: "2026-10-19", + cost_cents: 10, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-146", + group: "silent_end", + date: "2026-10-19", + cost_cents: 9, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-147", + group: "routing", + date: "2026-10-19", + cost_cents: 79, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-148", + group: "outside_change", + date: "2026-10-19", + cost_cents: 16, + done: 0, + total: 0, + human_only: true, + old_status: "needs_outside_change", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-149", + group: "fix_location", + date: "2026-10-20", + cost_cents: 19, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::AmbiguousTicket), + }, + Case { + name: "case-150", + group: "routing", + date: "2026-10-20", + cost_cents: 41, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-151", + group: "routing", + date: "2026-10-20", + cost_cents: 84, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-152", + group: "outside_change", + date: "2026-10-20", + cost_cents: 39, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-153", + group: "outside_change", + date: "2026-10-20", + cost_cents: 78, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-154", + group: "fix_location", + date: "2026-10-20", + cost_cents: 22, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::AmbiguousTicket), + }, + Case { + name: "case-155", + group: "outside_change", + date: "2026-10-20", + cost_cents: 42, + done: 0, + total: 0, + human_only: true, + old_status: "needs_outside_change", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-156", + group: "fix_location", + date: "2026-10-20", + cost_cents: 42, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::AmbiguousTicket), + }, + Case { + name: "case-157", + group: "routing", + date: "2026-10-20", + cost_cents: 179, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-158", + group: "outside_change", + date: "2026-10-20", + cost_cents: 63, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::MissingAccess), + }, + Case { + name: "case-159", + group: "fix_location", + date: "2026-10-20", + cost_cents: 24, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::AmbiguousTicket), + }, + Case { + name: "case-160", + group: "routing", + date: "2026-10-20", + cost_cents: 151, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-161", + group: "fix_location", + date: "2026-10-20", + cost_cents: 24, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::AmbiguousTicket), + }, + Case { + name: "case-162", + group: "fix_location", + date: "2026-10-21", + cost_cents: 23, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::AmbiguousTicket), + }, + Case { + name: "case-163", + group: "fix_location", + date: "2026-10-21", + cost_cents: 21, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::AmbiguousTicket), + }, + Case { + name: "case-164", + group: "routing", + date: "2026-10-21", + cost_cents: 77, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-165", + group: "routing", + date: "2026-10-21", + cost_cents: 26, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-166", + group: "questions", + date: "2026-10-26", + cost_cents: 256, + done: 0, + total: 0, + human_only: true, + old_status: "completed", + stop: ReplayStop::Asked(HumanOnly::ProductDecision), + }, + Case { + name: "case-167", + group: "duplicate", + date: "2026-10-26", + cost_cents: 101, + done: 0, + total: 0, + human_only: true, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::HeldByAnother), + }, + Case { + name: "case-168", + group: "duplicate", + date: "2026-10-26", + cost_cents: 70, + done: 0, + total: 0, + human_only: true, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::HeldByAnother), + }, + Case { + name: "case-169", + group: "duplicate", + date: "2026-10-26", + cost_cents: 35, + done: 0, + total: 0, + human_only: true, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::HeldByAnother), + }, + Case { + name: "case-170", + group: "fix_location", + date: "2026-10-26", + cost_cents: 26, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::AmbiguousTicket), + }, + Case { + name: "case-171", + group: "duplicate", + date: "2026-10-26", + cost_cents: 50, + done: 0, + total: 0, + human_only: true, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::HeldByAnother), + }, + Case { + name: "case-172", + group: "duplicate", + date: "2026-10-26", + cost_cents: 73, + done: 0, + total: 0, + human_only: true, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::HeldByAnother), + }, + Case { + name: "case-173", + group: "questions", + date: "2026-10-26", + cost_cents: 197, + done: 0, + total: 0, + human_only: true, + old_status: "completed", + stop: ReplayStop::Asked(HumanOnly::ProductDecision), + }, + Case { + name: "case-174", + group: "routing", + date: "2026-10-26", + cost_cents: 1050, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-175", + group: "questions", + date: "2026-10-27", + cost_cents: 55, + done: 0, + total: 0, + human_only: true, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::ProductDecision), + }, + Case { + name: "case-176", + group: "routing", + date: "2026-10-27", + cost_cents: 161, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-177", + group: "gate", + date: "2026-10-27", + cost_cents: 490, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-178", + group: "fix_location", + date: "2026-10-27", + cost_cents: 84, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::AmbiguousTicket), + }, + Case { + name: "case-179", + group: "codegen", + date: "2026-10-28", + cost_cents: 12, + done: 13, + total: 15, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-180", + group: "plan_coverage", + date: "2026-10-29", + cost_cents: 72, + done: 14, + total: 15, + human_only: false, + old_status: "retried", + stop: ReplayStop::Stall, + }, + Case { + name: "case-181", + group: "plan_coverage", + date: "2026-10-29", + cost_cents: 126, + done: 14, + total: 16, + human_only: false, + old_status: "failed", + stop: ReplayStop::Stall, + }, + Case { + name: "case-182", + group: "gate", + date: "2026-10-29", + cost_cents: 186, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-183", + group: "duplicate", + date: "2026-10-29", + cost_cents: 0, + done: 0, + total: 0, + human_only: true, + old_status: "covered_by_pr", + stop: ReplayStop::Asked(HumanOnly::HeldByAnother), + }, + Case { + name: "case-184", + group: "plan_coverage", + date: "2026-10-29", + cost_cents: 79, + done: 16, + total: 17, + human_only: false, + old_status: "retried", + stop: ReplayStop::Stall, + }, + Case { + name: "case-185", + group: "plan_coverage", + date: "2026-10-29", + cost_cents: 411, + done: 15, + total: 16, + human_only: false, + old_status: "failed", + stop: ReplayStop::Stall, + }, + Case { + name: "case-186", + group: "plan_coverage", + date: "2026-10-29", + cost_cents: 494, + done: 14, + total: 16, + human_only: false, + old_status: "retried", + stop: ReplayStop::Stall, + }, + Case { + name: "case-187", + group: "gate", + date: "2026-10-29", + cost_cents: 187, + done: 32, + total: 33, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-188", + group: "ci_red", + date: "2026-10-29", + cost_cents: 2369, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::RedCi, + }, + Case { + name: "case-189", + group: "gate", + date: "2026-10-29", + cost_cents: 0, + done: 15, + total: 15, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Errored, + }, + Case { + name: "case-190", + group: "fix_location", + date: "2026-10-29", + cost_cents: 98, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::AmbiguousTicket), + }, + Case { + name: "case-191", + group: "budget", + date: "2026-10-29", + cost_cents: 303, + done: 0, + total: 0, + human_only: false, + old_status: "failed", + stop: ReplayStop::OutOfTime, + }, + Case { + name: "case-192", + group: "own_review", + date: "2026-10-29", + cost_cents: 1677, + done: 0, + total: 0, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::OwnFindings, + }, + Case { + name: "case-193", + group: "silent_end", + date: "2026-11-02", + cost_cents: 28, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-194", + group: "silent_end", + date: "2026-11-02", + cost_cents: 34, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-195", + group: "gate", + date: "2026-11-02", + cost_cents: 93, + done: 11, + total: 11, + human_only: false, + old_status: "completed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-196", + group: "questions", + date: "2026-11-02", + cost_cents: 175, + done: 0, + total: 0, + human_only: true, + old_status: "needs_input", + stop: ReplayStop::Asked(HumanOnly::ProductDecision), + }, + Case { + name: "case-197", + group: "gate", + date: "2026-11-02", + cost_cents: 0, + done: 4, + total: 4, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-198", + group: "gate", + date: "2026-11-03", + cost_cents: 174, + done: 32, + total: 32, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-199", + group: "gate", + date: "2026-11-03", + cost_cents: 146, + done: 11, + total: 11, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-200", + group: "gate", + date: "2026-11-03", + cost_cents: 165, + done: 10, + total: 10, + human_only: false, + old_status: "failed", + stop: ReplayStop::Errored, + }, + Case { + name: "case-201", + group: "gate", + date: "2026-11-03", + cost_cents: 189, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-202", + group: "gate", + date: "2026-11-04", + cost_cents: 174, + done: 11, + total: 11, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-203", + group: "duplicate", + date: "2026-11-05", + cost_cents: 121, + done: 10, + total: 11, + human_only: true, + old_status: "covered_by_pr", + stop: ReplayStop::Asked(HumanOnly::HeldByAnother), + }, + Case { + name: "case-204", + group: "fix_location", + date: "2026-11-05", + cost_cents: 176, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Asked(HumanOnly::AmbiguousTicket), + }, + Case { + name: "case-205", + group: "no_change", + date: "2026-11-06", + cost_cents: 902, + done: 8, + total: 34, + human_only: false, + old_status: "retried", + stop: ReplayStop::Errored, + }, + Case { + name: "case-206", + group: "plan_coverage", + date: "2026-11-06", + cost_cents: 1670, + done: 23, + total: 38, + human_only: false, + old_status: "retried", + stop: ReplayStop::Stall, + }, + Case { + name: "case-207", + group: "ci_red", + date: "2026-11-09", + cost_cents: 943, + done: 0, + total: 0, + human_only: false, + old_status: "completed", + stop: ReplayStop::RedCi, + }, + Case { + name: "case-208", + group: "ci_red", + date: "2026-11-09", + cost_cents: 1024, + done: 5, + total: 5, + human_only: true, + old_status: "completed", + stop: ReplayStop::RedOnBase, + }, + Case { + name: "case-209", + group: "budget", + date: "2026-11-09", + cost_cents: 392, + done: 0, + total: 0, + human_only: false, + old_status: "retried", + stop: ReplayStop::Stall, + }, + Case { + name: "case-210", + group: "own_review", + date: "2026-11-10", + cost_cents: 934, + done: 37, + total: 38, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::OwnFindings, + }, + Case { + name: "case-211", + group: "questions", + date: "2026-11-10", + cost_cents: 609, + done: 7, + total: 7, + human_only: true, + old_status: "completed", + stop: ReplayStop::Asked(HumanOnly::ProductDecision), + }, + Case { + name: "case-212", + group: "plan_coverage", + date: "2026-11-11", + cost_cents: 376, + done: 7, + total: 8, + human_only: false, + old_status: "completed", + stop: ReplayStop::Stall, + }, + Case { + name: "case-213", + group: "ci_red", + date: "2026-11-11", + cost_cents: 425, + done: 8, + total: 8, + human_only: false, + old_status: "completed", + stop: ReplayStop::RedCi, + }, + Case { + name: "case-214", + group: "ci_red", + date: "2026-11-11", + cost_cents: 299, + done: 2, + total: 2, + human_only: true, + old_status: "completed", + stop: ReplayStop::RedOnBase, + }, + Case { + name: "case-215", + group: "ci_red", + date: "2026-11-11", + cost_cents: 586, + done: 12, + total: 12, + human_only: true, + old_status: "completed", + stop: ReplayStop::RedOnBase, + }, + Case { + name: "case-216", + group: "github_api", + date: "2026-11-12", + cost_cents: 725, + done: 24, + total: 24, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Errored, + }, + Case { + name: "case-217", + group: "model_output", + date: "2026-11-12", + cost_cents: 1095, + done: 8, + total: 9, + human_only: false, + old_status: "needs_input", + stop: ReplayStop::Stall, + }, +];