diff --git a/docs/incidents/xc_owed_proof_runs_its_routes.md b/docs/incidents/xc_owed_proof_runs_its_routes.md new file mode 100644 index 000000000..c15aff05a --- /dev/null +++ b/docs/incidents/xc_owed_proof_runs_its_routes.md @@ -0,0 +1,7 @@ +# xc. `xc_owed_proof_runs_its_routes` + +**What happened:** A run fixing a failing end-to-end test opened its pull request, and CoderHelm's own review asked for one thing: the test passing a set number of times in a row with retries off. The fix round ran the repeat in the sandbox against the team's staging site and against the pull request's preview. Every attempt failed before the page loaded, because the sandbox's network refused both hosts: its allowlist held only what the team had typed into its settings, though the repository's own end-to-end config and preview workflow named both. The round made no change and asked a person to widen CoderHelm's allowlist or run the command themselves, and it called a repeat on CI "a CI change outside this ticket". The findings had already had their round on that head, so nothing picked them up again, and the pull request waited on CoderHelm's own review. + +**The guarantee:** Where the team's apps are served is read from the default branch only (its end-to-end config, env templates, workflow environments and deploys), never from a pull request's head, and each host is kept with its source. A host is allowed when it falls under a domain the team verified; a domain not verified yet is suggested once in Settings, and every host under it is automatic after an admin confirms it. A repeat proof is a plan with routes tried in order: the sandbox against the preview, against staging, against the app started from the repository's own dev or start script, then CI (the end-to-end workflow with its repeat input, started once per run needed, or its run re-run). A route that ran the test gives the result; the plan says it couldn't only after every route, each with its own reason. Neither the allowlist nor a CI repeat is ever a person's step. A pull request whose own review asks for a proof the sandbox couldn't reach is picked up by the sweep, including ones that were already waiting, and is proven or held on a real result with nobody commenting. + +**Where it's enforced:** `agent_policy::repo_hosts::{from_files, from_deploys, sort}` and `agent::policy::{learn_repo_hosts, sandbox_egress}`, with the suggestions in the reviewer settings (`suggested_web_domains`). Also: `e2e::proof_routes::{Plan, outcome_of, local_app, ci_way, ci_step}`, `passes::proof_routes::advance`, `pr_watch::{proof_due, Act::ProveOwed}`, `own_review_ledger::{owed_proofs, proof_given, round_rules, instruction}`, and the test fix's ready check (`test_fix::ready_gate`). diff --git a/services/common/src/agent_policy/mod.rs b/services/common/src/agent_policy/mod.rs index b01d431e1..fabed627a 100644 --- a/services/common/src/agent_policy/mod.rs +++ b/services/common/src/agent_policy/mod.rs @@ -40,6 +40,7 @@ pub mod notify; pub mod pause; pub mod presets; pub mod registry; +pub mod repo_hosts; pub mod sandbox; pub mod signin; pub mod store; diff --git a/services/common/src/agent_policy/repo_hosts.rs b/services/common/src/agent_policy/repo_hosts.rs new file mode 100644 index 000000000..996ac4894 --- /dev/null +++ b/services/common/src/agent_policy/repo_hosts.rs @@ -0,0 +1,451 @@ +//! The team's own app hosts its repositories name, for the sandbox's +//! network allowlist. +//! +//! A test fix's own review asked for its proof: the test run repeatedly +//! with retries off. The round ran it against the team's staging site and +//! against the pull request's preview, and every attempt failed before the +//! page loaded: the sandbox's allowlist held only what the team had typed +//! into its settings, and neither host was there, though the repository's +//! own end-to-end config and its preview deploys named both. The round then +//! asked a person to widen CoderHelm's own allowlist. +//! +//! Hosts are derived here, never typed by a person, under three rules that +//! keep the allowlist the team's and nobody else's: +//! +//! 1. **The default branch only.** Addresses are read from the default +//! branch's end-to-end config, env templates and workflow files, and from +//! its deploy outputs ([`from_files`], [`from_deploys`]). A pull request's +//! head is never read for hosts: a change could otherwise name a host to +//! send data to and have the sandbox reach it. +//! 2. **Under a verified domain.** A derived host is allowed only when it +//! falls under a domain the team verified in its settings (its web +//! domains, the ones `check_url` reads) ([`sort`]). Anything else becomes +//! a suggestion an admin confirms once in Settings ([`Proposed`]); from +//! then on every host under it is automatic. +//! 3. **Each host with its source.** Every allowed host keeps where it was +//! read from and the verified domain it falls under ([`Allowed`]), so the +//! list says why each entry is there. +//! +//! Shared hosting suffixes (`vercel.app`, `cloudfront.net`, a bare +//! `co.uk`) are never proposed as a domain: they are every customer's. + +use serde::{Deserialize, Serialize}; + +use super::sandbox::{domain_matches, valid_domain}; + +/// A host or domain read from the default branch. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Derived { + /// The exact host, or for an address template (`pr-{n}.preview.…`) the + /// domain its hosts live under. + pub domain: String, + /// Read from a template: `domain` covers every host under it. + pub template: bool, + /// Where it was read, in words (`playwright.config.ts on main`). + pub source: String, +} + +/// A host the sandbox reaches, with why. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Allowed { + pub host: String, + pub source: String, + /// The verified domain it falls under. + pub under: String, +} + +/// A domain the default branch names that the team hasn't verified: shown +/// in Settings for an admin to confirm once. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Proposed { + pub domain: String, + pub source: String, +} + +/// Shared hosting and cloud suffixes: a host under one belongs to one +/// customer of that service, the suffix itself to all of them. +pub const SHARED_HOSTS: &[&str] = &[ + "vercel.app", + "netlify.app", + "pages.dev", + "workers.dev", + "herokuapp.com", + "cloudfront.net", + "amazonaws.com", + "azurewebsites.net", + "azurestaticapps.net", + "web.app", + "firebaseapp.com", + "appspot.com", + "onrender.com", + "fly.dev", + "railway.app", + "github.io", + "githubusercontent.com", + "github.com", + "gitlab.io", + "ngrok.io", + "ngrok-free.app", + "surge.sh", + "glitch.me", +]; + +/// Second-level labels country registries sell under (`co.uk`, `com.au`). +const REGISTRY_LABELS: &[&str] = &["co", "com", "net", "org", "gov", "ac", "edu", "ne", "or"]; + +/// Whether `domain` is a shared suffix: one of [`SHARED_HOSTS`], a bare +/// top-level domain, or a registry pair like `co.uk`. +pub fn is_shared(domain: &str) -> bool { + let d = domain.trim().trim_end_matches('.').to_ascii_lowercase(); + let labels: Vec<&str> = d.split('.').filter(|l| !l.is_empty()).collect(); + if labels.len() < 2 { + return true; + } + if labels.len() == 2 && REGISTRY_LABELS.contains(&labels[0]) && labels[1].len() == 2 { + return true; + } + SHARED_HOSTS.iter().any(|s| d == *s) +} + +/// Words on a line that name the address the app under test is served at: +/// `baseURL`, `E2E_BASE_URL=`, a workflow environment's `url:`. +const ADDRESS_KEYS: &[&str] = &[ + "baseurl", + "base_url", + "app_url", + "site_url", + "staging_url", + "preview_url", + "e2e_url", + "target_url", + "url:", +]; + +/// Template markers in an address, each read as one placeholder label: +/// `${{ github.event.number }}`, `${PR}`, `$PR`, `{pr}`. +fn placeholders(url: &str) -> String { + let mut out = String::new(); + let mut rest = url; + while let Some(i) = rest.find('$') { + out.push_str(&rest[..i]); + let after = &rest[i + 1..]; + let skip = if let Some(inner) = after.strip_prefix("{{") { + inner.find("}}").map(|j| 2 + j + 2) + } else if let Some(inner) = after.strip_prefix('{') { + inner.find('}').map(|j| 1 + j + 1) + } else { + Some( + after + .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .unwrap_or(after.len()), + ) + }; + out.push_str("{x}"); + rest = &after[skip.unwrap_or(after.len()).min(after.len())..]; + } + out.push_str(rest); + out +} + +/// The addresses on one line, with their template markers made plain. +fn urls_on(line: &str) -> Vec { + let mut out = Vec::new(); + for (i, _) in line.match_indices("http") { + let rest = &line[i..]; + if !(rest.starts_with("https://") || rest.starts_with("http://")) { + continue; + } + // Up to the first character that ends a quoted or bare value, + // keeping `${{ … }}` whole. + let mut end = rest.len(); + let mut depth = 0i32; + for (j, c) in rest.char_indices() { + match c { + '{' => depth += 1, + '}' => depth -= 1, + _ if depth > 0 => {} + '\'' | '"' | '`' | ',' | ')' | ' ' | '\t' | ';' => { + end = j; + break; + } + _ => {} + } + } + out.push(placeholders(&rest[..end])); + } + out +} + +/// The host of an address, or for a template the domain under its +/// placeholder label; `None` for loopback, bare addresses and shared +/// suffixes. +fn domain_of(url: &str) -> Option<(String, bool)> { + let rest = url + .strip_prefix("https://") + .or_else(|| url.strip_prefix("http://"))?; + let host = rest + .split(['/', '?', '#']) + .next() + .unwrap_or("") + .split(':') + .next() + .unwrap_or("") + .trim_end_matches('.') + .to_ascii_lowercase(); + let (domain, template) = match host.rfind('}') { + None => (host, false), + Some(i) => { + let d = host[i + 1..].split_once('.').map(|(_, d)| d).unwrap_or(""); + (d.to_string(), true) + } + }; + let numeric = domain + .split('.') + .all(|l| l.chars().all(|c| c.is_ascii_digit())); + let local = + domain == "localhost" || domain.ends_with(".localhost") || domain.ends_with(".local"); + if domain.is_empty() + || domain.contains('{') + || numeric + || local + || !valid_domain(&domain) + || is_shared(&domain) + { + return None; + } + Some((domain, template)) +} + +fn push(out: &mut Vec, d: Derived) { + if !out.iter().any(|o| o.domain == d.domain) { + out.push(d); + } +} + +/// The app addresses the default branch's files name (`files`: path and +/// text, read at `branch`): end-to-end configs' `baseURL`, env templates' +/// `*_BASE_URL=` and workflows' `url:` and base-address env values. Only +/// lines that name such an address are read. +pub fn from_files(files: &[(String, String)], branch: &str) -> Vec { + let mut out = Vec::new(); + for (path, text) in files { + for line in text.lines() { + let low = line.to_ascii_lowercase(); + if !ADDRESS_KEYS.iter().any(|k| low.contains(k)) { + continue; + } + for url in urls_on(line) { + if let Some((domain, template)) = domain_of(&url) { + push( + &mut out, + Derived { + domain, + template, + source: format!("`{path}` on {branch}"), + }, + ); + } + } + } + } + out +} + +/// The hosts the default branch's deploys published (`urls`: the address +/// and the deploy's name). +pub fn from_deploys(urls: &[(String, String)]) -> Vec { + let mut out = Vec::new(); + for (url, name) in urls { + if let Some((domain, template)) = domain_of(&placeholders(url.trim())) { + push( + &mut out, + Derived { + domain, + template, + source: format!("the default branch's deploy ({name})"), + }, + ); + } + } + out +} + +/// The domain to propose for a host no verified domain covers: a +/// template's own domain, else the host without its first label when that +/// is still the team's (`staging.acme-books.example` proposes +/// `acme-books.example`), else the host itself. +pub fn proposal_of(d: &Derived) -> String { + if d.template { + return d.domain.clone(); + } + match d.domain.split_once('.') { + Some((_, parent)) if parent.contains('.') && !is_shared(parent) => parent.to_string(), + _ => d.domain.clone(), + } +} + +/// Derived hosts sorted against the team's verified domains: allowed (under +/// one, with its source) or proposed (for an admin to confirm once). +pub fn sort(derived: &[Derived], verified: &[String]) -> (Vec, Vec) { + let mut allowed: Vec = Vec::new(); + let mut proposed: Vec = Vec::new(); + for d in derived { + match verified.iter().find(|v| domain_matches(v, &d.domain)) { + Some(v) => { + if !allowed.iter().any(|a| a.host == d.domain) { + allowed.push(Allowed { + host: d.domain.clone(), + source: d.source.clone(), + under: v.trim().trim_start_matches("*.").to_ascii_lowercase(), + }); + } + } + None => { + let domain = proposal_of(d); + if !proposed.iter().any(|p| domain_matches(&p.domain, &domain)) { + proposed.retain(|p| !domain_matches(&domain, &p.domain)); + proposed.push(Proposed { + domain, + source: d.source.clone(), + }); + } + } + } + } + (allowed, proposed) +} + +/// What the default branch says, kept per repository on the team's +/// settings (`SANDBOX_HOSTS#REPO#{owner/repo}`). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct RepoHosts { + pub repo: String, + /// The default branch's commit it was read at. + pub sha: String, + pub derived: Vec, + pub at: String, +} + +/// The settings sort key of a repository's derived hosts. +pub fn settings_sk(repo: &str) -> String { + format!("{SK_PREFIX}{}", repo.to_ascii_lowercase()) +} + +/// The prefix of every repository's derived hosts. +pub const SK_PREFIX: &str = "SANDBOX_HOSTS#REPO#"; + +/// Whether a default-branch file may name the app's address: end-to-end +/// configs, env templates (never a real `.env`) and workflows. +pub fn reads(path: &str) -> bool { + let low = path.to_ascii_lowercase(); + let name = low.rsplit('/').next().unwrap_or(&low); + name.starts_with("playwright.config") + || name.starts_with("cypress.config") + || name.starts_with("wdio.conf") + || matches!( + name, + ".env.example" | ".env.sample" | ".env.test" | ".env.e2e" | ".env.ci" | ".env.template" + ) + || (low.starts_with(".github/workflows/") + && (low.ends_with(".yml") || low.ends_with(".yaml"))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn files() -> Vec<(String, String)> { + vec![ + ( + "e2e/playwright.config.ts".into(), + "export default defineConfig({\n use: { baseURL: process.env.E2E_BASE_URL ?? 'https://staging.acme-books.example' },\n webServer: { url: 'http://localhost:3000' },\n});\n".into(), + ), + ( + ".github/workflows/preview.yml".into(), + "jobs:\n deploy:\n environment:\n name: preview\n url: https://pr-${{ github.event.number }}.preview-web.acme-books.example\n steps:\n - run: curl https://telemetry.vendor.example/ping\n".into(), + ), + ( + ".env.example".into(), + "E2E_BASE_URL=https://staging.acme-books.example\nAPI_TOKEN=\n".into(), + ), + ] + } + + #[test] + fn the_default_branch_names_the_staging_host_and_the_preview_domain() { + let d = from_files(&files(), "main"); + let got: Vec<(&str, bool)> = d.iter().map(|x| (x.domain.as_str(), x.template)).collect(); + assert_eq!( + got, + vec![ + ("staging.acme-books.example", false), + ("preview-web.acme-books.example", true), + ] + ); + assert_eq!(d[0].source, "`e2e/playwright.config.ts` on main"); + // A line that names no app address (a curl in a step) adds nothing, + // nor does the local web server. + assert!(!d.iter().any(|x| x.domain.contains("vendor"))); + } + + #[test] + fn only_hosts_under_a_verified_domain_are_allowed_and_the_rest_are_proposed() { + let d = from_files(&files(), "main"); + let (allowed, proposed) = sort(&d, &["acme-books.example".to_string()]); + assert_eq!(allowed.len(), 2); + assert!(allowed.iter().all(|a| a.under == "acme-books.example")); + assert!(proposed.is_empty()); + + let (allowed, proposed) = sort(&d, &[]); + assert!(allowed.is_empty()); + assert_eq!( + proposed, + vec![Proposed { + domain: "acme-books.example".into(), + source: "`e2e/playwright.config.ts` on main".into() + }] + ); + } + + #[test] + fn shared_hosting_is_never_proposed_as_a_domain() { + let d = from_deploys(&[ + ( + "https://web-git-fix-acme.vercel.app".into(), + "Preview".into(), + ), + ("https://pr-{pr}.vercel.app".into(), "Preview".into()), + ("https://shop.acme-books.co.uk".into(), "Production".into()), + ]); + let (_, proposed) = sort(&d, &[]); + let names: Vec<&str> = proposed.iter().map(|p| p.domain.as_str()).collect(); + assert_eq!( + names, + vec!["web-git-fix-acme.vercel.app", "acme-books.co.uk"] + ); + assert!(is_shared("vercel.app") && is_shared("co.uk") && is_shared("example")); + assert!(!is_shared("acme-books.example")); + } + + #[test] + fn loopback_and_bare_addresses_are_never_hosts() { + let f = vec![( + "playwright.config.ts".to_string(), + "baseURL: 'http://127.0.0.1:4173'\nbaseURL: 'http://localhost:3000'\n".to_string(), + )]; + assert!(from_files(&f, "main").is_empty()); + } + + #[test] + fn only_config_env_templates_and_workflows_are_read() { + assert!(reads("apps/web/playwright.config.ts")); + assert!(reads(".github/workflows/e2e.yml")); + assert!(reads(".env.example")); + assert!(!reads(".env")); + assert!(!reads("src/api/client.ts")); + } +} diff --git a/services/common/src/ci_repro.rs b/services/common/src/ci_repro.rs index 7507c8094..46e73dba3 100644 --- a/services/common/src/ci_repro.rs +++ b/services/common/src/ci_repro.rs @@ -761,13 +761,13 @@ pub fn leg_of(target: &str, output: &str) -> Leg { leg } -fn quote(s: &str) -> Option { +pub(crate) fn quote(s: &str) -> Option { (!s.is_empty() && !s.contains('\'') && !s.contains('\n') && !s.starts_with('-')) .then(|| format!("'{s}'")) } /// A test title as a `--grep` pattern: its regex characters escaped. -fn grep_of(title: &str) -> String { +pub(crate) fn grep_of(title: &str) -> String { let mut out = String::new(); for c in title.chars() { if "\\^$.|?*+()[]{}".contains(c) { diff --git a/services/common/src/e2e/mod.rs b/services/common/src/e2e/mod.rs index bc4317b0e..c2b5a6ab8 100644 --- a/services/common/src/e2e/mod.rs +++ b/services/common/src/e2e/mod.rs @@ -57,6 +57,7 @@ pub mod model; pub mod owners; pub mod parse; pub mod probe; +pub mod proof_routes; pub mod quarantine; pub mod report_source; pub mod shots; diff --git a/services/common/src/e2e/proof_routes.rs b/services/common/src/e2e/proof_routes.rs new file mode 100644 index 000000000..0251e0c30 --- /dev/null +++ b/services/common/src/e2e/proof_routes.rs @@ -0,0 +1,887 @@ +//! A test's repeat proof as a plan with routes, tried in order, each +//! recorded with its own result. +//! +//! A test fix's own review asked for one thing: the test passing a set +//! number of times in a row with retries off. The round ran it in the sandbox against the +//! staging site and the preview; both were refused by the sandbox's +//! network, and the round stopped there: it called a repeat on CI "a CI +//! change outside this ticket" and asked a person to run the command. The +//! pull request waited on its own review for a week. +//! +//! Proving the fix is the ticket. "This test passes N times" has four +//! routes ([`Route`]), tried in this order until one gives a result: +//! +//! 1. the sandbox against the pull request's preview; +//! 2. the sandbox against the staging site; +//! 3. the sandbox against the app started inside the sandbox from the +//! repository's own dev or start script, so no outside page host is +//! needed ([`local_app`]); +//! 4. CI: the end-to-end workflow on the head, with its repeat input when it +//! has one, else started once per run needed, else its run re-run, and +//! the results read from its runs ([`CiWay`], [`ci_step`]). +//! +//! A route that ran the test gives the result, pass or fail: a real failure +//! is a result, never a reason to try another host. A route that couldn't +//! run it (no address, refused by the network, no start script) records why +//! and the next one is tried. The plan says it couldn't only when every +//! route failed, with each route's own reason ([`Verdict::Exhausted`]). + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// One way to run the repeat proof, in the order they are tried. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Route { + Preview, + Staging, + LocalApp, + Ci, +} + +/// Every route, in order. +pub const ORDER: [Route; 4] = [Route::Preview, Route::Staging, Route::LocalApp, Route::Ci]; + +impl Route { + pub fn words(self) -> &'static str { + match self { + Route::Preview => "the sandbox against the pull request's preview", + Route::Staging => "the sandbox against the staging site", + Route::LocalApp => { + "the sandbox against the app started from the repository's own script" + } + Route::Ci => "the repository's end-to-end workflow on CI", + } + } +} + +/// What one route gave. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Outcome { + /// The test ran `runs` times and passed every time. + Passed { runs: u32 }, + /// The test ran and failed: a result. + Failed { + passed: u32, + failed: u32, + error: String, + }, + /// The route couldn't run the test, and why. + Unavailable { why: String }, + /// Started on CI: its runs are read on the next look. + Started { at: String }, +} + +impl Outcome { + /// The test ran on this route (a pass or a real failure). + pub fn ran(&self) -> bool { + matches!(self, Outcome::Passed { .. } | Outcome::Failed { .. }) + } +} + +/// One route tried. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Attempt { + pub route: Route, + pub outcome: Outcome, + #[serde(default)] + pub at: String, +} + +/// The repeat proof of `tests` on one head. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Plan { + pub head: String, + /// `spec › title` (or a spec file alone). + pub tests: Vec, + pub repeat: u32, + pub attempts: Vec, + /// The CI route in flight. + pub ci: Option, + /// The result was handed to the review of this head. + pub reported: bool, +} + +/// Run-record field holding the plan, as JSON. +pub const FIELD: &str = "proof_routes"; + +/// Where the plan stands. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Verdict { + /// A route ran the test `runs` times, all passed. + Proven { route: Route, runs: u32 }, + /// A route ran the test and it failed: the fix doesn't hold. + Disproven { + route: Route, + passed: u32, + failed: u32, + }, + /// CI is running it. + Pending, + /// Routes are left to try. + Open, + /// Every route failed to run it, each with its reason. + Exhausted(Vec<(Route, String)>), +} + +impl Plan { + pub fn new(head: &str, tests: &[String], repeat: u32) -> Plan { + Plan { + head: head.to_string(), + tests: tests.to_vec(), + repeat: repeat.max(1), + ..Default::default() + } + } + + pub fn of_json(json: &str) -> Option { + serde_json::from_str(json).ok() + } + + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_default() + } + + fn last(&self, route: Route) -> Option<&Outcome> { + self.attempts + .iter() + .rev() + .find(|a| a.route == route) + .map(|a| &a.outcome) + } + + /// Records what `route` gave; a later result replaces a `Started`. + pub fn record(&mut self, route: Route, outcome: Outcome, at: &str) { + self.attempts + .retain(|a| !(a.route == route && matches!(a.outcome, Outcome::Started { .. }))); + self.attempts.push(Attempt { + route, + outcome, + at: at.to_string(), + }); + } + + pub fn verdict(&self) -> Verdict { + for route in ORDER { + match self.last(route) { + Some(Outcome::Passed { runs }) if *runs >= self.repeat => { + return Verdict::Proven { route, runs: *runs } + } + // Fewer runs than asked: not the proof, and not a failure. + Some(Outcome::Passed { .. }) => {} + Some(Outcome::Failed { passed, failed, .. }) => { + return Verdict::Disproven { + route, + passed: *passed, + failed: *failed, + } + } + Some(Outcome::Started { .. }) => return Verdict::Pending, + _ => {} + } + } + if ORDER.iter().all(|r| self.last(*r).is_some()) { + return Verdict::Exhausted( + ORDER + .iter() + .map(|r| { + let why = match self.last(*r) { + Some(Outcome::Unavailable { why }) => why.clone(), + Some(Outcome::Passed { runs }) => { + format!("it ran {runs} of the {} times asked", self.repeat) + } + _ => String::new(), + }; + (*r, why) + }) + .collect(), + ); + } + Verdict::Open + } + + /// The next route to try: the first not tried yet, while nothing has + /// given a result. + pub fn next(&self) -> Option { + match self.verdict() { + Verdict::Open => ORDER.into_iter().find(|r| self.last(*r).is_none()), + _ => None, + } + } + + /// The account the next review of the head reads: the result, or every + /// route with its own reason. + pub fn account(&self) -> String { + let what = if self.tests.is_empty() { + "the affected test".to_string() + } else { + self.tests + .iter() + .map(|t| format!("`{t}`")) + .collect::>() + .join(", ") + }; + let short = self.head.get(..7).unwrap_or(&self.head); + let tried = self + .attempts + .iter() + .map(|a| { + let r = match &a.outcome { + Outcome::Passed { runs } => format!("passed {runs} of {runs}"), + Outcome::Failed { + passed, + failed, + error, + } => { + let e = if error.is_empty() { + String::new() + } else { + format!(" ({})", crate::truncate_str(error, 200)) + }; + format!("failed {failed} of {}{e}", passed + failed) + } + Outcome::Unavailable { why } => format!("couldn't run: {why}"), + Outcome::Started { .. } => "running".to_string(), + }; + format!("- {}: {r}", a.route.words()) + }) + .collect::>() + .join("\n"); + let head = match self.verdict() { + Verdict::Proven { route, runs } => format!( + "Repeat proof on `{short}`: {what} passed {runs} of {runs} runs with retries off, on {}.", + route.words() + ), + Verdict::Disproven { + route, + passed, + failed, + } => format!( + "Repeat proof on `{short}`: {what} failed {failed} of {} runs with retries off, on {}. The fix doesn't hold yet.", + passed + failed, + route.words() + ), + Verdict::Pending => format!( + "Repeat proof on `{short}`: {what} is running {} times on CI.", + self.repeat + ), + Verdict::Open => format!("Repeat proof on `{short}`: {what}, routes still to try."), + Verdict::Exhausted(_) => format!( + "Repeat proof on `{short}`: no route could run {what}; each route's reason is below." + ), + }; + if tried.is_empty() { + head + } else { + format!("{head}\n{tried}") + } + } +} + +/// A sandbox route's output as an outcome: refused by the network or never +/// started is the route being unavailable; counts are a result. +pub fn outcome_of(output: &str, repeat: u32) -> Outcome { + use crate::stop_rules::tooling; + let hosts = tooling::blocked_hosts(output); + if !hosts.is_empty() { + return Outcome::Unavailable { + why: format!("the sandbox's network refused {}", hosts.join(", ")), + }; + } + if let Some(why) = tooling::runner_never_started(output) { + return Outcome::Unavailable { + why: crate::truncate_str(&why, 300).to_string(), + }; + } + let leg = crate::ci_repro::leg_of("", output); + if !leg.ran { + return Outcome::Unavailable { + why: if leg.note.is_empty() { + "the test didn't run".into() + } else { + leg.note + }, + }; + } + if leg.failed > 0 { + return Outcome::Failed { + passed: leg.passed, + failed: leg.failed, + error: leg.note, + }; + } + if leg.passed >= repeat { + Outcome::Passed { runs: leg.passed } + } else { + Outcome::Unavailable { + why: format!("only {} of {repeat} runs reported", leg.passed), + } + } +} + +/// The repeat count a finding asks for (`--repeat-each=20`, "20 repeat +/// runs", "20 times"), else `default`. +pub fn repeat_asked(text: &str, default: u32) -> u32 { + let low = text.to_ascii_lowercase(); + if let Some(i) = low.find("repeat-each=") { + let n: String = low[i + 12..] + .chars() + .take_while(|c| c.is_ascii_digit()) + .collect(); + if let Ok(n) = n.parse::() { + return n.clamp(1, 200); + } + } + let words: Vec<&str> = low.split_whitespace().collect(); + for w in words.windows(2) { + if let Ok(n) = w[0] + .trim_matches(|c: char| !c.is_ascii_digit()) + .parse::() + { + if w[1].starts_with("repeat") || w[1].starts_with("times") || w[1].starts_with("runs") { + return n.clamp(1, 200); + } + } + } + default +} + +/// Whether a review finding asks for a repeat run of a test. +pub fn asks_repeat(text: &str) -> bool { + let low = text.to_ascii_lowercase(); + low.contains("repeat-each") || low.contains("repeat run") || low.contains("runs in a row") +} + +// ── the sandbox routes' commands ───────────────────────────────────────── + +/// The command that runs `spec` (its `title` when given) `repeat` times, +/// retries off, against `target`, in the package at `dir`. `prelude` runs +/// first (the local app's start). `None` when a part can't be quoted. +pub fn repeat_cmd( + dir: &str, + spec: &str, + title: &str, + target: &str, + repeat: u32, + prelude: &str, +) -> Option { + use crate::ci_repro::{grep_of, quote}; + let dir = quote(if dir.is_empty() { "." } else { dir })?; + let spec = quote(spec)?; + let t = quote(target)?; + let grep = if title.trim().is_empty() { + String::new() + } else { + format!(" --grep {}", quote(&grep_of(title.trim()))?) + }; + Some(format!( + "cd {dir} && {install}; {prelude}\ + BASE_URL={t} PLAYWRIGHT_BASE_URL={t} PLAYWRIGHT_TEST_BASE_URL={t} E2E_BASE_URL={t} \ + npx --no-install playwright test {spec}{grep} --repeat-each={repeat} --retries=0 --workers=1 --reporter=line", + install = crate::e2e::test_package::BROWSER_INSTALL + )) +} + +/// The app started inside the sandbox: the repository's own script and the +/// port it serves on. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LocalApp { + pub script: String, + pub port: u16, +} + +/// Scripts that serve the app, preferred first: one written for end-to-end +/// runs, then the dev server (no build needed), then start and preview. +const SERVE_SCRIPTS: &[&str] = &[ + "e2e:serve", + "serve:e2e", + "start:e2e", + "dev", + "start", + "preview", + "serve", +]; + +fn port_in(text: &str) -> Option { + let low = text.to_ascii_lowercase(); + for key in [ + "--port=", + "--port ", + "-p ", + "port=", + "port: ", + "localhost:", + "127.0.0.1:", + ] { + if let Some(i) = low.find(key) { + let n: String = low[i + key.len()..] + .trim_start() + .chars() + .take_while(|c| c.is_ascii_digit()) + .collect(); + if let Ok(p) = n.parse::() { + if p >= 80 { + return Some(p); + } + } + } + } + None +} + +/// The local app from a package's `package.json` (and its Playwright +/// config's `webServer`, which names the port the tests expect). `None` +/// when the package has no script that serves it. +pub fn local_app(package_json: &str, playwright_config: Option<&str>) -> Option { + let v: Value = serde_json::from_str(package_json).ok()?; + let scripts = v.get("scripts")?.as_object()?; + let (name, body) = SERVE_SCRIPTS + .iter() + .find_map(|s| scripts.get(*s).and_then(|b| b.as_str()).map(|b| (*s, b)))?; + let web_server = + playwright_config.and_then(|c| c.find("webServer").map(|i| &c[i..c.len().min(i + 400)])); + let port = port_in(body) + .or_else(|| web_server.and_then(port_in)) + .unwrap_or_else(|| { + let b = body.to_ascii_lowercase(); + if b.contains("vite") { + 5173 + } else if b.contains("astro") { + 4321 + } else if b.contains("ng serve") { + 4200 + } else { + 3000 + } + }); + Some(LocalApp { + script: name.to_string(), + port, + }) +} + +/// The prelude that starts the local app with the package's own manager +/// and waits (up to three minutes) for its port. +pub fn local_prelude(app: &LocalApp, runner: &str) -> Option { + let script = crate::ci_repro::quote(&app.script)?; + Some(format!( + "({runner} run {script} > /tmp/ch-local-app.log 2>&1 &); i=0; until curl -s -o /dev/null http://127.0.0.1:{port}; do i=$((i+1)); if [ $i -gt 90 ]; then echo 'the app did not start'; tail -c 1500 /tmp/ch-local-app.log; break; fi; sleep 2; done; ", + port = app.port + )) +} + +// ── the CI route ───────────────────────────────────────────────────────── + +/// How the end-to-end workflow repeats the test on CI. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum CiWay { + /// Started by hand with its repeat input (and a filter, when it has one): + /// one run does every repeat. + Inputs { + repeat_input: String, + #[serde(default)] + grep_input: Option, + }, + /// Started by hand once per run needed (with its filter input when it + /// has one): each run runs the test once. + Dispatches { + #[serde(default)] + grep_input: Option, + }, + /// No manual start: its run on the head is re-run until enough runs + /// passed. + Reruns, +} + +/// The input names a workflow's manual start takes. +fn dispatch_inputs(yaml: &str) -> Option> { + let v: serde_yaml::Value = serde_yaml::from_str(yaml).ok()?; + let on = v + .get("on") + .or_else(|| v.get(serde_yaml::Value::Bool(true)))?; + let d = match on { + serde_yaml::Value::Mapping(m) => m.get("workflow_dispatch").map(Some)?, + serde_yaml::Value::Sequence(s) => s + .iter() + .any(|e| e.as_str() == Some("workflow_dispatch")) + .then_some(None)?, + serde_yaml::Value::String(s) if s == "workflow_dispatch" => None, + _ => return None, + }; + Some( + d.and_then(|d| d.get("inputs")) + .and_then(|i| i.as_mapping()) + .map(|m| { + m.keys() + .filter_map(|k| k.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default(), + ) +} + +/// How the workflow at `yaml` repeats a test. +pub fn ci_way(yaml: &str) -> CiWay { + let Some(names) = dispatch_inputs(yaml) else { + return CiWay::Reruns; + }; + let pick = |wanted: &[&str]| { + names + .iter() + .find(|n| wanted.contains(&n.to_lowercase().replace('-', "_").as_str())) + .cloned() + }; + let grep_input = pick(&[ + "grep", + "test_grep", + "filter", + "test_filter", + "grep_pattern", + "spec", + "tests", + ]); + match pick(&["repeat_each", "repeat", "repeats", "repeat_count"]) { + Some(repeat_input) => CiWay::Inputs { + repeat_input, + grep_input, + }, + None => CiWay::Dispatches { grep_input }, + } +} + +/// The CI route in flight. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct CiRun { + /// The workflow's file (`.github/workflows/e2e.yml`). + pub workflow: String, + pub way: Option, + /// When it was started (RFC 3339): runs before it aren't this proof's. + pub started_at: String, + /// Manual starts made. + pub dispatched: u32, + /// For [`CiWay::Reruns`]: the run re-run, and each attempt's result. + pub run_id: u64, + pub attempts: Vec<(u32, bool)>, +} + +/// Manual starts in flight at once: CI isn't flooded. +pub const CI_IN_FLIGHT: u32 = 4; + +/// What the CI route does next. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CiNext { + /// Start the workflow this many more times. + Dispatch(u32), + /// Re-run this run. + Rerun(u64), + Wait, + Done(Outcome), +} + +/// The CI route's next step from the workflow's runs (`runs`: its runs on +/// the head, newest first; for [`CiWay::Reruns`], the one run re-run) and +/// `repeat`. Records a finished re-run attempt on `ci`. +pub fn ci_step(ci: &mut CiRun, head: &str, runs: &[Value], repeat: u32) -> CiNext { + let repeat = repeat.max(1); + match ci.way.clone() { + None => CiNext::Done(Outcome::Unavailable { + why: "no end-to-end workflow was found to run it".into(), + }), + Some(CiWay::Reruns) => { + let Some(r) = runs.iter().find(|r| r["id"].as_u64() == Some(ci.run_id)) else { + return CiNext::Wait; + }; + if r["status"].as_str() != Some("completed") { + return CiNext::Wait; + } + let attempt = r["run_attempt"].as_u64().unwrap_or(1) as u32; + if !ci.attempts.iter().any(|(a, _)| *a == attempt) { + ci.attempts + .push((attempt, r["conclusion"].as_str() == Some("success"))); + } + let passed = ci.attempts.iter().filter(|(_, ok)| *ok).count() as u32; + let failed = ci.attempts.len() as u32 - passed; + if failed > 0 { + return CiNext::Done(Outcome::Failed { + passed, + failed, + error: "the end-to-end workflow failed on a re-run".into(), + }); + } + if passed >= repeat { + return CiNext::Done(Outcome::Passed { runs: passed }); + } + CiNext::Rerun(ci.run_id) + } + Some(way) => { + let ours: Vec<&Value> = runs + .iter() + .filter(|r| { + r["event"].as_str() == Some("workflow_dispatch") + && r["head_sha"].as_str() == Some(head) + && r["created_at"].as_str().unwrap_or("") >= ci.started_at.as_str() + }) + .collect(); + let done: Vec<&&Value> = ours + .iter() + .filter(|r| r["status"].as_str() == Some("completed")) + .collect(); + let passed = done + .iter() + .filter(|r| r["conclusion"].as_str() == Some("success")) + .count() as u32; + let failed = done.len() as u32 - passed; + let running = ours.len() as u32 - done.len() as u32; + let (wanted, per_run) = match way { + CiWay::Inputs { .. } => (1, repeat), + _ => (repeat, 1), + }; + if failed > 0 { + return CiNext::Done(Outcome::Failed { + passed: passed * per_run, + failed: failed * per_run, + error: "the end-to-end workflow failed on CI".into(), + }); + } + if passed >= wanted { + return CiNext::Done(Outcome::Passed { + runs: passed * per_run, + }); + } + let left = wanted.saturating_sub(ci.dispatched); + let room = CI_IN_FLIGHT + .saturating_sub(running.max(ci.dispatched.saturating_sub(passed + failed))); + if left > 0 && room > 0 { + CiNext::Dispatch(left.min(room)) + } else { + CiNext::Wait + } + } + } +} + +/// The inputs one manual start sends. +pub fn ci_inputs(way: &CiWay, tests: &[String], repeat: u32) -> serde_json::Map { + let mut m = serde_json::Map::new(); + let titles: Vec = tests + .iter() + .map(|t| t.rsplit(" › ").next().unwrap_or(t).to_string()) + .collect(); + let grep = titles + .iter() + .map(|t| crate::ci_repro::grep_of(t)) + .collect::>() + .join("|"); + match way { + CiWay::Inputs { + repeat_input, + grep_input, + } => { + m.insert(repeat_input.clone(), Value::String(repeat.to_string())); + if let Some(g) = grep_input.as_ref().filter(|_| !grep.is_empty()) { + m.insert(g.clone(), Value::String(grep.clone())); + } + } + CiWay::Dispatches { grep_input } => { + if let Some(g) = grep_input.as_ref().filter(|_| !grep.is_empty()) { + m.insert(g.clone(), Value::String(grep)); + } + } + CiWay::Reruns => {} + } + m +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const TEST: &str = "e2e/checkout.spec.ts › adds a book to the cart"; + + #[test] + fn a_route_the_network_refused_hands_on_to_the_next_and_a_result_ends_the_plan() { + let mut p = Plan::new("abc1234def", &[TEST.to_string()], 20); + assert_eq!(p.next(), Some(Route::Preview)); + let refused = "Error: page.goto: net::ERR_TUNNEL_CONNECTION_FAILED at https://pr-7.preview-web.acme-books.example/\n 20 failed\nCODERHELM_EGRESS_BLOCKED pr-7.preview-web.acme-books.example\n"; + p.record(Route::Preview, outcome_of(refused, 20), "t1"); + assert_eq!(p.next(), Some(Route::Staging)); + p.record( + Route::Staging, + Outcome::Unavailable { + why: "no staging address".into(), + }, + "t2", + ); + assert_eq!(p.next(), Some(Route::LocalApp)); + p.record( + Route::LocalApp, + outcome_of(" 20 passed (1.2m)\n", 20), + "t3", + ); + assert_eq!( + p.verdict(), + Verdict::Proven { + route: Route::LocalApp, + runs: 20 + } + ); + assert_eq!(p.next(), None); + let a = p.account(); + assert!(a.contains("passed 20 of 20 runs with retries off")); + assert!(a.contains("couldn't run: the sandbox's network refused")); + } + + #[test] + fn a_real_failure_is_the_result_never_a_reason_to_try_elsewhere() { + let mut p = Plan::new("abc1234def", &[TEST.to_string()], 20); + p.record( + Route::Preview, + outcome_of( + " 1) checkout.spec.ts › adds\n 3 failed\n 17 passed\n", + 20, + ), + "t", + ); + assert!(matches!(p.verdict(), Verdict::Disproven { failed: 3, .. })); + assert_eq!(p.next(), None); + } + + #[test] + fn it_says_it_couldnt_only_after_every_route_with_each_reason() { + let mut p = Plan::new("abc1234def", &[], 20); + for r in ORDER { + assert!(!matches!(p.verdict(), Verdict::Exhausted(_))); + p.record( + r, + Outcome::Unavailable { + why: format!("{r:?} reason"), + }, + "t", + ); + } + let Verdict::Exhausted(why) = p.verdict() else { + panic!("exhausted") + }; + assert_eq!(why.len(), 4); + assert!(why.iter().all(|(r, w)| w == &format!("{r:?} reason"))); + } + + #[test] + fn the_ci_way_follows_the_workflow_inputs() { + let inputs = "on:\n pull_request:\n workflow_dispatch:\n inputs:\n grep:\n type: string\n repeat-each:\n default: '1'\njobs: {}\n"; + assert_eq!( + ci_way(inputs), + CiWay::Inputs { + repeat_input: "repeat-each".into(), + grep_input: Some("grep".into()) + } + ); + let bare = "on:\n pull_request:\n workflow_dispatch:\njobs: {}\n"; + assert_eq!(ci_way(bare), CiWay::Dispatches { grep_input: None }); + let none = "on: [pull_request]\njobs: {}\n"; + assert_eq!(ci_way(none), CiWay::Reruns); + } + + fn run(id: u64, status: &str, conclusion: &str) -> Value { + json!({"id": id, "event": "workflow_dispatch", "head_sha": "abc", "created_at": "2026-11-30T10:00:00Z", "status": status, "conclusion": conclusion}) + } + + #[test] + fn ci_without_a_repeat_input_is_started_once_per_run_needed_a_few_at_a_time() { + let mut ci = CiRun { + workflow: ".github/workflows/e2e.yml".into(), + way: Some(CiWay::Dispatches { grep_input: None }), + started_at: "2026-11-30T09:00:00Z".into(), + ..Default::default() + }; + assert_eq!( + ci_step(&mut ci, "abc", &[], 20), + CiNext::Dispatch(CI_IN_FLIGHT) + ); + ci.dispatched = 4; + let runs: Vec = (0..4).map(|i| run(i, "in_progress", "")).collect(); + assert_eq!(ci_step(&mut ci, "abc", &runs, 20), CiNext::Wait); + let runs: Vec = (0..4).map(|i| run(i, "completed", "success")).collect(); + assert_eq!(ci_step(&mut ci, "abc", &runs, 20), CiNext::Dispatch(4)); + ci.dispatched = 20; + let runs: Vec = (0..20).map(|i| run(i, "completed", "success")).collect(); + assert_eq!( + ci_step(&mut ci, "abc", &runs, 20), + CiNext::Done(Outcome::Passed { runs: 20 }) + ); + let mut red = runs.clone(); + red[3] = run(3, "completed", "failure"); + assert!(matches!( + ci_step(&mut ci, "abc", &red, 20), + CiNext::Done(Outcome::Failed { failed: 1, .. }) + )); + } + + #[test] + fn ci_with_no_manual_start_reruns_the_heads_run() { + let mut ci = CiRun { + way: Some(CiWay::Reruns), + run_id: 77, + ..Default::default() + }; + let r = |attempt: u64| json!({"id": 77, "status": "completed", "conclusion": "success", "run_attempt": attempt}); + for a in 1..3u64 { + assert_eq!(ci_step(&mut ci, "abc", &[r(a)], 3), CiNext::Rerun(77)); + } + assert_eq!( + ci_step(&mut ci, "abc", &[r(3)], 3), + CiNext::Done(Outcome::Passed { runs: 3 }) + ); + } + + #[test] + fn the_local_app_comes_from_the_repositorys_own_script() { + let pkg = r#"{"scripts": {"build": "next build", "dev": "next dev -p 4000", "test:e2e": "playwright test"}}"#; + assert_eq!( + local_app(pkg, None), + Some(LocalApp { + script: "dev".into(), + port: 4000 + }) + ); + let vite = r#"{"scripts": {"dev": "vite"}}"#; + assert_eq!(local_app(vite, None).map(|a| a.port), Some(5173)); + let cfg = "webServer: { command: 'npm run dev', url: 'http://localhost:8080' }"; + // The port the tests' own web server names wins over a default. + assert_eq!(local_app(vite, Some(cfg)).map(|a| a.port), Some(8080)); + let plain = r#"{"scripts": {"start": "node server.js"}}"#; + assert_eq!(local_app(plain, Some(cfg)).map(|a| a.port), Some(8080)); + assert_eq!( + local_app(r#"{"scripts": {"lint": "eslint ."}}"#, None), + None + ); + let pre = local_prelude(&local_app(pkg, None).unwrap(), "npm").unwrap(); + assert!(pre.contains("npm run 'dev'") && pre.contains("127.0.0.1:4000")); + } + + #[test] + fn the_repeat_asked_is_read_from_the_finding() { + assert_eq!( + repeat_asked("Prove it with `--repeat-each=20 --retries=0`", 5), + 20 + ); + assert_eq!(repeat_asked("needs 30 repeat runs", 5), 30); + assert_eq!(repeat_asked("prove it", 5), 5); + assert!(asks_repeat("run it with --repeat-each=20")); + let cmd = repeat_cmd( + "e2e", + "checkout.spec.ts", + "adds a book", + "https://staging.acme-books.example", + 20, + "", + ) + .unwrap(); + assert!(cmd.contains("--repeat-each=20 --retries=0")); + } +} diff --git a/services/gateway/src/routes/reviewer.rs b/services/gateway/src/routes/reviewer.rs index 121259453..b4544a532 100644 --- a/services/gateway/src/routes/reviewer.rs +++ b/services/gateway/src/routes/reviewer.rs @@ -78,14 +78,49 @@ pub async fn get_org_config( .and_then(|v| v.as_l().ok()) .map(|l| l.iter().filter_map(|v| v.as_s().ok().cloned()).collect()) .unwrap_or_default(); + let suggested = suggested_web_domains(&state, &claims.team_id, &web_domains).await; Ok(Json(json!({ "instructions": item_str(&item, "instructions", ""), // The team's own public sites agents may check pages on (check_url); // a domain covers its subdomains. "web_domains": web_domains, + // Domains the team's default branches name as where their apps are + // served (end-to-end config, workflow environments, deploys) that + // aren't verified yet: an admin adds one to `web_domains` once, and + // CoderHelm's sandbox reaches the hosts under it from then on. + "suggested_web_domains": suggested, }))) } +/// The domains the repositories' default branches name that the team +/// hasn't verified (`common::agent_policy::repo_hosts`), each with where it +/// was read. +async fn suggested_web_domains(state: &AppState, team_id: &str, verified: &[String]) -> Vec { + use common::agent_policy::repo_hosts::{self, RepoHosts}; + let items = state + .dynamo + .query() + .table_name(&state.config.settings_table_name) + .key_condition_expression("pk = :pk AND begins_with(sk, :sk)") + .expression_attribute_values(":pk", attr_s(team_id)) + .expression_attribute_values(":sk", attr_s(repo_hosts::SK_PREFIX)) + .send() + .await + .map(|o| o.items().to_vec()) + .unwrap_or_default(); + let derived: Vec = items + .iter() + .filter_map(|i| i.get("hosts").and_then(|v| v.as_s().ok())) + .filter_map(|j| serde_json::from_str::(j).ok()) + .flat_map(|r| r.derived) + .collect(); + let (_, proposed) = repo_hosts::sort(&derived, verified); + proposed + .into_iter() + .map(|p| json!({"domain": p.domain, "source": p.source})) + .collect() +} + /// The `web_domains` a PUT sets: `None` when the body doesn't send them (so /// they're kept), `Err` with the entries that aren't domains. fn web_domains_from(body: &Value) -> Result>, Vec> { diff --git a/services/worker/src/agent/policy.rs b/services/worker/src/agent/policy.rs index 9769198df..d2f4394bb 100644 --- a/services/worker/src/agent/policy.rs +++ b/services/worker/src/agent/policy.rs @@ -123,7 +123,137 @@ async fn own_hosts(state: &WorkerState, team: &str) -> Vec { .filter_map(|i| i.get("address").and_then(|v| v.as_s().ok()).cloned()), ); } - common::agent_policy::sandbox::own_hosts(&domains, &addresses) + let mut own = common::agent_policy::sandbox::own_hosts(&domains, &addresses); + // The hosts the repositories' default branches name, each kept with its + // source when it falls under a verified domain + // (`agent_policy::repo_hosts`); the rest wait as suggestions in Settings. + let derived = state + .dynamo + .query() + .table_name(&state.config.settings_table_name) + .key_condition_expression("pk = :pk AND begins_with(sk, :sk)") + .expression_attribute_values(":pk", AttributeValue::S(team.to_string())) + .expression_attribute_values( + ":sk", + AttributeValue::S(common::agent_policy::repo_hosts::SK_PREFIX.into()), + ) + .send() + .await; + if let Ok(o) = derived { + let derived: Vec = o + .items() + .iter() + .filter_map(|i| i.get("hosts").and_then(|v| v.as_s().ok())) + .filter_map(|j| { + serde_json::from_str::(j).ok() + }) + .flat_map(|r| r.derived) + .collect(); + let (allowed, _) = common::agent_policy::repo_hosts::sort(&derived, &domains); + for a in allowed { + if !common::agent_policy::sandbox::domain_allowed(&own, &a.host) { + own.push(a.host.clone()); + } + tracing::debug!(team, host = %a.host, source = %a.source, under = %a.under, "Sandbox reaches the team's own host"); + } + } + own +} + +/// Reads where the repository's apps are served from its default branch +/// (end-to-end config, env templates, workflow environments, the default +/// branch's deploys) and keeps it on the team's settings +/// (`agent_policy::repo_hosts`). Never a pull request's head: a change could +/// otherwise name a host for the sandbox to reach. Read again only when the +/// default branch moved. +pub async fn learn_repo_hosts( + state: &WorkerState, + github: &crate::clients::github::GitHubClient, + team: &str, + owner: &str, + repo: &str, +) { + use common::agent_policy::repo_hosts::{self, RepoHosts}; + let full = format!("{owner}/{repo}"); + let Ok(branch) = github.get_default_branch(owner, repo).await else { + return; + }; + let Ok(sha) = github.get_ref(owner, repo, &branch).await else { + return; + }; + let sk = repo_hosts::settings_sk(&full); + let kept = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", AttributeValue::S(team.to_string())) + .key("sk", AttributeValue::S(sk.clone())) + .send() + .await + .ok() + .and_then(|o| o.item().cloned()) + .and_then(|i| i.get("hosts").and_then(|v| v.as_s().ok()).cloned()) + .and_then(|j| serde_json::from_str::(&j).ok()); + if kept.as_ref().is_some_and(|k| k.sha == sha) { + return; + } + let Ok(tree) = github.get_tree(owner, repo, &sha).await else { + return; + }; + let mut files: Vec<(String, String)> = Vec::new(); + for p in tree + .iter() + .map(|e| e.path.as_str()) + .filter(|p| !p.contains("node_modules/") && repo_hosts::reads(p)) + .take(16) + { + if let Ok(text) = github.read_file(owner, repo, p, &sha).await { + files.push((p.to_string(), text)); + } + } + let mut derived = repo_hosts::from_files(&files, &branch); + let deploys: Vec<(String, String)> = github + .deployments_with_statuses(owner, repo, &sha) + .await + .unwrap_or_default() + .iter() + .flat_map(|(d, statuses)| { + let name = d["environment"].as_str().unwrap_or("deploy").to_string(); + statuses + .iter() + .filter_map(|s| s["environment_url"].as_str()) + .filter(|u| !u.is_empty()) + .map(move |u| (u.to_string(), name.clone())) + .collect::>() + }) + .collect(); + for d in repo_hosts::from_deploys(&deploys) { + if !derived.iter().any(|x| x.domain == d.domain) { + derived.push(d); + } + } + let record = RepoHosts { + repo: full.clone(), + sha, + derived, + at: chrono::Utc::now().to_rfc3339(), + }; + tracing::info!(team, repo = %full, hosts = record.derived.len(), "Read where the repository's apps are served from its default branch"); + if let Err(e) = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", AttributeValue::S(team.to_string())) + .item("sk", AttributeValue::S(sk)) + .item( + "hosts", + AttributeValue::S(serde_json::to_string(&record).unwrap_or_default()), + ) + .send() + .await + { + tracing::warn!(team, repo = %full, error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "Could not keep the repository's app hosts"); + } } /// How long a run waits for an answer: until two minutes before its diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index 3ca703029..984a94d37 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -1678,13 +1678,13 @@ async fn no_burn_in_note( r.events.push(event( "flaky", "flaky", - "Fix opened without repeat runs: the E2E workflow can't be started with repeats.".into(), + "Fix opened; the E2E workflow takes no repeat input, so its proof goes along the other routes.".into(), )); if let Some(pr) = pr { let _ = crate::passes::conversation::github(gh, owner, repo, pr, common::conversation::Say::note("e2e", format!( - "CoderHelm couldn't prove this fix with repeat runs, because the E2E workflow has no `workflow_dispatch` input for repeats, so it's ready for review without them. Run `{}` about 20 times (e.g. `npx playwright test --grep \"{}\" --repeat-each=20`) before merging. Adding a `repeat_each` input to the workflow lets CoderHelm do this itself.", + "The E2E workflow takes no repeat input, so CoderHelm proves `{}` along its other routes on this pull request: the sandbox against the preview, staging or the app started from the repository's own script, else the workflow started once per run until it reaches {} runs.", r.title, - grep_for(std::slice::from_ref(&r.title)) + BURN_IN_RUNS ))) .await; } diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 6de59966f..36383da83 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -371,6 +371,16 @@ pub async fn run( let sandbox = if !state.config.sandbox_bucket_name.is_empty() && !state.config.sandbox_project_name.is_empty() { + // Where the team's apps are served, from the default branch, so the + // sandbox's network reaches its own staging site and previews. + crate::agent::policy::learn_repo_hosts( + state, + github, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + ) + .await; Some( crate::clients::sandbox::SandboxClient::new( &state.codebuild, diff --git a/services/worker/src/passes/incidents/xc_owed_proof_runs_its_routes.rs b/services/worker/src/passes/incidents/xc_owed_proof_runs_its_routes.rs new file mode 100644 index 000000000..3c4bc9d7d --- /dev/null +++ b/services/worker/src/passes/incidents/xc_owed_proof_runs_its_routes.rs @@ -0,0 +1,355 @@ +//! xc. A run fixing a failing end-to-end test opened its pull request, and +//! CoderHelm's own review asked for one thing: the test passing a set +//! number of times in a row with retries off. The fix round ran the repeat in the sandbox +//! against the team's staging site and against the pull request's preview, +//! and every attempt failed before the page loaded: the sandbox's network +//! refused both hosts, because its allowlist held only what the team had +//! typed into its settings, though the repository's own end-to-end config +//! and preview workflow named both. The round made no change and wrote +//! that a person should widen CoderHelm's allowlist or run the command +//! themselves; it called a repeat on CI "a CI change outside this ticket". +//! Its findings had their round on that head, so nothing picked them up +//! again, and the pull request waited on CoderHelm's own review. +//! +//! Guarantee: the hosts where the team's apps are served are read from the +//! default branch's config and deploys (never a pull request's head), kept +//! with their source, and allowed when they fall under a domain the team +//! verified; a domain not verified yet is suggested once in Settings. A +//! repeat proof is a plan with routes tried in order (the sandbox against +//! the preview, against staging, against the app started from the +//! repository's own script, then CI started or re-run until the count is +//! reached), and it says it couldn't only after every route, each with its +//! reason. A pull request whose own review asks for a proof the sandbox +//! couldn't reach is picked up by the sweep, proven or held on a real +//! result, with nobody commenting. + +use crate::passes::own_review_ledger::{Blocker, Ledger, Settled, Track}; +use crate::passes::pr_watch::{self, Marks, Seen}; +use common::agent_policy::repo_hosts; +use common::agent_policy::sandbox::{domain_allowed, own_hosts, run_allowlist}; +use common::e2e::proof_routes::{ + self as routes, CiNext, CiRun, CiWay, Outcome, Plan, Route, Verdict, +}; +use serde_json::json; + +const HEAD: &str = "5e1f0aa7c3d2b9e8f1a0"; +const STAGING: &str = "staging.acme-books.example"; +const PREVIEW: &str = "pr-58.preview-web.acme-books.example"; +const TEST: &str = "e2e/cart.spec.ts › keeps the book in the cart after sign-in"; +const FINDING: &str = + "Prove the fix: run it with `--repeat-each=20 --retries=0` (`e2e/cart.spec.ts:14`)"; + +/// The bookstore's default branch: its Playwright config and preview +/// workflow name where its apps are served. +fn default_branch_files() -> Vec<(String, String)> { + vec![ + ( + "e2e/playwright.config.ts".into(), + format!("export default defineConfig({{ use: {{ baseURL: process.env.E2E_BASE_URL ?? 'https://{STAGING}' }} }});\n"), + ), + ( + ".github/workflows/preview.yml".into(), + "on: pull_request\njobs:\n deploy:\n environment:\n name: preview\n url: https://pr-${{ github.event.number }}.preview-web.acme-books.example\n".into(), + ), + ] +} + +fn blocked(host: &str) -> String { + format!("Error: page.goto: net::ERR_TUNNEL_CONNECTION_FAILED at https://{host}/cart\n 20 failed\nCODERHELM_EGRESS_BLOCKED {host}\n") +} + +#[test] +fn the_preview_host_from_the_default_branch_is_allowed_and_the_repeat_proof_runs() { + let derived = repo_hosts::from_files(&default_branch_files(), "main"); + // Verified in Settings: the bookstore's own domain. + let verified = vec!["acme-books.example".to_string()]; + let (allowed, proposed) = repo_hosts::sort(&derived, &verified); + assert!(proposed.is_empty()); + assert!(allowed + .iter() + .all(|a| a.under == "acme-books.example" && a.source.contains("on main"))); + let own = own_hosts(&verified, &[]); + let list = run_allowlist(&["registry.npmjs.org".to_string()], &own); + for host in [STAGING, PREVIEW] { + assert!(domain_allowed(&list, host), "{host}"); + } + // A host the default branch never named stays outside. + assert!(!domain_allowed(&list, "collector.elsewhere.example")); + + // Not verified yet: the domain is suggested once, nothing is allowed. + let (allowed, proposed) = repo_hosts::sort(&derived, &[]); + assert!(allowed.is_empty()); + assert_eq!(proposed.len(), 1); + assert_eq!(proposed[0].domain, "acme-books.example"); + + // With the host reachable, the first route gives the proof. + let mut plan = Plan::new(HEAD, &[TEST.to_string()], routes::repeat_asked(FINDING, 5)); + assert_eq!(plan.repeat, 20); + assert_eq!(plan.next(), Some(Route::Preview)); + plan.record( + Route::Preview, + routes::outcome_of(" 20 passed (48s)\n", 20), + "t", + ); + assert_eq!( + plan.verdict(), + Verdict::Proven { + route: Route::Preview, + runs: 20 + } + ); +} + +#[test] +fn with_the_sandbox_blocked_the_proof_goes_through_ci_repeats_and_the_review_settles() { + let mut plan = Plan::new(HEAD, &[TEST.to_string()], 20); + plan.record( + Route::Preview, + routes::outcome_of(&blocked(PREVIEW), 20), + "t1", + ); + plan.record( + Route::Staging, + routes::outcome_of(&blocked(STAGING), 20), + "t2", + ); + plan.record( + Route::LocalApp, + Outcome::Unavailable { + why: "the package has no dev, start or preview script to serve the app".into(), + }, + "t3", + ); + assert_eq!(plan.next(), Some(Route::Ci)); + + // The workflow runs each test once and takes no repeat input: it is + // started once per run needed, a few at a time. + let yaml = + "on:\n pull_request:\n workflow_dispatch:\njobs:\n e2e:\n runs-on: ubuntu-latest\n"; + let mut ci = CiRun { + workflow: ".github/workflows/e2e.yml".into(), + way: Some(routes::ci_way(yaml)), + started_at: "2026-11-30T09:00:00Z".into(), + ..Default::default() + }; + assert_eq!(ci.way, Some(CiWay::Dispatches { grep_input: None })); + assert_eq!( + routes::ci_step(&mut ci, HEAD, &[], 20), + CiNext::Dispatch(routes::CI_IN_FLIGHT) + ); + plan.record(Route::Ci, Outcome::Started { at: "t4".into() }, "t4"); + assert_eq!(plan.verdict(), Verdict::Pending); + ci.dispatched = 20; + let runs: Vec = (0..20) + .map(|i| json!({"id": i, "event": "workflow_dispatch", "head_sha": HEAD, "created_at": "2026-11-30T09:05:00Z", "status": "completed", "conclusion": "success"})) + .collect(); + let CiNext::Done(done) = routes::ci_step(&mut ci, HEAD, &runs, 20) else { + panic!("done") + }; + plan.record(Route::Ci, done, "t5"); + assert_eq!( + plan.verdict(), + Verdict::Proven { + route: Route::Ci, + runs: 20 + } + ); + + // The result is the round the next review of the head reads. + let mut ledger = stuck_ledger(); + assert_eq!(ledger.owed_proofs(), vec![FINDING.to_string()]); + ledger.proof_given(&[FINDING.to_string()], &plan.account()); + let last = ledger.last.as_ref().expect("a round to read"); + assert!( + last.ended + && last + .account + .contains("passed 20 of 20 runs with retries off") + ); + assert!(last + .account + .contains("refused pr-58.preview-web.acme-books.example")); + assert!(ledger.owed_proofs().is_empty()); + for words in ["outside this ticket", "yourself", "allowlist"] { + assert!(!last.account.to_lowercase().contains(words), "{words}"); + } +} + +#[test] +fn neither_the_allowlist_nor_ci_repeats_is_ever_a_persons_step() { + let rules = crate::passes::own_review_ledger::round_rules("Fix the cart test."); + assert!(rules.contains("A repeat run is never a person's")); + assert!(rules.contains("never a CI change outside it")); + let unblock = crate::passes::own_review_ledger::instruction( + &crate::passes::own_review_ledger::Approach::Unblock(vec![Blocker::Tooling]), + &[FINDING.to_string()], + ); + assert!(unblock.contains("CoderHelm runs the proof on CI itself")); + assert!(unblock.contains("never a CI change outside it")); + + // A round that still writes the hand-off is read as CoderHelm's own block. + let mut l = Ledger::default(); + l.observe(&[FINDING.to_string()], ""); + l.start_round(&[FINDING.to_string()]); + l.end_round( + vec![Blocker::Tooling], + &format!("NEEDS A PERSON: {FINDING} :: outside_reach :: Add `{STAGING}` to CoderHelm's sandbox network allowlist, or run the command yourself"), + ); + l.observe(&[FINDING.to_string()], ""); + let t = &l.findings[0]; + assert!(t.person_reason.is_empty() && t.tooling == 1); + assert!(!matches!(t.settled, Some(Settled::Deferred { .. }))); + + // Every sandbox route refused and CI unavailable: the plan names each + // route's own reason, and the review reads it, never a person's to-do. + let mut plan = Plan::new(HEAD, &[TEST.to_string()], 20); + for r in routes::ORDER { + plan.record( + r, + Outcome::Unavailable { + why: format!("{} reason", r.words()), + }, + "t", + ); + } + assert!(matches!(plan.verdict(), Verdict::Exhausted(ref w) if w.len() == 4)); + assert!(!plan.account().contains("NEEDS A PERSON")); +} + +fn stuck_ledger() -> Ledger { + Ledger { + findings: vec![Track { + item: FINDING.to_string(), + attempts: 2, + tooling: 2, + blocked: 2, + last_blocked: vec![Blocker::Tooling], + settled: Some(Settled::Noted { + why: "the sandbox couldn't run it".into(), + }), + ..Default::default() + }], + ..Default::default() + } +} + +#[test] +fn an_already_stuck_pr_is_picked_up_by_the_sweep_after_deploy() { + let seen = Seen { + open: true, + head: HEAD.into(), + reviewer_on: true, + own_verdict: Some(("REQUEST_CHANGES".into(), HEAD.into())), + ..Default::default() + }; + // Its findings already had their round on this head: the usual act + // does nothing, which is how it sat. + let marks = Marks { + findings_head: HEAD.into(), + review_head: HEAD.into(), + ..Default::default() + }; + assert_eq!( + pr_watch::decide("completed", &seen, &marks), + pr_watch::Act::Nothing + ); + let owed = stuck_ledger().owed_proofs(); + assert!(pr_watch::proof_due("completed", &seen, &marks, &owed, "")); + + // The run record as the table holds it carries the ledger. + let mut item = std::collections::HashMap::new(); + for (k, v) in [ + ("team_id", "t-acme"), + ("run_id", "r-58"), + ("status", "completed"), + ("repo", "acme/bookstore"), + ("pr_url", "https://github.com/acme/bookstore/pull/58"), + ] { + item.insert( + k.to_string(), + aws_sdk_dynamodb::types::AttributeValue::S(v.into()), + ); + } + for (k, v) in [("pr_number", "58"), ("installation_id", "7")] { + item.insert( + k.to_string(), + aws_sdk_dynamodb::types::AttributeValue::N(v.into()), + ); + } + item.insert( + crate::passes::own_review_ledger::FIELD.to_string(), + aws_sdk_dynamodb::types::AttributeValue::S(stuck_ledger().to_json()), + ); + let c = pr_watch::candidate_of(&item).expect("a candidate"); + assert_eq!(c.owed_proofs, vec![FINDING.to_string()]); + + // Once its result was handed to the review of the head, it's done. + let mut plan = Plan::new(HEAD, &[TEST.to_string()], 20); + plan.record( + Route::Ci, + Outcome::Failed { + passed: 17, + failed: 3, + error: String::new(), + }, + "t", + ); + assert!(matches!( + plan.verdict(), + Verdict::Disproven { failed: 3, .. } + )); + plan.reported = true; + assert!(!pr_watch::proof_due( + "completed", + &seen, + &marks, + &owed, + &plan.to_json() + )); + // A new head starts over. + let moved = Seen { + head: "9a8b7c6d".into(), + own_verdict: Some(("REQUEST_CHANGES".into(), "9a8b7c6d".into())), + ..seen.clone() + }; + let marks2 = Marks { + findings_head: "9a8b7c6d".into(), + ..Default::default() + }; + assert!(pr_watch::proof_due( + "completed", + &moved, + &marks2, + &owed, + &plan.to_json() + )); + // A person's approval path or a closed pull request is left alone. + let closed = Seen { + open: false, + ..seen + }; + assert!(!pr_watch::proof_due( + "completed", + &closed, + &marks, + &owed, + "" + )); +} + +#[test] +fn the_pipeline_still_calls_the_sweep_and_the_routes() { + let src = |p: &str| { + std::fs::read_to_string(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(p)).expect(p) + }; + let watch = src("src/passes/pr_watch.rs"); + assert!(watch.contains("proof_due(&c.status, &seen, &c.marks, &c.owed_proofs, &c.proof_plan)")); + assert!(watch.contains("super::proof_routes::advance(")); + let gate = src("src/passes/test_fix.rs"); + assert!(gate.contains("super::proof_routes::advance(")); + assert!(!gate.contains("mark this ready yourself")); + let implement = src("src/passes/implement.rs"); + assert!(implement.contains("learn_repo_hosts(")); + let e2e = src("src/passes/e2e.rs"); + assert!(!e2e.contains("before merging. Adding a `repeat_each` input")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index a4b9f1a00..3a129ec7e 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1403,6 +1403,7 @@ mod pr_risk; pub mod pr_watch; pub mod preview; mod proof; +pub(crate) mod proof_routes; mod push_checks; pub mod quarantine; pub mod quarantine_work; diff --git a/services/worker/src/passes/own_review_ledger.rs b/services/worker/src/passes/own_review_ledger.rs index 4f379dbe0..4cc0c040f 100644 --- a/services/worker/src/passes/own_review_ledger.rs +++ b/services/worker/src/passes/own_review_ledger.rs @@ -413,7 +413,10 @@ pub fn round_rules(ticket: &str) -> String { allowlist refuses a site, a browser won't install or a tool is missing, say so in one \ line with the exact error, then get the proof another way (the repository's CI on this \ branch, read with `github_history`; a page check with `check_url`) and write what is \ - proven and what is not.{ticket}", + proven and what is not. A repeat run is never a person's either: CoderHelm runs it in \ + the sandbox against the preview, staging or the app started from the repository's own \ + script, and else on CI by starting the end-to-end workflow as many times as the count \ + needs. Proving the fix is the ticket's work, never a CI change outside it.{ticket}", codes.join(", ") ) } @@ -717,6 +720,43 @@ impl Ledger { } } + /// The findings whose proof CoderHelm's own environment kept it from + /// running (a round met [`Blocker::Tooling`]) and that ask for a repeat + /// run: their proof is owed, along every route + /// (`common::e2e::proof_routes`), never a person's. + pub fn owed_proofs(&self) -> Vec { + self.findings + .iter() + .filter(|t| matches!(t.settled, None | Some(Settled::Noted { .. }))) + .filter(|t| t.tooling > 0 || t.last_blocked.contains(&Blocker::Tooling)) + .filter(|t| common::e2e::proof_routes::asks_repeat(&t.item)) + .map(|t| t.item.clone()) + .collect() + } + + /// The owed proof of `items` gave its result (`account`): it is the + /// round the next review of the head reads, and the findings are open + /// again for that review to settle on the result. + pub fn proof_given(&mut self, items: &[String], account: &str) { + for t in self + .findings + .iter_mut() + .filter(|t| items.iter().any(|i| same_finding(&t.item, i))) + { + t.tooling = 0; + t.last_blocked.retain(|b| *b != Blocker::Tooling); + if matches!(t.settled, Some(Settled::Noted { .. })) { + t.settled = None; + } + } + self.last = Some(LastRound { + taken: items.to_vec(), + blocked: Vec::new(), + account: common::truncate_str(account, 6_000).to_string(), + ended: true, + }); + } + /// Whether every finding still open on `open` is settled with a reason /// (a person-gate reason, or the ticket), so the review's verdict on the /// head must not hold on it. @@ -803,11 +843,16 @@ pub fn instruction(approach: &Approach, focus: &[String]) -> String { "\n\n## This round's approach\nThe last round on {what} didn't fail on the code: \ {}. That is CoderHelm's own environment, never a person's step, and the sandbox now \ reaches the team's own sites and Playwright's browser downloads. Run what the finding \ - asks for again first, as its own `bash` call. If the sandbox still can't, change \ - approach: read the repository's CI runs on this branch with `github_history` (the \ - end-to-end workflow's results on this head are the proof), check the pages with \ - `check_url`, and write what is proven and what is not, with the exact error. Never \ - write a {NEEDS_A_PERSON} line for CoderHelm's sandbox, its allowlist or its tools.", + asks for again first, as its own `bash` call, and if the staging site or the preview \ + is refused, against the app started in the sandbox from the repository's own dev or \ + start script. If the sandbox still can't, write the exact error, read what the end-to-end workflow \ + already shows on this head with `github_history` and check the pages with \ + `check_url`: \ + CoderHelm runs the proof on CI itself (the end-to-end workflow started or re-run on \ + this head until the repeat count is reached) and the review reads its result. \ + Proving the fix is this ticket's work, never a CI change outside it. Never write a \ + {NEEDS_A_PERSON} line for CoderHelm's sandbox, its allowlist, its tools or a repeat \ + run.", b.iter().map(|x| x.words()).collect::>().join("; ") ), Approach::Unblock(b) => format!( diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 84bd624a0..43daa03cf 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -202,6 +202,10 @@ pub enum Act { /// covers the change is closed by CoderHelm, also on pull requests /// whose run finished before this existed. Preview, + /// Run the proof the run's own review asks for and its sandbox + /// couldn't reach, along its routes (`proof_routes::advance`), and hand + /// the result to the review of the head ([`proof_due`]). + ProveOwed, } impl Act { @@ -218,6 +222,9 @@ impl Act { // Done on every look until the head's preview is settled; each // step of it is idempotent per head (`preview_state`). Act::Preview => None, + // Each step is kept on the run's plan for the head + // (`proof_routes`), which ends once its result is handed over. + Act::ProveOwed => None, } } } @@ -330,6 +337,31 @@ pub fn preview_due(stored: &str, head: &str, fresh: bool, now: &str) -> bool { } } +/// Whether the proof the run's own review asks for is owed on the head: the +/// review asks for changes on this very head, its findings already had their +/// fix round here (so nothing else picks them up), and one of them is a +/// repeat run CoderHelm's sandbox couldn't reach (`owed`, from the run's +/// ledger: `own_review_ledger::Ledger::owed_proofs`). A pull request once +/// sat a week this way. Done until the proof's plan for the head (`plan`) +/// handed its result over. Pull requests whose run finished before this +/// existed are picked up by the same sweep. +pub fn proof_due(status: &str, seen: &Seen, marks: &Marks, owed: &[String], plan: &str) -> bool { + let changes = + matches!(&seen.own_verdict, Some((v, sha)) if v == "REQUEST_CHANGES" && *sha == seen.head); + let handed = common::e2e::proof_routes::Plan::of_json(plan) + .is_some_and(|p| p.head == seen.head && p.reported); + watched(status) + && status != "merged" + && seen.open + && !seen.merged + && !seen.head.is_empty() + && seen.reviewer_on + && changes + && marks.findings_head == seen.head + && !owed.is_empty() + && !handed +} + /// The round to run again before anything else is decided: one GitHub's /// rate limit ended (`limit_ended`: when that round stopped, "" when the /// run's last round wasn't ended by a limit), on a pull request still open, @@ -387,6 +419,11 @@ pub struct Candidate { /// Its pull request is held as a draft (`draft_hold` on the run): the /// run's work waits on CoderHelm's next look, so it is looked at first. pub draft_held: bool, + /// Its own review's findings whose repeat proof the sandbox couldn't + /// reach (`own_review_ledger::Ledger::owed_proofs`). + pub owed_proofs: Vec, + /// The proof's plan for the head, as kept (`proof_routes`), "" when none. + pub proof_plan: String, } impl Candidate { @@ -448,6 +485,8 @@ pub fn candidate_of(item: &HashMap) -> Option hold: common::draft_hold::DraftHold::of_item(item), checks_passed: s("ci_last") == "passed", draft_held: item.contains_key(common::draft_hold::FIELD), + owed_proofs: super::own_review_ledger::of_item(item).owed_proofs(), + proof_plan: s(common::e2e::proof_routes::FIELD), }; (pr > 0 && c.installation_id > 0 && !c.team_id.is_empty() && !c.run_id.is_empty()).then_some(c) } @@ -710,7 +749,11 @@ pub fn is_working(act: &Act, performed: Performed, status: &str) -> bool { let started = performed == Performed::Started && matches!( act, - Act::ReviewHead | Act::FixFindings | Act::ResolveConflict | Act::ResumeRound(_) + Act::ReviewHead + | Act::FixFindings + | Act::ResolveConflict + | Act::ResumeRound(_) + | Act::ProveOwed ); started || common::run_status::IN_FLIGHT.contains(&status) } @@ -731,6 +774,7 @@ async fn perform( match act { Act::Nothing => Performed::Settled, Act::Preview => preview(state, github, c).await, + Act::ProveOwed => prove_owed(state, github, c, seen).await, Act::ResolveConflict => super::resume::start_conflict_round( state, &c.team_id, @@ -917,6 +961,102 @@ async fn preview(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> P Performed::Settled } +/// Runs one process's owed proofs one at a time: a sandbox route runs a +/// build for minutes. +static PROVING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Moves the owed proof of the head on by one route, and once it gave its +/// result (proven, a real failure, or every route's reason) hands it to the +/// review of the head as the round it reads (`Ledger::proof_given`). +async fn prove_owed( + state: &WorkerState, + github: &GitHubClient, + c: &Candidate, + seen: &Seen, +) -> Performed { + use common::e2e::proof_routes::{self as routes, Verdict}; + if PROVING.swap(true, std::sync::atomic::Ordering::SeqCst) { + return Performed::NotStarted; + } + let mut ledger = super::own_review_ledger::load(state, &c.team_id, &c.run_id).await; + let items = ledger.owed_proofs(); + let branch = github + .get_pull_request(&c.owner, &c.repo, c.pr) + .await + .ok() + .and_then(|p| p["head"]["ref"].as_str().map(str::to_string)) + .unwrap_or_default(); + if items.is_empty() || branch.is_empty() { + PROVING.store(false, std::sync::atomic::Ordering::SeqCst); + return Performed::Settled; + } + let tests = owed_tests(state, c, &items).await; + let repeat = routes::repeat_asked(&items.join(" "), common::e2e::test_package::REPEAT_RUNS); + let target = super::ci_repro::Target { + team_id: &c.team_id, + run_id: &c.run_id, + owner: &c.owner, + repo: &c.repo, + pr: c.pr, + branch: &branch, + head: &seen.head, + }; + let mut plan = super::proof_routes::advance(state, github, target, &tests, repeat).await; + PROVING.store(false, std::sync::atomic::Ordering::SeqCst); + match plan.verdict() { + Verdict::Pending | Verdict::Open => Performed::Started, + _ => { + let account = plan.account(); + ledger.proof_given(&items, &account); + super::own_review_ledger::save(state, &c.team_id, &c.run_id, &ledger).await; + plan.reported = true; + super::proof_routes::save(state, &c.team_id, &c.run_id, &plan).await; + super::add_progress_note( + state, + &c.team_id, + &c.run_id, + account.lines().next().unwrap_or(""), + ) + .await; + info!(run_id = %c.run_id, pr = c.pr, "PR watch: the owed proof gave its result; the head is reviewed with it"); + review_head(state, c, &seen.head).await + } + } +} + +/// The tests an owed proof repeats: the ones the run's failing-test +/// evidence names (`spec › title`), else its spec files, else the files +/// the findings point at. +async fn owed_tests(state: &WorkerState, c: &Candidate, items: &[String]) -> Vec { + if let Some(ev) = super::test_fix::load(state, &c.team_id, &c.run_id).await { + let named: Vec = ev + .read + .tests + .iter() + .filter(|t| t.contains(" › ")) + .cloned() + .collect(); + if !named.is_empty() { + return named; + } + if !ev.spec_files.is_empty() { + return ev.spec_files.clone(); + } + } + items + .iter() + .filter_map(|i| i.rsplit_once("(`").map(|(_, at)| at)) + .map(|at| { + at.trim_end_matches([')', '`']) + .split(':') + .next() + .unwrap_or("") + .to_string() + }) + .filter(|p| !p.is_empty()) + .collect() +} + /// Asks for CoderHelm's review of the head. async fn review_head(state: &WorkerState, c: &Candidate, head: &str) -> Performed { (!matches!( @@ -1060,8 +1200,11 @@ pub async fn look(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> })); let mut act = resume_after_limit(&c.status, &seen, &c.marks, &c.limit_ended) .unwrap_or_else(|| decide_all(&c.status, &seen, &c.marks)); + if act == Act::Nothing && proof_due(&c.status, &seen, &c.marks, &c.owed_proofs, &c.proof_plan) { + act = Act::ProveOwed; + } let mut performed = Performed::NotStarted; - if act == Act::Preview { + if matches!(act, Act::Preview | Act::ProveOwed) { performed = perform(state, github, c, &seen, &act).await; } else if let Some((field, value)) = act.claim(&seen) { if !claim(state, c, field, &value).await { diff --git a/services/worker/src/passes/proof_routes.rs b/services/worker/src/passes/proof_routes.rs new file mode 100644 index 000000000..c888377a9 --- /dev/null +++ b/services/worker/src/passes/proof_routes.rs @@ -0,0 +1,400 @@ +//! Runs a test's repeat proof along its routes +//! (`common::e2e::proof_routes`): the sandbox against the preview, against +//! staging, against the app started in the sandbox, then CI. Each route's +//! result is kept on the run (`proof_routes`), one route per call for the +//! sandbox routes and one step per call for CI, so a sweep moves it on +//! without holding a look for long. + +use std::collections::HashMap; + +use common::e2e::proof_routes::{self as pr, CiNext, CiRun, Outcome, Plan, Route}; +use common::e2e::test_package; +use serde_json::Value; +use tracing::{info, warn}; + +use super::attr_s; +use super::ci_repro::Target; +use crate::clients::github::GitHubClient; +use crate::WorkerState; + +/// The plan kept on the run, if any. +pub(crate) async fn load(state: &WorkerState, team_id: &str, run_id: &str) -> Option { + let item = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("#f") + .expression_attribute_names("#f", pr::FIELD) + .send() + .await + .ok()?; + item.item()? + .get(pr::FIELD) + .and_then(|v| v.as_s().ok()) + .and_then(|j| Plan::of_json(j)) +} + +pub(crate) async fn save(state: &WorkerState, team_id: &str, run_id: &str, plan: &Plan) { + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .condition_expression("attribute_exists(run_id)") + .update_expression("SET #f = :v") + .expression_attribute_names("#f", pr::FIELD) + .expression_attribute_values(":v", attr_s(&plan.to_json())) + .send() + .await + { + warn!(run_id, error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "Could not keep the repeat proof's routes on the run"); + } +} + +/// Moves the repeat proof of `tests` on `t.head` on by one route (or one CI +/// step) and keeps it. A new head starts a new plan. +pub(crate) async fn advance( + state: &WorkerState, + github: &GitHubClient, + t: Target<'_>, + tests: &[String], + repeat: u32, +) -> Plan { + let mut plan = load(state, t.team_id, t.run_id) + .await + .filter(|p| p.head == t.head) + .unwrap_or_else(|| Plan::new(t.head, tests, repeat)); + let now = chrono::Utc::now().to_rfc3339(); + if let Some(route) = plan.next() { + let outcome = match route { + Route::Ci => start_ci(state, github, t, &mut plan).await, + sandbox => sandbox_route(state, github, t, &plan, sandbox).await, + }; + info!( + run_id = t.run_id, + ?route, + ?outcome, + "Repeat proof: a route was tried" + ); + plan.record(route, outcome, &now); + } else if matches!(plan.verdict(), pr::Verdict::Pending) { + if let Some(outcome) = step_ci(github, t, &mut plan).await { + info!( + run_id = t.run_id, + ?outcome, + "Repeat proof: CI gave its result" + ); + plan.record(Route::Ci, outcome, &now); + } + } + save(state, t.team_id, t.run_id, &plan).await; + plan +} + +/// One sandbox route: the address it runs against, the command, the run. +async fn sandbox_route( + state: &WorkerState, + github: &GitHubClient, + t: Target<'_>, + plan: &Plan, + route: Route, +) -> Outcome { + let unavailable = |why: &str| Outcome::Unavailable { why: why.into() }; + if state.config.sandbox_bucket_name.is_empty() || state.config.sandbox_project_name.is_empty() { + return unavailable("no sandbox in this install"); + } + let (owner, repo, head) = (t.owner, t.repo, t.head); + let test = plan.tests.first().cloned().unwrap_or_default(); + let (spec, title) = common::ci_repro::spec_and_title(&test); + if spec.is_empty() { + return unavailable("no test named to run"); + } + let tree: Vec = match github.get_tree(owner, repo, head).await { + Ok(t) => t.into_iter().map(|e| e.path).collect(), + Err(e) => return unavailable(&format!("the head's files couldn't be read ({e})")), + }; + let Some(path) = tree + .iter() + .find(|p| p.ends_with(&spec) || p.ends_with(&format!("/{spec}"))) + .cloned() + else { + return unavailable(&format!("`{spec}` isn't a file on the head")); + }; + let dir = test_package::package_dir(&tree, &path).unwrap_or_default(); + let mut texts: HashMap = HashMap::new(); + let config = tree + .iter() + .find(|p| { + p.starts_with(dir.as_str()) + && p.rsplit('/') + .next() + .unwrap_or("") + .starts_with("playwright.config") + }) + .cloned(); + for p in [format!("{dir}/package.json"), "package.json".to_string()] + .into_iter() + .map(|p| p.trim_start_matches('/').to_string()) + .chain(config.clone()) + { + if let Ok(text) = github.read_file(owner, repo, &p, head).await { + texts.insert(p, text); + } + } + let Some(pkg) = test_package::package_of(&tree, &path, &|p| texts.get(p).cloned()) + .filter(|p| p.runner == Some(test_package::Runner::Playwright)) + else { + return unavailable("the spec's runner isn't Playwright, the one CoderHelm repeats"); + }; + let rel = path + .strip_prefix(&format!("{}/", pkg.dir)) + .unwrap_or(&path) + .to_string(); + let configured = + super::ci_repro::test_address(state, t.team_id, &format!("{owner}/{repo}")).await; + let (target, prelude) = match route { + Route::Preview => { + let preview = super::preview::load(state, t.team_id, t.run_id) + .await + .filter(|p| p.head == head && !p.url.trim().is_empty()) + .map(|p| p.url) + .or_else(|| { + configured + .as_deref() + .filter(|c| c.contains("{pr}")) + .map(|c| c.replace("{pr}", &t.pr.to_string())) + }); + match preview { + Some(u) => (u, String::new()), + None => return unavailable("no preview address for this head"), + } + } + Route::Staging => { + match super::ci_repro::base_address( + github, + (owner, repo, head), + &tree, + configured.as_deref(), + ) + .await + { + Some(u) => (u, String::new()), + None => { + return unavailable( + "no staging address in the Tests settings or the end-to-end setup", + ) + } + } + } + _ => { + let pkg_json = texts + .get(format!("{}/package.json", pkg.dir).trim_start_matches('/')) + .cloned() + .unwrap_or_default(); + let cfg = config + .as_ref() + .and_then(|c| texts.get(c)) + .map(String::as_str); + let Some(app) = pr::local_app(&pkg_json, cfg) else { + return unavailable( + "the package has no dev, start or preview script to serve the app", + ); + }; + let Some(prelude) = pr::local_prelude( + &app, + match pkg.manager { + test_package::Manager::Npm => "npm", + test_package::Manager::Pnpm => "pnpm", + test_package::Manager::Yarn => "yarn", + test_package::Manager::Bun => "bun", + }, + ) else { + return unavailable("the start script's name can't be run as is"); + }; + (format!("http://localhost:{}", app.port), prelude) + } + }; + let Some(cmd) = pr::repeat_cmd(&pkg.dir, &rel, &title, &target, plan.repeat, &prelude) else { + return unavailable(&format!("`{target}` can't be run against")); + }; + let install = test_package::install_cmd(&pkg); + let ctx = common::agent_policy::GateCtx::new(t.team_id, common::agent_policy::Agent::Coder) + .repo(&format!("{owner}/{repo}")) + .run(t.run_id); + let gate = crate::agent::policy::gate(state, ctx, None); + for c in [&install, &cmd] { + if !matches!( + gate.check_command(c, "Repeat the affected test to prove the fix") + .await, + common::agent_policy::Outcome::Run { .. } + ) { + return unavailable("the team's agent permissions don't allow the repeat command"); + } + } + crate::agent::policy::learn_repo_hosts(state, github, t.team_id, owner, repo).await; + let sandbox = crate::clients::sandbox::SandboxClient::new( + &state.codebuild, + &state.s3, + &state.logs, + &state.config.sandbox_bucket_name, + &state.config.sandbox_project_name, + ) + .with_egress(crate::agent::policy::sandbox_egress(state, t.team_id).await); + let source = match sandbox + .ensure_source(t.run_id, head, || { + github.download_tarball(owner, repo, head) + }) + .await + { + Ok(k) => k, + Err(e) => { + return unavailable(&format!( + "the branch couldn't be prepared in the sandbox ({e})" + )) + } + }; + let script = common::ci_repro::script(&[("install", install), ("proof", cmd)]); + let node = super::detect_node_version(github, owner, repo, t.branch).await; + match sandbox + .run_checks(&source, &script, node.as_deref(), None, None) + .await + { + Ok(o) if o.ran => match common::ci_repro::split(&o.output, "proof") { + Some(out) => pr::outcome_of(&out, plan.repeat), + None => unavailable("the run printed nothing"), + }, + Ok(o) => unavailable(&format!("the sandbox gave no result ({})", o.reason)), + Err(e) => unavailable(&format!("the sandbox couldn't run ({e})")), + } +} + +/// The end-to-end workflow that tests the head: the workflow of a +/// test-related check on it, else a workflow file named for end-to-end +/// tests on the default branch. +async fn e2e_workflow( + github: &GitHubClient, + owner: &str, + repo: &str, + head: &str, +) -> Option<(String, Option)> { + let runs = github + .list_check_runs_for_ref(owner, repo, head) + .await + .ok() + .and_then(|v| v["check_runs"].as_array().cloned()) + .unwrap_or_default(); + let checks = common::e2e::check_gate::checks(&runs, &[]); + for c in checks + .iter() + .filter(|c| common::e2e::check_gate::is_test_related(&c.name)) + { + let Some(run) = c.run_id else { continue }; + if let Ok(r) = github.get_workflow_run(owner, repo, run).await { + if let Some(p) = r["path"].as_str().filter(|p| !p.is_empty()) { + return Some((p.to_string(), Some(run))); + } + } + } + let tree = github.get_tree(owner, repo, head).await.ok()?; + tree.into_iter() + .map(|e| e.path) + .find(|p| { + let low = p.to_ascii_lowercase(); + low.starts_with(".github/workflows/") + && (low.contains("e2e") || low.contains("playwright") || low.contains("end-to-end")) + }) + .map(|p| (p, None)) +} + +/// Starts the CI route: finds the workflow, reads how it repeats, and makes +/// the first step. +async fn start_ci( + state: &WorkerState, + github: &GitHubClient, + t: Target<'_>, + plan: &mut Plan, +) -> Outcome { + let _ = state; + let Some((workflow, run_id)) = e2e_workflow(github, t.owner, t.repo, t.head).await else { + return Outcome::Unavailable { + why: "the repository has no end-to-end workflow to run it on".into(), + }; + }; + let yaml = github + .read_file(t.owner, t.repo, &workflow, t.head) + .await + .unwrap_or_default(); + let way = pr::ci_way(&yaml); + if way == pr::CiWay::Reruns && run_id.is_none() { + return Outcome::Unavailable { + why: format!("`{workflow}` has no manual start and no run on this head to re-run"), + }; + } + plan.ci = Some(CiRun { + workflow, + way: Some(way), + started_at: chrono::Utc::now().to_rfc3339(), + run_id: run_id.unwrap_or(0), + ..Default::default() + }); + match step_ci(github, t, plan).await { + Some(done) => done, + None => Outcome::Started { + at: chrono::Utc::now().to_rfc3339(), + }, + } +} + +/// One CI step: start more runs, re-run, or read the result. `Some` once +/// CI gave one. +async fn step_ci(github: &GitHubClient, t: Target<'_>, plan: &mut Plan) -> Option { + let tests = plan.tests.clone(); + let repeat = plan.repeat; + let ci = plan.ci.as_mut()?; + let file = ci + .workflow + .rsplit('/') + .next() + .unwrap_or(&ci.workflow) + .to_string(); + let runs: Vec = match ci.way { + Some(pr::CiWay::Reruns) => github + .get_workflow_run(t.owner, t.repo, ci.run_id) + .await + .map(|r| vec![r]) + .unwrap_or_default(), + _ => github + .list_workflow_runs(t.owner, t.repo, &file, t.branch) + .await + .unwrap_or_default(), + }; + match pr::ci_step(ci, t.head, &runs, repeat) { + CiNext::Done(o) => Some(o), + CiNext::Wait => None, + CiNext::Rerun(id) => match github.rerun_workflow_run(t.owner, t.repo, id).await { + Ok(()) => None, + Err(e) => Some(Outcome::Unavailable { + why: common::e2e::workflow_gate::dispatch_refusal(&e.to_string()), + }), + }, + CiNext::Dispatch(n) => { + let way = ci.way.clone().unwrap_or(pr::CiWay::Reruns); + let inputs = Value::Object(pr::ci_inputs(&way, &tests, repeat)); + for _ in 0..n { + if let Err(e) = github + .dispatch_workflow(t.owner, t.repo, &file, t.branch, &inputs) + .await + { + return Some(Outcome::Unavailable { + why: common::e2e::workflow_gate::dispatch_refusal(&e.to_string()), + }); + } + ci.dispatched += 1; + } + None + } + } +} diff --git a/services/worker/src/passes/test_fix.rs b/services/worker/src/passes/test_fix.rs index d636b5706..579425d6b 100644 --- a/services/worker/src/passes/test_fix.rs +++ b/services/worker/src/passes/test_fix.rs @@ -2895,6 +2895,40 @@ pub async fn ready_gate( } } } + // No repeat input to start on CI: the proof goes along its routes (the + // sandbox against the preview, staging, the app started in the + // sandbox, then the workflow started or re-run until the count is + // reached), never handed to a person. + let mut routes_note = String::new(); + if repeat_ok.is_none() && g.ci_workflow.is_empty() && !g.run_id.is_empty() { + let tests = if g.tests.is_empty() { + g.specs.clone() + } else { + g.tests.clone() + }; + let plan = super::proof_routes::advance( + state, + github, + super::ci_repro::Target { + team_id, + run_id: &g.run_id, + owner, + repo, + pr: pr_number, + branch: &head_ref, + head: &sha, + }, + &tests, + test_package::REPEAT_RUNS, + ) + .await; + repeat_ok = match plan.verdict() { + common::e2e::proof_routes::Verdict::Proven { .. } => Some(true), + common::e2e::proof_routes::Verdict::Disproven { .. } => Some(false), + _ => None, + }; + routes_note = plan.account(); + } let mut hold = decide(&refused, &standing, &skipped, draft, repeat_ok); if let Hold::RunsWhenReady(gated) = &hold { @@ -2910,17 +2944,14 @@ pub async fn ready_gate( .await; } if let Hold::Wait(why) | Hold::Refused(why) = hold.clone() { - let no_repeat = repeat_ok.is_none() && g.ci_workflow.is_empty(); if g.noted != sha { g.noted = sha.clone(); - let how = if no_repeat { - format!( - " No repeat run could start: the end-to-end workflow has no `workflow_dispatch` input for repeats and no test address is set in Tests settings. Run the affected test about {} times (Playwright: `--repeat-each={}`) and mark this ready yourself, or add a `repeat_each` input so CoderHelm can.", - test_package::REPEAT_RUNS, - test_package::REPEAT_RUNS - ) - } else { + // Where the repeat proof stands, route by route: CoderHelm's own + // work, never a person's step. + let how = if routes_note.is_empty() { String::new() + } else { + format!("\n\n{routes_note}") }; let _ = crate::passes::conversation::github( github,