From 138ece76d69171a5a43a79ad64c975f43a2ad400 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Thu, 3 Dec 2026 13:37:00 -0500 Subject: [PATCH 1/2] Checks, the stale label and CI fix loops follow the work - A workspace root installs the whole workspace once (with the sandbox's package cache); members reuse it. The runner whose config picks a test file up decides whether it runs in the sandbox: unit tests beside Playwright specs run under their own runner. - CoderHelm's stale label comes off on the webhook for a push, review, comment or ready for review, with the sweep as backstop, in every mode but the preview. A push counts by the head the warning recorded. Removal is idempotent, a person's label stays theirs, a failure is an alert. - The CI fix loop goes on while its fixes make progress, past its usual cycles and pushes; a per-test cap stops it only when nothing else moved. Its own endings are typed and alerted, never a person's to-do. - Incident xk replays all three. --- ...ks_labels_and_fix_loops_follow_the_work.md | 9 + infra/lib/worker-stack.ts | 13 +- services/common/src/e2e/mod.rs | 1 + services/common/src/e2e/test_owner.rs | 630 ++++++++++++++++++ services/common/src/e2e/test_package.rs | 26 + services/common/src/messages.rs | 10 +- services/common/src/run_round.rs | 28 + services/common/src/stale_prs.rs | 148 +++- services/common/src/stop_rules/tooling.rs | 3 + services/common/src/test_env.rs | 37 +- services/gateway/src/routes/github_webhook.rs | 2 + services/gateway/src/routes/stale_prs.rs | 43 ++ services/worker/src/main.rs | 4 + services/worker/src/passes/habits_check.rs | 14 +- .../incidents/af_lockfiles_out_of_sync.rs | 5 +- .../cy_own_sandbox_never_handed_back.rs | 1 + .../incidents/ga_fix_pushed_unchecked.rs | 2 +- .../incidents/uh_content_step_before_merge.rs | 16 +- .../wh_rounds_that_cant_change_anything.rs | 16 +- ...ks_labels_and_fix_loops_follow_the_work.rs | 480 +++++++++++++ services/worker/src/passes/mod.rs | 23 + services/worker/src/passes/resume.rs | 70 +- services/worker/src/passes/review_verify.rs | 183 ++++- services/worker/src/passes/stale_prs.rs | 190 +++++- 24 files changed, 1886 insertions(+), 68 deletions(-) create mode 100644 docs/incidents/xk_checks_labels_and_fix_loops_follow_the_work.md create mode 100644 services/common/src/e2e/test_owner.rs create mode 100644 services/worker/src/passes/incidents/xk_checks_labels_and_fix_loops_follow_the_work.rs diff --git a/docs/incidents/xk_checks_labels_and_fix_loops_follow_the_work.md b/docs/incidents/xk_checks_labels_and_fix_loops_follow_the_work.md new file mode 100644 index 000000000..a971c4707 --- /dev/null +++ b/docs/incidents/xk_checks_labels_and_fix_loops_follow_the_work.md @@ -0,0 +1,9 @@ +# xk. `xk_checks_labels_and_fix_loops_follow_the_work` + +**What happened:** On one team's pnpm monorepo three things went wrong at once. The review's own verification said part of it "couldn't run": the root workspace's type-check stopped on a member's `node_modules missing`. The same review left four unit tests kept in the end-to-end package out as "an end-to-end spec: it runs against a preview", though Vitest runs them. The stale label stayed on pull requests that people were working on again. And on another pull request CoderHelm's CI fix loop stopped while its fixes were still changing what failed. + +**Why:** The root package was installed with `--ignore-workspace`, so the workspace's members had nothing installed when the root's type-check ran them all. A test file was called an end-to-end spec by where it sat: its package's dependencies named Playwright, or it sat under the folder holding the Playwright config. The stale label came off only in the hourly sweep, which skipped the removal in "Preview only" mode; commits made before the label and pushed after it carried older dates, so they never counted; a person's label was taken off like CoderHelm's own; and a failed removal was a warning line. The CI fix loop ended on fixed counts (ten cycles, eight pushes, two fixes per failing test) whether or not its fixes made progress, and its endings asked a person to look at the check. + +**The guarantee:** A repository root that declares a workspace installs the whole workspace once, with the sandbox's package cache, and every member's checks reuse that install. The review calls its own verification incomplete only when a step really couldn't run. Whether a test file runs in the sandbox is decided by the runner whose config picks it up (its folder and patterns, the runner's defaults standing in): only a file Playwright, Cypress or WebdriverIO picks up waits for a preview. CoderHelm's stale label comes off as soon as the pull request is active again: on the webhook for a push, a review, a review comment, a comment or ready for review, and in the sweep as a backstop, in every mode except the dashboard's preview. A push since the warning counts by the head the warning recorded. Removal is idempotent (a label already gone is done), a label a person put on stays theirs, and a failure is an internal alert, CoderHelm's own problem. The CI fix loop goes on while its fixes make progress: past its usual cycles and pushes while the failure keeps changing, up to twice them, and a test still red after its fixes stops the loop only when nothing else moved. Two cycles without progress end it. Every ending of its own is typed and alerted, never a person's to-do. + +**Where it's enforced:** `common::e2e::test_owner::{owner, configs_for}`, `common::e2e::test_package::{package_of, install_cmd}` (`workspace_root`), `common::test_env::{script_files, package_test_command, narrow}`, the worker's `review_verify::{plan, script}` and `habits_check::is_e2e_spec`. `common::stale_prs::{webhook_activity, last_activity_since_mark, head_when_warned, unmark_on_activity, decide}`, the gateway's `stale_prs::on_webhook` and the worker's `stale_prs::{on_activity, activity, run_repo}`. `common::run_round::{ci_cycle_goes_on, ci_push_cap, test_cap_stops}`, the worker's `GaveUp::own_problem` and `resume::hand_off_red_ci`. diff --git a/infra/lib/worker-stack.ts b/infra/lib/worker-stack.ts index 4c1dcd71d..0c4c56ea9 100644 --- a/infra/lib/worker-stack.ts +++ b/infra/lib/worker-stack.ts @@ -407,9 +407,10 @@ export class WorkerStack extends cdk.Stack { }, }, logging: { cloudWatch: { logGroup: sandboxLogGroup } }, - // Playwright's browsers, kept on the build host between builds (the - // buildspec's `cache.paths`): an end-to-end run, page check or probe - // reuses the last download instead of fetching ~200 MB each time. + // Playwright's browsers and the package managers' downloads, kept on + // the build host between builds (the buildspec's `cache.paths`): an + // end-to-end run, page check or probe reuses the last browser + // download, and an install the last packages fetched. cache: codebuild.Cache.local(codebuild.LocalCacheMode.CUSTOM), // NO_SOURCE: the worker passes a presigned URL for the tarball + the // derived check command as env overrides. The buildspec fetches, extracts, runs the @@ -532,7 +533,11 @@ export class WorkerStack extends cdk.Stack { ], }, }, - cache: { paths: ["/root/.cache/ms-playwright/**/*"] }, + // The package managers' downloads too (`review_verify::PM_CACHE`): + // a workspace install fetches only what changed since the last build. + cache: { + paths: ["/root/.cache/ms-playwright/**/*", "/root/.cache/coderhelm-pm/**/*"], + }, }), }); diff --git a/services/common/src/e2e/mod.rs b/services/common/src/e2e/mod.rs index 4eb7113b4..65fd64ed1 100644 --- a/services/common/src/e2e/mod.rs +++ b/services/common/src/e2e/mod.rs @@ -70,6 +70,7 @@ pub mod signature; pub mod stats; pub mod store; pub mod suggest; +pub mod test_owner; pub mod test_package; pub mod triage; pub mod workflow_gate; diff --git a/services/common/src/e2e/test_owner.rs b/services/common/src/e2e/test_owner.rs new file mode 100644 index 000000000..a4896315a --- /dev/null +++ b/services/common/src/e2e/test_owner.rs @@ -0,0 +1,630 @@ +//! Which test runner runs a test file, read from the runners' own configs. +//! +//! The review's verification used to call a file an end-to-end spec by where +//! it sat: anything in a package whose dependencies name Playwright, or under +//! the folder that holds the Playwright config. A package of end-to-end +//! tests often keeps fast unit tests beside its specs (`e2e/unit/*.test.ts` +//! run by Vitest or Node, `e2e/tests/**/*.spec.ts` run by Playwright), and +//! those unit tests were never run: "it runs against a preview". +//! +//! Now the runner that picks the file up decides. Each runner config at or +//! above the file (`playwright.config.*`, `cypress.config.*`, +//! `vitest.config.*`, a `vite.config.*` with a `test` block, `jest.config.*`, +//! a manifest's `jest` key) claims the file when its folder and patterns +//! (`testDir`, `testMatch`, `testIgnore`, `specPattern`, `include`, +//! `exclude`, `roots`) cover it, the runner's defaults standing in for what +//! the config leaves out. A claim from a pattern the config names beats one +//! from a default. A file only Playwright or Cypress picks up runs against a +//! preview; a file a unit runner picks up, or that no end-to-end config +//! picks up, runs in the sandbox. + +use super::test_package::{package_dir, Runner}; + +/// What runs a test file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Owner { + /// An end-to-end runner (Playwright, Cypress, WebdriverIO): it runs + /// against a preview. + EndToEnd(Runner), + /// A unit runner (Vitest, Jest, or Node's own `--test` when `None`), or + /// no end-to-end config picks it up: it runs in the sandbox. + Unit(Option), +} + +const CODE: &[&str] = &["ts", "js", "mjs", "cjs", "mts", "cts"]; + +/// The runner a config file's name says, if it is one. +fn config_runner(name: &str) -> Option { + if name == "cypress.json" { + return Some(Runner::Cypress); + } + let (stem, ext) = name.rsplit_once('.')?; + if !CODE.contains(&ext) { + return None; + } + match stem { + "playwright.config" => Some(Runner::Playwright), + "cypress.config" => Some(Runner::Cypress), + "vitest.config" | "vite.config" => Some(Runner::Vitest), + "jest.config" => Some(Runner::Jest), + "wdio.conf" => Some(Runner::Wdio), + _ => None, + } +} + +fn parent(path: &str) -> &str { + path.rsplit_once('/').map(|(d, _)| d).unwrap_or("") +} + +/// The runner configs at or above `file`, nearest folder first: what the +/// planner reads to tell who runs it. +pub fn configs_for(tree: &[String], file: &str) -> Vec { + let mut out = Vec::new(); + let mut dir = parent(file).to_string(); + loop { + for p in tree { + if parent(p) == dir + && !p.contains("node_modules/") + && config_runner(p.rsplit('/').next().unwrap_or(p)).is_some() + { + out.push(p.clone()); + } + } + if dir.is_empty() { + return out; + } + dir = parent(&dir).to_string(); + } +} + +/// The string literals of `key`'s value in a config's source: one string, +/// or each string of an array. A `path.join(__dirname, 'tests')` gives its +/// last literal. `None` when the config doesn't name the key. +fn literals(src: &str, key: &str) -> Option> { + let bytes = src.as_bytes(); + let mut from = 0; + while let Some(at) = src[from..].find(key) { + let start = from + at; + from = start + key.len(); + let before_ok = start == 0 || { + let c = bytes[start - 1] as char; + !(c.is_ascii_alphanumeric() || c == '_' || c == '.') + }; + let rest = src[from..].trim_start(); + let rest = rest + .strip_prefix('"') + .or_else(|| rest.strip_prefix('\'')) + .map(|r| r.trim_start()) + .unwrap_or(rest); + if !before_ok || !rest.starts_with(':') { + continue; + } + let value = rest[1..].trim_start(); + // The value up to the end of its array, call or line. + let end = if value.starts_with('[') { + value.find(']').map(|i| i + 1) + } else if let Some(open) = value.find('(').filter(|o| { + value[..*o] + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_') + }) { + value[open..].find(')').map(|i| open + i + 1) + } else { + value.find([',', '\n', '}']) + } + .unwrap_or(value.len()); + let value = &value[..end]; + let mut out = Vec::new(); + let mut chars = value.char_indices().peekable(); + while let Some((i, c)) = chars.next() { + if matches!(c, '\'' | '"' | '`') { + if let Some(j) = value[i + 1..].find(c) { + out.push(value[i + 1..i + 1 + j].to_string()); + while chars.peek().is_some_and(|(k, _)| *k <= i + 1 + j) { + chars.next(); + } + } + } + } + // A regular expression literal. + if let Some(re) = value.strip_prefix('/') { + if let Some(j) = re.rfind('/') { + out.push(format!("re:{}", &re[..j])); + } + } + if !value.starts_with('[') && value.contains('(') { + // A call: only its last literal is the folder. + out = out.split_off(out.len().saturating_sub(1)); + } + return Some(out); + } + None +} + +/// Folder `path` relative to the config's folder `base`, with `./` and +/// trailing slashes gone (`""` is the config's own folder). +fn under(base: &str, path: &str) -> String { + let p = path.trim().trim_start_matches("./").trim_end_matches('/'); + let p = if p == "." { "" } else { p }; + match (base.is_empty(), p.is_empty()) { + (true, _) => p.to_string(), + (false, true) => base.to_string(), + (false, false) => format!("{base}/{p}"), + } +} + +/// `rel` with `dir/` taken off; `None` when it isn't under `dir`. +fn strip<'a>(dir: &str, rel: &'a str) -> Option<&'a str> { + if dir.is_empty() { + Some(rel) + } else { + rel.strip_prefix(&format!("{dir}/")) + } +} + +/// The alternatives of the first `{a,b}`, `?(a|b)`, `@(a|b)` or `+(a|b)` +/// group in `glob`, expanded; the glob itself when it has none. +fn expand(glob: &str) -> Vec { + let b = glob.as_bytes(); + for (i, c) in glob.char_indices() { + let (open, close, sep, empty) = match c { + '{' => ('{', '}', ',', false), + '(' if i > 0 && matches!(b[i - 1], b'?' | b'@' | b'+' | b'!') => { + ('(', ')', '|', b[i - 1] == b'?') + } + _ => continue, + }; + let mut depth = 0; + let mut end = None; + for (j, d) in glob[i..].char_indices() { + if d == '{' || d == '(' { + depth += 1; + } else if d == '}' || d == ')' { + depth -= 1; + if depth == 0 && d == close { + end = Some(i + j); + break; + } + } + } + let Some(end) = end else { continue }; + let pre_end = if open == '(' { i - 1 } else { i }; + let (pre, inner, post) = (&glob[..pre_end], &glob[i + 1..end], &glob[end + 1..]); + let mut parts: Vec<&str> = inner.split(sep).collect(); + if empty { + parts.push(""); + } + return parts + .into_iter() + .flat_map(|p| expand(&format!("{pre}{p}{post}"))) + .collect(); + } + vec![glob.to_string()] +} + +/// One path segment against one glob segment (`*`, `?`, `[...]`). +fn seg_match(g: &[u8], s: &[u8]) -> bool { + match (g.first(), s.first()) { + (None, None) => true, + (Some(b'*'), _) => seg_match(&g[1..], s) || (!s.is_empty() && seg_match(g, &s[1..])), + (Some(b'?'), Some(_)) => seg_match(&g[1..], &s[1..]), + (Some(b'['), Some(c)) => match g.iter().position(|x| *x == b']') { + Some(close) => { + let set = &g[1..close]; + let hit = set + .windows(3) + .any(|w| w[1] == b'-' && w[0] <= *c && *c <= w[2]) + || set.contains(c); + hit && seg_match(&g[close + 1..], &s[1..]) + } + None => g[0] == *c && seg_match(&g[1..], &s[1..]), + }, + (Some(a), Some(c)) => a == c && seg_match(&g[1..], &s[1..]), + _ => false, + } +} + +fn segs_match(g: &[&str], p: &[&str]) -> bool { + match g.first() { + None => p.is_empty(), + Some(&"**") => (0..=p.len()).any(|k| segs_match(&g[1..], &p[k..])), + Some(first) => { + !p.is_empty() + && seg_match(first.as_bytes(), p[0].as_bytes()) + && segs_match(&g[1..], &p[1..]) + } + } +} + +/// Whether `path` (relative to the config's folder) matches a runner's +/// glob or `re:` regular expression. A glob without a slash matches the +/// file's name anywhere, as Playwright reads one. +pub fn glob_match(glob: &str, path: &str) -> bool { + if let Some(re) = glob.strip_prefix("re:") { + return regex::Regex::new(re).is_ok_and(|r| r.is_match(path)); + } + let glob = glob.trim().trim_start_matches("./"); + let parts: Vec<&str> = path.split('/').collect(); + expand(glob).iter().any(|g| { + let gs: Vec<&str> = g.split('/').filter(|s| !s.is_empty()).collect(); + if gs.len() == 1 && !g.contains('/') { + return segs_match(&["**", gs[0]], &parts); + } + segs_match(&gs, &parts) + }) +} + +fn any_match(globs: &[String], path: &str) -> bool { + globs.iter().any(|g| glob_match(g, path)) +} + +/// A unit runner's default test file: `*.test.*` or `*.spec.*` code. +fn default_unit(path: &str) -> bool { + glob_match("**/*.{test,spec}.?(c|m)[jt]s?(x)", path) +} + +/// One config's claim on the file: its runner, and whether a pattern the +/// config names covers it (rather than a default). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Claim { + runner: Runner, + named: bool, +} + +/// What a config says of `file` (from the repository root). +fn claim(config: &str, src: &str, file: &str) -> Option { + let name = config.rsplit('/').next().unwrap_or(config); + let runner = config_runner(name)?; + let base = parent(config); + let rel = strip(base, file)?; + match runner { + Runner::Playwright | Runner::Wdio => { + let dir_lit = literals(src, "testDir").and_then(|v| v.last().cloned()); + let test_dir = under("", dir_lit.as_deref().unwrap_or("")); + let in_dir = strip(&test_dir, rel)?; + let matched = literals(src, "testMatch"); + if literals(src, "testIgnore").is_some_and(|i| any_match(&i, in_dir)) { + return None; + } + let hit = match &matched { + Some(m) if !m.is_empty() => any_match(m, in_dir), + _ => glob_match("**/*.@(spec|test).?(c|m)[jt]s?(x)", in_dir), + }; + hit.then_some(Claim { + runner, + named: dir_lit.is_some() || matched.is_some_and(|m| !m.is_empty()), + }) + } + Runner::Cypress => { + if name == "cypress.json" { + let v: serde_json::Value = serde_json::from_str(src).ok()?; + let dir = v["integrationFolder"] + .as_str() + .unwrap_or("cypress/integration"); + return strip(&under("", dir), rel).map(|_| Claim { + runner, + named: v["integrationFolder"].is_string(), + }); + } + let named = literals(src, "specPattern").filter(|v| !v.is_empty()); + let hit = match &named { + Some(p) => any_match(p, rel), + None => glob_match("cypress/e2e/**/*.cy.{js,jsx,ts,tsx}", rel), + }; + hit.then_some(Claim { + runner, + named: named.is_some(), + }) + } + Runner::Vitest => { + // Only the `test` block is Vitest's: a Vite config's other + // `include` lists (dependency optimizing) aren't tests. + // A Vitest config with no `test` block runs the defaults. + let block = match src.find("test:").or_else(|| src.find("test :")) { + Some(at) => &src[at..], + None if name.starts_with("vitest.") => "", + None => return None, + }; + if literals(block, "exclude").is_some_and(|e| any_match(&e, rel)) + || rel.split('/').any(|s| s == "node_modules") + { + return None; + } + let named = literals(block, "include").filter(|v| !v.is_empty()); + let hit = match &named { + Some(p) => any_match(p, rel), + None => default_unit(rel), + }; + hit.then_some(Claim { + runner, + named: named.is_some(), + }) + } + Runner::Jest => jest_claim( + literals(src, "testMatch").filter(|v| !v.is_empty()), + literals(src, "testRegex").map(|v| v.into_iter().map(|r| format!("re:{r}")).collect()), + literals(src, "roots"), + rel, + ), + } +} + +fn jest_claim( + test_match: Option>, + test_regex: Option>, + roots: Option>, + rel: &str, +) -> Option { + if let Some(roots) = roots.filter(|r| !r.is_empty()) { + let inside = roots.iter().any(|r| { + let r = r.trim_start_matches("").trim_start_matches('/'); + strip(&under("", r), rel).is_some() + }); + if !inside { + return None; + } + } + let named = test_match.is_some() || test_regex.is_some(); + let hit = match (&test_match, &test_regex) { + (Some(m), _) => any_match(m, rel), + (None, Some(r)) => any_match(r, rel), + (None, None) => { + glob_match("**/__tests__/**/*.[jt]s?(x)", rel) + || glob_match("**/?(*.)+(spec|test).[jt]s?(x)", rel) + } + }; + hit.then_some(Claim { + runner: Runner::Jest, + named, + }) +} + +fn is_e2e(r: Runner) -> bool { + matches!(r, Runner::Playwright | Runner::Cypress | Runner::Wdio) +} + +/// The unit runner a package's scripts call, if any (`None` inside +/// `Some`: Node's own `--test`). +fn script_runner(manifest: &str) -> Option> { + let v: serde_json::Value = serde_json::from_str(manifest).ok()?; + let scripts = v["scripts"].as_object()?; + let bodies: Vec = scripts + .values() + .filter_map(|b| b.as_str().map(str::to_ascii_lowercase)) + .collect(); + let calls = |w: &str| { + bodies.iter().any(|b| { + b.split_whitespace() + .any(|x| x.rsplit('/').next() == Some(w)) + }) + }; + if calls("vitest") { + Some(Some(Runner::Vitest)) + } else if calls("jest") { + Some(Some(Runner::Jest)) + } else if bodies.iter().any(|b| b.contains("--test")) { + Some(None) + } else { + None + } +} + +/// Who runs `file`, from the runner configs at or above it (`read` gives +/// their text) and its package's scripts. `None` when nothing read says: +/// the caller keeps its own reading then. +pub fn owner(tree: &[String], file: &str, read: &dyn Fn(&str) -> Option) -> Option { + let mut claims: Vec = Vec::new(); + let mut e2e_read = false; + let mut unread = false; + for c in configs_for(tree, file) { + let Some(src) = read(&c) else { + unread = true; + continue; + }; + let name = c.rsplit('/').next().unwrap_or(&c); + if config_runner(name).is_some_and(is_e2e) { + e2e_read = true; + } + claims.extend(claim(&c, &src, file)); + } + let dir = package_dir(tree, file); + let manifest = dir.as_deref().and_then(|d| { + read(&if d.is_empty() { + "package.json".to_string() + } else { + format!("{d}/package.json") + }) + }); + // A manifest's own `jest` block. + if let Some(v) = manifest + .as_deref() + .and_then(|m| serde_json::from_str::(m).ok()) + .filter(|v| v["jest"].is_object()) + { + let d = dir.as_deref().unwrap_or(""); + if let Some(rel) = strip(d, file) { + let list = |k: &str| { + v["jest"][k].as_array().map(|a| { + a.iter() + .filter_map(|x| x.as_str().map(str::to_string)) + .collect::>() + }) + }; + let regex = match &v["jest"]["testRegex"] { + serde_json::Value::String(s) => Some(vec![format!("re:{s}")]), + _ => None, + }; + claims.extend(jest_claim(list("testMatch"), regex, list("roots"), rel)); + } + } + let pool: Vec = if claims.iter().any(|c| c.named) { + claims.into_iter().filter(|c| c.named).collect() + } else { + claims + }; + if let Some(c) = pool.iter().find(|c| is_e2e(c.runner)) { + // Claimed by both kinds alike: the end-to-end runner runs it too, + // so it stays with the preview. + return Some(Owner::EndToEnd(c.runner)); + } + if let Some(c) = pool.first() { + return Some(Owner::Unit(Some(c.runner))); + } + // No config picks it up. An end-to-end config that was read and passes + // it over never runs it: a unit test beside the specs. + if e2e_read && !unread { + let by = manifest.as_deref().and_then(script_runner); + return Some(Owner::Unit(by.flatten())); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + fn files(list: &[(&str, &str)]) -> (Vec, HashMap) { + ( + list.iter().map(|(p, _)| p.to_string()).collect(), + list.iter() + .filter(|(_, t)| !t.is_empty()) + .map(|(p, t)| (p.to_string(), t.to_string())) + .collect(), + ) + } + + #[test] + fn globs_cover_what_the_runners_mean() { + assert!(glob_match("**/*.spec.ts", "a/b/c.spec.ts")); + assert!(glob_match("*.spec.ts", "a/b/c.spec.ts")); + assert!(glob_match("unit/**/*.test.ts", "unit/x.test.ts")); + assert!(!glob_match("unit/**/*.test.ts", "tests/x.test.ts")); + assert!(glob_match( + "**/*.{test,spec}.?(c|m)[jt]s?(x)", + "unit/x.test.ts" + )); + assert!(glob_match( + "**/*.{test,spec}.?(c|m)[jt]s?(x)", + "unit/x.spec.tsx" + )); + assert!(!glob_match("**/*.{test,spec}.?(c|m)[jt]s?(x)", "unit/x.ts")); + assert!(glob_match("re:.*\\.e2e\\.ts$", "a/b.e2e.ts")); + } + + #[test] + fn literals_read_strings_arrays_and_calls() { + let src = "export default defineConfig({\n testDir: path.join(__dirname, './tests'),\n testMatch: ['**/*.spec.ts', \"**/*.flow.ts\"],\n use: { baseURL: 'http://localhost:3000' },\n});"; + assert_eq!(literals(src, "testDir"), Some(vec!["./tests".into()])); + assert_eq!( + literals(src, "testMatch"), + Some(vec!["**/*.spec.ts".into(), "**/*.flow.ts".into()]) + ); + assert_eq!(literals(src, "testIgnore"), None); + assert_eq!( + literals("{ testDir: './specs' }", "testDir"), + Some(vec!["./specs".into()]) + ); + } + + /// An invented end-to-end package: Playwright specs under `tests/`, + /// Vitest unit tests under `unit/`. + fn e2e_package() -> (Vec, HashMap) { + files(&[ + ("package.json", r#"{"name":"shop","private":true}"#), + ("pnpm-workspace.yaml", "packages:\n - apps/*\n - e2e\n"), + ( + "e2e/package.json", + r#"{"scripts":{"test":"playwright test","test:unit":"vitest run"},"devDependencies":{"@playwright/test":"1","vitest":"2"}}"#, + ), + ( + "e2e/playwright.config.ts", + "import { defineConfig } from '@playwright/test';\nexport default defineConfig({\n testDir: './tests',\n use: { baseURL: process.env.BASE_URL },\n});\n", + ), + ( + "e2e/vitest.config.ts", + "import { defineConfig } from 'vitest/config';\nexport default defineConfig({\n test: { include: ['unit/**/*.test.ts'], environment: 'node' },\n});\n", + ), + ("e2e/unit/cart-total.test.ts", ""), + ("e2e/tests/checkout/flow.spec.ts", ""), + ]) + } + + #[test] + fn a_unit_test_beside_the_specs_is_vitests_and_a_spec_is_playwrights() { + let (tree, texts) = e2e_package(); + let read = |p: &str| texts.get(p).cloned(); + assert_eq!( + owner(&tree, "e2e/unit/cart-total.test.ts", &read), + Some(Owner::Unit(Some(Runner::Vitest))) + ); + assert_eq!( + owner(&tree, "e2e/tests/checkout/flow.spec.ts", &read), + Some(Owner::EndToEnd(Runner::Playwright)) + ); + assert_eq!( + configs_for(&tree, "e2e/unit/cart-total.test.ts"), + ["e2e/playwright.config.ts", "e2e/vitest.config.ts"] + ); + } + + #[test] + fn a_node_test_runner_beside_playwright_is_a_unit_owner() { + let (tree, texts) = files(&[ + ( + "e2e/package.json", + r#"{"scripts":{"test":"playwright test","test:unit":"node --import tsx --test unit/"}}"#, + ), + ( + "e2e/playwright.config.ts", + "export default { testDir: 'tests' };", + ), + ("e2e/unit/a.test.ts", ""), + ]); + let read = |p: &str| texts.get(p).cloned(); + assert_eq!( + owner(&tree, "e2e/unit/a.test.ts", &read), + Some(Owner::Unit(None)) + ); + } + + #[test] + fn nothing_read_leaves_the_caller_to_decide() { + let (tree, _) = e2e_package(); + assert_eq!(owner(&tree, "e2e/unit/cart-total.test.ts", &|_| None), None); + let (tree, texts) = files(&[("web/package.json", "{}"), ("web/a.test.ts", "")]); + let read = |p: &str| texts.get(p).cloned(); + assert_eq!(owner(&tree, "web/a.test.ts", &read), None); + } + + #[test] + fn playwright_without_a_test_dir_claims_its_default_matches() { + let (tree, texts) = files(&[ + ("qa/package.json", "{}"), + ("qa/playwright.config.ts", "export default {};"), + ("qa/login.spec.ts", ""), + ("qa/helpers.ts", ""), + ]); + let read = |p: &str| texts.get(p).cloned(); + assert_eq!( + owner(&tree, "qa/login.spec.ts", &read), + Some(Owner::EndToEnd(Runner::Playwright)) + ); + } + + #[test] + fn a_manifest_jest_block_claims_its_matches() { + let (tree, texts) = files(&[ + ( + "api/package.json", + r#"{"jest":{"testMatch":["**/__checks__/**/*.ts"]}}"#, + ), + ("api/src/__checks__/sum.ts", ""), + ]); + let read = |p: &str| texts.get(p).cloned(); + assert_eq!( + owner(&tree, "api/src/__checks__/sum.ts", &read), + Some(Owner::Unit(Some(Runner::Jest))) + ); + } +} diff --git a/services/common/src/e2e/test_package.rs b/services/common/src/e2e/test_package.rs index f45555845..8038c8f41 100644 --- a/services/common/src/e2e/test_package.rs +++ b/services/common/src/e2e/test_package.rs @@ -65,6 +65,10 @@ pub struct TestPackage { pub runner: Option, /// Changed files, relative to `dir`. pub files: Vec, + /// The repository root that declares a workspace (`pnpm-workspace.yaml` + /// or a `workspaces` list): its install is the whole workspace's. + #[serde(default)] + pub workspace_root: bool, } const LOCKFILES: &[(&str, Manager)] = &[ @@ -231,6 +235,7 @@ pub fn packages_outside( lint: has_eslint(tree, &dir, &pj), runner: runner_of(&pj), files: vec![rel], + workspace_root: false, }); } out @@ -286,6 +291,9 @@ pub fn package_of( lint: has_eslint(tree, &dir, &pj), runner, files: vec![rel], + workspace_root: dir.is_empty() + && (tree.iter().any(|p| p == "pnpm-workspace.yaml") + || !workspace_globs(Some(&pj), None).is_empty()), }) } @@ -354,6 +362,12 @@ pub fn install_dir(p: &TestPackage) -> String { /// workspace was installed on its own (`cd apps/web && pnpm install /// --ignore-workspace --frozen-lockfile`): its folder has no lockfile, so /// pnpm stopped with `ERR_PNPM_NO_LOCKFILE` before any test. +/// +/// The workspace's root installs the whole workspace too +/// ([`TestPackage::workspace_root`]): a root `check-types` runs every +/// member's (turbo or `pnpm -r`), and a root install that ignored the +/// workspace left every member without its `node_modules`, so the review +/// said its own verification "couldn't run". pub fn install_cmd(p: &TestPackage) -> String { format!("{}{}", ensure_manager(p.manager), install_only(p)) } @@ -377,6 +391,16 @@ fn install_only(p: &TestPackage) -> String { Manager::Bun => "bun install --frozen-lockfile".into(), }; } + if p.workspace_root { + let f = if frozen { " --frozen-lockfile" } else { "" }; + return match p.manager { + Manager::Npm if frozen => "npm ci --no-audit --no-fund".into(), + Manager::Npm => "npm install --no-audit --no-fund".into(), + Manager::Pnpm => format!("pnpm install{f}"), + Manager::Yarn => format!("yarn install --ignore-engines{f}"), + Manager::Bun => format!("bun install{f}"), + }; + } match p.manager { Manager::Npm if frozen => "npm ci --no-audit --no-fund --workspaces=false".into(), Manager::Npm => "npm install --no-audit --no-fund --workspaces=false".into(), @@ -763,6 +787,7 @@ mod tests { lint: false, runner: None, files: vec!["a.spec.ts".into()], + workspace_root: false, }; assert_eq!( install_cmd(&p), @@ -850,6 +875,7 @@ mod tests { lint: true, runner: Some(Runner::Playwright), files: vec![], + workspace_root: false, }; let specs = vec!["tests/items.spec.ts".to_string()]; let pw = repeat_cmd(&p, &specs, 20, Some("https://staging.example.com")).unwrap(); diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 56917308e..ffd4340b0 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -734,12 +734,20 @@ pub struct CustomerGuardMessage { pub attempt: u32, } -/// One repository's stale pull request preview (`common::stale_prs`). +/// One repository's stale pull request preview (`common::stale_prs`), or, +/// with `pr`, activity on one of its pull requests that takes CoderHelm's +/// stale label off at once (`worker::passes::stale_prs::on_activity`). #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct StalePrsPreviewMessage { pub team_id: String, /// `owner/name`. pub repo: String, + /// The pull request that saw activity (0: the repository's preview). + #[serde(default, skip_serializing_if = "is_zero_u64")] + pub pr: u64, + /// What the activity was, in plain words ("a review"). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub activity: String, } /// One repo of a Setup run to analyze. diff --git a/services/common/src/run_round.rs b/services/common/src/run_round.rs index 09df97697..640a54341 100644 --- a/services/common/src/run_round.rs +++ b/services/common/src/run_round.rs @@ -69,6 +69,34 @@ pub const MAX_STEPS: u32 = 12; /// Steps in a row that saved nothing new on the round's WIP branch: a /// round with this many is at a dead end and stops. pub const MAX_IDLE_STEPS: u32 = 2; +/// Whether the CI fix loop takes another cycle, by the same rule as a +/// round's steps: it goes on while its fixes make progress. Under `usual` +/// cycles it always may; past them while the last cycle made progress +/// (`idle` 0: the failure changed), up to twice `usual`. After +/// [`MAX_IDLE_STEPS`] cycles in a row without progress it stops: a dead +/// end, said as CoderHelm's own. +pub fn ci_cycle_goes_on(cycle: u32, usual: u32, idle: u32) -> bool { + idle < MAX_IDLE_STEPS && (cycle < usual || (idle == 0 && cycle < usual.saturating_mul(2))) +} + +/// The pushes the CI fix loop may claim now: the usual number, or twice it +/// while the last cycle made progress ([`ci_cycle_goes_on`]). +pub fn ci_push_cap(usual: u32, idle: u32) -> u32 { + if idle == 0 { + usual.saturating_mul(2) + } else { + usual + } +} + +/// Whether one test still red after its pushed fixes stops the loop: only +/// when the last cycle made no progress anywhere (`idle` above 0). While +/// other failures change, the loop takes its next route instead of ending +/// on one test's count. +pub fn test_cap_stops(idle: u32) -> bool { + idle > 0 +} + /// How long past a round's deadline the stuck-run sweep waits before it /// decides the worker is gone. pub const SWEEP_GRACE_SECS: u64 = 300; diff --git a/services/common/src/stale_prs.rs b/services/common/src/stale_prs.rs index 05d72d640..d17bdc1c0 100644 --- a/services/common/src/stale_prs.rs +++ b/services/common/src/stale_prs.rs @@ -20,7 +20,12 @@ //! comment, label change, review request, draft change or reopen counts. //! Other bots' commits, CI runs and pushes to the base branch don't. //! - A pull request with new activity after the warning, or whose stale -//! label a person removed, is un-staled: the label comes off on its own. +//! label a person removed, is un-staled: CoderHelm's label comes off at +//! once on the webhook ([`webhook_activity`]: a push, a review, a review +//! comment, a comment, ready for review), and in the sweep as a backstop, +//! in every mode but the dashboard's preview. A push counts by the head +//! the warning recorded ([`HEAD_MARK`]), whatever its commits' dates. A +//! label a person put on stays theirs. //! - Exempt: a label from [`StaleConfig::exempt_labels`], a draft (when //! [`StaleConfig::exempt_drafts`]), an exempt author, a pull request kept //! open from the dashboard or with `@coderhelm keep open`, one a CoderHelm @@ -55,6 +60,10 @@ pub const LOG_TTL_DAYS: i64 = 90; /// Written into every comment CoderHelm posts for this, so its own comments /// are recognized. pub const MARKER: &str = ""; +/// The warning comment's record of the head it was posted at +/// (``): a push of commits made earlier +/// (their dates are older than the label) still moves the head. +pub const HEAD_MARK: &str = "coderhelm:stale-head"; pub fn repo_sk(repo: &str) -> String { format!("{REPO_PREFIX}{repo}") @@ -231,6 +240,14 @@ impl StaleConfig { format!("{}\n\n{MARKER}", self.fill(&self.warn_message)) } + /// The warning comment, recording the head it was posted at. + pub fn warn_comment_at(&self, head: &str) -> String { + if head.is_empty() || !head.chars().all(|c| c.is_ascii_hexdigit()) { + return self.warn_comment(); + } + format!("{}\n", self.warn_comment()) + } + /// The closing comment, with its marker. `branch_deleted`: the branch /// went with it, and the comment says how to get it back. pub fn close_comment(&self, branch_deleted: bool) -> String { @@ -397,6 +414,118 @@ pub fn last_activity(pr: &Value, timeline: &[Value], label: &str) -> Activity { best } +/// The head CoderHelm's newest stale warning was posted at, from its +/// marker in the timeline's comments. +pub fn head_when_warned(timeline: &[Value]) -> Option { + timeline + .iter() + .filter(|e| { + e["event"].as_str() == Some("commented") + && is_own( + e["actor"]["login"] + .as_str() + .or(e["user"]["login"].as_str()) + .unwrap_or(""), + ) + }) + .filter_map(|e| { + let body = e["body"].as_str()?; + let at = body.find(HEAD_MARK)? + HEAD_MARK.len(); + let sha: String = body[at..] + .trim_start() + .chars() + .take_while(|c| c.is_ascii_hexdigit()) + .collect(); + (!sha.is_empty()).then_some(sha) + }) + .next_back() +} + +/// The newest activity ([`last_activity`]) for a marked pull request, +/// counting a push since the warning: the head moved from the one the +/// warning recorded. Commits pushed after the label but made before it +/// carry older dates than the label, so their dates alone never un-staled +/// it. +pub fn last_activity_since_mark( + pr: &Value, + timeline: &[Value], + label: &str, + marked_at: Option>, +) -> Activity { + let last = last_activity(pr, timeline, label); + let (Some(at), Some(warned)) = (marked_at, head_when_warned(timeline)) else { + return last; + }; + let head = pr["head"]["sha"].as_str().unwrap_or(""); + if head.is_empty() || head.starts_with(&warned) || last.at > at { + return last; + } + Activity { + at: at + Duration::seconds(1), + what: "new commits pushed".to_string(), + by: String::new(), + } +} + +/// A webhook event that is activity on a pull request, read from GitHub's +/// payload: its repository, number, labels, and what happened. Activity by +/// a person, and CoderHelm's own pushes (work on the branch); never +/// CoderHelm's own comments (its warning would un-stale itself) and never +/// another bot's. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WebhookActivity { + pub repo: String, + pub pr: u64, + pub labels: Vec, + pub what: String, +} + +pub fn webhook_activity(event: &str, payload: &Value) -> Option { + let action = payload["action"].as_str().unwrap_or(""); + let sender = &payload["sender"]; + let login = sender["login"].as_str().unwrap_or(""); + let person = by_person(sender); + let (item, what) = match (event, action) { + ("pull_request", "synchronize") if person || is_own(login) => { + (&payload["pull_request"], "new commits pushed") + } + ("pull_request", "ready_for_review" | "reopened" | "converted_to_draft" | "edited") + if person => + { + (&payload["pull_request"], "an update") + } + ("pull_request_review", "submitted") if person => (&payload["pull_request"], "a review"), + ("pull_request_review_comment", "created") if person => { + (&payload["pull_request"], "a review comment") + } + ("issue_comment", "created") if person && payload["issue"]["pull_request"].is_object() => { + (&payload["issue"], "a comment") + } + _ => return None, + }; + let pr = item["number"].as_u64().filter(|n| *n > 0)?; + let repo = payload["repository"]["full_name"].as_str()?.to_string(); + let labels = item["labels"] + .as_array() + .into_iter() + .flatten() + .filter_map(|l| l["name"].as_str().map(String::from)) + .collect(); + Some(WebhookActivity { + repo, + pr, + labels, + what: what.to_string(), + }) +} + +/// Whether activity that just happened takes the label off: CoderHelm put +/// the label there. A label a person put on (or put back) stays theirs, and +/// a label with no `labeled` event read is left alone. +pub fn unmark_on_activity(marked: Option<(DateTime, bool)>) -> bool { + marked.is_some_and(|(_, own)| own) +} + /// When the stale label went on (the newest `labeled` event for it) and /// whether CoderHelm put it there. pub fn marked(timeline: &[Value], label: &str) -> Option<(DateTime, bool)> { @@ -511,10 +640,21 @@ pub fn decide(cfg: &StaleConfig, f: &Facts) -> Plan { }; } match f.marked { - Some((at, _)) => { + Some((at, own)) => { if f.last.at > at { - Plan::Unmark { - why: format!("{} after it was marked", f.last.what), + if own { + Plan::Unmark { + why: format!("{} after it was marked", f.last.what), + } + } else { + // A person put the label on (or back): it stays theirs, + // and the activity since keeps the pull request open. + Plan::Leave { + why: format!( + "{} after a person labelled it; their label stays", + f.last.what + ), + } } } else { let closes_at = at + Duration::days(cfg.close_days as i64); diff --git a/services/common/src/stop_rules/tooling.rs b/services/common/src/stop_rules/tooling.rs index edfc0d11d..b71011d59 100644 --- a/services/common/src/stop_rules/tooling.rs +++ b/services/common/src/stop_rules/tooling.rs @@ -853,6 +853,7 @@ mod tests { lint: true, runner: None, files: vec![], + workspace_root: false, } } @@ -900,6 +901,7 @@ mod tests { &p, test_package::check_steps(&TestPackage { files: vec!["tests/a.spec.ts".into()], + workspace_root: false, ..p.clone() }) .unwrap(), @@ -1127,6 +1129,7 @@ mod tests { &pkg("e2e", Manager::Pnpm, Some("pnpm-lock.yaml")), test_package::check_steps(&TestPackage { files: vec!["tests/a.spec.ts".into()], + workspace_root: false, ..pkg("e2e", Manager::Pnpm, Some("pnpm-lock.yaml")) }) .unwrap(), diff --git a/services/common/src/test_env.rs b/services/common/src/test_env.rs index 9bde02e4d..37fa4aedd 100644 --- a/services/common/src/test_env.rs +++ b/services/common/src/test_env.rs @@ -455,7 +455,8 @@ fn safe_path(p: &str) -> bool { /// place CoderHelm narrows a runner: pytest and `python -m unittest` take /// the path, Vitest and Jest take it as a filter (they print "no test files /// found" when it matches nothing, never a pass), `go test` takes the -/// file's package, `cargo test` an integration test's target. A runner's +/// file's package, `cargo test` an integration test's target, `node --test` +/// the file in place of its paths. A runner's /// own flags after it are dropped with the rest of the line. pub fn narrow(cmd: &str, file: &str) -> Option { if !safe_path(file) { @@ -486,6 +487,17 @@ pub fn narrow(cmd: &str, file: &str) -> Option { if base == "jest" { return Some(format!("{} {file}", prefix(i))); } + // Node's own runner: `node [--import tsx] --test [paths]` takes the + // file in place of its paths, its flags before `--test` kept. + if base == "node" || base == "tsx" { + let stop = low[i + 1..] + .iter() + .position(|w| matches!(w.as_str(), "&&" | ";" | "||" | "|")) + .map_or(low.len(), |p| i + 1 + p); + if let Some(t) = low[i + 1..stop].iter().position(|w| w == "--test") { + return Some(format!("{} {file}", prefix(i + 1 + t))); + } + } if w == "go" && low.get(i + 1).is_some_and(|n| n == "test") && file.ends_with("_test.go") { let dir = file.rsplit_once('/').map_or(".", |(d, _)| d); let pre = prefix(i + 1); @@ -695,6 +707,14 @@ pub fn script_files(env: Option<&TestEnv>, tree: &[String], files: &[String]) -> add(join(&d, "package.json")); } } + // The runner configs that say who runs each file + // (`e2e::test_owner`), and the root manifest a workspace is read from. + for f in files { + for c in crate::e2e::test_owner::configs_for(tree, f) { + add(c); + } + } + add("package.json".to_string()); for p in tree .iter() .filter(|p| p.ends_with("/package.json") && !p.contains("node_modules/")) @@ -721,8 +741,19 @@ pub fn package_test_command( } else { file.strip_prefix(&format!("{dir}/"))? }; - for script in ["test:unit", "test:run", "test"] { - let Some(body) = v["scripts"][script].as_str() else { + // The usual names first, then any other script whose runner takes one + // file (an end-to-end package's `unit` script beside its `test`). + let mut names: Vec = ["test:unit", "test:run", "test"] + .iter() + .map(|s| s.to_string()) + .collect(); + if let Some(o) = v["scripts"].as_object() { + let mut rest: Vec<&String> = o.keys().filter(|k| !names.contains(k)).collect(); + rest.sort(); + names.extend(rest.into_iter().cloned()); + } + for script in &names { + let Some(body) = v["scripts"][script.as_str()].as_str() else { continue; }; let (at, body) = diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 15767ebce..5f49ad5a7 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -495,6 +495,8 @@ async fn dispatch( delivery_id, ) .await; + // Activity on a pull request takes CoderHelm's stale label off now. + super::stale_prs::on_webhook(state, event_type, payload, team_id).await; // A plan task's pull request moved: its plan's state follows. if matches!( event_type, diff --git a/services/gateway/src/routes/stale_prs.rs b/services/gateway/src/routes/stale_prs.rs index 20575c7b3..265d57b61 100644 --- a/services/gateway/src/routes/stale_prs.rs +++ b/services/gateway/src/routes/stale_prs.rs @@ -89,6 +89,48 @@ fn config_of(item: Option<&Item>) -> Option { item.and_then(|i| StaleConfig::from_json(&s(i, stale::ATTR_CONFIG))) } +/// A webhook event that is activity on a pull request carrying the +/// repository's stale label (`stale::webhook_activity`: a push, a review, a +/// review comment, a comment, ready for review): the worker takes +/// CoderHelm's label off now, in every mode, instead of waiting for the +/// hourly sweep. Events on pull requests without the label cost nothing +/// more than reading the payload. +pub async fn on_webhook(state: &AppState, event: &str, payload: &Value, team_id: &str) { + let Some(a) = stale::webhook_activity(event, payload) else { + return; + }; + if a.labels.is_empty() { + return; + } + let team = get(state, team_id, stale::TEAM_SK).await.ok().flatten(); + let own = get(state, team_id, &stale::repo_sk(&a.repo)) + .await + .ok() + .flatten(); + let cfg = stale::effective( + config_of(team.as_ref()).as_ref(), + config_of(own.as_ref()).as_ref(), + ); + if !a.labels.iter().any(|l| l.eq_ignore_ascii_case(&cfg.label)) { + return; + } + let msg = WorkerMessage::StalePrsPreview(StalePrsPreviewMessage { + team_id: team_id.to_string(), + repo: a.repo.clone(), + pr: a.pr, + activity: a.what.clone(), + }); + match super::github_webhook::send_to_queue(state, &state.config.ticket_queue_url, &msg).await { + Ok(_) => { + info!(team = %team_id, repo = %a.repo, pr = a.pr, what = %a.what, "Stale label: activity queued") + } + // The hourly sweep takes the label off if this never lands. + Err(e) => { + warn!(team = %team_id, repo = %a.repo, pr = a.pr, error = ?e, "Stale label: activity not queued") + } + } +} + /// GET /api/reviewer/stale/config?repo=owner/name pub async fn get_config( State(state): State>, @@ -436,6 +478,7 @@ pub async fn preview( let msg = WorkerMessage::StalePrsPreview(StalePrsPreviewMessage { team_id: claims.team_id.clone(), repo: repo.clone(), + ..Default::default() }); super::github_webhook::send_to_queue(&state, &state.config.ticket_queue_url, &msg).await?; info!(team = %claims.team_id, repo, "Stale PR preview queued"); diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index c6a9314ea..a0b4d04f7 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -873,6 +873,10 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe passes::security_fixes::on_event(&state, &msg).await; } } + models::WorkerMessage::StalePrsPreview(msg) if msg.pr != 0 => { + info!(team_id = %msg.team_id, repo = %msg.repo, pr = msg.pr, "Stale PR activity"); + passes::stale_prs::activity(&state, &msg).await; + } models::WorkerMessage::StalePrsPreview(msg) => { info!(team_id = %msg.team_id, repo = %msg.repo, "Stale PR preview"); passes::stale_prs::preview(&state, &msg).await; diff --git a/services/worker/src/passes/habits_check.rs b/services/worker/src/passes/habits_check.rs index 5c24c9a4b..77ef05cb8 100644 --- a/services/worker/src/passes/habits_check.rs +++ b/services/worker/src/passes/habits_check.rs @@ -1265,14 +1265,24 @@ const KIND: &str = "unit"; /// unit sandbox (CI and the end-to-end proof run it there). pub const E2E_SPEC: &str = "an end-to-end spec: it runs against a preview, not in the unit sandbox"; -/// Whether `file` is an end-to-end spec: its package's runner drives a -/// browser, or it sits in the repository's end-to-end suite. +/// Whether `file` is an end-to-end spec. The runner whose config picks it +/// up decides (`common::e2e::test_owner`): a unit test kept beside the +/// specs in an end-to-end package runs under Vitest, Jest or Node, in the +/// sandbox. Only when no config read says does the old reading stand: its +/// package's runner drives a browser, or it sits in the repository's +/// end-to-end suite. pub(crate) fn is_e2e_spec( tree: &[String], file: &str, texts: &dyn Fn(&str) -> Option, ) -> bool { + use common::e2e::test_owner::{owner, Owner}; use test_package::Runner as R; + match owner(tree, file, texts) { + Some(Owner::EndToEnd(_)) => return true, + Some(Owner::Unit(_)) => return false, + None => {} + } let runner = test_package::package_of(tree, file, texts).and_then(|p| p.runner); matches!(runner, Some(R::Playwright | R::Cypress | R::Wdio)) || common::preview::e2e_suite(tree) diff --git a/services/worker/src/passes/incidents/af_lockfiles_out_of_sync.rs b/services/worker/src/passes/incidents/af_lockfiles_out_of_sync.rs index cb179bae3..a364d7cd6 100644 --- a/services/worker/src/passes/incidents/af_lockfiles_out_of_sync.rs +++ b/services/worker/src/passes/incidents/af_lockfiles_out_of_sync.rs @@ -218,10 +218,9 @@ async fn out_of_sync_lockfiles_are_regenerated_by_code_before_any_model_round() }; let repair_at = at("let repair = lock_repair_on_pr("); assert!(at("common::lockfile_sync::mismatches(&logs)") < repair_at); - assert!(repair_at < at("let over_cycle = cycle >= MAX_CI_FIX_CYCLES;")); + assert!(repair_at < at("let over_cycle =")); assert!( - repair_at - < at("if check_and_record_stall(state, &msg.team_id, &msg.run_id, &gap_text).await") + repair_at < at("check_and_record_stall(state, &msg.team_id, &msg.run_id, &gap_text).await") ); assert!(repair_at < at("ci_fix_effort(attempt, max_attempts),")); // And in a re-run that finds its pull request red, before its model. diff --git a/services/worker/src/passes/incidents/cy_own_sandbox_never_handed_back.rs b/services/worker/src/passes/incidents/cy_own_sandbox_never_handed_back.rs index 4ce2bb021..b4a828e44 100644 --- a/services/worker/src/passes/incidents/cy_own_sandbox_never_handed_back.rs +++ b/services/worker/src/passes/incidents/cy_own_sandbox_never_handed_back.rs @@ -135,6 +135,7 @@ fn playwrights_browsers_come_through_the_proxys_mirror_and_are_kept() { lint: false, runner: Some(common::e2e::test_package::Runner::Playwright), files: Vec::new(), + workspace_root: false, }; let repeat = common::e2e::test_package::repeat_cmd(&pkg, &["tests/a.spec.ts".into()], 20, None).unwrap(); diff --git a/services/worker/src/passes/incidents/ga_fix_pushed_unchecked.rs b/services/worker/src/passes/incidents/ga_fix_pushed_unchecked.rs index fa479cd5a..d692462b9 100644 --- a/services/worker/src/passes/incidents/ga_fix_pushed_unchecked.rs +++ b/services/worker/src/passes/incidents/ga_fix_pushed_unchecked.rs @@ -206,7 +206,7 @@ fn a_test_red_after_two_pushed_fixes_stops_named_without_a_rollback() { assert!(text.contains("nothing was rolled back")); // The run had several attempts and a rollback; the stop now comes first. let src = include_str!("../resume.rs"); - let stop_at = src.find("ledger.stop(&failing_keys)").unwrap(); + let stop_at = src.find(".stop(&failing_keys)").unwrap(); assert!(stop_at < src.find("// Implement fix").unwrap()); } diff --git a/services/worker/src/passes/incidents/uh_content_step_before_merge.rs b/services/worker/src/passes/incidents/uh_content_step_before_merge.rs index e991610db..ecd39f6e3 100644 --- a/services/worker/src/passes/incidents/uh_content_step_before_merge.rs +++ b/services/worker/src/passes/incidents/uh_content_step_before_merge.rs @@ -111,10 +111,18 @@ fn the_ci_loop_reads_the_gap_before_it_claims_a_fix_round() { let read = src .find("content_verdict(state, &msg.team_id") .expect("read"); - let claim = src[read..] - .find("claim_auto_fix_slot(") - .expect("the claim after it"); - assert!(claim < 4000, "read right before the fix budget is claimed"); + // The cycle's budget starts with its progress check (the stall + // record), then the claim: both after the read. + let budget = src[read..] + .find("check_and_record_stall(state") + .expect("the progress check after it"); + assert!(budget < 4000, "read right before the fix budget is claimed"); + assert!( + src[read + budget..] + .find("claim_auto_fix_slot") + .expect("the claim") + < 2000 + ); let finish = fn_src(src, "\nasync fn finish_awaits_content("); assert!(finish.contains("GaveUp::AwaitsContent")); assert!(finish.contains("mark_pr_ready(")); diff --git a/services/worker/src/passes/incidents/wh_rounds_that_cant_change_anything.rs b/services/worker/src/passes/incidents/wh_rounds_that_cant_change_anything.rs index bfbec3e51..76077ead5 100644 --- a/services/worker/src/passes/incidents/wh_rounds_that_cant_change_anything.rs +++ b/services/worker/src/passes/incidents/wh_rounds_that_cant_change_anything.rs @@ -191,10 +191,18 @@ fn the_ci_loop_reads_the_ticket_before_it_claims_a_round_and_never_retries_a_no_ let read = src .find("common::red_reach::before_round(&red, &readings)") .expect("read before the round"); - let claim = src[read..] - .find("claim_auto_fix_slot(") - .expect("the claim after it"); - assert!(claim < 2500, "read right before the fix budget is claimed"); + // The cycle's budget starts with its progress check (the stall + // record), then the claim: both after the read. + let budget = src[read..] + .find("check_and_record_stall(state") + .expect("the progress check after it"); + assert!(budget < 2500, "read right before the fix budget is claimed"); + assert!( + src[read + budget..] + .find("claim_auto_fix_slot") + .expect("the claim") + < 2000 + ); // Every round is asked for the typed verdict. assert!(src.contains("feedback.push_str(common::red_reach::ASK);")); assert_eq!(src.matches("+ common::red_reach::ASK").count(), 2); diff --git a/services/worker/src/passes/incidents/xk_checks_labels_and_fix_loops_follow_the_work.rs b/services/worker/src/passes/incidents/xk_checks_labels_and_fix_loops_follow_the_work.rs new file mode 100644 index 000000000..73c86fb57 --- /dev/null +++ b/services/worker/src/passes/incidents/xk_checks_labels_and_fix_loops_follow_the_work.rs @@ -0,0 +1,480 @@ +//! xk. Three things on one team's pnpm monorepo went wrong at once. +//! +//! The review's own verification said part of it "couldn't run": the root +//! workspace's type-check failed with a member's `node_modules missing`, +//! because the root was installed with `--ignore-workspace`. It also left +//! out four unit tests kept in the end-to-end package (`e2e/unit/*.test.ts`, +//! run by Vitest) as "an end-to-end spec: it runs against a preview", +//! because the package's dependencies named Playwright. +//! +//! The stale label stayed on pull requests that were active again: only the +//! hourly sweep took it off, never in "Preview only" mode, a push of commits +//! made before the label never counted, and a failed removal was a warning +//! nobody read. +//! +//! The CI fix loop ended on counts while its fixes still made progress: ten +//! cycles, eight pushes, two fixes per failing test, and its endings asked a +//! person to look at the check. +//! +//! Guarantee: a workspace root installs the whole workspace once, and the +//! runner whose config picks a test file up decides whether it runs in the +//! sandbox. CoderHelm's stale label comes off as soon as the pull request is +//! active again (the webhook, with the sweep as the backstop), in every mode, +//! idempotently; a person's label stays theirs; a failure is CoderHelm's own +//! alert. The CI fix loop goes on while it makes progress and ends typed. + +use super::fixture::fn_src; +use crate::passes::review_verify::{plan, Kind}; +use crate::passes::stale_prs::{on_activity, run_repo, Env, Inputs, LogEntry, Unstale}; +use chrono::{DateTime, Utc}; +use common::run_round::{ci_cycle_goes_on, ci_push_cap, test_cap_stops, MAX_IDLE_STEPS}; +use common::stale_prs::{self as stale, StaleConfig}; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::sync::Mutex; + +type Error = Box; + +// ── The review's verification ─────────────────────────────────────── + +fn shop() -> (Vec, HashMap) { + let files: &[(&str, &str)] = &[ + ( + "package.json", + r#"{"name":"shop","private":true,"scripts":{"check-types":"turbo run check-types"}}"#, + ), + ("pnpm-workspace.yaml", "packages:\n - apps/*\n - e2e\n"), + ("pnpm-lock.yaml", ""), + ("turbo.json", ""), + ( + "apps/web/package.json", + r#"{"name":"web","scripts":{"check-types":"tsc --noEmit"}}"#, + ), + ( + "apps/cms/package.json", + r#"{"name":"cms","scripts":{"check-types":"tsc --noEmit"}}"#, + ), + ( + "e2e/package.json", + r#"{"name":"e2e","scripts":{"check-types":"tsc --noEmit","test":"playwright test","test:unit":"vitest run"},"devDependencies":{"@playwright/test":"1","vitest":"2"}}"#, + ), + ( + "e2e/playwright.config.ts", + "export default defineConfig({\n testDir: './tests',\n});\n", + ), + ( + "e2e/vitest.config.ts", + "export default defineConfig({\n test: { include: ['unit/**/*.test.ts'] },\n});\n", + ), + ("e2e/unit/banner-copy.test.ts", ""), + ("e2e/unit/menu-order.test.ts", ""), + ("e2e/tests/home/hero.spec.ts", ""), + ]; + ( + files.iter().map(|(p, _)| p.to_string()).collect(), + files + .iter() + .filter(|(_, t)| !t.is_empty()) + .map(|(p, t)| (p.to_string(), t.to_string())) + .collect(), + ) +} + +#[test] +fn the_workspace_installs_once_and_unit_tests_beside_the_specs_run() { + let (tree, texts) = shop(); + let changed: Vec = [ + "turbo.json", + "e2e/unit/banner-copy.test.ts", + "e2e/unit/menu-order.test.ts", + "e2e/tests/home/hero.spec.ts", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let p = plan(&tree, &changed, &[], &|f| texts.get(f).cloned()); + let installs: Vec<_> = p.steps.iter().filter(|s| s.kind == Kind::Install).collect(); + assert_eq!(installs.len(), 1); + assert!(installs[0].cmd.ends_with("pnpm install --frozen-lockfile")); + assert!(!installs[0].cmd.contains("--ignore-workspace")); + let tests: Vec<&str> = p + .steps + .iter() + .filter(|s| s.kind == Kind::Test) + .map(|s| s.cmd.as_str()) + .collect(); + assert_eq!(tests.len(), 2, "{tests:?}"); + assert!(tests.iter().all(|t| t.contains("vitest run unit/"))); + // Only the spec Playwright's config picks up waits for a preview. + assert_eq!(p.left_out.len(), 1); + assert!(p.left_out[0].contains("e2e/tests/home/hero.spec.ts")); + assert!(!p.left_out.iter().any(|l| l.contains("e2e/unit/"))); +} + +// ── The stale label ───────────────────────────────────────────────── + +#[derive(Default)] +struct Repo { + pulls: Vec, + timelines: HashMap>, + writes: Mutex>, + own: Mutex>, + /// What taking the label off answers: `None` is success. + remove_fails: Option<&'static str>, +} + +#[async_trait::async_trait] +impl Env for Repo { + async fn open_pulls(&self) -> Result, Error> { + Ok(self.pulls.clone()) + } + async fn pull(&self, pr: u64) -> Result { + self.pulls + .iter() + .find(|p| p["number"].as_u64() == Some(pr)) + .cloned() + .ok_or_else(|| "404 Not Found".into()) + } + async fn timeline(&self, pr: u64) -> Result, Error> { + Ok(self.timelines.get(&pr).cloned().unwrap_or_default()) + } + async fn held(&self, _pr: &Value) -> Option { + None + } + async fn add_label(&self, pr: u64, label: &str) -> Result<(), Error> { + self.writes + .lock() + .unwrap() + .push(format!("label #{pr} {label}")); + Ok(()) + } + async fn remove_label(&self, pr: u64, label: &str) -> Result<(), Error> { + if let Some(e) = self.remove_fails { + return Err(e.into()); + } + self.writes + .lock() + .unwrap() + .push(format!("unlabel #{pr} {label}")); + Ok(()) + } + async fn comment(&self, pr: u64, body: &str) -> Result<(), Error> { + self.writes + .lock() + .unwrap() + .push(format!("comment #{pr} {body}")); + Ok(()) + } + async fn close(&self, pr: u64) -> Result<(), Error> { + self.writes.lock().unwrap().push(format!("close #{pr}")); + Ok(()) + } + async fn delete_branch(&self, _branch: &str) -> Result<(), Error> { + Ok(()) + } + async fn end_run(&self, _pr: u64, _reason: &str) -> Option { + None + } + async fn log(&self, _e: LogEntry) {} + async fn first_time(&self, _key: &str) -> bool { + true + } + fn budget_low(&self) -> bool { + false + } + async fn pause(&self) {} + async fn own_problem(&self, pr: u64, text: &str) { + self.own.lock().unwrap().push(format!("#{pr}: {text}")); + } +} + +impl Repo { + fn writes(&self) -> Vec { + self.writes.lock().unwrap().clone() + } +} + +const HEAD_AT_MARK: &str = "aaa111"; +const HEAD_NOW: &str = "bbb222"; + +fn now() -> DateTime { + "2026-11-20T12:00:00Z".parse().unwrap() +} + +fn pr(n: u64, labels: &[&str], head: &str) -> Value { + json!({ + "number": n, "state": "open", "title": format!("Menu tweak {n}"), + "html_url": format!("https://github.com/acme/shop/pull/{n}"), + "created_at": "2026-10-01T00:00:00Z", "draft": false, + "user": {"login": "lena", "type": "User"}, + "labels": labels.iter().map(|l| json!({"name": l})).collect::>(), + "head": {"ref": format!("menu-{n}"), "sha": head, "repo": {"full_name": "acme/shop", "fork": false}}, + "base": {"ref": "main", "repo": {"full_name": "acme/shop", "default_branch": "main"}} + }) +} + +fn labeled(by: &str, kind: &str, at: &str) -> Value { + json!({"event": "labeled", "actor": {"login": by, "type": kind}, "label": {"name": "stale"}, "created_at": at}) +} + +fn ours(at: &str) -> Value { + labeled("coderhelm[bot]", "Bot", at) +} + +/// CoderHelm's warning, recording the head it was posted at. +fn warning(at: &str) -> Value { + json!({"event": "commented", "actor": {"login": "coderhelm[bot]", "type": "Bot"}, + "created_at": at, "body": StaleConfig::default().warn_comment_at(HEAD_AT_MARK)}) +} + +fn inputs(act: bool) -> Inputs { + Inputs { + cfg: StaleConfig { + enabled: true, + dry_run: !act, + ..Default::default() + }, + now: now(), + kept_open: HashMap::new(), + cursor: 0, + act, + tidy: true, + } +} + +#[tokio::test] +async fn a_commit_after_the_label_takes_it_off() { + let mut r = Repo { + pulls: vec![pr(1, &["Stale"], HEAD_NOW)], + ..Default::default() + }; + r.timelines.insert( + 1, + vec![ + ours("2026-11-15T00:00:00Z"), + warning("2026-11-15T00:00:01Z"), + json!({"event": "committed", "author": {"name": "Lena", "date": "2026-11-18T09:00:00Z"}, + "committer": {"name": "Lena", "date": "2026-11-18T09:00:00Z"}}), + ], + ); + run_repo(&r, &inputs(true)).await.unwrap(); + // Taken off as the pull request spells it. + assert_eq!(r.writes(), ["unlabel #1 Stale"]); +} + +#[tokio::test] +async fn commits_made_before_the_label_but_pushed_after_take_it_off() { + let mut r = Repo { + pulls: vec![pr(2, &["stale"], HEAD_NOW)], + ..Default::default() + }; + r.timelines.insert( + 2, + vec![ + json!({"event": "committed", "author": {"name": "Lena", "date": "2026-11-01T09:00:00Z"}, + "committer": {"name": "Lena", "date": "2026-11-01T09:00:00Z"}}), + ours("2026-11-15T00:00:00Z"), + warning("2026-11-15T00:00:01Z"), + ], + ); + run_repo(&r, &inputs(true)).await.unwrap(); + assert_eq!(r.writes(), ["unlabel #2 stale"]); + // The head the warning recorded: no push since, the label stays. + let mut quiet = Repo { + pulls: vec![pr(2, &["stale"], HEAD_AT_MARK)], + ..Default::default() + }; + quiet.timelines = r.timelines.clone(); + run_repo(&quiet, &inputs(true)).await.unwrap(); + assert!(quiet.writes().is_empty()); +} + +#[tokio::test] +async fn a_review_after_the_label_takes_it_off_from_the_webhook_and_the_sweep() { + let review = json!({ + "action": "submitted", + "sender": {"login": "omar", "type": "User"}, + "repository": {"full_name": "acme/shop"}, + "pull_request": {"number": 3, "labels": [{"name": "stale"}]} + }); + let a = stale::webhook_activity("pull_request_review", &review).unwrap(); + assert_eq!( + (a.repo.as_str(), a.pr, a.what.as_str()), + ("acme/shop", 3, "a review") + ); + let mut r = Repo { + pulls: vec![pr(3, &["stale"], HEAD_AT_MARK)], + ..Default::default() + }; + r.timelines.insert( + 3, + vec![ + ours("2026-11-15T00:00:00Z"), + json!({"event": "reviewed", "user": {"login": "omar", "type": "User"}, "submitted_at": "2026-11-19T00:00:00Z"}), + ], + ); + assert_eq!( + on_activity(&r, &StaleConfig::default(), 3, &a.what).await, + Unstale::Removed + ); + assert_eq!(r.writes(), ["unlabel #3 stale"]); + // The sweep is the backstop for a webhook that never arrived. + let backstop = Repo { + pulls: r.pulls.clone(), + timelines: r.timelines.clone(), + ..Default::default() + }; + run_repo(&backstop, &inputs(true)).await.unwrap(); + assert_eq!(backstop.writes(), ["unlabel #3 stale"]); + // Every kind of activity the webhook hears, and never CoderHelm's own + // comment (its warning would take its own label off). + let push = json!({"action": "synchronize", "sender": {"login": "lena", "type": "User"}, + "repository": {"full_name": "acme/shop"}, "pull_request": {"number": 3, "labels": []}}); + assert!(stale::webhook_activity("pull_request", &push).is_some()); + let ready = json!({"action": "ready_for_review", "sender": {"login": "lena", "type": "User"}, + "repository": {"full_name": "acme/shop"}, "pull_request": {"number": 3, "labels": []}}); + assert!(stale::webhook_activity("pull_request", &ready).is_some()); + let own = json!({"action": "created", "sender": {"login": "coderhelm[bot]", "type": "Bot"}, + "repository": {"full_name": "acme/shop"}, "issue": {"number": 3, "pull_request": {}, "labels": []}}); + assert!(stale::webhook_activity("issue_comment", &own).is_none()); + let person = json!({"action": "created", "sender": {"login": "lena", "type": "User"}, + "repository": {"full_name": "acme/shop"}, "issue": {"number": 3, "pull_request": {}, "labels": []}}); + assert!(stale::webhook_activity("issue_comment", &person).is_some()); +} + +#[tokio::test] +async fn a_persons_re_add_is_respected() { + let mut r = Repo { + pulls: vec![pr(4, &["stale"], HEAD_AT_MARK)], + ..Default::default() + }; + r.timelines.insert( + 4, + vec![ + ours("2026-11-10T00:00:00Z"), + json!({"event": "unlabeled", "actor": {"login": "coderhelm[bot]", "type": "Bot"}, "label": {"name": "stale"}, "created_at": "2026-11-12T00:00:00Z"}), + labeled("lena", "User", "2026-11-13T00:00:00Z"), + json!({"event": "commented", "actor": {"login": "omar", "type": "User"}, "created_at": "2026-11-19T00:00:00Z"}), + ], + ); + run_repo(&r, &inputs(true)).await.unwrap(); + assert!(r.writes().is_empty(), "{:?}", r.writes()); + assert_eq!( + on_activity(&r, &StaleConfig::default(), 4, "a comment").await, + Unstale::Left("a person put the label on".into()) + ); + assert!(r.writes().is_empty()); +} + +#[tokio::test] +async fn preview_only_never_adds_but_still_takes_its_own_label_off() { + let mut r = Repo { + pulls: vec![pr(5, &[], HEAD_AT_MARK), pr(6, &["stale"], HEAD_AT_MARK)], + ..Default::default() + }; + r.timelines.insert( + 6, + vec![ + ours("2026-11-10T00:00:00Z"), + json!({"event": "commented", "actor": {"login": "lena", "type": "User"}, "created_at": "2026-11-19T00:00:00Z"}), + ], + ); + let out = run_repo(&r, &inputs(false)).await.unwrap(); + assert_eq!(r.writes(), ["unlabel #6 stale"]); + assert!(out.items.iter().any(|i| i.pr == 5 && i.action == "mark")); + // The dashboard's preview changes nothing at all. + let preview = Repo { + pulls: r.pulls.clone(), + timelines: r.timelines.clone(), + ..Default::default() + }; + let mut inp = inputs(false); + inp.tidy = false; + run_repo(&preview, &inp).await.unwrap(); + assert!(preview.writes().is_empty()); +} + +#[tokio::test] +async fn removal_is_idempotent_and_a_failure_is_coderhelms_own_alert() { + let mut gone = Repo { + pulls: vec![pr(7, &["stale"], HEAD_AT_MARK)], + remove_fails: Some("404 Label does not exist"), + ..Default::default() + }; + gone.timelines.insert(7, vec![ours("2026-11-10T00:00:00Z")]); + assert_eq!( + on_activity(&gone, &StaleConfig::default(), 7, "a comment").await, + Unstale::Removed + ); + assert!(gone.own.lock().unwrap().is_empty()); + let broken = Repo { + pulls: gone.pulls.clone(), + timelines: gone.timelines.clone(), + remove_fails: Some("500 Internal Server Error"), + ..Default::default() + }; + assert!(matches!( + on_activity(&broken, &StaleConfig::default(), 7, "a comment").await, + Unstale::Failed(_) + )); + assert_eq!(broken.own.lock().unwrap().len(), 1); + // No label on it: nothing to do. + let clean = Repo { + pulls: vec![pr(8, &[], HEAD_AT_MARK)], + ..Default::default() + }; + assert_eq!( + on_activity(&clean, &StaleConfig::default(), 8, "a comment").await, + Unstale::Left("no stale label".into()) + ); +} + +#[test] +fn the_webhook_and_the_worker_are_wired() { + let hook = include_str!("../../../../gateway/src/routes/github_webhook.rs"); + assert!(hook.contains("super::stale_prs::on_webhook(state, event_type, payload, team_id)")); + let main = include_str!("../../main.rs"); + assert!(main.contains("passes::stale_prs::activity(&state, &msg)")); + let sweep = include_str!("../stale_prs.rs"); + assert!(fn_src(sweep, "async fn sweep_one(").contains("tidy: !preview")); +} + +// ── The CI fix loop ───────────────────────────────────────────────── + +#[test] +fn the_fix_loop_goes_on_while_it_makes_progress_and_ends_typed() { + // Under the usual count it always goes on; past it while the failure + // keeps changing, up to twice; never after two cycles without progress. + assert!(ci_cycle_goes_on(9, 10, 1)); + assert!(ci_cycle_goes_on(14, 10, 0)); + assert!(!ci_cycle_goes_on(14, 10, 1)); + assert!(!ci_cycle_goes_on(20, 10, 0)); + assert!(!ci_cycle_goes_on(3, 10, MAX_IDLE_STEPS)); + assert_eq!(ci_push_cap(8, 0), 16); + assert_eq!(ci_push_cap(8, 1), 8); + // One test still red after its fixes stops the loop only when nothing + // else moved. + assert!(!test_cap_stops(0)); + assert!(test_cap_stops(1)); + // Every ending of CoderHelm's own is typed and alerted, never a + // person's to-do. + use crate::passes::GaveUp; + use common::person_only::OwnSubject; + for (g, s) in [ + (GaveUp::Budget, OwnSubject::Budget), + (GaveUp::Stalled, OwnSubject::Unnamed), + (GaveUp::NoChange, OwnSubject::Unnamed), + (GaveUp::NoProgress, OwnSubject::Unnamed), + (GaveUp::FixError, OwnSubject::Tooling), + ] { + assert_eq!(g.own_problem("x").unwrap().subject, s); + } + assert!(GaveUp::NeedsPermission.own_problem("x").is_none()); + let src = include_str!("../resume.rs"); + assert!( + src.contains("run_round::ci_cycle_goes_on(cycle as u32, MAX_CI_FIX_CYCLES as u32, idle)") + ); + assert!(src.contains(".filter(|_| run_round::test_cap_stops(idle))")); + assert!(fn_src(src, "async fn hand_off_red_ci(").contains("why.own_problem(needed)")); + assert!(!src.contains("A person looks at the failing check")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 8f3c6af8b..11c4d4d13 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -9475,6 +9475,29 @@ pub(crate) enum GaveUp { } impl GaveUp { + /// The ending as CoderHelm's own problem, typed: its fix count, a dead + /// end (the same failure, fixes that change nothing) or its own fault. + /// `None` for an ending a reason outside CoderHelm owns (the base, an + /// unrelated test, content, a change outside the repository, a + /// permission): those are typed where they are read. + pub(crate) fn own_problem(self, text: &str) -> Option { + use common::person_only::{OwnProblem, OwnSubject}; + let subject = match self { + GaveUp::Budget => OwnSubject::Budget, + GaveUp::Stalled | GaveUp::NoChange | GaveUp::NoProgress => OwnSubject::Unnamed, + GaveUp::FixError => OwnSubject::Tooling, + GaveUp::RedOnBase + | GaveUp::UnrelatedTest + | GaveUp::AwaitsContent + | GaveUp::NeedsOutside + | GaveUp::NeedsPermission => return None, + }; + Some(OwnProblem { + subject, + text: format!("CI fix loop ended ({}): {text}", self.as_str()), + }) + } + pub(crate) fn as_str(self) -> &'static str { match self { GaveUp::Budget => "budget", diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 3b17af86b..be74c5ced 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -3054,15 +3054,16 @@ pub async fn run( .await; } } - let over_cycle = cycle >= MAX_CI_FIX_CYCLES; - // Atomically claim a shared auto-fix slot (skipped when the cycle cap has - // already tripped, so we don't consume a slot on the way out). - let claimed = - !over_cycle && super::claim_auto_fix_slot(state, &msg.team_id, &msg.run_id).await; - if over_cycle || !claimed { + // Halt-on-no-progress: if the SAME failure keeps recurring, the fixes + // aren't working (noop commits, placeholder stubs, wrong fixes). Stop + // churning the PR and hand it to a human — this fires long before the + // coarse cycle cap above. + let (idle, stalled) = + check_and_record_stall(state, &msg.team_id, &msg.run_id, &gap_text).await; + if stalled { warn!( run_id = msg.run_id, - cycle, "Fix budget reached — the PR stays a draft with what fails" + "CI fixes stalled on the same failure — the PR stays a draft with what fails" ); return hand_off_red_ci( state, @@ -3079,22 +3080,31 @@ pub async fn run( &usage, wall_clock_secs(created_at, &start), &events, - super::GaveUp::Budget, + super::GaveUp::Stalled, &excerpt_line, - &[format!("{cycle} fix cycle(s) on this pull request")], - "CoderHelm's fix budget for this run is spent: fix the failing check on this branch, or re-run it if it isn't the change's.", + &["the same failure came back after each fix".to_string()], + "CoderHelm's fixes kept meeting the same failure after it tried another route: CoderHelm's own dead end, and its maintainers were alerted. CI's result stands on this branch.", ) .await; } - // Halt-on-no-progress: if the SAME failure keeps recurring, the fixes - // aren't working (noop commits, placeholder stubs, wrong fixes). Stop - // churning the PR and hand it to a human — this fires long before the - // coarse cycle cap above. - if check_and_record_stall(state, &msg.team_id, &msg.run_id, &gap_text).await { + // Another cycle while the fixes make progress (`run_round`'s rule): + // past the usual count only while the last cycle changed what fails. + let over_cycle = !run_round::ci_cycle_goes_on(cycle as u32, MAX_CI_FIX_CYCLES as u32, idle); + // Atomically claim a shared auto-fix slot (skipped when the cycle cap has + // already tripped, so we don't consume a slot on the way out). + let claimed = !over_cycle + && super::claim_auto_fix_slot_upto( + state, + &msg.team_id, + &msg.run_id, + run_round::ci_push_cap(super::MAX_AUTO_FIX_PUSHES, idle), + ) + .await; + if over_cycle || !claimed { warn!( run_id = msg.run_id, - "CI fixes stalled on the same failure — the PR stays a draft with what fails" + cycle, "Fix budget reached — the PR stays a draft with what fails" ); return hand_off_red_ci( state, @@ -3111,10 +3121,10 @@ pub async fn run( &usage, wall_clock_secs(created_at, &start), &events, - super::GaveUp::Stalled, + super::GaveUp::Budget, &excerpt_line, - &["the same failure came back after each fix".to_string()], - "A person looks at the failing check: CoderHelm's fixes keep meeting the same failure.", + &[format!("{cycle} fix cycle(s) on this pull request")], + "CoderHelm's fix cycles for this run are spent after its fixes stopped making progress: CoderHelm's own limit, and its maintainers were alerted. CI's result stands on this branch.", ) .await; } @@ -3129,7 +3139,12 @@ pub async fn run( &failing_wf, ); let ledger = super::push_checks::load_ledger(state, &msg.team_id, &msg.run_id).await; - if let Some(stop) = ledger.stop(&failing_keys) { + // Only when the last cycle made no progress elsewhere: while other + // failures change, the loop goes on by its next route. + if let Some(stop) = ledger + .stop(&failing_keys) + .filter(|_| run_round::test_cap_stops(idle)) + { let error = evidence .as_ref() .map(|e| e.error.clone()) @@ -3813,7 +3828,7 @@ pub async fn run( &excerpt_line, &tried, &format!( - "The fix lives in this repository, but {why_here}: a person reads the failing check's report (its test name and error are above) and fixes it on this branch.", + "The fix lives in this repository, but {why_here}, and the lockfile repair was its other route: CoderHelm's own dead end, and its maintainers were alerted. The failing check's report (its test name and error) is above.", ), ) .await; @@ -4008,7 +4023,7 @@ pub async fn run( super::GaveUp::NoProgress, &excerpt_line, &["fixes stopped changing the code (same files, same bytes)".to_string()], - "A person looks at the failing check: CoderHelm's fixes stopped changing the code.", + "CoderHelm's fixes stopped changing the code after it tried another route: CoderHelm's own dead end, and its maintainers were alerted. CI's result stands on this branch.", ) .await; } @@ -6928,12 +6943,14 @@ fn collect_review_feedback(events: &[RunEvent]) -> String { /// Compare the current failure against the stored one, persist the update, and /// return true if the run has STALLED (same failure repeating → halt). The pure /// decision (`stall_decision` / `ci_failure_signature`) is unit-tested. +/// Records this cycle's failure against the last one: the cycles in a row +/// without progress, and whether that many stops the loop. async fn check_and_record_stall( state: &WorkerState, team_id: &str, run_id: &str, failure_text: &str, -) -> bool { +) -> (u32, bool) { let current_sig = ci_failure_signature(failure_text); let item = state .dynamo @@ -6976,7 +6993,7 @@ async fn check_and_record_stall( .expression_attribute_values(":c", attr_n(new_stall as u64)) .send() .await; - halt + (new_stall, halt) } /// After a fix lands: decide whether it moved the code at all (tree before @@ -8806,6 +8823,11 @@ async fn hand_off_red_ci( super::CiOutcome::HandedOff(why), ) .await; + // A loop that ends on its own count, a dead end or its own fault is + // CoderHelm's own problem, typed and alerted: never a person's to-do. + if let Some(p) = why.own_problem(needed) { + super::own_problems::record(state, &msg.team_id, &msg.run_id, &p).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 { diff --git a/services/worker/src/passes/review_verify.rs b/services/worker/src/passes/review_verify.rs index 4d1168ff6..465666c4c 100644 --- a/services/worker/src/passes/review_verify.rs +++ b/services/worker/src/passes/review_verify.rs @@ -325,16 +325,33 @@ fn node_package( let mut deps = vec![join(dir, "package.json")]; deps.extend(pkg.lockfile.clone()); deps.push(join(&install_at, "package.json")); - let install = push( - out, - Step { - kind: Kind::Install, - dir: shown_dir(&install_at), - cmd: install, - needs: None, - deps, - }, - ); + // One install per folder: the workspace root's install covers every + // member, so a member planned after it reuses it (and its dependency + // files join it) instead of installing the workspace again. + let install = match out + .steps + .iter() + .position(|s| s.kind == Kind::Install && s.dir == shown_dir(&install_at)) + { + Some(i) => { + for d in deps { + if !out.steps[i].deps.contains(&d) { + out.steps[i].deps.push(d); + } + } + i + } + None => push( + out, + Step { + kind: Kind::Install, + dir: shown_dir(&install_at), + cmd: install, + needs: None, + deps, + }, + ), + }; let manifest = read(&join(dir, "package.json")); let scripts = scripts_of(manifest.as_deref()); let check = if let Some((at, line)) = ci_typecheck(lines, dir, tree, read) { @@ -462,13 +479,33 @@ fn header(n: usize) -> String { format!("--- verify step {n} output ---") } +/// Where the package managers keep their downloads in the sandbox: the +/// sandbox keeps this folder between builds (the buildspec's cache paths), +/// so a workspace install fetches only what changed. +pub const PM_CACHE: &str = "/root/.cache/coderhelm-pm"; + +/// The line that points npm, pnpm and yarn at [`PM_CACHE`], unless the +/// build already chose a place. +pub fn cache_line() -> String { + format!( + "export npm_config_cache=\"${{npm_config_cache:-{PM_CACHE}/npm}}\" \ + npm_config_store_dir=\"${{npm_config_store_dir:-{PM_CACHE}/pnpm-store}}\" \ + YARN_CACHE_FOLDER=\"${{YARN_CACHE_FOLDER:-{PM_CACHE}/yarn}}\"\n" + ) +} + /// One shell script for the sandbox: each step in order with its output in /// its own log, a step whose install failed skipped, the tail of each /// failing step under its own header, and one marker per step with its exit -/// code. It exits non-zero when any step failed. +/// code. It exits non-zero when any step failed. The installs use the +/// sandbox's package cache ([`cache_line`]). pub fn script(steps: &[Step]) -> String { let per = 3_500 / steps.len().max(1); - let mut out = String::new(); + let mut out = if steps.iter().any(|s| s.kind == Kind::Install) { + cache_line() + } else { + String::new() + }; for (i, s) in steps.iter().enumerate() { let n = i + 1; let run = format!("( {} ) > /tmp/ch-verify-{n}.log 2>&1; ch_v{n}=$?", s.cmd); @@ -779,6 +816,128 @@ mod tests { assert_eq!(p.steps[1].needs, Some(0)); } + /// An invented pnpm workspace: two apps, and an end-to-end package + /// whose `unit/` tests run under Vitest and `tests/` specs under + /// Playwright. + fn shop() -> (Vec, std::collections::HashMap) { + let files: &[(&str, &str)] = &[ + ( + "package.json", + r#"{"name":"shop","private":true,"scripts":{"check-types":"turbo run check-types"}}"#, + ), + ("pnpm-workspace.yaml", "packages:\n - apps/*\n - e2e\n"), + ("pnpm-lock.yaml", ""), + ("turbo.json", ""), + ( + "apps/web/package.json", + r#"{"name":"web","scripts":{"check-types":"tsc --noEmit"}}"#, + ), + ("apps/web/src/cart.ts", ""), + ( + "apps/cms/package.json", + r#"{"name":"cms","scripts":{"check-types":"tsc --noEmit"}}"#, + ), + ( + "e2e/package.json", + r#"{"name":"e2e","scripts":{"check-types":"tsc --noEmit","test":"playwright test","test:unit":"vitest run"},"devDependencies":{"@playwright/test":"1","vitest":"2"}}"#, + ), + ( + "e2e/playwright.config.ts", + "export default defineConfig({\n testDir: './tests',\n use: { baseURL: process.env.BASE_URL },\n});\n", + ), + ( + "e2e/vitest.config.ts", + "export default defineConfig({\n test: { include: ['unit/**/*.test.ts'] },\n});\n", + ), + ("e2e/unit/cart-total.test.ts", ""), + ("e2e/unit/price-label.test.ts", ""), + ("e2e/tests/checkout/flow.spec.ts", ""), + ]; + ( + files.iter().map(|(p, _)| p.to_string()).collect(), + files + .iter() + .filter(|(_, t)| !t.is_empty()) + .map(|(p, t)| (p.to_string(), t.to_string())) + .collect(), + ) + } + + #[test] + fn a_workspace_root_check_installs_the_whole_workspace_once() { + let (t, texts) = shop(); + let changed: Vec = ["turbo.json", "e2e/unit/cart-total.test.ts"] + .iter() + .map(|s| s.to_string()) + .collect(); + let p = plan(&t, &changed, &[], &|f| texts.get(f).cloned()); + let installs: Vec<&Step> = p.steps.iter().filter(|s| s.kind == Kind::Install).collect(); + assert_eq!(installs.len(), 1, "{:#?}", p.steps); + assert_eq!(installs[0].dir, "."); + assert!( + installs[0].cmd.ends_with("pnpm install --frozen-lockfile"), + "{}", + installs[0].cmd + ); + assert!(!installs[0].cmd.contains("--ignore-workspace")); + // Both packages' checks and the unit test hang on that one install. + assert!(p + .steps + .iter() + .all(|s| s.kind == Kind::Install || s.needs == Some(0))); + let cmds: Vec<&str> = p.steps.iter().map(|s| s.cmd.as_str()).collect(); + assert!(cmds.contains(&"cd '.' && pnpm run check-types"), "{cmds:?}"); + assert!( + cmds.contains(&"cd 'e2e' && pnpm run check-types"), + "{cmds:?}" + ); + // The install's dependency files are the root's and the member's. + assert!(installs[0].deps.contains(&"e2e/package.json".to_string())); + assert!(installs[0].deps.contains(&"pnpm-lock.yaml".to_string())); + // The script points the install at the sandbox's package cache. + assert!(script(&p.steps).starts_with(&cache_line())); + // A root check that still prints a member's missing modules after + // the install passed is the run's own problem, said once. + let out = format!( + "{}\nweb:check-types: WARN Local package.json exists, but node_modules missing\n{STEP_MARK} 1 0\n{STEP_MARK} 2 1\n{STEP_MARK} 3 0\n{STEP_MARK} 4 0\n", + header(2) + ); + let v = judge(&p, &changed, &out); + assert!(!v.blocks()); + } + + #[test] + fn unit_tests_in_the_e2e_folder_run_and_only_playwrights_specs_wait_for_a_preview() { + let (t, texts) = shop(); + let changed: Vec = [ + "e2e/unit/cart-total.test.ts", + "e2e/unit/price-label.test.ts", + "e2e/tests/checkout/flow.spec.ts", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let p = plan(&t, &changed, &[], &|f| texts.get(f).cloned()); + let tests: Vec<&str> = p + .steps + .iter() + .filter(|s| s.kind == Kind::Test) + .map(|s| s.cmd.as_str()) + .collect(); + assert_eq!( + tests, + [ + "(cd e2e && npx --no-install vitest run unit/cart-total.test.ts)", + "(cd e2e && npx --no-install vitest run unit/price-label.test.ts)", + ] + ); + assert_eq!(p.left_out.len(), 1, "{:?}", p.left_out); + assert!( + p.left_out[0].starts_with("`e2e/tests/checkout/flow.spec.ts` is an end-to-end spec") + ); + assert!(!p.left_out.iter().any(|l| l.contains("unit/"))); + } + #[test] fn a_skipped_step_and_a_step_with_no_result_are_coderhelms() { let p = Plan { diff --git a/services/worker/src/passes/stale_prs.rs b/services/worker/src/passes/stale_prs.rs index 6dced4785..ff2134e0d 100644 --- a/services/worker/src/passes/stale_prs.rs +++ b/services/worker/src/passes/stale_prs.rs @@ -59,6 +59,8 @@ const MAX_PLAN: usize = 200; #[async_trait::async_trait] pub trait Env: Send + Sync { async fn open_pulls(&self) -> Result, Error>; + /// One pull request as GitHub has it now. + async fn pull(&self, pr: u64) -> Result; async fn timeline(&self, pr: u64) -> Result, Error>; /// Why CoderHelm's own work holds this pull request, if it does. async fn held(&self, pr: &Value) -> Option; @@ -77,6 +79,9 @@ pub trait Env: Send + Sync { fn budget_low(&self) -> bool; /// The pause between writes. async fn pause(&self); + /// CoderHelm's own problem with this pull request's label: an internal + /// alert for its maintainers, never a to-do for the team. + async fn own_problem(&self, pr: u64, text: &str); } /// One logged action. @@ -100,6 +105,11 @@ pub struct Inputs { pub cursor: usize, /// Change things on GitHub (false: a dry run or a preview). pub act: bool, + /// Take CoderHelm's own label off a pull request that is active again, + /// even in a dry run: the label is CoderHelm's to tidy, and a team that + /// went back to "Preview only" after labels went on still gets them off. + /// Only the dashboard's preview changes nothing at all. + pub tidy: bool, } /// What one repository's sweep did and found. @@ -258,13 +268,19 @@ pub async fn run_repo(env: &dyn Env, inp: &Inputs) -> Result { continue; } let labels = labels_of(pr); - let label_on = labels.iter().any(|l| l.eq_ignore_ascii_case(&cfg.label)); - let last = stale::last_activity(pr, &timeline, &cfg.label); + // The label as the pull request spells it: GitHub's names keep the + // case they were made with. + let on_pr = labels + .iter() + .find(|l| l.eq_ignore_ascii_case(&cfg.label)) + .cloned(); + let label_on = on_pr.is_some(); let marked = label_on.then(|| { // A label with no `labeled` event read (the record is gone): // the grace period starts now. stale::marked(&timeline, &cfg.label).unwrap_or((inp.now, false)) }); + let last = stale::last_activity_since_mark(pr, &timeline, &cfg.label, marked.map(|m| m.0)); let author = pr["user"]["login"].as_str().unwrap_or(""); let base_exempt = stale::Exemption { cfg, @@ -341,7 +357,8 @@ pub async fn run_repo(env: &dyn Env, inp: &Inputs) -> Result { } } env.pause().await; - if let Err(e) = env.comment(number, &cfg.warn_comment()).await { + let head = pr["head"]["sha"].as_str().unwrap_or(""); + if let Err(e) = env.comment(number, &cfg.warn_comment_at(head)).await { warn!(pr = number, error = %e, "stale PRs: the warning comment failed"); } env.pause().await; @@ -351,11 +368,12 @@ pub async fn run_repo(env: &dyn Env, inp: &Inputs) -> Result { .push(item(pr, "wait", "marked stale", &last, Some(closes_at))); } Plan::Unmark { why } => { - if !inp.act { + if !inp.act && !inp.tidy { out.items.push(item(pr, "unmark", why, &last, None)); continue; } - match env.remove_label(number, &cfg.label).await { + let name = on_pr.as_deref().unwrap_or(&cfg.label); + match unlabel(env, number, name).await { Ok(()) => { env.pause().await; out.unstaled += 1; @@ -366,7 +384,11 @@ pub async fn run_repo(env: &dyn Env, inp: &Inputs) -> Result { break; } Err(e) => { - warn!(pr = number, error = %e, "stale PRs: could not take the label off") + env.own_problem( + number, + &format!("the stale label couldn't be taken off ({why}): {e}"), + ) + .await; } } } @@ -438,6 +460,74 @@ pub async fn run_repo(env: &dyn Env, inp: &Inputs) -> Result { Ok(out) } +/// Takes the label off, once: a label already gone (GitHub's 404) is done. +async fn unlabel(env: &dyn Env, pr: u64, label: &str) -> Result<(), Error> { + match env.remove_label(pr, label).await { + Err(e) if !is_rate_limit(&e) && e.to_string().contains("404") => Ok(()), + r => r, + } +} + +/// What a pull request's activity did to its stale label. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Unstale { + /// CoderHelm's label came off. + Removed, + /// Nothing to take off: no stale label, or a person's. + Left(String), + /// Taking it off failed: CoderHelm's own problem, alerted. + Failed(String), +} + +/// Activity on one pull request, from its webhook (a push, a review, a +/// comment, ready for review): CoderHelm's stale label comes off at once, +/// in every mode, read from the pull request as it is now. A person's +/// label stays theirs. The hourly sweep is the backstop for an event that +/// never arrived. +pub async fn on_activity(env: &dyn Env, cfg: &StaleConfig, number: u64, what: &str) -> Unstale { + let pr = match env.pull(number).await { + Ok(p) => p, + Err(e) => { + let text = + format!("the pull request couldn't be read to take the stale label off: {e}"); + env.own_problem(number, &text).await; + return Unstale::Failed(text); + } + }; + if pr["state"].as_str().is_some_and(|s| s != "open") { + return Unstale::Left("not open".into()); + } + let Some(name) = labels_of(&pr) + .into_iter() + .find(|l| l.eq_ignore_ascii_case(&cfg.label)) + else { + return Unstale::Left("no stale label".into()); + }; + let timeline = match env.timeline(number).await { + Ok(t) => t, + Err(e) => { + let text = format!("the timeline couldn't be read to take the stale label off: {e}"); + env.own_problem(number, &text).await; + return Unstale::Failed(text); + } + }; + if !stale::unmark_on_activity(stale::marked(&timeline, &cfg.label)) { + return Unstale::Left("a person put the label on".into()); + } + let why = format!("{what} after it was marked"); + match unlabel(env, number, &name).await { + Ok(()) => { + env.log(entry(&pr, Action::Unstaled, &why)).await; + Unstale::Removed + } + Err(e) => { + let text = format!("the stale label couldn't be taken off ({why}): {e}"); + env.own_problem(number, &text).await; + Unstale::Failed(text) + } + } +} + // ── The real environment ──────────────────────────────────────────── struct Live<'a> { @@ -462,6 +552,12 @@ impl Env for Live<'_> { .await } + async fn pull(&self, pr: u64) -> Result { + self.github + .get_pull_request(self.owner, self.name, pr) + .await + } + async fn timeline(&self, pr: u64) -> Result, Error> { let v = self .github @@ -538,6 +634,17 @@ impl Env for Live<'_> { async fn pause(&self) { tokio::time::sleep(std::time::Duration::from_secs(1)).await; } + + async fn own_problem(&self, pr: u64, text: &str) { + super::own_problems::alert( + self.state, + self.team_id, + "", + "stale_label", + &format!("{}#{pr}: {text}", self.repo()), + ) + .await; + } } /// Why CoderHelm's own work holds the pull request: its newest run is still @@ -983,6 +1090,62 @@ pub async fn preview(state: &WorkerState, msg: &StalePrsPreviewMessage) { } } +/// A pull request's activity from its webhook: CoderHelm's stale label +/// comes off now ([`on_activity`]), whatever the team's mode. +pub async fn activity(state: &WorkerState, msg: &StalePrsPreviewMessage) { + let cfg = team_settings(state, &msg.team_id).await.for_repo(&msg.repo); + let Some((owner, name)) = msg.repo.split_once('/') else { + return; + }; + let Some(iid) = super::review_reminder::team_installation_id(state, &msg.team_id).await else { + super::own_problems::alert( + state, + &msg.team_id, + "", + "stale_label", + &format!( + "{}#{}: no GitHub installation to take the stale label off", + msg.repo, msg.pr + ), + ) + .await; + return; + }; + let github = match GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + iid, + &state.http, + ) { + Ok(g) => g, + Err(e) => { + super::own_problems::alert( + state, + &msg.team_id, + "", + "stale_label", + &format!("{}#{}: GitHub client: {e}", msg.repo, msg.pr), + ) + .await; + return; + } + }; + let env = Live { + state, + github, + team_id: &msg.team_id, + owner, + name, + }; + let what = if msg.activity.is_empty() { + "activity" + } else { + msg.activity.as_str() + }; + let r = on_activity(&env, &cfg, msg.pr, what).await; + info!(team_id = %msg.team_id, repo = %msg.repo, pr = msg.pr, result = ?r, "stale PRs: activity read"); +} + async fn sweep_one( state: &WorkerState, team_id: &str, @@ -1007,6 +1170,7 @@ async fn sweep_one( }; let inputs = Inputs { act: cfg.enabled && !cfg.dry_run && !preview, + tidy: !preview, kept_open: kept_open(state, team_id, repo).await, cursor: if preview { 0 @@ -1067,6 +1231,13 @@ mod tests { async fn open_pulls(&self) -> Result, Error> { Ok(self.pulls.clone()) } + async fn pull(&self, pr: u64) -> Result { + self.pulls + .iter() + .find(|p| p["number"].as_u64() == Some(pr)) + .cloned() + .ok_or_else(|| "404 Not Found".into()) + } async fn timeline(&self, pr: u64) -> Result, Error> { let mut n = self.reads.lock().unwrap(); *n += 1; @@ -1107,6 +1278,12 @@ mod tests { self.budget_low } async fn pause(&self) {} + async fn own_problem(&self, pr: u64, _text: &str) { + self.writes + .lock() + .unwrap() + .push(format!("own problem #{pr}")); + } } fn now() -> DateTime { @@ -1138,6 +1315,7 @@ mod tests { kept_open: HashMap::new(), cursor: 0, act, + tidy: act, } } From c258b8186175011b4b9a913e9129eb05fa134920 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Thu, 3 Dec 2026 15:41:36 -0500 Subject: [PATCH 2/2] A label already gone is read from GitHub's status, and a glob's character class closes no array - Taking the stale label off counts as done only on GitHub's 404 status, never on a 404 elsewhere in the error's URL or body (a pull request numbered 404, a repository name). The label lookup reads it the same way. - A config's array or call value ends at its matching bracket outside quoted strings: testMatch ['**/*.e2e.[jt]s'] keeps its glob. - The activity read takes the label's time itself (last_activity), in place of a second function beside it. - A pull request edit takes the label off only for a new title, the edit the sweep reads too; a body edit no longer flaps the label. - The stall check's comments describe what it returns and how the loop ends. --- ...ks_labels_and_fix_loops_follow_the_work.md | 2 +- services/common/src/e2e/test_owner.rs | 73 +++++++++++++++++- services/common/src/setup/facts.rs | 2 +- services/common/src/stale_prs.rs | 77 ++++++++++--------- services/worker/src/clients/github.rs | 2 +- ...ks_labels_and_fix_loops_follow_the_work.rs | 31 +++++++- services/worker/src/passes/resume.rs | 14 ++-- services/worker/src/passes/stale_prs.rs | 7 +- 8 files changed, 153 insertions(+), 55 deletions(-) diff --git a/docs/incidents/xk_checks_labels_and_fix_loops_follow_the_work.md b/docs/incidents/xk_checks_labels_and_fix_loops_follow_the_work.md index a971c4707..5d6fa24ab 100644 --- a/docs/incidents/xk_checks_labels_and_fix_loops_follow_the_work.md +++ b/docs/incidents/xk_checks_labels_and_fix_loops_follow_the_work.md @@ -6,4 +6,4 @@ **The guarantee:** A repository root that declares a workspace installs the whole workspace once, with the sandbox's package cache, and every member's checks reuse that install. The review calls its own verification incomplete only when a step really couldn't run. Whether a test file runs in the sandbox is decided by the runner whose config picks it up (its folder and patterns, the runner's defaults standing in): only a file Playwright, Cypress or WebdriverIO picks up waits for a preview. CoderHelm's stale label comes off as soon as the pull request is active again: on the webhook for a push, a review, a review comment, a comment or ready for review, and in the sweep as a backstop, in every mode except the dashboard's preview. A push since the warning counts by the head the warning recorded. Removal is idempotent (a label already gone is done), a label a person put on stays theirs, and a failure is an internal alert, CoderHelm's own problem. The CI fix loop goes on while its fixes make progress: past its usual cycles and pushes while the failure keeps changing, up to twice them, and a test still red after its fixes stops the loop only when nothing else moved. Two cycles without progress end it. Every ending of its own is typed and alerted, never a person's to-do. -**Where it's enforced:** `common::e2e::test_owner::{owner, configs_for}`, `common::e2e::test_package::{package_of, install_cmd}` (`workspace_root`), `common::test_env::{script_files, package_test_command, narrow}`, the worker's `review_verify::{plan, script}` and `habits_check::is_e2e_spec`. `common::stale_prs::{webhook_activity, last_activity_since_mark, head_when_warned, unmark_on_activity, decide}`, the gateway's `stale_prs::on_webhook` and the worker's `stale_prs::{on_activity, activity, run_repo}`. `common::run_round::{ci_cycle_goes_on, ci_push_cap, test_cap_stops}`, the worker's `GaveUp::own_problem` and `resume::hand_off_red_ci`. +**Where it's enforced:** `common::e2e::test_owner::{owner, configs_for}`, `common::e2e::test_package::{package_of, install_cmd}` (`workspace_root`), `common::test_env::{script_files, package_test_command, narrow}`, the worker's `review_verify::{plan, script}` and `habits_check::is_e2e_spec`. `common::stale_prs::{webhook_activity, last_activity, head_when_warned, unmark_on_activity, decide}`, the gateway's `stale_prs::on_webhook` and the worker's `stale_prs::{on_activity, activity, run_repo}`. `common::run_round::{ci_cycle_goes_on, ci_push_cap, test_cap_stops}`, the worker's `GaveUp::own_problem` and `resume::hand_off_red_ci`. diff --git a/services/common/src/e2e/test_owner.rs b/services/common/src/e2e/test_owner.rs index a4896315a..55da46fae 100644 --- a/services/common/src/e2e/test_owner.rs +++ b/services/common/src/e2e/test_owner.rs @@ -77,6 +77,39 @@ pub fn configs_for(tree: &[String], file: &str) -> Vec { } } +/// The index just past the `close` that matches the `open` at the start of +/// `src`, skipping brackets inside quoted strings (a glob's `[jt]` class) +/// and nested pairs. `None` when it never closes. +fn closing(src: &str, open: char, close: char) -> Option { + let mut depth = 0usize; + let mut quote: Option = None; + let mut escaped = false; + for (i, c) in src.char_indices() { + if let Some(q) = quote { + if escaped { + escaped = false; + } else if c == '\\' { + escaped = true; + } else if c == q { + quote = None; + } + continue; + } + match c { + '\'' | '"' | '`' => quote = Some(c), + c if c == open => depth += 1, + c if c == close => { + depth = depth.checked_sub(1)?; + if depth == 0 { + return Some(i + c.len_utf8()); + } + } + _ => {} + } + } + None +} + /// The string literals of `key`'s value in a config's source: one string, /// or each string of an array. A `path.join(__dirname, 'tests')` gives its /// last literal. `None` when the config doesn't name the key. @@ -102,13 +135,13 @@ fn literals(src: &str, key: &str) -> Option> { let value = rest[1..].trim_start(); // The value up to the end of its array, call or line. let end = if value.starts_with('[') { - value.find(']').map(|i| i + 1) + closing(value, '[', ']') } else if let Some(open) = value.find('(').filter(|o| { value[..*o] .chars() .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_') }) { - value[open..].find(')').map(|i| open + i + 1) + closing(&value[open..], '(', ')').map(|i| open + i) } else { value.find([',', '\n', '}']) } @@ -525,6 +558,25 @@ mod tests { literals("{ testDir: './specs' }", "testDir"), Some(vec!["./specs".into()]) ); + // A glob's character class closes no array. + assert_eq!( + literals( + "{ testMatch: ['**/*.e2e.[jt]s', 'flows/*.[jt]sx'], retries: 1 }", + "testMatch" + ), + Some(vec!["**/*.e2e.[jt]s".into(), "flows/*.[jt]sx".into()]) + ); + assert_eq!( + literals("{ testIgnore: ['**/*.skip.[jt]s'] }", "testIgnore"), + Some(vec!["**/*.skip.[jt]s".into()]) + ); + assert_eq!( + literals( + "{ testDir: path.join(__dirname, 'e2e (smoke)') }", + "testDir" + ), + Some(vec!["e2e (smoke)".into()]) + ); } /// An invented end-to-end package: Playwright specs under `tests/`, @@ -597,6 +649,23 @@ mod tests { assert_eq!(owner(&tree, "web/a.test.ts", &read), None); } + #[test] + fn a_test_match_with_a_character_class_claims_its_specs() { + let (tree, texts) = files(&[ + ("qa/package.json", "{}"), + ( + "qa/playwright.config.ts", + "export default { testMatch: ['**/*.e2e.[jt]s'] };", + ), + ("qa/checkout.e2e.ts", ""), + ]); + let read = |p: &str| texts.get(p).cloned(); + assert_eq!( + owner(&tree, "qa/checkout.e2e.ts", &read), + Some(Owner::EndToEnd(Runner::Playwright)) + ); + } + #[test] fn playwright_without_a_test_dir_claims_its_default_matches() { let (tree, texts) = files(&[ diff --git a/services/common/src/setup/facts.rs b/services/common/src/setup/facts.rs index ecfeeca07..79329832f 100644 --- a/services/common/src/setup/facts.rs +++ b/services/common/src/setup/facts.rs @@ -564,7 +564,7 @@ pub fn stale_effect( if exempt.is_some() { continue; } - let last = stale::last_activity(pr, timeline, &cfg.label); + let last = stale::last_activity(pr, timeline, &cfg.label, None); let mark_at = last.at + Duration::days(cfg.stale_days as i64); if mark_at > now { continue; diff --git a/services/common/src/stale_prs.rs b/services/common/src/stale_prs.rs index d17bdc1c0..732d37c8f 100644 --- a/services/common/src/stale_prs.rs +++ b/services/common/src/stale_prs.rs @@ -333,7 +333,16 @@ pub struct Activity { /// The newest activity from `pr` (the pull request) and its `timeline` /// (GitHub's issue timeline, oldest first). The pull request being opened /// is the floor. `label` is the stale label: adding it is never activity. -pub fn last_activity(pr: &Value, timeline: &[Value], label: &str) -> Activity { +/// `marked_at`, when the label is on: a push since the warning counts, read +/// by the head the warning recorded ([`head_when_warned`]). Commits pushed +/// after the label but made before it carry older dates than the label, so +/// their dates alone never un-staled it. +pub fn last_activity( + pr: &Value, + timeline: &[Value], + label: &str, + marked_at: Option>, +) -> Activity { let mut best = Activity { at: time(&pr["created_at"]).unwrap_or(DateTime::::MIN_UTC), what: "opened".to_string(), @@ -411,7 +420,18 @@ pub fn last_activity(pr: &Value, timeline: &[Value], label: &str) -> Activity { _ => {} } } - best + let (Some(at), Some(warned)) = (marked_at, head_when_warned(timeline)) else { + return best; + }; + let head = pr["head"]["sha"].as_str().unwrap_or(""); + if head.is_empty() || head.starts_with(&warned) || best.at > at { + return best; + } + Activity { + at: at + Duration::seconds(1), + what: "new commits pushed".to_string(), + by: String::new(), + } } /// The head CoderHelm's newest stale warning was posted at, from its @@ -441,32 +461,6 @@ pub fn head_when_warned(timeline: &[Value]) -> Option { .next_back() } -/// The newest activity ([`last_activity`]) for a marked pull request, -/// counting a push since the warning: the head moved from the one the -/// warning recorded. Commits pushed after the label but made before it -/// carry older dates than the label, so their dates alone never un-staled -/// it. -pub fn last_activity_since_mark( - pr: &Value, - timeline: &[Value], - label: &str, - marked_at: Option>, -) -> Activity { - let last = last_activity(pr, timeline, label); - let (Some(at), Some(warned)) = (marked_at, head_when_warned(timeline)) else { - return last; - }; - let head = pr["head"]["sha"].as_str().unwrap_or(""); - if head.is_empty() || head.starts_with(&warned) || last.at > at { - return last; - } - Activity { - at: at + Duration::seconds(1), - what: "new commits pushed".to_string(), - by: String::new(), - } -} - /// A webhook event that is activity on a pull request, read from GitHub's /// payload: its repository, number, labels, and what happened. Activity by /// a person, and CoderHelm's own pushes (work on the branch); never @@ -489,9 +483,13 @@ pub fn webhook_activity(event: &str, payload: &Value) -> Option ("pull_request", "synchronize") if person || is_own(login) => { (&payload["pull_request"], "new commits pushed") } - ("pull_request", "ready_for_review" | "reopened" | "converted_to_draft" | "edited") - if person => - { + ("pull_request", "ready_for_review" | "reopened" | "converted_to_draft") if person => { + (&payload["pull_request"], "an update") + } + // A new title only: the sweep reads it as `renamed`. A body or base + // edit leaves no timeline event, so the sweep would put the label + // straight back. + ("pull_request", "edited") if person && payload["changes"]["title"].is_object() => { (&payload["pull_request"], "an update") } ("pull_request_review", "submitted") if person => (&payload["pull_request"], "a review"), @@ -884,7 +882,7 @@ mod tests { json!({"event": "reviewed", "user": bot("coderhelm[bot]"), "submitted_at": "2026-10-03T00:00:00Z"}), json!({"event": "committed", "author": {"name": "dependabot[bot]", "email": "49699333+dependabot[bot]@users.noreply.github.com", "date": "2026-10-04T00:00:00Z"}, "committer": {"date": "2026-10-04T00:00:00Z"}}), ]; - let a = last_activity(&pr(), &tl, "stale"); + let a = last_activity(&pr(), &tl, "stale", None); assert_eq!(a.at, t("2026-09-05T00:00:00Z")); assert_eq!(a.what, "a comment"); assert_eq!(a.by, "ana"); @@ -894,19 +892,22 @@ mod tests { fn commits_reviews_and_review_comments_count() { let commit = json!({"event": "committed", "author": {"name": "Ana", "email": "ana@example.com", "date": "2026-09-10T00:00:00Z"}, "committer": {"date": "2026-09-11T00:00:00Z"}}); assert_eq!( - last_activity(&pr(), &[commit], "stale").at, + last_activity(&pr(), &[commit], "stale", None).at, t("2026-09-11T00:00:00Z") ); // CoderHelm's commits are work on the branch. let own = json!({"event": "committed", "author": {"name": "coderhelm[bot]", "email": "1+coderhelm[bot]@users.noreply.github.com"}, "committer": {"date": "2026-09-12T00:00:00Z"}}); - assert_eq!(last_activity(&pr(), &[own], "stale").what, "a commit"); + assert_eq!(last_activity(&pr(), &[own], "stale", None).what, "a commit"); let review = json!({"event": "reviewed", "user": person("bo"), "submitted_at": "2026-09-13T00:00:00Z"}); - assert_eq!(last_activity(&pr(), &[review], "stale").what, "a review"); + assert_eq!( + last_activity(&pr(), &[review], "stale", None).what, + "a review" + ); let line = json!({"event": "line-commented", "comments": [ {"user": person("bo"), "created_at": "2026-09-14T00:00:00Z"}, {"user": bot("coderhelm[bot]"), "created_at": "2026-09-20T00:00:00Z"} ]}); - let a = last_activity(&pr(), &[line], "stale"); + let a = last_activity(&pr(), &[line], "stale", None); assert_eq!( (a.at, a.what.as_str()), (t("2026-09-14T00:00:00Z"), "a review comment") @@ -915,12 +916,12 @@ mod tests { let tl = vec![ json!({"event": "labeled", "actor": person("bo"), "label": {"name": "Stale"}, "created_at": "2026-09-15T00:00:00Z"}), ]; - assert_eq!(last_activity(&pr(), &tl, "stale").what, "opened"); + assert_eq!(last_activity(&pr(), &tl, "stale", None).what, "opened"); let tl = vec![ json!({"event": "unlabeled", "actor": person("bo"), "label": {"name": "stale"}, "created_at": "2026-09-16T00:00:00Z"}), ]; assert_eq!( - last_activity(&pr(), &tl, "stale").what, + last_activity(&pr(), &tl, "stale", None).what, "the stale label removed" ); } diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 3b289f96e..81b618416 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -4372,7 +4372,7 @@ impl GitHubClient { ); match self.get(&url).await { Ok(v) => Ok(Some(v)), - Err(e) if e.to_string().contains("404") => Ok(None), + Err(e) if is_not_found(&*e) => Ok(None), Err(e) => Err(e), } } diff --git a/services/worker/src/passes/incidents/xk_checks_labels_and_fix_loops_follow_the_work.rs b/services/worker/src/passes/incidents/xk_checks_labels_and_fix_loops_follow_the_work.rs index 73c86fb57..64f56066e 100644 --- a/services/worker/src/passes/incidents/xk_checks_labels_and_fix_loops_follow_the_work.rs +++ b/services/worker/src/passes/incidents/xk_checks_labels_and_fix_loops_follow_the_work.rs @@ -334,6 +334,16 @@ async fn a_review_after_the_label_takes_it_off_from_the_webhook_and_the_sweep() let ready = json!({"action": "ready_for_review", "sender": {"login": "lena", "type": "User"}, "repository": {"full_name": "acme/shop"}, "pull_request": {"number": 3, "labels": []}}); assert!(stale::webhook_activity("pull_request", &ready).is_some()); + // A new title is activity the sweep reads too (`renamed`); a body edit + // leaves no timeline event, so it never takes the label off. + let retitled = json!({"action": "edited", "changes": {"title": {"from": "Menu"}}, + "sender": {"login": "lena", "type": "User"}, + "repository": {"full_name": "acme/shop"}, "pull_request": {"number": 3, "labels": []}}); + assert!(stale::webhook_activity("pull_request", &retitled).is_some()); + let body_only = json!({"action": "edited", "changes": {"body": {"from": "x"}}, + "sender": {"login": "lena", "type": "User"}, + "repository": {"full_name": "acme/shop"}, "pull_request": {"number": 3, "labels": []}}); + assert!(stale::webhook_activity("pull_request", &body_only).is_none()); let own = json!({"action": "created", "sender": {"login": "coderhelm[bot]", "type": "Bot"}, "repository": {"full_name": "acme/shop"}, "issue": {"number": 3, "pull_request": {}, "labels": []}}); assert!(stale::webhook_activity("issue_comment", &own).is_none()); @@ -398,7 +408,9 @@ async fn preview_only_never_adds_but_still_takes_its_own_label_off() { async fn removal_is_idempotent_and_a_failure_is_coderhelms_own_alert() { let mut gone = Repo { pulls: vec![pr(7, &["stale"], HEAD_AT_MARK)], - remove_fails: Some("404 Label does not exist"), + remove_fails: Some( + "HTTP status client error (404 Not Found) for url (https://api.github.com/repos/acme/shop/issues/7/labels/stale): {\"message\":\"Label does not exist\"}", + ), ..Default::default() }; gone.timelines.insert(7, vec![ours("2026-11-10T00:00:00Z")]); @@ -410,7 +422,7 @@ async fn removal_is_idempotent_and_a_failure_is_coderhelms_own_alert() { let broken = Repo { pulls: gone.pulls.clone(), timelines: gone.timelines.clone(), - remove_fails: Some("500 Internal Server Error"), + remove_fails: Some("HTTP status server error (500 Internal Server Error) for url (https://api.github.com/repos/acme/shop/issues/7/labels/stale)"), ..Default::default() }; assert!(matches!( @@ -418,6 +430,21 @@ async fn removal_is_idempotent_and_a_failure_is_coderhelms_own_alert() { Unstale::Failed(_) )); assert_eq!(broken.own.lock().unwrap().len(), 1); + // A failure on a pull request numbered 404 (its URL and body carry the + // digits) is still a failure, never a label already gone. + let mut numbered = Repo { + pulls: vec![pr(404, &["stale"], HEAD_AT_MARK)], + remove_fails: Some("HTTP status client error (403 Forbidden) for url (https://api.github.com/repos/acme/shop/issues/404/labels/stale): {\"message\":\"Resource not accessible by integration\"}"), + ..Default::default() + }; + numbered + .timelines + .insert(404, vec![ours("2026-11-10T00:00:00Z")]); + assert!(matches!( + on_activity(&numbered, &StaleConfig::default(), 404, "a comment").await, + Unstale::Failed(_) + )); + assert_eq!(numbered.own.lock().unwrap().len(), 1); // No label on it: nothing to do. let clean = Repo { pulls: vec![pr(8, &[], HEAD_AT_MARK)], diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index be74c5ced..294cafdba 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -3056,8 +3056,9 @@ pub async fn run( } // Halt-on-no-progress: if the SAME failure keeps recurring, the fixes // aren't working (noop commits, placeholder stubs, wrong fixes). Stop - // churning the PR and hand it to a human — this fires long before the - // coarse cycle cap above. + // churning the PR and end on CoderHelm's own typed stop with what + // fails (`hand_off_red_ci`); this fires long before the coarse cycle + // cap above. let (idle, stalled) = check_and_record_stall(state, &msg.team_id, &msg.run_id, &gap_text).await; if stalled { @@ -6940,11 +6941,10 @@ fn collect_review_feedback(events: &[RunEvent]) -> String { .join("\n\n---\n\n") } -/// Compare the current failure against the stored one, persist the update, and -/// return true if the run has STALLED (same failure repeating → halt). The pure -/// decision (`stall_decision` / `ci_failure_signature`) is unit-tested. -/// Records this cycle's failure against the last one: the cycles in a row -/// without progress, and whether that many stops the loop. +/// Records this cycle's failure against the last one and returns the cycles +/// in a row without progress, and whether that many stops the loop (the same +/// failure came back). The pure decision (`stall_decision` / +/// `ci_failure_signature`) is unit-tested. async fn check_and_record_stall( state: &WorkerState, team_id: &str, diff --git a/services/worker/src/passes/stale_prs.rs b/services/worker/src/passes/stale_prs.rs index ff2134e0d..290f663f1 100644 --- a/services/worker/src/passes/stale_prs.rs +++ b/services/worker/src/passes/stale_prs.rs @@ -280,7 +280,7 @@ pub async fn run_repo(env: &dyn Env, inp: &Inputs) -> Result { // the grace period starts now. stale::marked(&timeline, &cfg.label).unwrap_or((inp.now, false)) }); - let last = stale::last_activity_since_mark(pr, &timeline, &cfg.label, marked.map(|m| m.0)); + let last = stale::last_activity(pr, &timeline, &cfg.label, marked.map(|m| m.0)); let author = pr["user"]["login"].as_str().unwrap_or(""); let base_exempt = stale::Exemption { cfg, @@ -460,10 +460,11 @@ pub async fn run_repo(env: &dyn Env, inp: &Inputs) -> Result { Ok(out) } -/// Takes the label off, once: a label already gone (GitHub's 404) is done. +/// Takes the label off, once: a label already gone (GitHub's 404 status, +/// never a 404 anywhere else in the error's URL or body) is done. async fn unlabel(env: &dyn Env, pr: u64, label: &str) -> Result<(), Error> { match env.remove_label(pr, label).await { - Err(e) if !is_rate_limit(&e) && e.to_string().contains("404") => Ok(()), + Err(e) if !is_rate_limit(&e) && crate::clients::github::is_not_found(&*e) => Ok(()), r => r, } }