From 2488ac511177b574f2c49c970c52bfe2cf09e80f Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 16 Nov 2026 17:28:12 -0500 Subject: [PATCH] No CoderHelm limit hands a pull request to a person Only a reason on the human-only list keeps a draft for a person. Four paths still did it over CoderHelm's own limits: a security fix whose CI stayed red after its fix rounds, a wait unchanged for two hours, lines in the description (security items, unfinished planned work, a failed check, review findings), and GitHub refusing to mark a pull request ready. - A hold reason names its human-only reason (Reason::person); only those make a hold a person's. Every other reason is CoderHelm's note on a pull request that goes ready, once its attempts are spent. - A stalled wait is CoderHelm's next action: its checks run on the head again in a fresh step, twice, then its note. - A security fix whose CI stays red after every set of bumps that could come out did is completed and ready, with the failing checks noted. - Dependency fixes: a scope's packages on one minor line are a family found from the lockfile when no registry record names their source, so a head that raises one alone fails the set. Tests cover the type check added when CI runs none and the major-override evidence section. - Incidents bv and bw reproduce the cases; older tests that encoded a person's hold for these reasons now read the reasons as found and assert the note. --- docs/incidents.md | 2 + services/common/src/draft_hold.rs | 52 +++- services/common/src/upgrade_quality/family.rs | 60 ++++ .../src/passes/incidents/aa_promised_round.rs | 22 +- .../passes/incidents/ac_partial_and_red_ci.rs | 16 +- .../bv_no_limit_hands_to_a_person.rs | 223 ++++++++++++++ .../incidents/bw_dependency_pr_review.rs | 146 +++++++++ .../passes/incidents/k_own_review_findings.rs | 2 +- services/worker/src/passes/incidents/mod.rs | 2 + .../src/passes/incidents/s_silent_draft.rs | 23 +- .../passes/incidents/t_unrun_check_hold.rs | 6 +- .../passes/incidents/v_dropped_field_hold.rs | 5 +- .../passes/incidents/w_stale_hold_recheck.rs | 7 +- .../passes/incidents/x_silent_review_hold.rs | 6 +- .../passes/incidents/y_skipped_checks_wait.rs | 32 +- services/worker/src/passes/ready.rs | 281 ++++++++++++++---- services/worker/src/passes/resume.rs | 112 +++++++ 17 files changed, 893 insertions(+), 104 deletions(-) create mode 100644 services/worker/src/passes/incidents/bv_no_limit_hands_to_a_person.rs create mode 100644 services/worker/src/passes/incidents/bw_dependency_pr_review.rs diff --git a/docs/incidents.md b/docs/incidents.md index 42d96bcc4..f196b8fd0 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -98,6 +98,8 @@ pipeline still calls it there. | br. `br_description_writer_upgrade` | After the description writer was upgraded (a final review in the one save, the repository's template as the structure), a pull request opened the day before kept its old text: six checks "Not run: still running when this was written", the file to read first and the way back said twice, filler and a raw page id. Its head had not moved and its checked text was unchanged, so its stamp said current and nothing rebuilt it. | The stamp names the writer version (`description::WRITER`, raised with every change to what a description says or how it is laid out); a description built by another writer, or before the version, is not current. The pull request watch's sweep catches up open pull requests CoderHelm opened, whatever the age of their run: a few per team each sweep (`pr_watch::CATCH_UP_PER_TEAM`), inside its GitHub budget, each rebuilt once and marked on its run. A description still wholly CoderHelm's is built again from the facts of the head alone: nothing of the old text is kept, not even in a fold, except a line that closes an issue. A description with no CoderHelm stamp, or whose checked text a person changed, is left as it is. | | bs. `bs_cut_plan_revision` | A ticket with a long history was planned, and the plan check sent the plan back with two open items. The revision reached the output limit partway through its last block. The planner was told the coder's note ("make a change in small edit_file calls"), wrote only its decision block again, and the worker read only that last turn: no tasks, no design. The run failed with "empty or malformed plan ... retry the run" and the first plan was thrown away. | A planner's cut answer is continued where it stopped and read together with what came before the cut, file by file (`plan_sections`). A cut turn's note fits its loop: the coder's edit note only where there are edit tools, the planner's "continue the document" note, a shorter answer for everyone else. A revision that comes back empty, cut off or malformed never replaces a valid file, and a send-back asks for only the files that change. Files still missing are asked for alone, twice at most, the second with a larger output budget. A plan still not usable is planned again in a fresh step, then reported as CoderHelm's own failure, saying what it lacked. No run tells a person to retry it. | | bt. `bt_proof_answer_closes` | A security update's own review asked for proof of the build and unit tests on the head. The fix rounds changed no code: the second ran every check on the head, all passing, and one runtime check it started was cut short by the step's time. The ledger counted that as a block, the round pushed nothing so no review read the head again, and the draft was held for a person ("Fix them on the branch, or remove a finding") while the merge standing said no person was needed. | A round that pushed nothing is read by a review of the same head, with the round's account in the reviewer's context, and a finding answered with proof closes there. A command, check or codegen a step is too short to start is owed: the pass continues in a fresh step that runs it first, and a round cut short by time is never a block. Nothing on CoderHelm's side holds a draft for a person: what is left after every approach is listed as CoderHelm's note and the pull request goes ready, with CoderHelm's verdict kept so nothing merges over it. A stuck run is sent back to its review on the next look of the ready sweep or the pull request's watch. | +| bv. `bv_no_limit_hands_to_a_person` | Four paths still ended a pull request "for a person" over CoderHelm's own limits: a security fix whose CI stayed red after its fix rounds stayed a draft with "Fix the failing checks on this branch" and the run waited or failed; a wait unchanged for two hours on one head became "Look at why it didn't happen ... or mark it ready yourself"; description lines (security items, planned work not finished, a check the change didn't pass, review findings) each held the draft with a person's to-do; and GitHub refusing to mark a pull request ready counted as a person's. | Only a reason on the human-only list keeps a draft for a person, made only by `Reason::person`; everything else, once CoderHelm's attempts are spent, is its note on a pull request that goes ready. A stalled wait is CoderHelm's next action (its checks run on the head again), twice, then its note. A security fix whose CI stays red after every set of bumps that could come out did is completed and ready with the failing checks as its note. The run guard waits on a person only with a human-only reason. | +| bw. `bw_dependency_pr_review` | A product owner's review of a dependency pull request asked for the type check on the changed package when CI runs none, for sibling packages of one scope to move together, and for each major override to say which package pulls it in and why the bump is safe. The family check found siblings only from a registry record naming their source repository. | The verification set adds the type check to steps that lack one, and a failing type check takes the set out. When no registry record names a source repository, the scope's packages the base lockfile installs on one minor line are a family (never `@types/`), held together, and a head that splits them fails the set. Each major's section is built from its lockfile dependency paths, its route and the parents an override moves outside their range. | ## Adding a case diff --git a/services/common/src/draft_hold.rs b/services/common/src/draft_hold.rs index 2ed0bcc22..68af2de5e 100644 --- a/services/common/src/draft_hold.rs +++ b/services/common/src/draft_hold.rs @@ -19,7 +19,12 @@ //! - a wait CoderHelm settles by itself ([`Kind::Waiting`]) leaves the //! status alone and says what it waits for; //! - once the pull request is ready (or closed), the hold is removed and -//! `draft_settled` says how it ended, so the sweep stops looking at it. +//! `draft_settled` says how it ended, so the sweep stops looking at it; +//! - only a reason on the human-only list (`crate::handback::HumanOnly`) +//! makes a hold a person's ([`Reason::person`], [`DraftHold::needs_person`]). +//! Every other reason is CoderHelm's own to finish, or to list as its note +//! on a pull request that goes ready: a red check, a stalled wait, a +//! finding its rounds left, planned work it deferred. use std::collections::HashMap; @@ -59,6 +64,10 @@ pub struct Reason { /// What to do about it, in plain words. #[serde(default, skip_serializing_if = "String::is_empty")] pub todo: String, + /// The human-only reason a person is needed for it (`HumanOnly::code`); + /// empty for everything CoderHelm finishes or notes itself. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub human: String, } fn one_line(s: &str, max: usize) -> String { @@ -71,9 +80,28 @@ impl Reason { Reason { what: one_line(what.as_ref(), MAX_WHAT), todo: one_line(todo.as_ref(), MAX_TODO), + human: String::new(), + } + } + + /// A reason only a person can settle, for `why` on the human-only list: + /// the one way a hold becomes a person's. + pub fn person( + why: crate::handback::HumanOnly, + what: impl AsRef, + todo: impl AsRef, + ) -> Self { + Reason { + human: why.code().to_string(), + ..Reason::new(what, todo) } } + /// The human-only reason it needs a person for, if any. + pub fn human_only(&self) -> Option { + crate::handback::HumanOnly::from_code(&self.human) + } + /// `what. todo`, one sentence each. pub fn line(&self) -> String { let what = self.what.trim().trim_end_matches('.'); @@ -110,6 +138,14 @@ pub struct DraftHold { /// drafts run, and it is still being proven (or failed its proof). #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub ready: bool, + /// Times CoderHelm took its own next action on a wait that stalled on + /// this head (`ready::MAX_STALL_RETRIES`). + #[serde(default, skip_serializing_if = "is_zero")] + pub retried: u32, +} + +fn is_zero(n: &u32) -> bool { + *n == 0 } /// A wait whose reason hasn't changed on the same head for this long is a @@ -139,6 +175,7 @@ impl DraftHold { checked_at: now, head: String::new(), ready: false, + retried: 0, }) } @@ -179,9 +216,12 @@ impl DraftHold { self } - /// Whether a person must act (the run waits on them). + /// Whether a person must act (the run waits on them): only a held + /// pull request with a reason on the human-only list. A hold for + /// anything else, and GitHub refusing to mark it ready, are CoderHelm's + /// to finish. pub fn needs_person(&self) -> bool { - matches!(self.kind, Kind::Held | Kind::Failed) + self.kind == Kind::Held && self.reasons.iter().any(|r| r.human_only().is_some()) } fn pr_words(&self) -> String { @@ -284,7 +324,8 @@ mod tests { ); let h = DraftHold::new( Kind::Held, - vec![Reason::new( + vec![Reason::person( + crate::handback::HumanOnly::MissingAccess, "Security items are open in the description", "Fix them on this branch, or delete each line once it is checked.", )], @@ -298,6 +339,9 @@ mod tests { description. Fix them on this branch, or delete each line once it is checked." ); assert!(h.needs_person()); + // The same reason without a human-only one is CoderHelm's to finish. + let own = DraftHold::new(Kind::Held, vec![Reason::new("x", "y")], 583, "").unwrap(); + assert!(!own.needs_person()); let w = h.waiting_on(); assert_eq!(w.action, "Deal with what keeps pull request #583 a draft"); assert!(w.detail.contains("Security items")); diff --git a/services/common/src/upgrade_quality/family.rs b/services/common/src/upgrade_quality/family.rs index 24069a2fe..a25400272 100644 --- a/services/common/src/upgrade_quality/family.rs +++ b/services/common/src/upgrade_quality/family.rs @@ -60,6 +60,10 @@ pub enum Evidence { }, /// The members share a scope or a name stem. Supporting only. NamePattern { pattern: String }, + /// No registry record named a source repository, and the base branch's + /// lockfile installs every member of the scope on one minor line + /// ([`scope_siblings`]). + ScopeAndLine { scope: String, line: String }, } impl Evidence { @@ -75,6 +79,9 @@ impl Evidence { format!("`{from}` declares the peer range `{range}` for `{on}`") } Evidence::NamePattern { pattern } => format!("the names share `{pattern}`"), + Evidence::ScopeAndLine { scope, line } => format!( + "the base branch's lockfile installs each package of `{scope}/` it has on {line}" + ), } } } @@ -298,9 +305,28 @@ pub fn detect( range: range.clone(), }); } + // No registry record named a source repository: the lockfile alone. + // Packages of the bumped one's scope the base branch installs on its + // minor line are released together (`@scope/common`, `@scope/core`, + // `@scope/platform-x`). A dependency pull request once raised one of + // them and left its siblings a minor behind. + let mut scope_line: Option<(String, String)> = None; + if source.is_none() && members.is_empty() { + let siblings = scope_siblings(package, from, base); + if !siblings.is_empty() { + scope_line = Some((stem(package).to_string(), minor_line(from).to_string())); + members.extend(siblings); + } + } if members.is_empty() && independent.is_empty() { return None; } + if let Some((scope, line)) = &scope_line { + evidence.push(Evidence::ScopeAndLine { + scope: scope.clone(), + line: line.clone(), + }); + } let mut patterns: Vec = members .iter() .filter_map(|m| name_pattern(package, m)) @@ -312,6 +338,7 @@ pub fn detect( } let key = match (&source, evidence.first()) { (Some(repo), Some(Evidence::SameSource { .. })) | (Some(repo), None) => repo.clone(), + (_, Some(Evidence::ScopeAndLine { scope, line })) => format!("{scope}/ on {line}"), _ => format!("peers of {package}"), }; members.insert(package.to_string()); @@ -327,6 +354,39 @@ pub fn detect( }) } +/// `major.minor` of a version (`1.4.2` is `1.4`); the version itself when +/// it has fewer parts. +pub fn minor_line(v: &str) -> &str { + let v = v.trim().trim_start_matches(['v', '=', '^', '~']); + match v.match_indices('.').nth(1) { + Some((i, _)) => &v[..i], + None => v, + } +} + +/// The packages of `package`'s scope the base branch's lockfile installs +/// on the minor line of `from`: its siblings when no registry record names +/// a source repository. Only scoped names (`@scope/x`); the scope of type +/// declarations, whose packages are versioned one by one, is never a +/// family. +pub fn scope_siblings(package: &str, from: &str, base: &[(String, String)]) -> Vec { + let scope = stem(package); + if !scope.starts_with('@') || scope.eq_ignore_ascii_case("@types") { + return vec![]; + } + let line = minor_line(from); + let mut out: Vec = base + .iter() + .filter(|(n, _)| !n.eq_ignore_ascii_case(package)) + .filter(|(n, _)| stem(n).eq_ignore_ascii_case(scope)) + .filter(|(_, v)| minor_line(v) == line) + .map(|(n, _)| n.clone()) + .collect(); + out.sort(); + out.dedup(); + out +} + /// The version a family moves to: the lowest of `wanted` (the versions /// that fix the advisory, lowest first) every member publishes. /// `published`: per member, which of `wanted` its registry has; a member diff --git a/services/worker/src/passes/incidents/aa_promised_round.rs b/services/worker/src/passes/incidents/aa_promised_round.rs index b3470306a..23befe967 100644 --- a/services/worker/src/passes/incidents/aa_promised_round.rs +++ b/services/worker/src/passes/incidents/aa_promised_round.rs @@ -89,13 +89,19 @@ fn says_coderhelm_works(text: &str) -> bool { } #[test] -fn with_no_round_left_the_hold_is_a_persons_and_promises_nothing() { +fn with_no_round_left_the_findings_are_coderhelms_note_and_promise_nothing() { // The run's budget as its record shows it: no round may be queued. let budget = resume::own_round_budget(&record("needs_input", 8), 0); let why = own_review::round_left(&budget, HEAD, 8, 10).unwrap_err(); assert!(why.contains("fix budget is spent"), "{why}"); - let d = ready::decide(&facts(false)); + // CoderHelm's limit: its note on a ready pull request, never a + // person's hold (incident bv). + assert!( + matches!(ready::decide(&facts(false)), Decision::Ready { open } + if open.iter().any(|o| o.starts_with(ready::NOTE_PREFIX))) + ); + let d = ready::found(&facts(false)); let Decision::Held { reasons } = &d else { panic!("{d:?}") }; @@ -203,13 +209,11 @@ fn the_wait_for_a_round_is_bounded_like_every_wait() { f.now = Some(t("2026-11-10T04:31:00Z")); assert!(matches!(ready::decide(&f), Decision::Wait { .. })); f.now = Some(t("2026-11-10T05:32:00Z")); - let d = ready::decide(&f); - let Decision::Held { reasons } = &d else { - panic!("{d:?}") - }; - assert!(reasons[0] - .what - .contains("hasn't changed in 2 hours on this head")); + // Stalled: CoderHelm's own next action, never a person's hold. + assert!(matches!( + ready::decide(&f), + Decision::Retry { attempt: 1, .. } + )); } #[test] 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 24bdcba80..74a54247b 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 @@ -328,7 +328,7 @@ fn a_draft_with_failing_ci_is_held_with_the_check_named() { ..Default::default() }; assert!(ready::reads_ci(&f)); - match ready::decide(&f) { + match ready::found(&f) { Decision::Held { reasons } => { assert!( reasons[0] @@ -392,9 +392,17 @@ fn the_ready_decision_keeps_the_rules_across_combinations() { }; let d = ready::decide(&f); let ci_state = CiState::of(&f.ci, f.red_on_base); - if matches!(d, Decision::Ready { .. } | Decision::Proving { .. }) { - assert!(ci_state.allows_done(), "ready with {ci_state:?}: {f:?}"); - assert!(!body_unfinished, "ready with planned work left"); + // Ready over red CI or planned work left only + // with it listed as CoderHelm's note (incident bv). + if let Decision::Ready { open } = &d { + let noted = open.iter().any(|o| o.starts_with(ready::NOTE_PREFIX)); + if !ci_state.allows_done() || body_unfinished { + assert!(noted, "ready without a note: {f:?}"); + } + } + if matches!(d, Decision::Proving { .. }) { + assert!(ci_state.allows_done(), "proving with {ci_state:?}: {f:?}"); + assert!(!body_unfinished, "proving with planned work left"); } n += 1; } diff --git a/services/worker/src/passes/incidents/bv_no_limit_hands_to_a_person.rs b/services/worker/src/passes/incidents/bv_no_limit_hands_to_a_person.rs new file mode 100644 index 000000000..90d52d569 --- /dev/null +++ b/services/worker/src/passes/incidents/bv_no_limit_hands_to_a_person.rs @@ -0,0 +1,223 @@ +//! bv. Four paths still ended a run's pull request "for a person" over +//! CoderHelm's own limits. A security fix whose CI stayed red after its +//! fix rounds stayed a draft with "Fix the failing checks on this branch", +//! and the run waited on a person or failed. A wait unchanged for two hours +//! on one head (a review, a fix round, checks still running) became "Look +//! at why it didn't happen ... or mark it ready yourself". Lines in the +//! description (security items under Open items, planned work under Not +//! finished, a check the change didn't pass, review findings) each held the +//! draft with a person's to-do, and a GitHub refusal to mark a pull request +//! ready counted as a person's. +//! +//! Guarantee: only a reason on the human-only list (`common::handback`) +//! keeps a draft for a person, and it is made only by `Reason::person`. +//! Every other reason is CoderHelm's: once its own attempts are spent it is +//! listed as CoderHelm's note and the pull request goes ready. A stalled +//! wait is CoderHelm's next action (its checks run again on the head), +//! twice, then its note. A security fix whose CI stays red after every set +//! of bumps that could come out did is completed, ready, with the failing +//! checks as its note. The run guard waits on a person only with a +//! human-only reason. + +use super::fixture::fn_src; +use crate::passes::ready::{self, Ci, Decision, Facts}; +use common::draft_hold::{DraftHold, Kind, Reason}; +use common::handback::HumanOnly; + +const HEAD: &str = "9c1e0d2b7a44"; + +fn draft(body: &str) -> Facts { + Facts { + draft: true, + body: body.into(), + head: HEAD.into(), + ci: Ci { + green: true, + why: String::new(), + }, + ..Default::default() + } +} + +fn notes(d: &Decision) -> Vec { + match d { + Decision::Ready { open } => open + .iter() + .filter(|o| o.starts_with(ready::NOTE_PREFIX)) + .cloned() + .collect(), + other => panic!("ready with notes, not {other:?}"), + } +} + +#[test] +fn a_security_fix_with_red_ci_goes_ready_with_the_failing_checks_as_its_note() { + let f = Facts { + security: true, + ci: Ci { + green: false, + why: "CI fails on this head: `unit-tests`".into(), + }, + ..draft("## Summary\nBumps.") + }; + let d = ready::decide(&f); + let n = notes(&d); + assert!( + n[0].contains("doesn't pass CI") && n[0].contains("unit-tests"), + "{n:?}" + ); + // The run ends completed with the note: never a person's wait. + use crate::passes::resume::{red_ci_ending, RedCiEnding}; + assert_eq!(red_ci_ending("SEC-1234ABCD"), RedCiEnding::NoteAndReady); + assert_eq!(red_ci_ending("PROJ-12"), RedCiEnding::Failed); + let resume = include_str!("../resume.rs"); + let hand_off = fn_src(resume, "\nasync fn hand_off_red_ci("); + let ending = hand_off + .find("finish_security_red(") + .expect("the security ending"); + // Every set that can come out comes out first; the ending comes after. + assert!(hand_off.find("revert_to_green(").unwrap() < ending); + assert!(ending < hand_off.find("wait_for_review(").unwrap()); + let rounds = fn_src(resume, "\npub(crate) async fn end_red_ci_rounds("); + assert!(rounds.find("finish_security_red(").unwrap() < rounds.find("fail_run(").unwrap()); + let finish = fn_src(resume, "\nasync fn finish_security_red("); + assert!(finish.contains("mark_pr_ready(") && finish.contains("COMPLETED")); + assert!(!finish.contains("needs_input") && !finish.contains("wait_for_review(")); +} + +#[test] +fn description_lines_are_coderhelm_notes_and_the_pull_request_goes_ready() { + let body = format!( + "## Summary\nx\n\n## Open items\n- Audit still reports 2 advisories {}\n\n{}\n- Task 3: deferred\n", + crate::passes::proof::SECURITY_MARK, + crate::passes::proof::UNFINISHED_START, + ); + let d = ready::decide(&draft(&body)); + let n = notes(&d); + assert!( + n.iter().any(|l| l.contains("Security items are open")), + "{n:?}" + ); + assert!( + n.iter().any(|l| l.contains("Planned work is not done yet")), + "{n:?}" + ); + // What only a person can settle still holds, alone. + let stacked = format!( + "{body}\n\n\n" + ); + match ready::decide(&draft(&stacked)) { + Decision::Held { reasons } => { + assert_eq!(reasons.len(), 1, "{reasons:?}"); + assert_eq!(reasons[0].human_only(), Some(HumanOnly::HeldByAnother)); + } + other => panic!("{other:?}"), + } + let put_back = Facts { + put_back_by: Some("a-teammate".into()), + ..draft(&body) + }; + assert!( + matches!(ready::decide(&put_back), Decision::Held { reasons } + if reasons[0].human_only() == Some(HumanOnly::PersonAction)) + ); +} + +#[test] +fn only_a_human_only_reason_makes_a_hold_a_persons() { + let own = DraftHold::new( + Kind::Held, + vec![Reason::new( + "A check the change didn't pass is listed", + "Fix it", + )], + 3, + "", + ) + .unwrap(); + assert!(!own.needs_person()); + let person = DraftHold::new( + Kind::Held, + vec![Reason::person( + HumanOnly::Credential, + "The deploy needs a token only a person has", + "Add it", + )], + 3, + "", + ) + .unwrap(); + assert!(person.needs_person()); + // GitHub refusing to mark it ready is CoderHelm's to try again. + let refused = + DraftHold::new(Kind::Failed, vec![Reason::new("GitHub refused", "")], 3, "").unwrap(); + assert!(!refused.needs_person()); + // A hold stored before reasons named their kind is not a person's. + let stored: DraftHold = serde_json::from_value(serde_json::json!({ + "kind": "held", + "reasons": [{"what": "1 finding from CoderHelm's review is still open", "todo": "Fix them"}], + "pr_number": 3 + })) + .unwrap(); + assert!(!stored.needs_person()); +} + +#[test] +fn a_stalled_wait_is_coderhelms_next_action_then_its_note() { + let why = "CoderHelm is fixing 1 finding from its review"; + let now = chrono::Utc::now(); + let waited = |retried: u32| { + let mut h = DraftHold::new(Kind::Waiting, vec![Reason::new(why, "")], 3, "").unwrap(); + h.head = HEAD.into(); + h.since = (now - chrono::Duration::hours(3)).to_rfc3339(); + h.retried = retried; + h + }; + let body = crate::passes::own_review::section(&["A finding (`a.rs:1`)".to_string()]); + let at = |retried: u32| Facts { + own_fixing: true, + prior: Some(waited(retried)), + now: Some(now), + ..draft(&body) + }; + assert_eq!( + ready::decide(&at(0)), + Decision::Retry { + why: why.into(), + attempt: 1 + } + ); + assert!(matches!( + ready::decide(&at(1)), + Decision::Retry { attempt: 2, .. } + )); + let spent = ready::decide(&at(ready::MAX_STALL_RETRIES)); + let n = notes(&spent); + assert!( + n[0].contains(why) && n[0].contains("ran its checks again 2 times"), + "{n:?}" + ); + // The attempts carry across waits on the same head, never to a new one. + assert_eq!(ready::carried_retries(Some(&waited(1)), HEAD), 1); + assert_eq!(ready::carried_retries(Some(&waited(1)), "another"), 0); + // The retry is CoderHelm's action: its checks run on the head again. + let src = include_str!("../ready.rs"); + let settle = fn_src(src, "\npub async fn settle("); + let retry = settle.find("Decision::Retry { why, attempt } =>").unwrap(); + assert!(settle[retry..].contains("super::recheck::start(")); + // Nothing in the decision names a person's to-do for a stall. + assert!(!src.contains("or mark it ready yourself; CoderHelm decides again")); +} + +#[test] +fn the_run_guard_waits_on_a_person_only_with_a_human_only_reason() { + let guard = include_str!("../run_guard.rs"); + let wait = fn_src(guard, "\nasync fn wait_on_open_pr("); + let gate = wait + .find("super::supervisor::hand_back_for(judged, reason) else") + .expect("the hand-back is gated"); + // The status write, named without its call so this file isn't one. + let write = concat!(".needs", "_input("); + assert!(gate < wait.find(write).unwrap()); + assert!(wait[..gate].find(write).is_none()); +} diff --git a/services/worker/src/passes/incidents/bw_dependency_pr_review.rs b/services/worker/src/passes/incidents/bw_dependency_pr_review.rs new file mode 100644 index 000000000..eadd57f00 --- /dev/null +++ b/services/worker/src/passes/incidents/bw_dependency_pr_review.rs @@ -0,0 +1,146 @@ +//! bw. A product owner's review of a dependency pull request asked three +//! things of every one: the type check is run on the changed package even +//! when CI doesn't run one, and a failing type check is a failure the +//! bisect acts on; packages of one family (`@scope/common`, `@scope/core`, +//! `@scope/platform-x`) move together, and the scope's packages on one +//! minor line count as a family even when no registry record names their +//! source repository; and each major override says which package pulls it +//! in and why the bump is safe, written from the lockfile's dependency +//! paths, never free text. +//! +//! Guarantee: the verification set adds the type check to steps that lack +//! one and a failing type check takes the set out; a family found from the +//! lockfile alone is held together and a head that installs it at two +//! versions fails the set; each major's section is built from its paths. + +use crate::passes::checks::{CheckKind, Step}; +use common::upgrade_quality::{family, safety, verify as vq}; + +#[test] +fn the_type_check_runs_whatever_ci_runs_and_a_failure_counts() { + // CI's steps run the build and the tests, no type check. + let ci = vec![Step { + kinds: vec![CheckKind::Build, CheckKind::Tests], + cmd: "pnpm build && pnpm test".into(), + scope: None, + }]; + let typed = vq::Plan { + lockfile: "packages/api/pnpm-lock.yaml".into(), + manager: "pnpm".into(), + dir: "packages/api".into(), + checks: vec![vq::Check { + kind: vq::Kind::Typecheck, + shown: "tsc --noEmit".into(), + cmd: "pnpm exec tsc --noEmit".into(), + found: "tsconfig.json".into(), + }], + ..Default::default() + }; + let steps = crate::passes::settle::with_min_set(ci, &[typed]); + let tc = steps + .iter() + .find(|s| s.kinds.contains(&CheckKind::Typecheck)) + .expect("the type check is added"); + assert!( + tc.cmd.contains("cd 'packages/api'") && tc.cmd.contains("tsc --noEmit"), + "{}", + tc.cmd + ); + // A failing type check is the change's: the bisect takes the set out. + assert!(vq::Kind::Typecheck.blames()); +} + +#[test] +fn scope_siblings_on_one_minor_line_are_a_family_found_from_the_lockfile() { + let base: Vec<(String, String)> = [ + ("@scope/common", "10.4.15"), + ("@scope/core", "10.4.15"), + ("@scope/platform-x", "10.4.15"), + ("@scope/testing", "9.1.0"), + ("@types/node", "10.4.15"), + ("other", "10.4.15"), + ] + .iter() + .map(|(n, v)| (n.to_string(), v.to_string())) + .collect(); + assert_eq!( + family::scope_siblings("@scope/core", "10.4.15", &base), + vec!["@scope/common".to_string(), "@scope/platform-x".to_string()] + ); + // Type declarations are versioned one by one; a plain name has no scope. + assert!(family::scope_siblings("@types/express", "10.4.1", &base).is_empty()); + assert!(family::scope_siblings("other", "10.4.15", &base).is_empty()); + // No registry record: the family comes from the lockfile. + let fam = family::detect("@scope/core", "10.4.15", "pnpm-lock.yaml", &base, &[], &[]) + .expect("a family"); + assert_eq!( + fam.members, + vec!["@scope/common", "@scope/core", "@scope/platform-x"] + ); + assert!( + fam.evidence_line().contains("`@scope/` it has on 10.4"), + "{}", + fam.evidence_line() + ); + // A head that raises one of them alone is a gate failure. + let head: Vec<(String, String)> = [ + ("@scope/common", "10.4.15"), + ("@scope/core", "10.4.22"), + ("@scope/platform-x", "10.4.15"), + ] + .iter() + .map(|(n, v)| (n.to_string(), v.to_string())) + .collect(); + assert_eq!( + family::splits(std::slice::from_ref(&fam), "pnpm-lock.yaml", &head).len(), + 1 + ); + let together: Vec<(String, String)> = head + .iter() + .map(|(n, _)| (n.clone(), "10.4.22".to_string())) + .collect(); + assert!(family::splits(&[fam], "pnpm-lock.yaml", &together).is_empty()); + let dep_fix = include_str!("../dep_fix.rs"); + assert!(dep_fix.contains("result.checks.push((df::FAMILY_CHECK.to_string(), false));")); +} + +#[test] +fn a_major_override_says_who_pulls_it_in_and_why_it_is_safe_from_the_lockfile() { + let paths = vec![safety::PathIn { + root: "build-tool".into(), + declared: safety::Declared::Development, + importers: vec![], + install_script: false, + scripts: vec!["build".into()], + }]; + let parents = vec![common::upgrade_notes::ParentSupport { + parent: "build-tool".into(), + version: "3.2.0".into(), + declares: "^6.0.0".into(), + admits: Some(false), + ..Default::default() + }]; + let s = safety::evidence(&safety::MajorIn { + package: "archive-lib", + from: "6.2.1", + to: "7.5.21", + ecosystem: "npm", + why_major: "no 6.x release fixes the advisory", + paths: &paths, + used_in: &[], + searched: "imports of `archive-lib`", + verdict: common::security_fixes::Verdict::NotReachable, + direct: false, + parents: &parents, + via_parent: None, + selector: "archive-lib@6", + }) + .section(); + assert!(s.contains("Path through `build-tool`"), "{s}"); + assert!( + s.contains("override scoped to its version line (`archive-lib@6`)"), + "{s}" + ); + assert!(s.contains("`build-tool` 3.2.0 declares `^6.0.0`"), "{s}"); + assert!(s.contains("Reachability:"), "{s}"); +} diff --git a/services/worker/src/passes/incidents/k_own_review_findings.rs b/services/worker/src/passes/incidents/k_own_review_findings.rs index 0ed672c37..bb20b075b 100644 --- a/services/worker/src/passes/incidents/k_own_review_findings.rs +++ b/services/worker/src/passes/incidents/k_own_review_findings.rs @@ -101,7 +101,7 @@ fn the_own_review_requests_changes_and_lists_every_non_optional_finding() { let holds = fn_src(ready, "pub fn body_holds_on("); assert!(holds.contains("own_review_reason(body)")); assert!(fn_src(ready, "fn own_review_reason(").contains("own_review::hold(body)")); - assert!(fn_src(ready, "pub fn decide(").contains("body_holds_on(&f.body, f.ci.green)")); + assert!(fn_src(ready, "fn decide_raw(").contains("body_holds_on(&f.body, f.ci.green)")); let main = include_str!("../../main.rs"); assert!(main.contains("passes::ready::on_message(&state, msg)")); // The run gets them as a fix round, not a completion. diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 0849ab389..9ab7d6523 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -59,6 +59,8 @@ mod bq_upstream_read_not_guessed; mod br_description_writer_upgrade; mod bs_cut_plan_revision; mod bt_proof_answer_closes; +mod bv_no_limit_hands_to_a_person; +mod bw_dependency_pr_review; mod c_codegen_egress; mod d_echoed_markers; mod e_large_generated_output; diff --git a/services/worker/src/passes/incidents/s_silent_draft.rs b/services/worker/src/passes/incidents/s_silent_draft.rs index fa9d51a75..63247f825 100644 --- a/services/worker/src/passes/incidents/s_silent_draft.rs +++ b/services/worker/src/passes/incidents/s_silent_draft.rs @@ -104,7 +104,7 @@ fn a_green_approved_pr_is_marked_ready_with_the_sandbox_failures_listed() { } #[test] -fn a_hold_that_remains_is_named_everywhere_and_the_run_waits_on_a_person() { +fn a_hold_that_remains_is_named_everywhere_and_waits_on_a_person_only_for_a_human_only_reason() { let mut end = Ending { status: "completed".into(), pr: Some(21), @@ -119,9 +119,20 @@ fn a_hold_that_remains_is_named_everywhere_and_the_run_waits_on_a_person() { }, ..the_pull_request_at_completion() }; - let d = ready::decide(&f); - let Decision::Held { reasons } = &d else { - panic!("{d:?}") + // What CoderHelm's own checks find is its note on a ready pull request + // (incident bv); a hold names a human-only reason, as here. + assert!(matches!(ready::decide(&f), Decision::Ready { open } + if open.iter().any(|o| o.starts_with(ready::NOTE_PREFIX)))); + let Decision::Held { reasons } = ready::found(&f) else { + panic!("found") + }; + let reasons: Vec = reasons + .into_iter() + .map(|r| Reason::person(common::handback::HumanOnly::MissingAccess, &r.what, &r.todo)) + .collect(); + let reasons = &reasons; + let d = Decision::Held { + reasons: reasons.clone(), }; // The description says it at the top, with what to do. let body = ready::body_for(&f.body, &d).unwrap(); @@ -223,8 +234,8 @@ fn a_refused_mark_ready_is_tried_again_and_the_last_refusal_is_recorded() { "", ) .unwrap(); - assert!(failed.needs_person()); - end.status = common::run_status::NEEDS_INPUT.into(); + // GitHub refusing is CoderHelm's to try again, never a person's wait. + assert!(!failed.needs_person()); end.said(failed.summary()); assert!(end.says("couldn't mark it: GitHub didn't mark it ready (GitHub's rate limit)")); end.never_says(OLD); diff --git a/services/worker/src/passes/incidents/t_unrun_check_hold.rs b/services/worker/src/passes/incidents/t_unrun_check_hold.rs index e314aa3d1..7b88dd2a5 100644 --- a/services/worker/src/passes/incidents/t_unrun_check_hold.rs +++ b/services/worker/src/passes/incidents/t_unrun_check_hold.rs @@ -66,7 +66,7 @@ fn facts(body: &str, ci_green: bool) -> Facts { fn a_tooling_failure_written_as_a_blocked_line_stops_holding_once_ci_is_green() { let body = the_description_as_written(); // While CI hasn't passed, the check it couldn't run is still unsettled. - match ready::decide(&facts(&body, false)) { + match ready::found(&facts(&body, false)) { Decision::Held { reasons } => assert!(reasons.iter().any(|r| r.what.contains(OLD))), d => panic!("held while CI isn't green, got {d:?}"), } @@ -107,7 +107,7 @@ fn a_check_the_change_really_failed_still_holds_with_ci_green() { "two new blocks aren't registered in the schema index", )]); let body = format!("## Summary\nx\n\n{gaps}"); - match ready::decide(&facts(&body, true)) { + match ready::found(&facts(&body, true)) { Decision::Held { reasons } => assert!(reasons.iter().any(|r| r.what.contains(OLD))), d => panic!("a real failed check holds, got {d:?}"), } @@ -177,6 +177,6 @@ fn the_pipeline_writes_gate_errors_through_check_item() { ); } let ready = include_str!("../ready.rs"); - assert!(super::fixture::fn_src(ready, "pub fn decide(") + assert!(super::fixture::fn_src(ready, "fn decide_raw(") .contains("body_holds_on(&f.body, f.ci.green)")); } diff --git a/services/worker/src/passes/incidents/v_dropped_field_hold.rs b/services/worker/src/passes/incidents/v_dropped_field_hold.rs index 66ed89fd9..42774b046 100644 --- a/services/worker/src/passes/incidents/v_dropped_field_hold.rs +++ b/services/worker/src/passes/incidents/v_dropped_field_hold.rs @@ -120,10 +120,7 @@ fn a_line_listing_only_dropped_fields_never_holds_the_pull_request() { "remove `isHeadingTwo` from every `activitiesCarousel` document that still has it", "give every `heroCenteredText` document a value for the now required `headingLevel`", ); - assert!(matches!( - ready::decide(&facts(&real)), - Decision::Held { .. } - )); + assert!(matches!(ready::found(&facts(&real)), Decision::Held { .. })); } #[test] diff --git a/services/worker/src/passes/incidents/w_stale_hold_recheck.rs b/services/worker/src/passes/incidents/w_stale_hold_recheck.rs index c4f1eaedf..5d959eaa7 100644 --- a/services/worker/src/passes/incidents/w_stale_hold_recheck.rs +++ b/services/worker/src/passes/incidents/w_stale_hold_recheck.rs @@ -83,9 +83,11 @@ fn a_hold_older_checks_wrote_is_checked_again_and_clears() { for body in [held_description(None), held_description(Some(OLD_VERSION))] { assert!(body.contains(proof::BLOCKED_MARK), "{body}"); let f = facts(&body); - let d = ready::decide(&f); + let d = ready::found(&f); assert!(matches!(d, Decision::Held { .. }), "{d:?}"); assert!(ready::recheck_due(&f, &d, now), "{body}"); + // As CoderHelm's note it is checked again too, before it goes ready. + assert!(ready::recheck_due(&f, &ready::decide(&f), now), "{body}"); } // The checks run again with the fixed rule and find nothing: the line // goes and the pull request is ready. @@ -105,9 +107,10 @@ fn a_line_the_running_checks_wrote_never_starts_another_check() { assert!(body.contains(&proof::checked_by(now)), "{body}"); assert_eq!(proof::checked_by_of(&body), Some(now)); let f = facts(&body); - let d = ready::decide(&f); + let d = ready::found(&f); assert!(matches!(d, Decision::Held { .. })); assert!(!ready::recheck_due(&f, &d, now)); + assert!(!ready::recheck_due(&f, &ready::decide(&f), now)); // A person's draft and a closed pull request are never checked again. let old = held_description(None); diff --git a/services/worker/src/passes/incidents/x_silent_review_hold.rs b/services/worker/src/passes/incidents/x_silent_review_hold.rs index a0e2a1b36..97356d6ba 100644 --- a/services/worker/src/passes/incidents/x_silent_review_hold.rs +++ b/services/worker/src/passes/incidents/x_silent_review_hold.rs @@ -85,7 +85,7 @@ fn says(d: &Decision) -> String { .map(|r| r.line()) .collect::>() .join("\n"), - Decision::Wait { why, .. } => why.clone(), + Decision::Wait { why, .. } | Decision::Retry { why, .. } => why.clone(), Decision::Ready { open } => open.join("\n"), Decision::Closed => String::new(), } @@ -121,7 +121,7 @@ fn a_missing_review_is_queued_and_waited_for_never_held_on() { ..held_facts() }; assert!(ready::wants_review(&ci_red)); - let d = ready::decide(&ci_red); + let d = ready::found(&ci_red); assert!(matches!(d, Decision::Held { .. })); assert!( says(&d).contains("CoderHelm is reviewing this head"), @@ -140,7 +140,7 @@ fn a_review_that_never_comes_is_named() { ..held_facts() }; assert!(!ready::wants_review(&off)); - let d = ready::decide(&off); + let d = ready::found(&off); assert!(matches!(d, Decision::Held { .. })); assert!( says(&d).contains("reviewer is off for this repository"), diff --git a/services/worker/src/passes/incidents/y_skipped_checks_wait.rs b/services/worker/src/passes/incidents/y_skipped_checks_wait.rs index 9b0ac0754..32e25caf5 100644 --- a/services/worker/src/passes/incidents/y_skipped_checks_wait.rs +++ b/services/worker/src/passes/incidents/y_skipped_checks_wait.rs @@ -172,10 +172,15 @@ fn the_draft_is_marked_ready_so_the_checks_that_skip_drafts_run() { }; let red = test_fix::decide(&[], &failed, &Skipped::default(), false, Some(true)); assert!(matches!(&red, Hold::Failed(w) if w.contains("E2E after staging deploy"))); - let d = ready::decide(&facts(red, false, &body)); + let d = ready::found(&facts(red.clone(), false, &body)); assert!( matches!(&d, Decision::Proving { reasons, .. } if reasons[0].what.contains("isn't proven")) ); + // CoderHelm's note on the ready pull request (incident bv). + assert!( + matches!(ready::decide(&facts(red, false, &body)), Decision::Ready { open } + if open.iter().any(|o| o.contains("isn't proven"))) + ); let held = ready::body_for(&body, &d).unwrap(); assert!(held.contains("it isn't proven") && held.contains("E2E after staging deploy")); } @@ -268,19 +273,18 @@ fn a_wait_that_does_not_change_for_two_hours_is_a_hold() { f.now = Some(t("2026-11-10T07:35:00Z")); assert!(matches!(ready::decide(&f), Decision::Wait { .. })); f.now = Some(t("2026-11-10T08:36:00Z")); - let d = ready::decide(&f); - let Decision::Held { reasons } = &d else { - panic!("{d:?}") - }; - assert!(reasons[0] - .what - .contains("hasn't changed in 2 hours on this head")); - assert!(reasons[0].what.starts_with(why)); - // The hold it became stays one on that head, and a push starts over. - let mut held = DraftHold::new(Kind::Held, reasons.clone(), 1508, "").unwrap(); - held.head = "bcf845d".into(); - f.prior = Some(held); - assert!(matches!(ready::decide(&f), Decision::Held { .. })); + // Stalled: CoderHelm acts again on that head (incident bv), and once its + // attempts are spent the wait is its note on a ready pull request. + assert!(matches!( + ready::decide(&f), + Decision::Retry { attempt: 1, .. } + )); + let mut spent = prior.clone(); + spent.retried = ready::MAX_STALL_RETRIES; + f.prior = Some(spent); + assert!(matches!(ready::decide(&f), Decision::Ready { open } + if open.iter().any(|o| o.contains(why)))); + // A push starts over. f.head = "0a1b2c3".into(); assert!(matches!(ready::decide(&f), Decision::Wait { .. })); } diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index e5f44b12c..8d4fc083b 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -239,6 +239,26 @@ pub enum Decision { /// With no `reasons` it waits for them (`why`); with reasons they /// failed or can't run, and a person deals with each. Proving { why: String, reasons: Vec }, + /// A wait stalled on this head: CoderHelm takes its own next action + /// (its checks run again on the head in a fresh step) and waits again, + /// `attempt` of [`MAX_STALL_RETRIES`]. + Retry { why: String, attempt: u32 }, +} + +/// Times CoderHelm acts on a wait that stalled on the same head before +/// what it waits for is listed as its note and the pull request goes ready. +pub const MAX_STALL_RETRIES: u32 = 2; + +/// How a CoderHelm-side reason is listed on a pull request that goes ready. +pub const NOTE_PREFIX: &str = "CoderHelm's note: "; + +/// What a stalled wait becomes ([`stalled`]). +#[derive(Debug, Clone, PartialEq, Eq)] +enum Stall { + /// CoderHelm acts again ([`Decision::Retry`]). + Retry { why: String, attempt: u32 }, + /// Its attempts are spent: listed as its note on a ready pull request. + Note(String), } fn check_names(v: &[String]) -> String { @@ -248,23 +268,45 @@ fn check_names(v: &[String]) -> String { .join(", ") } -/// The hold a wait becomes once it stalled on this head -/// (`DraftHold::stalled`), or `None` while it may still settle. -fn stalled(f: &Facts, why: &str) -> Option { +/// What a wait becomes once it stalled on this head +/// (`DraftHold::stalled`), or `None` while it may still settle. Never a +/// person's to-do: CoderHelm acts again, and once its attempts are spent +/// what it waited for is its note on a ready pull request. A stalled wait +/// once became "Look at why it didn't happen ... or mark it ready +/// yourself" after two hours. +fn stalled(f: &Facts, why: &str) -> Option { let (prior, now) = (f.prior.as_ref()?, f.now?); if !prior.stalled(why, &f.head, now) { return None; } - Some(Reason::new( - format!( - "{}, and that hasn't changed in {} hours on this head", - why.trim().trim_end_matches('.'), - common::draft_hold::WAIT_LIMIT_SECS / 3600 - ), - "Look at why it didn't happen (the checks on the pull request say), then push a fix, \ - start what didn't run, or mark it ready yourself; CoderHelm decides again on the next \ - push.", - )) + let tried = if prior.head == f.head { + prior.retried + } else { + 0 + }; + if tried < MAX_STALL_RETRIES { + return Some(Stall::Retry { + why: why.trim().trim_end_matches('.').to_string(), + attempt: tried + 1, + }); + } + Some(Stall::Note(format!( + "{}; it hadn't changed in {} hours on this head after CoderHelm ran its checks again {} \ + times", + why.trim().trim_end_matches('.'), + common::draft_hold::WAIT_LIMIT_SECS / 3600, + tried + ))) +} + +/// The open item a CoderHelm-side reason becomes on a ready pull request. +pub fn note_line(what: &str) -> String { + format!("{NOTE_PREFIX}{}", what.trim().trim_end_matches('.')) +} + +/// Whether a reason needs a person: only one on the human-only list. +pub fn needs_person(r: &Reason) -> bool { + r.human_only().is_some() } /// The reasons the description itself holds the draft for, each with what a @@ -315,14 +357,19 @@ pub fn body_holds_on(body: &str, ci_green: bool) -> Vec { // An infrastructure fix the replacement guard gave up on: it would // replace or destroy a resource that holds data. if let Some(why) = common::infra_vuln::guard::hold(body) { - out.push(Reason::new( + // Replacing or destroying a resource that holds data is hard to + // reverse: a person's decision. + out.push(Reason::person( + common::handback::HumanOnly::ProductDecision, why, "Correct the lines named at the top of the description on this branch, then remove that section and mark the pull request ready; or apply the update with the runbook on the finding.", )); } // A stacked change asks a person to look first. if let Some(why) = super::stack::hold(body) { - out.push(Reason::new( + // The change it builds on is someone else's to settle first. + out.push(Reason::person( + common::handback::HumanOnly::HeldByAnother, why, "Look at the change it builds on, then remove the hold line from its \"Builds on\" \ section.", @@ -337,8 +384,62 @@ fn own_review_reason(body: &str) -> Option { super::own_review::hold(body).map(|why| Reason::new(why, super::own_review::person_todo())) } -/// The one decision. Pure, so every case is tested. +/// The one decision. Pure, so every case is tested. Only a reason on the +/// human-only list keeps the draft for a person (`common::handback`): +/// every other reason, once CoderHelm's own attempts are spent, is listed +/// as its note and the pull request goes ready. pub fn decide(f: &Facts) -> Decision { + finish(f, decide_raw(f)) +} + +/// What the decision's reasons come to: the human-only ones hold; the rest +/// are CoderHelm's notes on a ready pull request. +fn finish(f: &Facts, raw: Decision) -> Decision { + let split = |reasons: Vec| -> (Vec, Vec) { + let (person, own): (Vec, Vec) = reasons.into_iter().partition(needs_person); + (person, own.iter().map(|r| note_line(&r.what)).collect()) + }; + let base_open = || match (&f.feature, f.ci.green && f.approved) { + (Some(h), true) => h.items(), + _ => Vec::new(), + }; + match raw { + Decision::Held { reasons } => { + let (person, notes) = split(reasons); + if person.is_empty() { + let mut open = base_open(); + open.extend(notes); + Decision::Ready { open } + } else { + Decision::Held { reasons: person } + } + } + Decision::Proving { why, reasons } if !reasons.is_empty() => { + let (person, notes) = split(reasons); + if person.is_empty() { + let mut open = base_open(); + open.extend(notes); + Decision::Ready { open } + } else { + Decision::Proving { + why, + reasons: person, + } + } + } + other => other, + } +} + +/// What holds the pull request before the human-only rule +/// ([`decide`]): every reason CoderHelm finds, each with its words. Tests +/// read the reasons here; what becomes of them is [`decide`]'s. +#[cfg(test)] +pub fn found(f: &Facts) -> Decision { + decide_raw(f) +} + +fn decide_raw(f: &Facts) -> Decision { if f.closed { return Decision::Closed; } @@ -354,7 +455,8 @@ pub fn decide(f: &Facts) -> Decision { // decides undoes it. if let Some(who) = f.put_back_by.as_ref().filter(|_| f.draft) { return Decision::Held { - reasons: vec![Reason::new( + reasons: vec![Reason::person( + common::handback::HumanOnly::PersonAction, format!("`{who}` put it back to draft"), "It stays a draft until a person marks it ready; CoderHelm doesn't undo that.", )], @@ -399,7 +501,11 @@ pub fn decide(f: &Facts) -> Decision { format!("This failing-test fix never cleared its ready check: {why}"), "Run the affected test on the branch and mark it ready yourself, or push a fix.", )), - Some(TestHold::Untriggered { what, todo }) => reasons.push(Reason::new( + // Checks only a person can start (a label the app may not add, a + // trigger the workflow doesn't offer CoderHelm): missing access. + Some(TestHold::Untriggered { what, todo }) => reasons.push(Reason::person( + common::handback::human_only_in(todo) + .unwrap_or(common::handback::HumanOnly::MissingAccess), format!("This failing-test fix can't be proven yet: {what}"), todo, )), @@ -520,10 +626,12 @@ pub fn decide(f: &Facts) -> Decision { if proving { return match proof_wait.or(wait) { Some(why) => match stalled(f, &why) { - Some(r) => Decision::Proving { - why: String::new(), - reasons: vec![r], - }, + Some(Stall::Retry { why, attempt }) => Decision::Retry { why, attempt }, + Some(Stall::Note(note)) => { + let mut open = open; + open.push(note_line(¬e)); + Decision::Ready { open } + } None => Decision::Proving { why, reasons: Vec::new(), @@ -533,10 +641,15 @@ pub fn decide(f: &Facts) -> Decision { }; } if let Some(why) = wait.or(proof_wait) { - if let Some(r) = stalled(f, &why) { - return Decision::Held { reasons: vec![r] }; + match stalled(f, &why) { + Some(Stall::Retry { why, attempt }) => return Decision::Retry { why, attempt }, + Some(Stall::Note(note)) => { + let mut open = open; + open.push(note_line(¬e)); + return Decision::Ready { open }; + } + None => return Decision::Wait { why, until: None }, } - return Decision::Wait { why, until: None }; } Decision::Ready { open } } @@ -546,7 +659,7 @@ pub fn decide(f: &Facts) -> Decision { /// (see `recheck`). Never for a pull request a person put back to draft, or /// one that isn't held. pub fn recheck_due(f: &Facts, d: &Decision, version: &str) -> bool { - matches!(d, Decision::Held { .. }) + matches!(d, Decision::Held { .. } | Decision::Ready { .. }) && f.draft && !f.closed && f.put_back_by.is_none() @@ -587,6 +700,14 @@ pub fn status_section(d: &Decision) -> String { items.join("\n") ) } + Decision::Retry { why, attempt } => format!( + "{STATUS_START}\n**This pull request stays a draft for now:** {}, and that hadn't \ + changed in {} hours, so CoderHelm runs its checks on this head again (attempt {attempt} \ + of {MAX_STALL_RETRIES}). It marks it ready when that is done, with anything still \ + open listed as its note.\n{STATUS_END}", + why.trim().trim_end_matches('.'), + common::draft_hold::WAIT_LIMIT_SECS / 3600 + ), Decision::Ready { .. } | Decision::Closed => String::new(), } } @@ -617,6 +738,14 @@ pub fn open_item_lines(body: &str, open: &[String]) -> Vec { .any(|l| !l.contains(super::proof::READY_OPEN_MARK) && l.contains(core)) }) .map(|o| { + if o.starts_with(NOTE_PREFIX) { + return format!( + "- {}. CoderHelm finished what its own access reaches and lists this for the \ + review; it doesn't keep the draft. {}", + o.trim().trim_end_matches('.'), + super::proof::READY_OPEN_MARK + ); + } format!( "- {}. CI is green and the review approved, so this doesn't keep the draft: \ look at it before merging. {}", @@ -824,21 +953,7 @@ pub async fn settle(ctx: &Ctx<'_>) -> Outcome { record_settled(ctx.state, ctx.team_id, &run_id, "closed").await; Outcome::Closed } - Decision::Ready { open } => { - if facts.draft { - info!(pr = ctx.pr, open = ?open, "Marking PR ready"); - if let Err(r) = make_ready(ctx, &facts).await { - return retry_or_give_up(ctx, &run_id, &pr_url, r).await; - } - info!(pr = ctx.pr, open = open.len(), "PR marked ready"); - } else { - info!(pr = ctx.pr, "PR already not a draft"); - } - write_body(ctx, &facts.body, &decision).await; - record_settled(ctx.state, ctx.team_id, &run_id, "ready").await; - Outcome::Ready - } - Decision::Held { .. } + Decision::Held { .. } | Decision::Ready { .. } if recheck_due(&facts, &decision, super::proof::checks_version()) && super::recheck::start( ctx.state, @@ -866,6 +981,20 @@ pub async fn settle(ctx: &Ctx<'_>) -> Outcome { } Outcome::Rechecking } + Decision::Ready { open } => { + if facts.draft { + info!(pr = ctx.pr, open = ?open, "Marking PR ready"); + if let Err(r) = make_ready(ctx, &facts).await { + return retry_or_give_up(ctx, &run_id, &pr_url, r).await; + } + info!(pr = ctx.pr, open = open.len(), "PR marked ready"); + } else { + info!(pr = ctx.pr, "PR already not a draft"); + } + write_body(ctx, &facts.body, &decision).await; + record_settled(ctx.state, ctx.team_id, &run_id, "ready").await; + Outcome::Ready + } Decision::Held { reasons } => { let lines: Vec = reasons.iter().map(Reason::line).collect(); // The sweep decides a held pull request again every hour: the @@ -888,9 +1017,40 @@ pub async fn settle(ctx: &Ctx<'_>) -> Outcome { Decision::Wait { why, .. } => { info!(pr = ctx.pr, run_id = %run_id, why = %why, "The PR stays a draft for now"); write_body(ctx, &facts.body, &decision).await; - if let Some(h) = + if let Some(mut h) = DraftHold::new(Kind::Waiting, vec![Reason::new(why, "")], ctx.pr, &pr_url) { + // CoderHelm's attempts on this head carry over the wait. + h.retried = carried_retries(facts.prior.as_ref(), &facts.head); + record_hold(ctx.state, ctx.team_id, &run_id, on_head(h)).await; + } + Outcome::Waiting + } + Decision::Retry { why, attempt } => { + // CoderHelm's own next action on a wait that stalled: its checks + // run on the head again in a fresh step (once per attempt), and + // the wait starts over. Never a person's to-do. + let started = super::recheck::start( + ctx.state, + ctx.team_id, + &run_id, + ctx.pr, + &facts.body, + &format!("{}#stall{attempt}", super::proof::checks_version()), + ) + .await; + info!(pr = ctx.pr, run_id = %run_id, why = %why, attempt, started, "A wait stalled on this head: CoderHelm acts again"); + write_body(ctx, &facts.body, &decision).await; + if let Some(mut h) = DraftHold::new( + Kind::Waiting, + vec![Reason::new( + format!("CoderHelm acts again on a stalled wait ({why})"), + "", + )], + ctx.pr, + &pr_url, + ) { + h.retried = *attempt; record_hold(ctx.state, ctx.team_id, &run_id, on_head(h)).await; } Outcome::Waiting @@ -924,6 +1084,13 @@ pub async fn settle(ctx: &Ctx<'_>) -> Outcome { } } +/// The stalled-wait attempts a new wait on `head` keeps from the last hold. +pub fn carried_retries(prior: Option<&DraftHold>, head: &str) -> u32 { + prior + .filter(|p| !head.is_empty() && p.head == head) + .map_or(0, |p| p.retried) +} + /// Reads what [`decide`] needs. A closed or ready pull request is decided /// from the pull request alone, so nothing with side effects runs for it /// (the failing-test check starts workflow runs, the link check rewrites @@ -2131,7 +2298,11 @@ mod tests { assert!(super::super::proof::holds_security_items( "- Token logged in plain text " )); - let d = decide(&f); + // CoderHelm's note on a ready pull request (incident bv); the + // reason as found names the checks. + assert!(matches!(decide(&f), Decision::Ready { open } + if open.iter().any(|o| o.starts_with(NOTE_PREFIX)))); + let d = found(&f); let Decision::Held { reasons } = &d else { panic!("held expected, got {d:?}"); }; @@ -2142,14 +2313,13 @@ mod tests { let section = status_section(&d); assert!(section.contains("**This pull request stays a draft.**")); assert!(section.contains("`test`")); - // The same pull request without the marker is any other run's: it - // is held on its failing check too, never marked ready red - // (`outcome::ci_blocker`). + // The same pull request without the marker is any other run's: its + // failing check is found the same way (`outcome::ci_blocker`). let plain = Facts { security: false, ..f.clone() }; - let Decision::Held { reasons } = decide(&plain) else { + let Decision::Held { reasons } = found(&plain) else { panic!("held expected"); }; assert!(reasons[0] @@ -2236,7 +2406,7 @@ mod tests { draft: true, ..Default::default() }; - match decide(&f) { + match found(&f) { Decision::Held { reasons } => { assert_eq!(reasons.len(), 1); assert!(reasons[0].what.contains("npm run test:unit")); @@ -2250,7 +2420,7 @@ mod tests { approved: false, ..green_approved() }; - assert!(matches!(decide(&f), Decision::Held { reasons } + assert!(matches!(found(&f), Decision::Held { reasons } if reasons[0].what.contains("review hasn't approved"))); } @@ -2266,8 +2436,11 @@ mod tests { body: security, ..green_approved() }; - assert!(matches!(decide(&f), Decision::Held { reasons } + // Found as a hold, and listed as CoderHelm's note: not a person's. + assert!(matches!(found(&f), Decision::Held { reasons } if reasons[0].what.contains("Security items"))); + assert!(matches!(decide(&f), Decision::Ready { open } + if open.iter().any(|o| o.contains("Security items")))); let f = Facts { put_back_by: Some("dana".into()), @@ -2282,26 +2455,26 @@ mod tests { )), ..green_approved() }; - assert!(matches!(decide(&f), Decision::Held { .. })); + assert!(matches!(found(&f), Decision::Held { .. })); let f = Facts { links_blocking: vec!["/old redirects to a 404".into()], ..green_approved() }; - assert!(matches!(decide(&f), Decision::Held { reasons } + assert!(matches!(found(&f), Decision::Held { reasons } if reasons[0].what.contains("/old redirects to a 404"))); let f = Facts { e2e: E2e::Refused, ..green_approved() }; - assert!(matches!(decide(&f), Decision::Held { .. })); + assert!(matches!(found(&f), Decision::Held { .. })); let f = Facts { test_fix: Some(TestHold::GaveUp("the repeat run never passed".into())), ..green_approved() }; - assert!(matches!(decide(&f), Decision::Held { reasons } + assert!(matches!(found(&f), Decision::Held { reasons } if reasons[0].todo.contains("mark it ready yourself"))); } diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 387a12031..3a3438b6f 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -6940,6 +6940,21 @@ async fn hand_off_red_ci( .await; mark_events_processed(state, &msg.run_id, events).await; let checks = failing_workflows(events); + if red_ci_ending(&ticket_msg.ticket_id) == RedCiEnding::NoteAndReady { + return finish_security_red( + state, + ticket_msg, + &msg.run_id, + github, + pr, + usage, + duration, + &checks, + excerpt, + tried, + ) + .await; + } let section = ci_failing_section(&checks, excerpt, tried, needed); match github.get_pull_request(pr.owner, pr.repo, pr.number).await { Ok(p) => { @@ -7022,6 +7037,12 @@ pub(crate) async fn end_red_ci_rounds( super::CiOutcome::HandedOff(super::GaveUp::NoProgress), ) .await; + if red_ci_ending(&ticket_msg.ticket_id) == RedCiEnding::NoteAndReady { + return finish_security_red( + state, ticket_msg, run_id, github, &pr, usage, duration, checks, excerpt, tried, + ) + .await; + } let failing = if checks.is_empty() { vec!["the repository's CI".to_string()] } else { @@ -7065,6 +7086,97 @@ pub(crate) async fn end_red_ci_rounds( Ok(()) } +/// How a run ends when its checks stay red and nothing more can come out. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum RedCiEnding { + /// A security fix: every set of bumps that could come out did (each + /// deferred with the check that failed and why); what is left is + /// CoderHelm's note on a pull request that goes ready, the run is + /// completed, and nothing merges while CI fails. Never a person's + /// to-do: a security fix once stayed a draft "for a person" with + /// "Fix the failing checks on this branch". + NoteAndReady, + /// Any other run: the run ends failed with exactly what fails. + Failed, +} + +/// [`RedCiEnding`] for the run's ticket. +pub(crate) fn red_ci_ending(ticket_id: &str) -> RedCiEnding { + if common::security_fixes::is_ticket(ticket_id) { + RedCiEnding::NoteAndReady + } else { + RedCiEnding::Failed + } +} + +/// What the pull request says when a security fix's CI stays red after +/// every set of bumps that could come out did. +pub(crate) const SECURITY_RED_NEEDED: &str = "CoderHelm took out every set of bumps that could \ + come out, each listed under \"Deferred\" with the check that failed; what is left is \ + listed here as its note. The pull request is ready for review and isn't merged while these \ + checks fail; CoderHelm's CI fix rounds take it again when the checks or the base branch \ + change."; + +/// The [`RedCiEnding::NoteAndReady`] ending: the failing checks named on +/// the pull request as CoderHelm's note, the pull request marked ready by +/// the one ready decision (a failing check is a note there, never a +/// person's hold), and the run completed. +#[allow(clippy::too_many_arguments)] +async fn finish_security_red( + state: &WorkerState, + ticket_msg: &TicketMessage, + run_id: &str, + github: &GitHubClient, + pr: &PrRef<'_>, + usage: &TokenUsage, + duration: u64, + checks: &[String], + excerpt: &str, + tried: &[String], +) -> Result<(), Box> { + let section = ci_failing_section(checks, excerpt, tried, SECURITY_RED_NEEDED); + match github.get_pull_request(pr.owner, pr.repo, pr.number).await { + Ok(p) => { + let body = with_ci_failing(p["body"].as_str().unwrap_or(""), §ion); + if let Err(e) = + crate::passes::description::save(github, pr.owner, pr.repo, pr.number, &body).await + { + warn!(run_id, error = %e, "Could not write what fails on the pull request"); + } + } + Err(e) => warn!(run_id, error = %e, "Could not read the pull request to say what fails"), + } + let reason = format!( + "{}{}", + super::ready::NOTE_PREFIX, + ci_failing_reason(checks, excerpt, tried.len()) + ); + super::add_progress_note(state, &ticket_msg.team_id, run_id, &reason).await; + mark_pr_ready( + state, + &ticket_msg.team_id, + github, + pr.owner, + pr.repo, + pr.number, + ) + .await; + warn!(run_id, reason = %reason, "A security fix's CI stays red after every set that could come out: ready with CoderHelm's note"); + end_run( + state, + ticket_msg, + run_id, + common::run_status::COMPLETED, + None, + (pr.url, pr.number, pr.branch), + usage, + duration, + None, + None, + ) + .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);