From 33b6a17bf561835c9233cb9d06ec03bcf3be5fda Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 30 Nov 2026 20:48:46 -0500 Subject: [PATCH] A hand-off to a person is typed, and CoderHelm owns its own limits A hand-off is a PersonOnly from a closed set (a named permission an owner or admin grants, a product decision, an approval the rules require, a credential, work someone else holds, a real-world action), built only through common::person_only. Words about CoderHelm's sandbox, allowlist, budgets, tools, CI use, labels, tests or reads make an OwnProblem instead: an internal alert and one run-page line. The person gate, hand-backs and a fix round's NEEDS A PERSON line all go through it. On its own pull request the reviewer blocks only on what a route can satisfy (review_feasible). A pull request with no progress for a day is diagnosed, retried along its next route and alerted (own_problems::check on the sweep). Hand-offs are counted per team by reason, own problems by subject, with the time each pull request spent blocked. Incident case xd_own_limits_never_a_persons. --- .../xd_own_limits_never_a_persons.md | 5 + services/common/src/handback.rs | 38 ++ services/common/src/lib.rs | 1 + services/common/src/person_gate.rs | 136 +++- services/common/src/person_only.rs | 636 ++++++++++++++++++ .../incidents/um_own_reads_never_handed.rs | 4 +- .../xd_own_limits_never_a_persons.rs | 183 +++++ services/worker/src/passes/mod.rs | 11 + services/worker/src/passes/own_problems.rs | 379 +++++++++++ .../worker/src/passes/own_review_ledger.rs | 29 +- services/worker/src/passes/person_gate.rs | 52 ++ services/worker/src/passes/pr_watch.rs | 1 + services/worker/src/passes/review_feasible.rs | 230 +++++++ services/worker/src/passes/review_pr.rs | 16 + services/worker/src/passes/settle.rs | 7 + 15 files changed, 1685 insertions(+), 43 deletions(-) create mode 100644 docs/incidents/xd_own_limits_never_a_persons.md create mode 100644 services/common/src/person_only.rs create mode 100644 services/worker/src/passes/incidents/xd_own_limits_never_a_persons.rs create mode 100644 services/worker/src/passes/own_problems.rs create mode 100644 services/worker/src/passes/review_feasible.rs diff --git a/docs/incidents/xd_own_limits_never_a_persons.md b/docs/incidents/xd_own_limits_never_a_persons.md new file mode 100644 index 000000000..062d2acd9 --- /dev/null +++ b/docs/incidents/xd_own_limits_never_a_persons.md @@ -0,0 +1,5 @@ +# xd. `xd_own_limits_never_a_persons` + +**What happened:** A fix run's own review asked for one proof: run the fixed end-to-end test twenty times. The fix round couldn't, because CoderHelm's own sandbox couldn't reach the sites the test runs against. It ended with "NEEDS A PERSON ... outside_reach", asking someone to widen CoderHelm's own network allowlist or run the command themselves. It called a repeat run in CI "outside this ticket". CoderHelm doesn't merge over its own review, so the pull request sat with nothing moving it. The same shape came back from other limits CoderHelm owns: its time budget, its tools, a workflow's triggers it hadn't read, and a proof its review asked for that none of its routes could run. + +**The guarantee:** A hand-off to a person is a typed value (`common::person_only::PersonOnly`) from a closed set: a named permission an owner or admin grants, a product decision, an approval the repository's or team's rules require, a credential only the person holds, work someone else holds, or a real-world action. Its text is private to the module, and no variant covers CoderHelm's sandbox, network allowlist, budgets, tools, CI use, labels, tests or reads. Every written hand-off goes through one parser (`person_only::parse`, `of_reason`, `of_human_only`): the person gate's items, a fix round's `NEEDS A PERSON` line, and hand-backs. A limit CoderHelm owns comes back as an `OwnProblem`. That becomes an internal alert for CoderHelm's maintainers and one plain line on the run page, and the work goes on by another route. On its own pull request, CoderHelm's reviewer blocks only on what one of its routes can satisfy: an edit, a sandbox run, CI, or a page check. Anything else becomes one question or CoderHelm's own note (`review_feasible`). A pull request with no progress for a day gets a self-diagnosis, a retry along its next route and an internal alert (`own_problems::check`, on the 15-minute sweep). The team's hand-offs are counted by reason, its own problems by subject, along with the time each pull request spent blocked. diff --git a/services/common/src/handback.rs b/services/common/src/handback.rs index f28f433d3..5be10b37e 100644 --- a/services/common/src/handback.rs +++ b/services/common/src/handback.rs @@ -109,8 +109,14 @@ pub struct HandBack { impl HandBack { /// `None` without a need: a hand-back says exactly what is needed. + /// `None` too when the need names a limit CoderHelm owns (its sandbox, + /// allowlist, budgets, tools, CI usage, labels, tests or reads, + /// `person_only::own_subject`): that is never a person's. pub fn new(why: HumanOnly, need: &str) -> Option { let n = need.split_whitespace().collect::>().join(" "); + if !n.is_empty() && typed(why) && crate::person_only::of_human_only(why, &n).is_err() { + return None; + } (!n.is_empty()).then(|| HandBack { why, need: crate::truncate_str(&n, 600).to_string(), @@ -170,6 +176,21 @@ impl HandBack { } } +/// Reasons whose need is something a person is asked for (and so goes +/// through `person_only`). The others record what already happened (a +/// person's action, the usage limit, another holder) or are the recovery +/// ladder's own end (`Unrepaired`). +fn typed(why: HumanOnly) -> bool { + matches!( + why, + HumanOnly::Credential + | HumanOnly::MissingAccess + | HumanOnly::ProductDecision + | HumanOnly::AmbiguousTicket + | HumanOnly::Approval + ) +} + /// 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, and for a read the team's @@ -179,6 +200,11 @@ pub fn human_only_in(text: &str) -> Option { if crate::aws_role_reads::is_install_grant(text) { return None; } + // Words about CoderHelm's own limits name no reason, whatever else they + // say ("grant access ... to CoderHelm's sandbox allowlist"). + if crate::person_only::own_subject(text).is_some() { + return None; + } let t = text.to_lowercase(); let any = |marks: &[&str]| marks.iter().any(|m| t.contains(m)); if any(&[ @@ -273,6 +299,18 @@ mod tests { ); } + #[test] + fn coderhelms_own_limits_are_never_a_hand_back() { + for t in [ + "Grant access: add staging.acme-books.example to CoderHelm's sandbox network allowlist", + "No access to the preview from the sandbox: net::ERR_TUNNEL_CONNECTION_FAILED", + "The e2e workflow has no repeat input; run the test 20 times yourself", + ] { + assert_eq!(human_only_in(t), None, "{t}"); + assert!(HandBack::new(HumanOnly::MissingAccess, t).is_none(), "{t}"); + } + } + #[test] fn a_read_the_aws_role_lacks_is_the_install_item_never_a_wait() { let asked = "Grant access: the team's read-only role was denied wafv2:ListWebACLs and \ diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index abd934fb7..ae37b97a1 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -323,6 +323,7 @@ pub mod person_gate; /// A person's lines on a CoderHelm branch stay theirs: writes that would undo them are /// kept out. pub mod person_lines; +pub mod person_only; /// Plugins: packages of skills, agents, tools, triggers and outputs a team installs. pub mod plugins; /// One shape for "something is wrong": set by a check, cleared by the same diff --git a/services/common/src/person_gate.rs b/services/common/src/person_gate.rs index 352cc2633..5d688d699 100644 --- a/services/common/src/person_gate.rs +++ b/services/common/src/person_gate.rs @@ -237,6 +237,10 @@ pub enum Work { Command(String), /// Its own step, as written (a query to run, a list to post). Own(String), + /// A limit CoderHelm owns that a writer tried to hand a person + /// (`person_only`): CoderHelm takes another route, its maintainers get + /// an internal alert, and the run page says so in one line. + Problem(crate::person_only::OwnProblem), } impl Work { @@ -251,6 +255,7 @@ impl Work { ), Work::Command(c) => format!("ran `{c}` in its sandbox"), Work::Own(w) => w.clone(), + Work::Problem(p) => p.line(), } } } @@ -287,6 +292,9 @@ impl Decision { #[derive(Debug, Clone, PartialEq, Eq)] pub struct HumanItem { reason: Reason, + /// The typed hand-off it stands for (`person_only`): a `HumanItem` + /// exists only for one. + person: crate::person_only::PersonOnly, action: String, who: String, why_not: String, @@ -298,6 +306,9 @@ impl HumanItem { pub fn reason(&self) -> Reason { self.reason } + pub fn person(&self) -> &crate::person_only::PersonOnly { + &self.person + } pub fn action(&self) -> &str { &self.action } @@ -823,7 +834,7 @@ fn reason_named(t: &str) -> Option { /// A step that spends real money: "paid" before an action a customer /// takes (a paid checkout, registration, booking, order), or a purchase /// made for real. No sandbox or test card stands in for one. -fn paid_action(t: &str) -> bool { +pub(crate) fn paid_action(t: &str) -> bool { const ACTIONS: &[&str] = &[ "checkout", "registration", @@ -1010,16 +1021,14 @@ pub fn decide(a: &Ask, ctx: &Context) -> Outcome { return deploy_item(a, &t, ctx); } return match reason_in(&cause) { - Some(reason @ (Reason::Grant | Reason::Credential | Reason::Approval)) => { - Outcome::Human(HumanItem { - reason, - action: first_nonempty(&a.how, &a.text), - who: who_for(reason, &a.owner), - why_not: first_nonempty(&a.why_not, reason.label()), - options: Vec::new(), - recommendation: String::new(), - }) - } + Some(reason @ (Reason::Grant | Reason::Credential | Reason::Approval)) => human( + reason, + first_nonempty(&a.how, &a.text), + who_for(reason, &a.owner), + first_nonempty(&a.why_not, reason.label()), + Vec::new(), + String::new(), + ), _ => Outcome::Do(Work::Own(one_line(&a.text))), }; } @@ -1043,14 +1052,14 @@ pub fn decide(a: &Ask, ctx: &Context) -> Outcome { } // 2. A listed reason the item itself names. if let Some(reason) = reason_in(&t) { - return Outcome::Human(HumanItem { + return human( reason, - action: first_nonempty(&a.how, &a.text), - who: who_for(reason, &a.owner), - why_not: first_nonempty(&a.why_not, reason.label()), - options: Vec::new(), - recommendation: String::new(), - }); + first_nonempty(&a.how, &a.text), + who_for(reason, &a.owner), + first_nonempty(&a.why_not, reason.label()), + Vec::new(), + String::new(), + ); } // 3. A choice: settled by a source, else decided, else (hard to // reverse, nothing settles it) one yes/no on the recommendation. @@ -1085,14 +1094,14 @@ pub fn decide(a: &Ask, ctx: &Context) -> Outcome { if options.is_empty() { options = vec![rec.clone(), "leaving it out".to_string()]; } - return Outcome::Human(HumanItem { - reason: Reason::Irreversible, - action: format!("Yes or no: {}", trim_end(&strip_question_marks(&a.text))), - who: who_for(Reason::Irreversible, &a.owner), - why_not: Reason::Irreversible.label().to_string(), + return human( + Reason::Irreversible, + format!("Yes or no: {}", trim_end(&strip_question_marks(&a.text))), + who_for(Reason::Irreversible, &a.owner), + Reason::Irreversible.label().to_string(), options, - recommendation: rec, - }); + rec, + ); } let chose = first_nonempty(&recommendation_of(a), &a.text); return Outcome::Decided(Decision { @@ -1143,14 +1152,14 @@ fn deploy_item(a: &Ask, t: &str, ctx: &Context) -> Outcome { } (m, _) => sentence_start(m), }; - Outcome::Human(HumanItem { + human( reason, action, - who: who_for(reason, &a.owner), - why_not: first_nonempty(&a.why_not, reason.label()), - options: Vec::new(), - recommendation: String::new(), - }) + who_for(reason, &a.owner), + first_nonempty(&a.why_not, reason.label()), + Vec::new(), + String::new(), + ) } impl Ask { @@ -1197,16 +1206,57 @@ pub fn for_reason(why: HumanOnly, a: &Ask) -> Option { HumanOnly::Approval => Reason::Approval, _ => return None, }; - Some(HumanItem { + human_item( + reason, + first_nonempty(&a.how, &a.text), + who_for(reason, &a.owner), + first_nonempty(&a.why_not, reason.label()), + Vec::new(), + String::new(), + ) + .ok() +} + +/// The one way a [`HumanItem`] is made: from a typed hand-off +/// (`person_only::of_reason`) for its reason and words. Words about +/// CoderHelm's own limits (its sandbox, allowlist, budgets, tools, CI +/// usage, labels, tests, reads) make no hand-off: they are its own problem. +fn human_item( + reason: Reason, + action: String, + who: String, + why_not: String, + options: Vec, + recommendation: String, +) -> Result { + let person = crate::person_only::of_reason(reason, &format!("{action}. {why_not}"))?; + Ok(HumanItem { reason, - action: first_nonempty(&a.how, &a.text), - who: who_for(reason, &a.owner), - why_not: first_nonempty(&a.why_not, reason.label()), - options: Vec::new(), - recommendation: String::new(), + person, + action, + who, + why_not, + options, + recommendation, }) } +/// [`human_item`] as the gate's outcome: an item for a person, or +/// CoderHelm's own problem ([`Work::Problem`]). +fn human( + reason: Reason, + action: String, + who: String, + why_not: String, + options: Vec, + recommendation: String, +) -> Outcome { + match human_item(reason, action, who, why_not, options, recommendation) { + Ok(h) => Outcome::Human(h), + Err(p) => Outcome::Do(Work::Problem(p)), + } +} + /// The stable key of an item's decision: its kind and topic, or its /// content words when it has no topic. pub fn key(a: &Ask) -> String { @@ -1259,6 +1309,18 @@ impl Gated { .collect() } + /// CoderHelm's own problems a writer tried to hand a person + /// (`person_only`): each is an internal alert and one run-page line. + pub fn problems(&self) -> Vec<&crate::person_only::OwnProblem> { + self.items + .iter() + .filter_map(|(_, o)| match o { + Outcome::Do(Work::Problem(p)) => Some(p), + _ => None, + }) + .collect() + } + /// What CoderHelm does itself. pub fn work(&self) -> Vec<&Work> { self.items diff --git a/services/common/src/person_only.rs b/services/common/src/person_only.rs new file mode 100644 index 000000000..d2e9f2c36 --- /dev/null +++ b/services/common/src/person_only.rs @@ -0,0 +1,636 @@ +//! The typed hand-off: the only value that lets CoderHelm hand work to a +//! person. +//! +//! A fix round once ended "NEEDS A PERSON ... outside_reach: add the hosts to +//! CoderHelm's sandbox network allowlist, or run the command yourself", and +//! its pull request sat for days. The same shape came back from other +//! limits CoderHelm owns itself: its time budget, its tools, a workflow's +//! triggers it hadn't read, a proof its own review asked for. Each time the +//! default was to stop and hand the job to a person. +//! +//! [`PersonOnly`] is a closed set of things only a person has. Every variant +//! carries the exact named thing (the permission, the secret, the rule, the +//! question) as a [`Named`], whose text field is private: a `Named` is made +//! only by this module, after [`own_subject`] found nothing of CoderHelm's +//! own in it. There is no variant for CoderHelm's sandbox, its network +//! allowlist, its budgets or time, its tools, its use of CI (repeats, +//! reruns, dispatches), labels, tests or reads, so a hand-off about any of +//! them can't be built: +//! +//! ```compile_fail +//! use common::person_only::{Named, PersonOnly}; +//! // The text field is private: a hand-off can't be built from loose words. +//! let p = PersonOnly::Credential { secret: Named("add the hosts to the allowlist".into()) }; +//! ``` +//! +//! Free text (a model's `NEEDS A PERSON` line, a gate reason code, an +//! outside step) goes through [`parse`] or [`admit`], which return +//! `Result`. An [`OwnProblem`] is CoderHelm's: the +//! caller tries its other routes, records an internal alert for CoderHelm's +//! maintainers and writes one plain line on the run page +//! ([`OwnProblem::line`]). It never reaches a person as a to-do. + +use std::fmt; + +/// Who grants a permission only a person can grant. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Grantor { + /// The GitHub organization's owner. + OrgOwner, + /// The repository's admin. + RepoAdmin, + /// The team's admin in CoderHelm's settings (a connection, a role). + TeamAdmin, +} + +impl Grantor { + pub fn words(self) -> &'static str { + match self { + Grantor::OrgOwner => "an organization owner", + Grantor::RepoAdmin => "a repository admin", + Grantor::TeamAdmin => "a team admin", + } + } +} + +/// The exact thing a person is asked for, in one line. Made only here, +/// after [`own_subject`] found nothing CoderHelm owns in it. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Named(String); + +impl Named { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for Named { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +/// The only things a person is handed. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum PersonOnly { + /// A permission only an owner or admin can grant, named (`actions: + /// write on the GitHub App`, `connect the ticket tracker`). + Grant { permission: Named, by: Grantor }, + /// A product or business decision nothing settles: one yes/no question. + ProductDecision { question: Named }, + /// An approval the repository's or team's own rules require, named. + Approval { rule: Named }, + /// A credential only the person holds, named. + Credential { secret: Named }, + /// Someone else already holds the work: CoderHelm waits on them. + HeldByAnother { holder: Named }, + /// An action in the physical or paying world (a purchase with real + /// money, a real device), named. + RealWorld { action: Named }, +} + +/// What kind of hand-off a writer asks for, before its words are checked. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Want { + Grant(Grantor), + ProductDecision, + Approval, + Credential, + HeldByAnother, + RealWorld, +} + +impl PersonOnly { + /// The reason code kept on the run and in the team's counts. + pub fn code(&self) -> &'static str { + match self { + PersonOnly::Grant { .. } => "grant", + PersonOnly::ProductDecision { .. } => "product_decision", + PersonOnly::Approval { .. } => "approval", + PersonOnly::Credential { .. } => "credential", + PersonOnly::HeldByAnother { .. } => "held_by_another", + PersonOnly::RealWorld { .. } => "real_world", + } + } + + /// The named thing. + pub fn named(&self) -> &Named { + match self { + PersonOnly::Grant { permission: n, .. } + | PersonOnly::ProductDecision { question: n } + | PersonOnly::Approval { rule: n } + | PersonOnly::Credential { secret: n } + | PersonOnly::HeldByAnother { holder: n } + | PersonOnly::RealWorld { action: n } => n, + } + } + + /// One line a person reads: who, and exactly what. + pub fn line(&self) -> String { + match self { + PersonOnly::Grant { permission, by } => { + format!("Needs {} to grant: {permission}", by.words()) + } + PersonOnly::ProductDecision { question } => format!("Your call: {question}"), + PersonOnly::Approval { rule } => { + format!("Needs the approval your rules require: {rule}") + } + PersonOnly::Credential { secret } => { + format!("Needs a credential only you hold: {secret}") + } + PersonOnly::HeldByAnother { holder } => format!("Held by someone else: {holder}"), + PersonOnly::RealWorld { action } => { + format!("Needs a person in the real world: {action}") + } + } + } +} + +/// What CoderHelm owns itself: never a person's to-do. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum OwnSubject { + /// Its sandbox: a browser, a package, a build that won't start there. + Sandbox, + /// Its sandbox's network allowlist. + Egress, + /// Its own time, turns, spend or round budgets. + Budget, + /// A tool it lacks or that failed. + Tooling, + /// Its use of CI: repeats, reruns, dispatches, a workflow's inputs. + CiUsage, + /// Labels on its pull request. + Labels, + /// Running tests, suites or end-to-end checks. + Testing, + /// Reading a log, a result, an artifact or a page. + Reads, + /// Words that name no reason a person has: CoderHelm finds another + /// route. + Unnamed, +} + +/// Every CoderHelm-owned subject. +pub const OWN_SUBJECTS: &[OwnSubject] = &[ + OwnSubject::Sandbox, + OwnSubject::Egress, + OwnSubject::Budget, + OwnSubject::Tooling, + OwnSubject::CiUsage, + OwnSubject::Labels, + OwnSubject::Testing, + OwnSubject::Reads, + OwnSubject::Unnamed, +]; + +impl OwnSubject { + pub fn code(self) -> &'static str { + match self { + OwnSubject::Sandbox => "sandbox", + OwnSubject::Egress => "egress", + OwnSubject::Budget => "budget", + OwnSubject::Tooling => "tooling", + OwnSubject::CiUsage => "ci_usage", + OwnSubject::Labels => "labels", + OwnSubject::Testing => "testing", + OwnSubject::Reads => "reads", + OwnSubject::Unnamed => "unnamed", + } + } + + fn words(self) -> &'static str { + match self { + OwnSubject::Sandbox => "its sandbox", + OwnSubject::Egress => "its sandbox's network allowlist", + OwnSubject::Budget => "its own time or budget", + OwnSubject::Tooling => "its tools", + OwnSubject::CiUsage => "how it runs CI", + OwnSubject::Labels => "labels on its pull request", + OwnSubject::Testing => "running the tests", + OwnSubject::Reads => "reading a result", + OwnSubject::Unnamed => "a step it has no route for yet", + } + } +} + +/// A limit CoderHelm owns, met while it worked: tried another way, sent to +/// CoderHelm's maintainers as an internal alert, and said on the run page +/// in one plain line. Never a person's step. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OwnProblem { + pub subject: OwnSubject, + /// The writer's words, one line. + pub text: String, +} + +impl OwnProblem { + /// The run page's one line. + pub fn line(&self) -> String { + format!( + "CoderHelm met a limit in {} and is taking another route; its maintainers were alerted: {}", + self.subject.words(), + crate::truncate_str(&self.text, 240) + ) + } +} + +fn one_line(s: &str) -> String { + s.split_whitespace().collect::>().join(" ") +} + +fn any(t: &str, marks: &[&str]) -> bool { + marks.iter().any(|m| t.contains(m)) +} + +/// A refusal GitHub sent on a named API, recorded with the permission it +/// needs: a permission a person grants, whatever CI words come with it. +fn recorded_refusal(t: &str) -> bool { + !t.contains(&crate::github_grants::INSTALL_LEVEL.to_lowercase()) + && crate::github_grants::Denial::parse(t).is_some() +} + +/// The CoderHelm-owned subject the words name, if any. +pub fn own_subject(text: &str) -> Option { + let t = one_line(text).to_lowercase(); + if t.is_empty() { + return Some(OwnSubject::Unnamed); + } + if any( + &t, + &[ + "allowlist", + "allow list", + "egress", + "err_tunnel_connection_failed", + "coderhelm_egress_blocked", + ], + ) { + return Some(OwnSubject::Egress); + } + if crate::stop_rules::tooling::names_own_tooling(&t) { + return Some(OwnSubject::Sandbox); + } + if any( + &t, + &[ + "time budget", + "time limit", + "step's time", + "ran out of time", + "spend cap", + "spend ceiling", + "fix budget", + "its budget", + "turn limit", + "fix rounds", + "out of turns", + ], + ) { + return Some(OwnSubject::Budget); + } + if any( + &t, + &[ + // A tool missing in its sandbox; never "the app isn't + // installed" on a repository, which is a person's grant. + "isn't installed in", + "is not installed in", + "command not found", + "missing tool", + "a tool failed", + "tool error", + ], + ) { + return Some(OwnSubject::Tooling); + } + // A recorded refusal names a real permission, even about a workflow. + if recorded_refusal(&t) { + return None; + } + if any( + &t, + &[ + "repeat-each", + "repeat run", + "repeat input", + "repeat_each", + "repeats", + "re-run the", + "rerun the", + "dispatch the", + "a ci change", + "outside this ticket", + "run the workflow", + "start the workflow", + ], + ) { + return Some(OwnSubject::CiUsage); + } + if any( + &t, + &[ + "add the label", + "add a label", + "add labels", + "label the pull request", + ], + ) && !t.contains("deploy") + { + return Some(OwnSubject::Labels); + } + if any( + &t, + &[ + "run the test", + "run the e2e", + "run the end-to-end", + "run the suite", + "run playwright", + "npx playwright", + "npx cypress", + "yourself", + ], + ) { + return Some(OwnSubject::Testing); + } + if crate::stop_rules::tooling::names_own_read(&t) { + return Some(OwnSubject::Reads); + } + None +} + +/// The hand-off `want` asks for, if its words name nothing CoderHelm owns. +pub fn admit(want: Want, text: &str) -> Result { + let line = one_line(text); + if let Some(subject) = own_subject(&line) { + return Err(OwnProblem { + subject, + text: line, + }); + } + let n = Named(crate::truncate_str(&line, 600).to_string()); + Ok(match want { + Want::Grant(by) => PersonOnly::Grant { permission: n, by }, + Want::ProductDecision => PersonOnly::ProductDecision { question: n }, + Want::Approval => PersonOnly::Approval { rule: n }, + Want::Credential => PersonOnly::Credential { secret: n }, + Want::HeldByAnother => PersonOnly::HeldByAnother { holder: n }, + Want::RealWorld => PersonOnly::RealWorld { action: n }, + }) +} + +/// A gate reason (`person_gate::Reason`) with the item's words. The +/// catch-all "outside every system" is a person's only when the words name +/// a real-world action (real money, a real device); else it is CoderHelm's +/// to find a route for. +pub fn of_reason(reason: crate::person_gate::Reason, text: &str) -> Result { + use crate::person_gate::Reason as R; + let t = text.to_lowercase(); + let want = match reason { + R::Credential => Want::Credential, + R::Grant => Want::Grant(grantor_in(&t)), + R::Irreversible => Want::ProductDecision, + R::HeldByAnother => Want::HeldByAnother, + R::Approval => Want::Approval, + R::OutsideReach if real_world(&t) => Want::RealWorld, + R::OutsideReach => match want_in(&t) { + Some(w) => w, + None => { + return Err(OwnProblem { + subject: own_subject(&t).unwrap_or(OwnSubject::Unnamed), + text: one_line(text), + }) + } + }, + }; + admit(want, text) +} + +/// A hand-back reason (`handback::HumanOnly`) with its need. +pub fn of_human_only( + why: crate::handback::HumanOnly, + need: &str, +) -> Result { + use crate::handback::HumanOnly as H; + let t = need.to_lowercase(); + let want = match why { + H::Credential => Want::Credential, + H::MissingAccess => Want::Grant(grantor_in(&t)), + H::ProductDecision | H::AmbiguousTicket => Want::ProductDecision, + H::HeldByAnother | H::PersonAction => Want::HeldByAnother, + H::Approval | H::UsageLimit => Want::Approval, + // An error CoderHelm couldn't get past is its own problem. + H::Unrepaired => { + return Err(OwnProblem { + subject: own_subject(&t).unwrap_or(OwnSubject::Unnamed), + text: one_line(need), + }) + } + }; + admit(want, need) +} + +/// A model's line ` :: ` (the fix +/// round's `NEEDS A PERSON` line): the one parser for written hand-offs. +pub fn parse(code: &str, what: &str) -> Result { + let reason = crate::person_gate::REASONS + .iter() + .copied() + .find(|r| r.code() == code.trim()); + match reason { + Some(r) => of_reason(r, what), + None => match want_in(&what.to_lowercase()) { + Some(w) => admit(w, what), + None => Err(OwnProblem { + subject: own_subject(what).unwrap_or(OwnSubject::Unnamed), + text: one_line(what), + }), + }, + } +} + +/// What a person must do that words ask for outright ("only an org owner +/// can grant ...", "needs the production credentials", "a manual check on a +/// real device"), as a typed hand-off. `None` when they ask nothing only a +/// person has, or name a CoderHelm-owned subject. +pub fn person_need_in(text: &str) -> Option { + let t = one_line(text).to_lowercase(); + let asks = any( + &t, + &[ + "only a person", + "a person must", + "needs a person", + "needs someone", + "only an org owner", + "only an organization owner", + "only an admin", + "an admin must", + "requires approval", + "needs approval", + "credentials only", + "credentials to", + "access to production", + "manual check on a real device", + "real device", + "product decision", + "business decision", + ], + ); + if !asks { + return None; + } + admit(want_in(&t)?, text).ok() +} + +fn real_world(t: &str) -> bool { + crate::person_gate::paid_action(t) + || any( + t, + &[ + "physical device", + "real device", + "real-device", + "in person", + "phone call", + "by phone", + "on site", + ], + ) +} + +fn grantor_in(t: &str) -> Grantor { + if any( + t, + &["org owner", "organization owner", "organisation owner"], + ) { + Grantor::OrgOwner + } else if any(t, &["settings", "connect ", "team admin"]) { + Grantor::TeamAdmin + } else { + Grantor::RepoAdmin + } +} + +/// The kind of hand-off plain words ask for, when they name one. +fn want_in(t: &str) -> Option { + if any(t, &["api key", "secret", "token", "password", "credential"]) { + return Some(Want::Credential); + } + if recorded_refusal(t) + || any( + t, + &[ + "org owner", + "organization owner", + "repository admin", + "grant the app", + "not turned on", + "app isn't installed", + "connect ", + ], + ) + { + return Some(Want::Grant(grantor_in(t))); + } + if any( + t, + &["product decision", "business decision", "product choice"], + ) { + return Some(Want::ProductDecision); + } + if any(t, &["approv"]) && any(t, &["policy", "rule", "codeowners", "required review"]) { + return Some(Want::Approval); + } + if real_world(t) { + return Some(Want::RealWorld); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::person_gate::Reason; + + /// Words about CoderHelm's own limits, as fix rounds and passes wrote + /// them (invented: the acme bookstore). + pub(crate) const OWN: &[&str] = &[ + "Add staging.acme-books.example and *.preview-web.acme-books.example to CoderHelm's sandbox network allowlist, or run the command yourself", + "The sandbox's network allowlist blocks the preview", + "net::ERR_TUNNEL_CONNECTION_FAILED on every repeat run", + "The e2e workflow runs each test once and has no repeat input; adding one would be a CI change outside this ticket", + "Run `npx playwright test tests/cart.spec.ts --repeat-each=20` yourself", + "The step reached its time limit before the repeat run finished", + "CoderHelm's fix budget for this run is spent", + "`terraform` isn't installed in CoderHelm's sandbox", + "Add the label run-e2e to the pull request", + "Re-run the end-to-end workflow on the head", + "Read the end-to-end result in the workflow's log", + ]; + + #[test] + fn coderhelms_own_limits_never_become_a_person_hand_off() { + for t in OWN { + assert!(own_subject(t).is_some(), "{t}"); + for r in crate::person_gate::REASONS { + assert!(of_reason(*r, t).is_err(), "{:?}: {t}", r); + } + for w in [ + Want::Grant(Grantor::OrgOwner), + Want::ProductDecision, + Want::Approval, + Want::Credential, + Want::HeldByAnother, + Want::RealWorld, + ] { + assert!(admit(w, t).is_err(), "{:?}: {t}", w); + } + assert!(parse("outside_reach", t).is_err(), "{t}"); + } + } + + #[test] + fn what_only_a_person_has_is_named_exactly() { + let p = parse( + "credential", + "Add the BOOKSTORE_PAYMENTS_KEY secret in the repository's settings", + ) + .unwrap(); + assert_eq!(p.code(), "credential"); + assert!(p.line().contains("BOOKSTORE_PAYMENTS_KEY")); + let g = of_reason( + Reason::Grant, + "An organization owner grants the CoderHelm app access to the catalog repository", + ) + .unwrap(); + assert!(matches!( + g, + PersonOnly::Grant { + by: Grantor::OrgOwner, + .. + } + )); + let paid = of_reason(Reason::OutsideReach, "complete a purchase on the preview").unwrap(); + assert_eq!(paid.code(), "real_world"); + } + + #[test] + fn outside_reach_with_no_named_reason_is_coderhelms() { + let e = parse("outside_reach", "Ask someone to look at the cart page").unwrap_err(); + assert_eq!(e.subject, OwnSubject::Unnamed); + assert!(e.line().contains("maintainers were alerted")); + // An unknown code with no named reason is CoderHelm's too. + assert!(parse("nonsense", "do the thing").is_err()); + } + + #[test] + fn an_unrepaired_error_is_coderhelms_own_problem() { + assert!(of_human_only(crate::handback::HumanOnly::Unrepaired, "the build fails").is_err()); + assert!(of_human_only( + crate::handback::HumanOnly::Credential, + "the API key for the shipping sandbox" + ) + .is_ok()); + } +} diff --git a/services/worker/src/passes/incidents/um_own_reads_never_handed.rs b/services/worker/src/passes/incidents/um_own_reads_never_handed.rs index 00d3341b5..1dafe573d 100644 --- a/services/worker/src/passes/incidents/um_own_reads_never_handed.rs +++ b/services/worker/src/passes/incidents/um_own_reads_never_handed.rs @@ -58,5 +58,7 @@ fn the_plan_and_the_review_ledger_keep_reads_as_coderhelms() { let plan = include_str!("../outside_work.rs"); assert!(plan.contains("names_own_read(&t)")); let ledger = include_str!("../own_review_ledger.rs"); - assert!(ledger.contains("tooling::names_own_read(&what)")); + // Read through the one hand-off parser, which counts reads as + // CoderHelm's own (`person_only::own_subject`). + assert!(ledger.contains("common::person_only::parse(&code, &what)")); } diff --git a/services/worker/src/passes/incidents/xd_own_limits_never_a_persons.rs b/services/worker/src/passes/incidents/xd_own_limits_never_a_persons.rs new file mode 100644 index 000000000..e4e7ce9b5 --- /dev/null +++ b/services/worker/src/passes/incidents/xd_own_limits_never_a_persons.rs @@ -0,0 +1,183 @@ +//! xd. A fix run for the acme bookstore's flaky checkout test opened its +//! pull request, and CoderHelm's own review asked for twenty repeat runs. +//! The fix round couldn't run them: CoderHelm's sandbox couldn't reach the +//! bookstore's staging site or the pull request's preview. It wrote +//! "NEEDS A PERSON ... outside_reach :: add the hosts to CoderHelm's +//! sandbox network allowlist, or run the command yourself", and called a +//! repeat input on CI "a CI change outside this ticket". CoderHelm does not +//! merge over its own review, so the pull request sat. +//! +//! Guarantee: a hand-off is a typed `PersonOnly` from a closed set, made +//! only through `person_only`. A limit CoderHelm owns is an `OwnProblem`: +//! an internal alert and one run-page line, never a person's step. Its own +//! reviewer blocks only on what a route it has can satisfy, a quiet pull +//! request is diagnosed and retried after a day, and hand-offs are counted +//! by reason. + +use common::person_gate::{self, Ask, Context, Kind, Outcome}; +use common::person_only::{self, OwnSubject, PersonOnly}; + +use crate::passes::own_review_ledger::{Blocker, Ledger, NEEDS_A_PERSON}; + +const FINDING: &str = + "Fix is unproven: no repeat run shows the checkout spec passes (`tests/checkout.spec.ts:12`)"; + +/// What the fix round and its passes wrote, invented for the bookstore. +const OWN_WORDS: &[&str] = &[ + "Add staging.acme-books.example and *.preview-shop.acme-books.example to CoderHelm's sandbox network allowlist, or run `npx playwright test tests/checkout.spec.ts --repeat-each=20 --retries=0` yourself", + "The e2e workflow runs each test once and has no repeat input; adding one would be a CI change outside this ticket", + "The step reached its time limit before the repeat run finished", + "`playwright` isn't installed in CoderHelm's sandbox", +]; + +#[test] +fn the_fix_rounds_hand_off_is_coderhelms_own_block() { + let mut l = Ledger::default(); + l.observe(&[FINDING.to_string()], ""); + l.start_round(&[FINDING.to_string()]); + l.end_round( + Vec::new(), + &format!( + "Every attempt failed before the page loaded.\n{NEEDS_A_PERSON} {FINDING} :: outside_reach :: {}", + OWN_WORDS[0] + ), + ); + l.observe(&[FINDING.to_string()], ""); + // Said as CoderHelm's own problem (an internal alert and one run-page + // line) when the round ends. + let account = format!( + "{NEEDS_A_PERSON} {FINDING} :: outside_reach :: {}", + OWN_WORDS[0] + ); + let own = crate::passes::own_review_ledger::own_problems_in(&account); + assert_eq!(own.len(), 1); + assert_eq!(own[0].subject, OwnSubject::Egress); + let t = &l.findings[0]; + assert_eq!(t.person_claims, 0, "no person claim was counted"); + assert!(t.person_reason.is_empty()); + assert_eq!(t.last_blocked, vec![Blocker::Tooling]); +} + +#[test] +fn no_coderhelm_owned_limit_ever_reaches_a_person() { + for w in OWN_WORDS { + assert!(person_only::own_subject(w).is_some(), "{w}"); + assert!(person_only::parse("outside_reach", w).is_err(), "{w}"); + for kind in [ + Kind::Assumption, + Kind::OpenItem, + Kind::Step, + Kind::Question, + Kind::Attempt, + ] { + let mut a = Ask::new(kind, w); + a.why_not = "outside_reach: it is outside every system CoderHelm reaches".into(); + let o = person_gate::decide(&a, &Context::default()); + assert!(!matches!(o, Outcome::Human(_)), "{kind:?}: {w}"); + } + assert_eq!(common::handback::human_only_in(w), None, "{w}"); + assert!( + common::handback::HandBack::new(common::handback::HumanOnly::MissingAccess, w) + .is_none(), + "{w}" + ); + } + // Written as a hand-off, it becomes CoderHelm's own problem with its + // run-page line, and it is counted by subject, not as a person's. + let g = person_gate::gate( + vec![Ask::new( + Kind::Step, + "Only a person can add staging.acme-books.example to CoderHelm's sandbox network allowlist (outside every system CoderHelm reaches)", + )], + &Context::default(), + ); + assert!(g.human().is_empty()); + let counts = crate::passes::own_problems::handoff_counts(&g); + assert!(counts.iter().all(|(k, _)| !k.starts_with("person_"))); + if let Some(p) = g.problems().first() { + assert_eq!(p.subject, OwnSubject::Egress); + assert!(p.line().contains("maintainers were alerted")); + } +} + +#[test] +fn what_only_a_person_has_still_reaches_them_named() { + let p = person_only::parse( + "credential", + "Add the ACME_BOOKS_PAYMENTS_KEY secret in the repository's Actions secrets", + ) + .unwrap(); + assert!(matches!(p, PersonOnly::Credential { .. })); + assert!(p.line().contains("ACME_BOOKS_PAYMENTS_KEY")); + let g = person_gate::gate( + vec![Ask::new( + Kind::OpenItem, + "Add the ACME_BOOKS_PAYMENTS_KEY secret: a credential only a person can provide", + )], + &Context::default(), + ); + let h = g.human(); + assert_eq!(h.len(), 1); + assert_eq!(h[0].person().code(), "credential"); + let counts = crate::passes::own_problems::handoff_counts(&g); + assert_eq!(counts, vec![("person_credential".to_string(), 1)]); +} + +#[test] +fn its_own_review_blocks_only_on_what_a_route_can_satisfy() { + use crate::passes::review_agent::Finding; + use crate::passes::review_feasible::{apply, check, Available}; + let proof = Finding { + file: "tests/checkout.spec.ts".into(), + line: 12, + severity: "blocking".into(), + category: "testing".into(), + title: "Fix is unproven".into(), + body: "Prove it with 20 repeat runs (`--repeat-each=20 --retries=0`).".into(), + evidence: Some("verified-defect".into()), + ..Default::default() + }; + // CI is a route even when the sandbox can't reach the sites: a block. + assert_eq!( + check( + &proof, + &Available { + sandbox: false, + ci: true + } + ), + None + ); + // No route at all: CoderHelm's own gap, never a block. + let mut v = vec![proof]; + let (_, gaps) = apply( + &mut v, + &Available { + sandbox: false, + ci: false, + }, + ); + assert_eq!(gaps.len(), 1); + assert!(!v[0].holds_merge()); + // The reviewer calls the check on CoderHelm's own pull request. + let src = include_str!("../review_pr.rs"); + assert!(src.contains("super::review_feasible::apply(&mut findings, &avail)")); +} + +#[test] +fn a_pull_request_quiet_for_a_day_is_diagnosed_and_retried() { + use crate::passes::own_problems::{stall, Route}; + let s = stall( + true, + "2030-03-01T09:00:00Z", + "", + "CoderHelm's review asks for changes", + "2030-03-02T10:00:00Z", + ) + .unwrap(); + assert_eq!(s.route, Route::Ready); + assert!(s.diagnosis.contains("No progress on this pull request")); + // The 15-minute sweep runs the detector on every pull request it looks at. + let src = include_str!("../pr_watch.rs"); + assert!(src.contains("super::own_problems::check(state, &c).await;")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index a4b9f1a00..4dd315f44 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1382,6 +1382,7 @@ pub mod outcome; pub mod outcome_learning; pub mod outside_exec; pub mod outside_work; +pub(crate) mod own_problems; pub mod own_review; pub mod own_review_ledger; pub mod ownership; @@ -1440,6 +1441,7 @@ pub mod review_configs; pub mod review_discipline; #[cfg(test)] mod review_eval; +pub(crate) mod review_feasible; pub(crate) mod review_fingerprint; pub mod review_fix; pub mod review_labels; @@ -9883,6 +9885,15 @@ async fn report_also_outside( // over: the hand-off analytics read these. if let Some(c) = decision.outside_change.as_ref() { person_gate::record_counts(state, &msg.team_id, run_id, &outside_work::counts(c)).await; + // The team's hand-offs by reason, and CoderHelm's own problems the + // steps named (each an internal alert): `own_problems`. + let mut asks: Vec = outside_work::steps_now(c, true) + .iter() + .map(|s| s.ask()) + .collect(); + asks.extend(outside_work::person_checks(c).iter().map(|s| s.ask())); + let gated = common::person_gate::gate(asks, &common::person_gate::Context::default()); + own_problems::record_handoffs(state, &msg.team_id, run_id, &gated).await; } // The ticket gets only what a person must do; with nothing for anyone // the comment says nothing (the conversation layer drops it from the diff --git a/services/worker/src/passes/own_problems.rs b/services/worker/src/passes/own_problems.rs new file mode 100644 index 000000000..d39d34bf5 --- /dev/null +++ b/services/worker/src/passes/own_problems.rs @@ -0,0 +1,379 @@ +//! CoderHelm's own problems, its hand-off counts and its stalls. +//! +//! - [`record`]: a limit CoderHelm owns that a writer tried to hand a +//! person (`common::person_only::OwnProblem`) is an internal alert for +//! CoderHelm's maintainers (an error log line carrying [`ALERT_MARK`], +//! which the log alarm reads, and a row under [`ALERT_PK`]) and one plain +//! line on the run page. The work goes on by another route. +//! - [`record_handoffs`]: the team's counts of hand-offs by reason and of +//! its own problems by subject ([`STATS_SK`]), so a rise shows. +//! - [`stall`]: a CoderHelm pull request or run with no progress for +//! [`STALL_HOURS`] gets a self-diagnosis line, a retry along its next +//! route, and an internal alert. It never sits silent for days. + +use aws_sdk_dynamodb::types::AttributeValue; +use common::person_only::{OwnProblem, OwnSubject, PersonOnly}; +use tracing::{error, warn}; + +use super::{attr_n, attr_s}; +use crate::WorkerState; + +/// The marker on every internal alert's log line. +pub const ALERT_MARK: &str = "CODERHELM_OWN_PROBLEM"; +/// Where internal alerts are kept, across teams (settings table). +pub const ALERT_PK: &str = "CODERHELM#OWN_PROBLEMS"; +/// The team's hand-off counts (settings table, under the team). +pub const STATS_SK: &str = "HANDOFF_STATS"; +/// Hours without progress before a pull request or run counts as stalled. +pub const STALL_HOURS: i64 = 24; +/// Alerts are kept this long. +const ALERT_DAYS: i64 = 30; + +/// The count attribute for a hand-off reason. +pub fn person_attr(p: &PersonOnly) -> String { + format!("person_{}", p.code()) +} + +/// The count attribute for an own problem's subject. +pub fn own_attr(s: OwnSubject) -> String { + format!("own_{}", s.code()) +} + +/// Records one own problem: the internal alert and the run page's line. +pub async fn record(state: &WorkerState, team_id: &str, run_id: &str, p: &OwnProblem) { + alert(state, team_id, run_id, p.subject.code(), &p.text).await; + super::add_progress_note(state, team_id, run_id, &p.line()).await; + add(state, team_id, &[(own_attr(p.subject), 1)]).await; +} + +/// An internal alert for CoderHelm's maintainers: never shown to the team +/// as a to-do. +pub async fn alert(state: &WorkerState, team_id: &str, run_id: &str, kind: &str, text: &str) { + error!( + marker = ALERT_MARK, + team_id, run_id, kind, text, "CoderHelm met a limit it owns" + ); + let now = chrono::Utc::now(); + let ttl = (now + chrono::Duration::days(ALERT_DAYS)).timestamp(); + if let Err(e) = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", attr_s(ALERT_PK)) + .item( + "sk", + attr_s(&format!("{}#{team_id}#{run_id}#{kind}", now.to_rfc3339())), + ) + .item("team_id", attr_s(team_id)) + .item("run_id", attr_s(run_id)) + .item("kind", attr_s(kind)) + .item("text", attr_s(common::truncate_str(text, 1_000))) + .item("ttl", AttributeValue::N(ttl.to_string())) + .send() + .await + { + warn!(team_id, run_id, error = %e, "Could not keep the internal alert"); + } +} + +/// The counts one gated list adds: each hand-off by its reason, each own +/// problem by its subject. +pub fn handoff_counts(g: &common::person_gate::Gated) -> Vec<(String, u64)> { + let mut out: Vec<(String, u64)> = Vec::new(); + let mut bump = |k: String| match out.iter_mut().find(|(a, _)| *a == k) { + Some((_, n)) => *n += 1, + None => out.push((k, 1)), + }; + for h in g.human() { + bump(person_attr(h.person())); + } + for p in g.problems() { + bump(own_attr(p.subject)); + } + out +} + +/// Keeps a gated list's hand-offs and own problems: the team's counts, and +/// each own problem as an internal alert with its run-page line. +pub async fn record_handoffs( + state: &WorkerState, + team_id: &str, + run_id: &str, + g: &common::person_gate::Gated, +) { + let counts = handoff_counts(g); + if counts.is_empty() { + return; + } + add(state, team_id, &counts).await; + let mut seen: Vec<&str> = Vec::new(); + for p in g.problems() { + if seen.contains(&p.text.as_str()) { + continue; + } + seen.push(&p.text); + alert(state, team_id, run_id, p.subject.code(), &p.text).await; + super::add_progress_note(state, team_id, run_id, &p.line()).await; + } +} + +/// Adds to the team's counts. Best effort. +async fn add(state: &WorkerState, team_id: &str, counts: &[(String, u64)]) { + if counts.is_empty() { + return; + } + let mut req = state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(STATS_SK)); + let mut parts = Vec::new(); + for (i, (k, n)) in counts.iter().enumerate() { + parts.push(format!("#k{i} :v{i}")); + req = req + .expression_attribute_names(format!("#k{i}"), k.clone()) + .expression_attribute_values(format!(":v{i}"), attr_n(*n)); + } + if let Err(e) = req + .update_expression(format!("ADD {}", parts.join(", "))) + .send() + .await + { + warn!(team_id, error = %e, "Could not keep the team's hand-off counts"); + } +} + +// ── stalls ─────────────────────────────────────────────────────────────── + +/// The run attribute holding when the stall detector last acted, and how +/// many times, as `#`. +pub const STALL_FIELD: &str = "stall_seen"; +/// The run attribute holding the seconds its pull request spent blocked. +pub const BLOCKED_FIELD: &str = "blocked_secs"; + +/// The next route a stalled pull request takes, by how many times the +/// detector already acted on the same stall. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Route { + /// Ask the ready decision again (it re-reads checks, previews, holds). + Ready, + /// Ask CoderHelm's review of the head again, with what the run settled. + Review, + /// Ask the ready decision and the review again together. + Both, +} + +/// What the detector does about one pull request now, or `None`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Stall { + pub route: Route, + pub tries: u32, + /// The run page's self-diagnosis line. + pub diagnosis: String, +} + +fn hours_between(from: &str, to: &str) -> Option { + let a = chrono::DateTime::parse_from_rfc3339(from).ok()?; + let b = chrono::DateTime::parse_from_rfc3339(to).ok()?; + Some((b - a).num_hours()) +} + +/// Whether the run's pull request stalled: open, no change to the run for +/// [`STALL_HOURS`], and not already acted on in the last [`STALL_HOURS`] +/// (`seen`: [`STALL_FIELD`]). `waiting` is what the pull request waits on +/// as the run page says it. Pure. +pub fn stall(open: bool, updated_at: &str, seen: &str, waiting: &str, now: &str) -> Option { + if !open || updated_at.is_empty() { + return None; + } + if hours_between(updated_at, now)? < STALL_HOURS { + return None; + } + let (at, tries) = match seen.split_once('#') { + Some((at, n)) => (at, n.parse::().unwrap_or(0)), + None => ("", 0), + }; + if !at.is_empty() && hours_between(at, now).is_some_and(|h| h < STALL_HOURS) { + return None; + } + let route = match tries % 3 { + 0 => Route::Ready, + 1 => Route::Review, + _ => Route::Both, + }; + let what = if waiting.trim().is_empty() { + "nothing it recorded".to_string() + } else { + waiting.trim().trim_end_matches('.').to_string() + }; + let next = match route { + Route::Ready => "asking the ready decision again", + Route::Review => "asking its own review of the head again", + Route::Both => "asking the ready decision and its review again", + }; + Some(Stall { + route, + tries: tries + 1, + diagnosis: format!( + "No progress on this pull request for {} hours. It was waiting on: {what}. CoderHelm is {next}, and its maintainers were alerted.", + hours_between(updated_at, now).unwrap_or(STALL_HOURS) + ), + }) +} + +/// Seconds a pull request spent blocked since the last look: the time +/// between looks while its standing said it waits on something other than +/// CoderHelm. Pure. +pub fn blocked_delta(standing_json: &str, looked_at: &str, now: &str) -> i64 { + let Some(s) = common::merge_standing::Standing::from_json(standing_json) else { + return 0; + }; + let blocked = s.needs_person + || matches!( + s.code.as_str(), + "review_changes_requested" | "draft" | "checks_failing" | "conflict" + ); + if !blocked || looked_at.is_empty() { + return 0; + } + let (Ok(a), Ok(b)) = ( + chrono::DateTime::parse_from_rfc3339(looked_at), + chrono::DateTime::parse_from_rfc3339(now), + ) else { + return 0; + }; + (b - a).num_seconds().clamp(0, 6 * 3600) +} + +/// The detector, for one pull request the 15-minute sweep looked at: keeps +/// the time it spent blocked, and acts on a stall. +pub async fn check(state: &WorkerState, c: &super::pr_watch::Candidate) { + let now = chrono::Utc::now().to_rfc3339(); + let open = super::pr_watch::watched(&c.status) && c.status != "merged"; + let blocked = blocked_delta(&c.standing, &c.looked_at, &now); + if blocked > 0 { + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&c.team_id)) + .key("run_id", attr_s(&c.run_id)) + .update_expression("ADD #b :d") + .condition_expression("attribute_exists(run_id)") + .expression_attribute_names("#b", BLOCKED_FIELD) + .expression_attribute_values(":d", attr_n(blocked as u64)) + .send() + .await; + add( + state, + &c.team_id, + &[("pr_blocked_secs".to_string(), blocked as u64)], + ) + .await; + } + let standing = common::merge_standing::Standing::from_json(&c.standing); + let waiting = c.waiting_line(standing.as_ref()); + let seen = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&c.team_id)) + .key("run_id", attr_s(&c.run_id)) + .projection_expression("#s") + .expression_attribute_names("#s", STALL_FIELD) + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| i.get(STALL_FIELD).and_then(|v| v.as_s().ok()).cloned()) + .unwrap_or_default(); + let Some(s) = stall(open, &c.updated_at, &seen, &waiting, &now) else { + return; + }; + // Claimed first: a second sweep never acts on the same stall. + let claimed = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&c.team_id)) + .key("run_id", attr_s(&c.run_id)) + .update_expression("SET #s = :new") + .condition_expression( + "attribute_exists(run_id) AND (attribute_not_exists(#s) OR #s = :old)", + ) + .expression_attribute_names("#s", STALL_FIELD) + .expression_attribute_values(":new", attr_s(&format!("{now}#{}", s.tries))) + .expression_attribute_values(":old", attr_s(&seen)) + .send() + .await + .is_ok(); + if !claimed { + return; + } + super::add_progress_note(state, &c.team_id, &c.run_id, &s.diagnosis).await; + alert(state, &c.team_id, &c.run_id, "stall", &s.diagnosis).await; + add(state, &c.team_id, &[("stalls".to_string(), 1)]).await; + if matches!(s.route, Route::Ready | Route::Both) { + super::ready::request_for( + state, + &c.team_id, + c.installation_id, + &c.owner, + &c.repo, + c.pr, + ) + .await; + } + if matches!(s.route, Route::Review | Route::Both) { + let head = super::pr_watch::Probe::parse(&c.probe) + .map(|p| p.seen.head) + .unwrap_or_default(); + if !head.is_empty() { + super::review_pr::review_for_ready( + state, + &c.team_id, + c.installation_id, + (&c.owner, &c.repo, c.pr), + &head, + ) + .await; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pull_request_quiet_for_a_day_is_diagnosed_and_retried_along_routes() { + let now = "2026-11-20T12:00:00Z"; + assert!(stall(true, "2026-11-20T00:00:00Z", "", "a review", now).is_none()); + let s = stall(true, "2026-11-18T12:00:00Z", "", "CoderHelm's review", now).unwrap(); + assert_eq!(s.route, Route::Ready); + assert!(s.diagnosis.contains("48 hours")); + assert!(s.diagnosis.contains("CoderHelm's review")); + // Acted on within the day: nothing more yet. + assert!(stall( + true, + "2026-11-18T12:00:00Z", + "2026-11-20T06:00:00Z#1", + "", + now + ) + .is_none()); + // A day later the next route. + let s = stall( + true, + "2026-11-18T12:00:00Z", + "2026-11-19T06:00:00Z#1", + "", + now, + ) + .unwrap(); + assert_eq!((s.route, s.tries), (Route::Review, 2)); + // Closed or merged: never. + assert!(stall(false, "2026-11-01T00:00:00Z", "", "", now).is_none()); + } +} diff --git a/services/worker/src/passes/own_review_ledger.rs b/services/worker/src/passes/own_review_ledger.rs index 4f379dbe0..3daf492c7 100644 --- a/services/worker/src/passes/own_review_ledger.rs +++ b/services/worker/src/passes/own_review_ledger.rs @@ -507,11 +507,12 @@ impl Ledger { Some((code, rest.get(1).map(|w| w.to_string()).unwrap_or_default())) }) { - if common::stop_rules::tooling::names_own_tooling(&what) - || common::stop_rules::tooling::names_own_read(&what) - { - // "Add the hosts to CoderHelm's sandbox allowlist": its - // own setup, a block the next round removes. + // The one parser for a written hand-off (`person_only`): + // "add the hosts to CoderHelm's sandbox allowlist", "run it + // 20 times yourself", "a CI change outside this ticket" make + // no hand-off. + if common::person_only::parse(&code, &what).is_err() { + // CoderHelm's own setup, a block the next round removes. if !blocked.contains(&Blocker::Tooling) { blocked.push(Blocker::Tooling); } @@ -976,6 +977,24 @@ pub async fn record_round_end( let mut l = load(state, team_id, run_id).await; l.end_round(blocked, account); save(state, team_id, run_id, &l).await; + // A hand-off the round wrote about CoderHelm's own limits is its own + // problem: an internal alert and one run-page line (`person_only`). + for p in own_problems_in(account) { + super::own_problems::record(state, team_id, run_id, &p).await; + } +} + +/// The `NEEDS A PERSON` lines of a round's account that name no reason only +/// a person has (`person_only::parse`): CoderHelm's own problems. +pub fn own_problems_in(account: &str) -> Vec { + marked(account, NEEDS_A_PERSON) + .into_iter() + .filter_map(|(_, rest)| { + let code = rest.first().copied().unwrap_or(""); + let what = rest.get(1).copied().unwrap_or(code); + common::person_only::parse(code, what).err() + }) + .collect() } /// The ticket, the comments people wrote on it and the plan's cause, from diff --git a/services/worker/src/passes/person_gate.rs b/services/worker/src/passes/person_gate.rs index dcbef307a..cf34b4db5 100644 --- a/services/worker/src/passes/person_gate.rs +++ b/services/worker/src/passes/person_gate.rs @@ -399,6 +399,58 @@ mod tests { ); } + /// A hand-off to a person is a typed `person_only::PersonOnly`: every + /// place that builds one, or reads one a model wrote, goes through that + /// module. A new builder that doesn't fails here. + #[test] + fn every_hand_off_is_typed_and_none_is_coderhelms_own() { + // The gate's items: one constructor, built from a typed hand-off. + let pg = src("../common/src/person_gate.rs"); + let pg = code(&pg); + let literals = pg.matches("HumanItem {").count() + - pg.matches("pub struct HumanItem {").count() + - pg.matches("impl HumanItem {").count(); + assert_eq!(literals, 1, "a HumanItem is built outside `human_item`"); + assert!(body_of(pg, "fn human_item(").contains("person_only::of_reason(")); + // Hand-backs. + let hb = src("../common/src/handback.rs"); + assert!(body_of(code(&hb), "pub fn new(").contains("person_only::of_human_only(")); + assert!(body_of(code(&hb), "pub fn human_only_in(").contains("person_only::own_subject(")); + // Every file that reads a model's `NEEDS A PERSON` line, writes the + // catch-all reason into a step, or counts hand-offs goes through it. + // (Rendering an item the gate already typed is not a builder.) + const BUILDERS: &[&str] = &[ + "NEEDS_A_PERSON)", + "reason: \"outside_reach\"", + "handoff_human", + ]; + const TYPED_ELSEWHERE: &[&str] = &[ + // Defines the reasons and maps them through `human_item`. + "person_gate.rs", + "handback.rs", + "person_only.rs", + ]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); + let mut files = Vec::new(); + rs_files(&root.join("src"), &mut files); + rs_files(&root.join("../common/src"), &mut files); + for f in files { + let name = f.file_name().unwrap().to_string_lossy().to_string(); + if TYPED_ELSEWHERE.contains(&name.as_str()) { + continue; + } + let text = std::fs::read_to_string(&f).unwrap(); + let body = code(&text); + if BUILDERS.iter().any(|b| body.contains(b)) { + assert!( + body.contains("person_only::") || body.contains("own_problems::"), + "{} builds or reads a hand-off without `person_only`", + f.display() + ); + } + } + } + #[test] fn the_standard_is_in_front_of_every_model_that_writes_for_people() { for rel in [ diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 84bd624a0..e41f1eed7 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -1249,6 +1249,7 @@ pub async fn sweep(state: &WorkerState) -> SweepReport { } report.looked_at += 1; let act = look(state, &clients[&c.installation_id], &c).await; + super::own_problems::check(state, &c).await; if act != Act::Nothing { report .acted diff --git a/services/worker/src/passes/review_feasible.rs b/services/worker/src/passes/review_feasible.rs new file mode 100644 index 000000000..1d7f25c81 --- /dev/null +++ b/services/worker/src/passes/review_feasible.rs @@ -0,0 +1,230 @@ +//! A blocking finding on CoderHelm's own pull request is one some route +//! CoderHelm has can satisfy. +//! +//! A fix run's own review once asked for a proof (twenty repeat runs) that +//! CoderHelm's sandbox could not run at the time, and held the pull request +//! for days: CoderHelm "does not merge over its own review", and its review +//! asked for what none of its routes could do. Before CoderHelm's reviewer +//! posts a blocking finding on its own pull request, [`check`] asks whether +//! a route can satisfy it: an edit to the code, a run in the sandbox, a CI +//! run (dispatched, labelled or re-run), a page check. When none can: +//! +//! - what only a person has (a permission, a credential, an approval, a +//! product decision, a real-world action) is one typed question +//! (`common::person_only::PersonOnly`), never a block; +//! - anything else is CoderHelm's own gap: a note on the finding and an +//! internal alert, never a block. + +use common::person_only::PersonOnly; + +use super::review_agent::Finding; + +/// The routes CoderHelm has on this pull request. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Available { + /// Its sandbox is set up for this install. + pub sandbox: bool, + /// It can start the repository's CI on the head (a dispatch, a label, + /// a re-run): true unless the install has no Actions access at all. + pub ci: bool, +} + +/// A route that can satisfy a finding. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Route { + Edit, + Sandbox, + Ci, + PageCheck, +} + +/// What [`check`] found for a blocking finding no route satisfies. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Infeasible { + /// Only a person has it: one typed question. + Person(PersonOnly), + /// CoderHelm lacks every route for it: its own gap. + Own(String), +} + +fn asks_for_proof(t: &str) -> bool { + [ + "unproven", + "not proven", + "no proof", + "prove ", + "repeat run", + "repeat-each", + "runs in a row", + "never ran", + "not run", + "run the test", + ] + .iter() + .any(|m| t.contains(m)) +} + +/// The routes that could satisfy `f`, given what is available. +pub fn routes(f: &Finding, a: &Available) -> Vec { + let t = format!("{} {}", f.title, f.body).to_lowercase(); + let mut out = Vec::new(); + // A finding on a line of the change is answered by an edit, unless it + // asks only for proof. + if !f.file.trim().is_empty() && !asks_for_proof(&t) { + out.push(Route::Edit); + } + if a.sandbox { + out.push(Route::Sandbox); + } + if a.ci { + out.push(Route::Ci); + } + if t.contains("page") || t.contains("preview") { + out.push(Route::PageCheck); + } + out +} + +/// Whether `f`, which holds the merge, is one CoderHelm can satisfy. +/// `None`: it can, and it stays a block. +pub fn check(f: &Finding, a: &Available) -> Option { + if !f.holds_merge() { + return None; + } + let text = format!("{} {}", f.title, f.body); + // What only a person has is never satisfied by CoderHelm's routes, + // when no edit answers it. + if f.suggestion.is_none() { + if let Some(p) = common::person_only::person_need_in(&text) { + return Some(Infeasible::Person(p)); + } + } + if routes(f, a).is_empty() { + return Some(Infeasible::Own(format!( + "no route CoderHelm has satisfies \"{}\" (no edit answers it, and neither its sandbox nor CI is available)", + common::truncate_str(&f.title, 160) + ))); + } + None +} + +/// Makes each blocking finding no route satisfies a note: the person's one +/// question, or CoderHelm's own gap. Returns what changed, as +/// `(title, why)`, and the own gaps to alert on. +pub fn apply(findings: &mut [Finding], a: &Available) -> (Vec<(String, String)>, Vec) { + let mut made = Vec::new(); + let mut gaps = Vec::new(); + for f in findings.iter_mut() { + let Some(why) = check(f, a) else { continue }; + let note = match &why { + Infeasible::Person(p) => format!( + "A question, not a block: nothing CoderHelm can do settles this. {}", + p.line() + ), + Infeasible::Own(g) => { + gaps.push(g.clone()); + format!("A note, not a block: {g}; CoderHelm's maintainers were alerted.") + } + }; + super::review_policy::demote(f, ¬e); + made.push((f.title.clone(), note)); + } + (made, gaps) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn f(title: &str, body: &str, file: &str) -> Finding { + Finding { + file: file.into(), + line: if file.is_empty() { 0 } else { 3 }, + severity: "blocking".into(), + category: "bug".into(), + title: title.into(), + body: body.into(), + evidence: Some("verified-defect".into()), + ..Default::default() + } + } + + const ALL: Available = Available { + sandbox: true, + ci: true, + }; + + #[test] + fn a_proof_some_route_can_run_stays_a_block() { + let proof = f( + "Fix is unproven", + "Prove it with 20 repeat runs of the cart checkout spec.", + "tests/cart.spec.ts", + ); + assert_eq!(check(&proof, &ALL), None); + // Only CI is left: still a route. + assert_eq!( + check( + &proof, + &Available { + sandbox: false, + ci: true + } + ), + None + ); + } + + #[test] + fn a_proof_no_route_can_run_is_coderhelms_gap_not_a_block() { + let mut v = vec![f( + "Fix is unproven", + "Prove it with 20 repeat runs.", + "tests/cart.spec.ts", + )]; + let (made, gaps) = apply( + &mut v, + &Available { + sandbox: false, + ci: false, + }, + ); + assert_eq!(made.len(), 1); + assert_eq!(gaps.len(), 1); + assert!(!v[0].holds_merge()); + } + + #[test] + fn what_only_a_person_has_is_one_question_never_a_block() { + let mut v = vec![f( + "Storefront key", + "Only an org owner can grant the app access to the bookstore's payments repository.", + "src/pay.ts", + )]; + let (made, gaps) = apply(&mut v, &ALL); + assert!(gaps.is_empty()); + assert!(made[0].1.contains("A question, not a block")); + assert!(!v[0].holds_merge()); + } + + #[test] + fn a_code_defect_stays_a_block() { + let bug = f( + "Off by one in the page count", + "`pages` skips the last page of the catalog.", + "src/catalog.ts", + ); + assert_eq!(check(&bug, &ALL), None); + // Even with no sandbox or CI, an edit answers it. + assert_eq!( + check( + &bug, + &Available { + sandbox: false, + ci: false + } + ), + None + ); + } +} diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 4ec54f427..ec44cb861 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -4232,6 +4232,22 @@ async fn run_once( for m in &made { info!(pr = msg.pr_number, file = %m.file, title = %m.title, why = %m.why, "A finding that would hold the merge made a note"); } + // On CoderHelm's own pull request a block is only what some route it + // has can satisfy (`review_feasible`). + if let Some(run_id) = &own_run { + let avail = super::review_feasible::Available { + sandbox: !state.config.sandbox_bucket_name.is_empty(), + ci: true, + }; + let (made, gaps) = super::review_feasible::apply(&mut findings, &avail); + for (title, why) in &made { + info!(pr = msg.pr_number, title = %title, why = %why, "A block no route satisfies made a note"); + } + for g in &gaps { + super::own_problems::alert(state, &msg.team_id, run_id, "review_infeasible", g) + .await; + } + } } info!( pr = msg.pr_number, diff --git a/services/worker/src/passes/settle.rs b/services/worker/src/passes/settle.rs index 21f9a2dda..3a0645748 100644 --- a/services/worker/src/passes/settle.rs +++ b/services/worker/src/passes/settle.rs @@ -1746,6 +1746,13 @@ async fn write_down( "Settle: the open items" ); super::person_gate::record_counts(w.state, &w.msg.team_id, w.run_id, &settled.counts).await; + // The team's hand-offs by reason, and CoderHelm's own problems the open + // items named (each an internal alert): `own_problems`. + let gated = person_gate::gate( + settled.open.iter().map(ask_of).collect(), + &person_gate::Context::default(), + ); + super::own_problems::record_handoffs(w.state, &w.msg.team_id, w.run_id, &gated).await; if !settled.closed.is_empty() || !settled.dropped.is_empty() { super::add_progress_note( w.state,