From 1440aac0382aac7f366cc86c6f58cabb531ab800 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 16 Nov 2026 13:51:45 -0500 Subject: [PATCH 1/4] Web changes are proven on their preview before they are called ready A web pull request was marked ready with its preview deploy and preview end-to-end checks skipped (they skip drafts and run on a label), listed as "skipped (its conditions left this PR out)" next to passing unit tests, with no screenshot, "npm test" as the way to check it, and a tests check that passed on 0 of 6 changed tests failing without the change. - common::preview reads the repository's workflow files (on: events, paths, branches, types, and each job's if: labels) into the preview and end-to-end jobs that cover the change, the labels that start them (the test map's areas first, never a shared environment's label) and which skip drafts; it also decides from the paths and the tree whether a visible change needs an end-to-end spec, the pages to capture, the capture script and the real "How to check" commands. - worker::preview starts the preview (labels, a push when the workflow reads labels only on one), reads its checks and address, captures the changed pages at desktop and phone width in the sandbox and keeps them on refs/coderhelm/screenshots; the PR watch does it for finished runs. - The ready decision marks a draft ready for preview checks that skip drafts and waits on them; a failed preview or a visible change with no end-to-end spec holds it. - A skipped check that covers the change is a gap in the description, never evidence; the description shows the preview, its checks and the captured pages. - The tests check never passes on zero tests failing without the change; the reviewer requests changes on a visible change with no end-to-end spec; the coder and planner prompts say so too. - common::waiting_line gives the run page and the description one line on what the pull request waits on; the gateway serves it with the preview. --- docs/api/openapi.json | 180 ++ services/common/src/lib.rs | 2 + services/common/src/pr_body.rs | 40 +- services/common/src/pr_facts.rs | 100 +- services/common/src/preview.rs | 1715 +++++++++++++++++ services/common/src/waiting_line.rs | 240 +++ services/gateway/src/routes/api.rs | 133 ++ services/worker/src/clients/github.rs | 96 +- services/worker/src/passes/description.rs | 54 +- .../worker/src/passes/description_facts.rs | 37 +- .../description_goldens/before_rewritten.md | 2 + .../passes/description_goldens/ui_change.md | 2 + services/worker/src/passes/habits_check.rs | 181 +- .../worker/src/passes/host_steps_readers.rs | 1 + services/worker/src/passes/implement.rs | 9 +- .../src/passes/incidents/aj_coder_habits.rs | 5 +- .../src/passes/incidents/ax_github_budget.rs | 2 +- .../incidents/bu_web_change_unchecked.rs | 270 +++ services/worker/src/passes/incidents/mod.rs | 1 + services/worker/src/passes/mod.rs | 14 + services/worker/src/passes/plan.rs | 10 + services/worker/src/passes/pr_watch.rs | 182 +- services/worker/src/passes/preview.rs | 677 +++++++ services/worker/src/passes/ready.rs | 178 ++ services/worker/src/passes/review_pr.rs | 22 + services/worker/src/passes/review_rules.rs | 67 + 26 files changed, 4187 insertions(+), 33 deletions(-) create mode 100644 services/common/src/preview.rs create mode 100644 services/common/src/waiting_line.rs create mode 100644 services/worker/src/passes/incidents/bu_web_change_unchecked.rs create mode 100644 services/worker/src/passes/preview.rs diff --git a/docs/api/openapi.json b/docs/api/openapi.json index bdf06cdd0..49a36c31d 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -3982,6 +3982,17 @@ "null" ] }, + "preview": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunPreview", + "description": "Where the preview of the pull request's head stands: its checks,\naddress and captured pages. Null when nothing was recorded." + } + ] + }, "progress_notes": { "description": "Notes it wrote while working, in order.", "examples": [ @@ -4165,6 +4176,16 @@ "null" ] }, + "waiting_line": { + "description": "What the run's pull request waits on, in one plain line, and\nwhether it is ready for review: \"Waiting on: an approving review from\na person on #12 (this repo requires one before CoderHelm merges).\nReady for review: checks passed, preview checked.\" Built from\n`merge_standing`, `draft_hold` and `preview`. Null before the run\nhas a pull request.", + "examples": [ + null + ], + "type": [ + "string", + "null" + ] + }, "waiting_on": { "oneOf": [ { @@ -4804,6 +4825,165 @@ ], "type": "object" }, + "RunPreview": { + "description": "Where the preview of the run's pull request head stands\n(`common::preview`).", + "properties": { + "checks": { + "description": "The preview and end-to-end checks that cover the change, on the head.", + "examples": [ + [ + { + "name": "E2E on preview", + "outcome": "passed", + "url": "https://github.com/acme/web/actions/runs/1/job/2" + } + ] + ], + "items": { + "$ref": "#/components/schemas/RunPreviewCheck" + }, + "type": "array" + }, + "e2e_covered": { + "description": "The change adds or updates an end-to-end spec.", + "examples": [ + true + ], + "type": "boolean" + }, + "e2e_required": { + "description": "The change alters what a person sees in a repository with an\nend-to-end suite, so it needs an end-to-end spec.", + "examples": [ + true + ], + "type": "boolean" + }, + "labels_added": { + "description": "Labels CoderHelm added to start the preview and its end-to-end checks.", + "examples": [ + [ + "E2E:signup" + ] + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "shots": { + "description": "The changed pages captured on the preview, at desktop and phone width.", + "examples": [ + [ + { + "page": "/signup", + "src": "https://github.com/acme/web/blob/abc/pr-1/abc/signup-desktop.png?raw=true", + "width": "desktop" + } + ] + ], + "items": { + "$ref": "#/components/schemas/RunPreviewShot" + }, + "type": "array" + }, + "stage": { + "description": "`not_needed`, `triggered`, `deploying`, `ready`, `checked`,\n`failed` or `blocked`.", + "examples": [ + "checked" + ], + "type": "string" + }, + "url": { + "description": "The preview's address; empty when it isn't known.", + "examples": [ + "https://pr-1.preview-web.example.com" + ], + "type": "string" + }, + "why": { + "description": "Why there is no preview or no capture, one line; empty otherwise.", + "examples": [ + "" + ], + "type": "string" + } + }, + "required": [ + "stage", + "url", + "labels_added", + "checks", + "shots", + "why", + "e2e_required", + "e2e_covered" + ], + "type": "object" + }, + "RunPreviewCheck": { + "description": "One preview or end-to-end check on the head of the run's pull request.", + "properties": { + "name": { + "description": "The check's name, as GitHub shows it.", + "examples": [ + "E2E on preview" + ], + "type": "string" + }, + "outcome": { + "description": "`passed`, `failed`, `running` or `skipped`.", + "examples": [ + "passed" + ], + "type": "string" + }, + "url": { + "description": "The check's page on GitHub; empty when it has none.", + "examples": [ + "https://github.com/acme/web/actions/runs/1/job/2" + ], + "type": "string" + } + }, + "required": [ + "name", + "outcome", + "url" + ], + "type": "object" + }, + "RunPreviewShot": { + "description": "One page captured on the preview.", + "properties": { + "page": { + "description": "The page's path on the preview.", + "examples": [ + "/signup" + ], + "type": "string" + }, + "src": { + "description": "The image's address.", + "examples": [ + "https://github.com/acme/web/blob/abc/pr-1/abc/signup-desktop.png?raw=true" + ], + "type": "string" + }, + "width": { + "description": "`desktop` or `phone`.", + "examples": [ + "desktop" + ], + "type": "string" + } + }, + "required": [ + "page", + "width", + "src" + ], + "type": "object" + }, "RunQuestion": { "description": "A question a run asked a person.", "properties": { diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index e42b58ffb..b0305d4c3 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -188,7 +188,9 @@ pub mod pr_review; pub mod pr_steps; /// A repository's pull request template as the description's structure. pub mod pr_template; +pub mod preview; pub mod run_prs; +pub mod waiting_line; // review_stats: time-ordered review records for analytics /// What people write on a ticket while a run works on it: kept, acknowledged, acted on. /// One engineer's voice per ticket and per pull request: every comment diff --git a/services/common/src/pr_body.rs b/services/common/src/pr_body.rs index 5b3de6a5f..d7b398710 100644 --- a/services/common/src/pr_body.rs +++ b/services/common/src/pr_body.rs @@ -234,6 +234,9 @@ pub enum Screens { }, /// One line: why there is no screenshot. Missing(String), + /// Each changed page captured on the preview: its path, then the + /// desktop and phone images (empty when that width didn't load). + Pages(Vec<(String, String, String)>), } // ── The body ─────────────────────────────────────────────────────────── @@ -267,6 +270,9 @@ pub struct Body { pub results_of: String, /// One sentence, only when merging without an action breaks something. pub alert: String, + /// What the pull request waits on, in one line (`waiting_line`): the + /// first thing a reader sees. + pub waiting: String, pub summary: String, /// Work CoderHelm did outside the diff, one sentence. pub outside: String, @@ -764,6 +770,30 @@ fn screens_markdown(s: &Screens) -> String { ) } Screens::Missing(why) => format!("No screenshot: {}.", part(why)), + Screens::Pages(pages) => { + let img = |src: &str, alt: String| { + if src.starts_with("https://") { + format!( + "\"{}\"", + src.replace('"', "%22"), + if alt.contains("phone") { 180 } else { 380 }, + alt.replace('"', "'") + ) + } else { + "didn't load".to_string() + } + }; + let mut out = String::from("| Page | Desktop | Phone |\n|---|---|---|\n"); + for (page, desktop, phone) in pages { + let p = one_line(page).replace('|', "/").replace('`', "'"); + out.push_str(&format!( + "| `{p}` | {} | {} |\n", + img(desktop, format!("{p} at desktop width")), + img(phone, format!("{p} at phone width")) + )); + } + out.trim_end().to_string() + } } } @@ -842,9 +872,13 @@ fn blocks(b: &Body) -> Blocks { } else { String::new() }; - if !alert.is_empty() { - out.alert = format!("> [!IMPORTANT]\n> {alert}."); - } + let waiting = one_line(&b.waiting); + out.alert = match (waiting.is_empty(), alert.is_empty()) { + (true, true) => String::new(), + (true, false) => format!("> [!IMPORTANT]\n> {alert}."), + (false, true) => format!("> [!NOTE]\n> {waiting}"), + (false, false) => format!("> [!IMPORTANT]\n> {waiting} {alert}."), + }; out.summary = summary_paragraph(&b.summary, ticket, &b.outside); if !b.needed.is_empty() { let mut s = String::from("### Needed from you\n\n"); diff --git a/services/common/src/pr_facts.rs b/services/common/src/pr_facts.rs index 8ede27984..5fe640ceb 100644 --- a/services/common/src/pr_facts.rs +++ b/services/common/src/pr_facts.rs @@ -373,6 +373,14 @@ pub struct Facts { /// A UI change's screenshots, or why there are none. #[serde(default)] pub screens: Option, + /// What the pull request waits on, one line (`crate::waiting_line`). + #[serde(default)] + pub waiting: String, + /// Where the preview of the head stands (`crate::preview`): its + /// checks, address and captured pages. A preview or end-to-end check + /// that covers the change and was skipped is a gap, never evidence. + #[serde(default)] + pub preview: Option, /// The feedback wanted, when something more specific than the records /// says it. #[serde(default)] @@ -1196,6 +1204,70 @@ fn conclusion_with_signoffs(f: &Facts) -> String { /// The body every description shows, from the facts of its head. `ticked`: /// the item ids a person ticked in the body this one replaces. +/// How a skipped check that covers the change reads: a gap CoderHelm +/// closes, never "nothing to do". +pub const GAP_WORDS: &str = + "not run yet: it covers this change, so CoderHelm starts it on the preview and reads its result"; + +/// The preview's captures, or the one line saying why there are none. +fn screens_of(p: &crate::preview::State, visible: bool) -> Option { + use crate::pr_body::Screens; + use crate::preview::Stage; + if !p.shots.is_empty() { + let mut pages: Vec<(String, String, String)> = Vec::new(); + for s in &p.shots { + let at = match pages.iter().position(|x| x.0 == s.page) { + Some(i) => i, + None => { + pages.push((s.page.clone(), String::new(), String::new())); + pages.len() - 1 + } + }; + if s.width == "phone" { + pages[at].2 = s.src.clone(); + } else { + pages[at].1 = s.src.clone(); + } + } + return Some(Screens::Pages(pages)); + } + let why = match p.stage { + Stage::Triggered | Stage::Deploying => { + "the preview is still deploying; its pages are captured once it is up".to_string() + } + Stage::Ready => "the preview is up and its pages are being captured".to_string(), + Stage::Failed => { + "the preview checks failed; its pages are captured once they pass".to_string() + } + _ if !p.why.trim().is_empty() => p.why.clone(), + _ if !visible => "the change has no page a person sees".to_string(), + _ => return None, + }; + Some(Screens::Missing(why)) +} + +/// The checks that cover the change and haven't run on the head. +pub fn preview_gaps(f: &Facts) -> Vec { + let visible = f + .files + .iter() + .any(|x| crate::preview::is_user_visible(&x.path)); + let covers = f + .preview + .as_ref() + .map(|p| p.covers.as_slice()) + .unwrap_or(&[]); + f.checks + .iter() + .filter(|c| { + c.outcome == Outcome::DidNotRun + && (crate::preview::is_covering(covers, &c.name) + || crate::preview::skipped_is_gap(&c.name, visible)) + }) + .map(|c| c.name.clone()) + .collect() +} + pub fn body_of(f: &Facts, ticked: &[String]) -> crate::pr_body::Body { use crate::pr_body::{Body, Focus, Level, ReadFirst, Screens, Ticket}; let head = f.short_head().to_string(); @@ -1360,12 +1432,17 @@ pub fn body_of(f: &Facts, ticked: &[String]) -> crate::pr_body::Body { }; } } - let screens = match &f.screens { - Some(s) => Some(s.clone()), - None if f.files.iter().any(|x| is_ui(&x.path)) => Some(Screens::Missing( + let visible = f + .files + .iter() + .any(|x| crate::preview::is_user_visible(&x.path)); + let screens = match (&f.screens, &f.preview) { + (Some(s), _) => Some(s.clone()), + (None, Some(p)) => screens_of(p, visible), + (None, None) if f.files.iter().any(|x| is_ui(&x.path)) => Some(Screens::Missing( "CoderHelm had no runnable preview to capture for this run".into(), )), - None => None, + (None, None) => None, }; // The full list of checks, and how to check by hand. let mut evidence: Vec = Vec::new(); @@ -1373,9 +1450,22 @@ pub fn body_of(f: &Facts, ticked: &[String]) -> crate::pr_body::Body { if !how.is_empty() { evidence.push(format!("How to check: {how}.")); } + if let Some(p) = &f.preview { + if p.url.starts_with("https://") { + evidence.push(format!("Preview: {}", p.url)); + } + } if !f.checks.is_empty() { + let covers = f + .preview + .as_ref() + .map(|p| p.covers.as_slice()) + .unwrap_or(&[]); let mut s = String::from("Every check on this head:\n"); for c in &f.checks { + let gap = c.outcome == Outcome::DidNotRun + && (crate::preview::is_covering(covers, &c.name) + || crate::preview::skipped_is_gap(&c.name, visible)); s.push_str(&format!( "- {}: {}\n", linked(c), @@ -1383,6 +1473,7 @@ pub fn body_of(f: &Facts, ticked: &[String]) -> crate::pr_body::Body { Outcome::Passed => "passed", Outcome::Failed => "failed", Outcome::Running => "still running", + Outcome::DidNotRun if gap => GAP_WORDS, Outcome::DidNotRun => "skipped (its conditions left this PR out)", } )); @@ -1426,6 +1517,7 @@ pub fn body_of(f: &Facts, ticked: &[String]) -> crate::pr_body::Body { head, results_of: String::new(), alert: String::new(), + waiting: f.waiting.clone(), summary, outside, needed: items, diff --git a/services/common/src/preview.rs b/services/common/src/preview.rs new file mode 100644 index 000000000..b63cbf5ed --- /dev/null +++ b/services/common/src/preview.rs @@ -0,0 +1,1715 @@ +//! A web change is checked on its preview before it is called ready: the +//! repository's own preview deploy and end-to-end checks run on it, and the +//! changed pages are captured at desktop and phone width. +//! +//! A run once opened a pull request on a web app whose preview deploy and +//! preview end-to-end checks run only with a label. CoderHelm added no +//! label, so every deploy and end-to-end check on the head was skipped, and +//! the description listed them as "skipped (its conditions left this PR +//! out)" next to passing unit tests, said "No screenshot: CoderHelm had no +//! runnable preview" and gave `npm test` as the way to check it. Nothing had +//! been looked at in a browser. A skipped preview check is not evidence: it +//! is a check CoderHelm didn't start. +//! +//! The rules, all read from the repository itself (its workflow files and +//! its tree), nothing about any one repository written here: +//! +//! - [`role_of`] reads what a check is for from its name: a preview deploy, +//! end-to-end tests, a staging or production deploy, a cleanup. +//! - [`plan`] reads each workflow's `on:` (pull request events, `paths`, +//! `paths-ignore`, `branches`, the event `types`) and each job's `if:` +//! (through `workflow_gate`) and returns the preview and end-to-end jobs +//! that cover the change, the labels that start them (the end-to-end area +//! labels that match the changed paths among them), whether a push is +//! needed for a label to count, and what keeps a job from running that +//! CoderHelm can't change. A staging, production or other shared +//! environment label is never chosen. +//! - [`gaps`] are the checks that cover the change and didn't run on the +//! head: an open gap CoderHelm closes, never evidence. +//! - [`e2e_need`] says, from the changed paths and the repository's e2e +//! suite, whether the change needs a new or updated end-to-end spec and +//! whether it has one. +//! - [`routes`] picks the pages to capture from the repository's page files +//! and the changed paths; [`capture_script`] is the sandbox script that +//! captures them. +//! - [`State`] is what the run records ([`FIELD`]) and the description and +//! the run page read. + +use serde::{Deserialize, Serialize}; + +use crate::e2e::workflow_gate::{self, LabelWay}; + +/// The run attribute holding the [`State`] JSON. +pub const FIELD: &str = "preview_state"; + +/// Viewport widths a page is captured at: desktop, then phone. +pub const DESKTOP: (u32, u32) = (1280, 800); +pub const PHONE: (u32, u32) = (390, 844); +/// Pages captured per change at most. +pub const MAX_PAGES: usize = 3; +/// The Playwright release the capture script installs when the repository +/// has none of its own in the sandbox. +pub const PLAYWRIGHT: &str = "1.49.1"; + +// ── what a check is for ──────────────────────────────────────────────────── + +/// What a check or job is for, read from its name. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Role { + /// Deploys the pull request's own preview. + Preview, + /// End-to-end tests (on the preview, or anywhere else a pull request + /// runs them). + E2e, + /// A shared staging environment. + Staging, + /// Production or a release. + Production, + /// Tears a preview down. + Cleanup, + Other, +} + +fn words(s: &str) -> Vec { + s.to_ascii_lowercase() + .split(|c: char| !c.is_ascii_alphanumeric()) + .filter(|w| !w.is_empty()) + .map(str::to_string) + .collect() +} + +/// The role a check's name shows. Cleanup first (a preview's cleanup is not +/// its deploy), then the shared environments (an end-to-end run after the +/// staging deploy is staging's), then end-to-end, then the preview. +pub fn role_of(name: &str) -> Role { + let w = words(name); + let has = |xs: &[&str]| w.iter().any(|x| xs.contains(&x.as_str())); + let low = name.to_ascii_lowercase(); + if has(&[ + "cleanup", "clean", "teardown", "destroy", "delete", "remove", "close", "closed", + ]) { + return Role::Cleanup; + } + if has(&["prod", "production", "release", "publish"]) { + return Role::Production; + } + if has(&["staging", "stage", "stg", "uat"]) { + return Role::Staging; + } + if has(&["e2e", "playwright", "cypress", "acceptance"]) + || low.contains("end-to-end") + || low.contains("end to end") + { + return Role::E2e; + } + if has(&["preview", "previews"]) || low.contains("review app") || low.contains("review-app") { + return Role::Preview; + } + Role::Other +} + +/// A label CoderHelm never adds: one that deploys to, or runs against, an +/// environment the team shares (staging, production, a release). A preview +/// deploy label is the pull request's own and may be added. +pub fn is_shared_env_label(name: &str) -> bool { + let w = words(name); + let has = |xs: &[&str]| w.iter().any(|x| xs.contains(&x.as_str())); + let low = name.to_ascii_lowercase(); + if has(&[ + "prod", + "production", + "staging", + "stage", + "stg", + "uat", + "release", + ]) { + return true; + } + low.contains("deploy") && !low.contains("preview") +} + +// ── a workflow's triggers ────────────────────────────────────────────────── + +/// What starts a workflow on a pull request. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Triggers { + /// `pull_request` or `pull_request_target`. + pub on_pr: bool, + /// The pull request event types it lists; empty: GitHub's default + /// (opened, synchronize, reopened). + pub types: Vec, + pub paths: Vec, + pub paths_ignore: Vec, + pub branches: Vec, + /// It can be started by hand (`workflow_dispatch`). + pub dispatch: bool, +} + +fn strings(v: Option<&serde_yaml::Value>) -> Vec { + match v { + Some(serde_yaml::Value::String(s)) => vec![s.clone()], + Some(serde_yaml::Value::Sequence(s)) => s + .iter() + .filter_map(|x| x.as_str().map(str::to_string)) + .collect(), + _ => Vec::new(), + } +} + +/// A workflow's triggers, from its text. Never fails: an unreadable file +/// starts on nothing. +pub fn triggers(yaml: &str) -> Triggers { + let mut t = Triggers::default(); + let Ok(v) = serde_yaml::from_str::(yaml) else { + return t; + }; + // `on:` is read by YAML 1.1 parsers as the boolean `true`. + let Some(on) = v.get("on").or_else(|| v.get(serde_yaml::Value::Bool(true))) else { + return t; + }; + let names: Vec = match on { + serde_yaml::Value::String(s) => vec![s.clone()], + serde_yaml::Value::Sequence(_) => strings(Some(on)), + serde_yaml::Value::Mapping(m) => m + .keys() + .filter_map(|k| k.as_str().map(str::to_string)) + .collect(), + _ => Vec::new(), + }; + t.dispatch = names.iter().any(|n| n == "workflow_dispatch"); + for ev in ["pull_request", "pull_request_target"] { + if !names.iter().any(|n| n == ev) { + continue; + } + t.on_pr = true; + let e = on.get(ev); + t.types.extend(strings(e.and_then(|e| e.get("types")))); + t.paths.extend(strings(e.and_then(|e| e.get("paths")))); + t.paths_ignore + .extend(strings(e.and_then(|e| e.get("paths-ignore")))); + t.branches + .extend(strings(e.and_then(|e| e.get("branches")))); + } + t +} + +/// GitHub's filter glob: `*` within a path segment, `**` across them, `?` +/// one character. +pub fn glob(pattern: &str, path: &str) -> bool { + fn go(p: &[u8], s: &[u8]) -> bool { + match p.first() { + None => s.is_empty(), + Some(b'*') if p.get(1) == Some(&b'*') => { + let rest = &p[2..]; + let rest = rest.strip_prefix(b"/").unwrap_or(rest); + (0..=s.len()).any(|i| go(rest, &s[i..])) || (p.get(2) == Some(&b'/') && go(rest, s)) + } + Some(b'*') => { + let rest = &p[1..]; + let mut i = 0; + loop { + if go(rest, &s[i..]) { + return true; + } + if i >= s.len() || s[i] == b'/' { + return false; + } + i += 1; + } + } + Some(b'?') => !s.is_empty() && s[0] != b'/' && go(&p[1..], &s[1..]), + Some(c) => s.first() == Some(c) && go(&p[1..], &s[1..]), + } + } + go(pattern.as_bytes(), path.as_bytes()) +} + +impl Triggers { + /// Whether a pull request into `base` changing `changed` starts it. + /// `paths` with `!` exclusions is read in order, as GitHub does. + pub fn applies(&self, changed: &[String], base: &str) -> bool { + if !self.on_pr { + return false; + } + if !self.branches.is_empty() && !self.branches.iter().any(|b| glob(b, base)) { + return false; + } + if !self.paths.is_empty() { + let hit = changed.iter().any(|f| { + let mut on = false; + for p in &self.paths { + match p.strip_prefix('!') { + Some(neg) if glob(neg, f) => on = false, + None if glob(p, f) => on = true, + _ => {} + } + } + on + }); + if !hit { + return false; + } + } + if !self.paths_ignore.is_empty() + && !changed.is_empty() + && changed + .iter() + .all(|f| self.paths_ignore.iter().any(|p| glob(p, f))) + { + return false; + } + true + } + + /// Adding a label starts it (its types list `labeled`). Otherwise a + /// label counts only from the next push. + pub fn starts_on_label(&self) -> bool { + self.types.iter().any(|t| t == "labeled") + } +} + +// ── the plan ─────────────────────────────────────────────────────────────── + +/// One preview or end-to-end job that covers the change. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Covering { + /// The check's name as GitHub shows it (the job's `name`, else its key). + pub check: String, + pub role: Option, + pub workflow: String, +} + +/// What it takes to run the preview and its end-to-end checks on the change. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Plan { + /// The jobs that cover the change. + pub covers: Vec, + /// Existing repository labels to add, in order. + pub add: Vec, + /// A label only counts from the next push in a workflow that needs one. + pub needs_push: bool, + /// What keeps a covering job from running that CoderHelm doesn't + /// change, one plain line each. + pub blocked: Vec, + /// Covering checks whose workflow skips drafts: they run once the pull + /// request is marked ready, so a draft is marked ready for them and + /// waits on them as proof (`ready::Decision::Proving`), never treated + /// as skipped for good. + pub draft_gated: Vec, +} + +impl Plan { + /// The repository has a preview or end-to-end path for this change. + pub fn has_path(&self) -> bool { + !self.covers.is_empty() + } +} + +/// What [`plan`] reads. +#[derive(Debug, Clone, Default)] +pub struct PlanInput<'a> { + /// Each workflow file: its path and text. + pub workflows: &'a [(String, String)], + pub changed: &'a [String], + pub base: &'a str, + pub repo_labels: &'a [String], + pub on_pr: &'a [String], + /// Labels the team's settings name. + pub preferred: &'a [String], + /// The end-to-end areas of the repository's test map that cover the + /// changed paths (`e2e::coverage`): an area label is chosen from these + /// when the repository keeps a map, from the paths' names otherwise. + pub areas: &'a [String], +} + +fn norm(s: &str) -> String { + s.chars() + .filter(|c| c.is_ascii_alphanumeric()) + .flat_map(|c| c.to_lowercase()) + .collect() +} + +/// A contains pattern whose text is only the start of a label +/// (`*E2E:*`, from `contains(join(labels), 'E2E:')`): read as that prefix. +fn prefix_of_contains(pattern: &str) -> Option<&str> { + pattern + .strip_prefix('*') + .and_then(|p| p.strip_suffix('*')) + .filter(|i| !i.is_empty() && workflow_gate::is_bare_prefix(i)) +} + +/// The area a label names after its pattern's fixed part (`E2E:payments` +/// for `E2E:*` is `payments`). +fn area_of(pattern: &str, label: &str) -> String { + let low = label.to_ascii_lowercase(); + if let Some(f) = prefix_of_contains(pattern).map(str::to_ascii_lowercase) { + if low.starts_with(&f) { + return norm(&label[f.len()..]); + } + } + let fixed = pattern.trim_matches('*'); + let f = fixed.to_ascii_lowercase(); + let rest = if pattern.ends_with('*') && low.starts_with(&f) { + &label[f.len()..] + } else if pattern.starts_with('*') && low.ends_with(&f) { + &label[..label.len() - f.len()] + } else { + label + }; + norm(rest) +} + +/// Whether an area names part of the change: a changed path's directory or +/// file name is that area. +pub fn area_matches(area: &str, changed: &[String]) -> bool { + if area.len() < 3 { + return false; + } + changed.iter().any(|p| { + p.split('/').any(|seg| { + let stem = seg.split('.').next().unwrap_or(seg); + let s = norm(stem); + !s.is_empty() && (s == area || (area.len() >= 4 && s.contains(area))) + }) + }) +} + +/// The repository labels a pattern means for this change: an exact or +/// contains pattern is the one label it names; a prefix or suffix pattern +/// (`E2E:*`) is every label of it whose area matches the changed paths. +fn labels_for(pattern: &str, i: &PlanInput) -> Vec { + let prefix = prefix_of_contains(pattern); + if prefix.is_none() + && (workflow_gate::is_exact(pattern) + || (pattern.starts_with('*') && pattern.ends_with('*') && pattern.len() > 2)) + { + return workflow_gate::resolve(pattern, i.repo_labels, i.preferred) + .into_iter() + .collect(); + } + let fits = |l: &str| match prefix { + Some(p) => l.len() > p.len() && l.to_ascii_lowercase().starts_with(&p.to_ascii_lowercase()), + None => workflow_gate::matches(pattern, l), + }; + // The repository's test map names its areas: its labels are those, + // created on first use when the repository doesn't have one yet. + if !i.areas.is_empty() { + let fixed = prefix.unwrap_or(pattern.trim_matches('*')); + if !pattern.ends_with('*') { + return Vec::new(); + } + let mut out = Vec::new(); + for a in i.areas { + let want = norm(a); + let existing = i + .repo_labels + .iter() + .find(|l| fits(l) && area_of(pattern, l) == want); + let label = existing.cloned().unwrap_or_else(|| format!("{fixed}{a}")); + if fits(&label) && !workflow_gate::is_bare_prefix(&label) { + push_unique(&mut out, &label); + } + } + return out; + } + i.repo_labels + .iter() + .filter(|l| !workflow_gate::is_bare_prefix(l) && fits(l)) + .filter(|l| area_matches(&area_of(pattern, l), i.changed)) + .cloned() + .collect() +} + +/// A way that runs the change's own areas comes before one that runs +/// every test. +fn uses_area(w: &LabelWay) -> bool { + w.need.iter().any(|p| !workflow_gate::is_exact(p)) +} + +fn push_unique(out: &mut Vec, l: &str) { + if !out.iter().any(|o| o.eq_ignore_ascii_case(l)) { + out.push(l.to_string()); + } +} + +fn has_label(on_pr: &[String], pattern: &str) -> bool { + on_pr.iter().any(|l| workflow_gate::matches(pattern, l)) +} + +/// The labels one way needs added, or why it can't be taken. +fn take_way(w: &LabelWay, i: &PlanInput) -> Result, String> { + if let Some(f) = w.forbid.iter().find(|f| has_label(i.on_pr, f)) { + return Err(format!( + "the label `{}` on the pull request stops it", + f.trim_matches('*') + )); + } + let mut add = Vec::new(); + for need in &w.need { + if has_label(i.on_pr, need) { + continue; + } + let real = labels_for(need, i); + if real.is_empty() { + return Err(format!( + "it needs a `{}` label and none in the repository fits this change", + need.trim_matches('*') + )); + } + if let Some(s) = real.iter().find(|l| is_shared_env_label(l)) { + return Err(format!( + "it needs `{s}`, which deploys to an environment the team shares" + )); + } + for l in real { + push_unique(&mut add, &l); + } + } + Ok(add) +} + +/// The preview and end-to-end jobs that cover the change and what starts +/// them. Pure: every case is tested. +pub fn plan(i: &PlanInput) -> Plan { + let mut out = Plan::default(); + let mut area_patterns: Vec = Vec::new(); + for (path, yaml) in i.workflows { + let t = triggers(yaml); + if !t.applies(i.changed, i.base) { + continue; + } + let wf_name = serde_yaml::from_str::(yaml) + .ok() + .and_then(|v| v.get("name").and_then(|n| n.as_str()).map(str::to_string)) + .unwrap_or_default(); + let gate = workflow_gate::read(yaml); + for job in &gate.jobs { + let shown = if job.name.is_empty() || job.name.contains("${{") { + job.id.clone() + } else { + job.name.clone() + }; + let role = match role_of(&shown) { + Role::Other => role_of(&wf_name), + r => r, + }; + if !matches!(role, Role::Preview | Role::E2e) { + continue; + } + out.covers.push(Covering { + check: shown.clone(), + role: Some(role), + workflow: path.clone(), + }); + if gate.draft { + push_unique(&mut out.draft_gated, &shown); + } + if job.unreadable { + out.blocked.push(format!( + "`{shown}`: its `if:` condition can't be read, so CoderHelm can't tell what starts it" + )); + continue; + } + for w in &job.ways { + for p in w.need.iter().filter(|p| !workflow_gate::is_exact(p)) { + push_unique(&mut area_patterns, p); + } + } + if job.ways.is_empty() { + continue; + } + if job.ways.iter().any(|w| { + w.need.iter().all(|n| has_label(i.on_pr, n)) + && !w.forbid.iter().any(|f| has_label(i.on_pr, f)) + }) { + continue; + } + let mut best: Option<((bool, usize), Vec)> = None; + let mut why: Vec = Vec::new(); + for w in &job.ways { + match take_way(w, i) { + Ok(add) => { + let rank = (!uses_area(w), add.len()); + if best.as_ref().is_none_or(|(r, _)| rank < *r) { + best = Some((rank, add)); + } + } + Err(e) => push_unique(&mut why, &e), + } + } + match best.map(|(_, a)| a) { + Some(add) => { + for l in &add { + push_unique(&mut out.add, l); + } + if !add.is_empty() && !t.starts_on_label() { + out.needs_push = true; + } + } + None => out + .blocked + .push(format!("`{shown}` doesn't run: {}", why.join("; "))), + } + } + } + // The end-to-end areas the change touches run too, when the workflows + // read area labels. + if !out.add.is_empty() { + for p in &area_patterns { + for l in labels_for(p, i) { + if !is_shared_env_label(&l) && !has_label(i.on_pr, &l) { + push_unique(&mut out.add, &l); + } + } + } + } + out.add.retain(|l| !is_shared_env_label(l)); + out +} + +/// A check's result on the head, as [`gaps`] and [`progress`] read it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Outcome { + Passed, + Failed, + Running, + Skipped, +} + +/// Whether a check on the head is one of the covering jobs (a matrix or +/// reusable workflow's check carries the job's name first). +pub fn is_covering(covers: &[Covering], check: &str) -> bool { + let c = check.trim().to_ascii_lowercase(); + covers.iter().any(|k| { + let n = k.check.trim().to_ascii_lowercase(); + c == n || c.starts_with(&format!("{n} / ")) || c.starts_with(&format!("{n} (")) + }) +} + +/// Whether a skipped check on the head would have covered this change: a +/// preview or end-to-end check skipped on a change with a visible surface. +/// Read from its name, so it holds even when the workflows couldn't be read. +pub fn skipped_is_gap(check: &str, visible: bool) -> bool { + visible && matches!(role_of(check), Role::Preview | Role::E2e) +} + +/// The checks that cover the change and didn't run on the head: CoderHelm +/// starts them, they are never listed as evidence. +pub fn gaps(checks: &[(String, Outcome)], covers: &[Covering], visible: bool) -> Vec { + checks + .iter() + .filter(|(n, o)| { + *o == Outcome::Skipped && (is_covering(covers, n) || skipped_is_gap(n, visible)) + }) + .map(|(n, _)| n.clone()) + .collect() +} + +// ── where the preview stands ─────────────────────────────────────────────── + +/// Where the preview stands on a head. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Stage { + /// No visible surface, or the repository has no preview path for it. + #[default] + NotNeeded, + /// CoderHelm added what starts the preview; it hasn't reported yet. + Triggered, + /// The preview deploy or its end-to-end checks are running. + Deploying, + /// The preview is up and its end-to-end checks passed. + Ready, + /// The preview is checked: up, end-to-end passed, pages captured (or + /// why not said). + Checked, + /// The preview deploy or its end-to-end checks failed. + Failed, + /// Something CoderHelm doesn't change keeps it from running. + Blocked, +} + +/// One captured page. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Shot { + /// The page's path (`/join`). + pub page: String, + /// `desktop` or `phone`. + pub width: String, + /// The image's address. + pub src: String, +} + +/// One end-to-end or preview check's result on the head. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CheckResult { + pub name: String, + pub outcome: Outcome, + #[serde(default)] + pub url: String, +} + +/// What the run records about the preview of its pull request's head. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct State { + pub head: String, + pub stage: Stage, + /// The checks that cover the change. + pub covers: Vec, + /// Labels CoderHelm added to start them. + pub labels_added: Vec, + pub url: String, + /// The preview and end-to-end checks' results on the head. + pub checks: Vec, + pub shots: Vec, + /// One line: why there is no preview, what blocks it, or why no page + /// was captured. + pub why: String, + /// The change needs a new or updated end-to-end spec and has one. + pub e2e_required: bool, + pub e2e_covered: bool, + /// Covering checks that skip drafts: they run once it is ready. + pub draft_gated: Vec, + /// The commands that check the changed area ([`how_to_check`]). + pub how_to_check: String, +} + +impl State { + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_default() + } + + pub fn from_json(s: &str) -> Option { + serde_json::from_str(s).ok() + } + + /// Still on its way: the description and the ready decision wait. + pub fn pending(&self) -> bool { + matches!( + self.stage, + Stage::Triggered | Stage::Deploying | Stage::Ready + ) + } + + /// One plain phrase for a status line ("preview checked"). + pub fn phrase(&self) -> Option<&'static str> { + match self.stage { + Stage::NotNeeded => None, + Stage::Triggered | Stage::Deploying => Some("preview deploying"), + Stage::Ready => Some("preview up, pages being captured"), + Stage::Checked => Some("preview checked"), + Stage::Failed => Some("preview checks failed"), + Stage::Blocked => Some("preview not run"), + } + } +} + +/// The stage the covering checks on the head show. `triggered`: CoderHelm +/// started them on this head. +pub fn progress(results: &[CheckResult], triggered: bool) -> Stage { + if results.iter().any(|r| r.outcome == Outcome::Failed) { + return Stage::Failed; + } + if results.iter().any(|r| r.outcome == Outcome::Running) { + return Stage::Deploying; + } + let ran: Vec<&CheckResult> = results + .iter() + .filter(|r| r.outcome == Outcome::Passed) + .collect(); + if !ran.is_empty() && results.iter().all(|r| r.outcome == Outcome::Passed) { + return Stage::Ready; + } + if triggered { + return Stage::Triggered; + } + if !ran.is_empty() { + return Stage::Ready; + } + Stage::Triggered +} + +/// A preview address in text (a check's output, a deployment, a comment): +/// the first https URL whose host names a preview. +pub fn url_in(text: &str) -> Option { + for (i, _) in text.match_indices("https://") { + let rest = &text[i..]; + let end = rest + .find(|c: char| { + c.is_whitespace() || matches!(c, ')' | '"' | '\'' | '>' | '<' | ']' | '`') + }) + .unwrap_or(rest.len()); + let url = rest[..end].trim_end_matches(['.', ',', ';']); + let host = url["https://".len()..].split('/').next().unwrap_or(""); + if host.to_ascii_lowercase().contains("preview") && !host.contains('@') { + return Some(url.to_string()); + } + } + None +} + +/// The preview address from the head's deployments: (environment, url) +/// pairs, a preview environment first, never a shared one. +pub fn url_from_deployments(deps: &[(String, String)]) -> Option { + let ok = |(env, url): &&(String, String)| { + url.starts_with("https://") && !is_shared_env_label(env) && role_of(env) != Role::Production + }; + deps.iter() + .filter(ok) + .find(|(env, url)| { + env.to_ascii_lowercase().contains("preview") + || url.to_ascii_lowercase().contains("preview") + }) + .or_else(|| deps.iter().find(ok)) + .map(|(_, u)| u.clone()) +} + +// ── end-to-end specs ─────────────────────────────────────────────────────── + +/// The repository's end-to-end suite: the folder its runner's config is in. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Suite { + /// The folder (`e2e`, `apps/web/e2e`), "" for the repository's root. + pub dir: String, + pub runner: String, +} + +/// The e2e suite in a repository's tree, if it has one. +pub fn e2e_suite(tree: &[String]) -> Option { + let mut found: Vec = tree + .iter() + .filter(|p| !p.contains("node_modules/")) + .filter_map(|p| { + let name = p.rsplit('/').next().unwrap_or(p); + let runner = if name.starts_with("playwright.config.") { + "playwright" + } else if name.starts_with("cypress.config.") || name == "cypress.json" { + "cypress" + } else { + return None; + }; + let dir = p.rsplit_once('/').map(|(d, _)| d).unwrap_or("").to_string(); + Some(Suite { + dir, + runner: runner.to_string(), + }) + }) + .collect(); + // The suite nearest the root, then the shortest path. + found.sort_by_key(|s| (s.dir.matches('/').count(), s.dir.len())); + found.into_iter().next() +} + +fn is_test_file(p: &str) -> bool { + let p = p.to_ascii_lowercase(); + p.contains("/test/") + || p.contains("/tests/") + || p.contains("__tests__") + || p.contains(".test.") + || p.contains(".spec.") + || p.contains("_test.") + || p.contains(".cy.") + || p.contains("/e2e/") + || p.starts_with("e2e/") +} + +/// Whether a path is an end-to-end spec (or its page object or fixture) of +/// the suite. +pub fn is_e2e_spec(path: &str, suite: &Suite) -> bool { + let p = path.to_ascii_lowercase(); + let code = [".ts", ".tsx", ".js", ".mjs", ".cjs", ".jsx", ".feature"] + .iter() + .any(|e| p.ends_with(e)); + if !code || p.contains("playwright.config.") || p.contains("cypress.config.") { + return false; + } + if suite.dir.is_empty() { + p.starts_with("e2e/") + || p.contains("/e2e/") + || p.starts_with("cypress/") + || p.contains(".e2e.") + || p.contains(".cy.") + } else { + p.starts_with(&format!("{}/", suite.dir.to_ascii_lowercase())) + } +} + +/// A changed file a person sees in the browser: UI code, styles, pages, +/// a page's actions and hooks. Never a test, a config or generated output. +pub fn is_user_visible(path: &str) -> bool { + let p = path.to_ascii_lowercase(); + if is_test_file(&p) || crate::pr_facts::is_generated(&p) { + return false; + } + let name = p.rsplit('/').next().unwrap_or(&p); + if name.contains(".config.") || name.starts_with('.') || name.ends_with(".d.ts") { + return false; + } + if crate::pr_facts::is_ui(&p) { + return true; + } + let ext = name.rsplit('.').next().unwrap_or(""); + let web = ["ts", "js", "mjs", "tsx", "jsx", "vue", "svelte"].contains(&ext); + let at = format!("/{p}"); + web && [ + "/app/", + "/pages/", + "/actions/", + "/hooks/", + "/views/", + "/routes/", + "/screens/", + "/features/", + ] + .iter() + .any(|d| at.contains(d)) +} + +/// Whether the change needs an end-to-end spec, and whether it has one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum E2eNeed { + /// No visible surface, or the repository has no e2e suite. + NotNeeded, + /// A visible change in a repository with a suite: `covered` when the + /// change adds or updates a spec in it. + Required { + suite: Suite, + visible: Vec, + covered: bool, + }, +} + +impl E2eNeed { + pub fn missing(&self) -> bool { + matches!(self, E2eNeed::Required { covered: false, .. }) + } + + /// The one line the coder, the reviewer and the ready check act on + /// when a spec is missing. + pub fn instruction(&self) -> Option { + let E2eNeed::Required { + suite, + visible, + covered: false, + } = self + else { + return None; + }; + let at = if suite.dir.is_empty() { + "the repository's end-to-end folder".to_string() + } else { + format!("`{}/`", suite.dir) + }; + Some(format!( + "The change alters what a person sees in the browser ({}) and the repository has a {} end-to-end suite in {at}, but no end-to-end spec there covers it. Write or update one for the new behaviour, following the suite's own conventions (its folders, page objects, tags and area labels, and the repository's AGENTS.md or CLAUDE.md), so it fails without the change and passes with it.", + visible + .iter() + .take(3) + .map(|v| format!("`{v}`")) + .collect::>() + .join(", "), + suite.runner + )) + } +} + +/// [`E2eNeed`] from the changed paths and the repository's suite. +pub fn e2e_need(changed: &[String], suite: Option<&Suite>) -> E2eNeed { + let Some(suite) = suite else { + return E2eNeed::NotNeeded; + }; + let visible: Vec = changed + .iter() + .filter(|p| is_user_visible(p) && !is_e2e_spec(p, suite)) + .cloned() + .collect(); + if visible.is_empty() { + return E2eNeed::NotNeeded; + } + let covered = changed.iter().any(|p| is_e2e_spec(p, suite)); + E2eNeed::Required { + suite: suite.clone(), + visible, + covered, + } +} + +// ── pages to capture ─────────────────────────────────────────────────────── + +const GENERIC: &[&str] = &[ + "apps", + "app", + "src", + "web", + "lib", + "libs", + "components", + "component", + "pages", + "page", + "features", + "feature", + "index", + "use", + "hooks", + "hook", + "actions", + "action", + "services", + "service", + "test", + "tests", + "utils", + "util", + "types", + "packages", + "client", + "server", + "ui", + "layout", + "shared", + "common", + "modules", + "module", + "tsx", + "jsx", + "mjs", + "the", + "and", +]; + +fn tokens(path: &str) -> Vec { + let mut out: Vec = Vec::new(); + let mut cur = String::new(); + let mut prev_lower = false; + for c in path.chars() { + if c.is_ascii_alphanumeric() { + if c.is_ascii_uppercase() && prev_lower && !cur.is_empty() { + out.push(std::mem::take(&mut cur)); + } + prev_lower = c.is_ascii_lowercase() || c.is_ascii_digit(); + cur.push(c.to_ascii_lowercase()); + } else { + if !cur.is_empty() { + out.push(std::mem::take(&mut cur)); + } + prev_lower = false; + } + } + if !cur.is_empty() { + out.push(cur); + } + out.retain(|t| t.len() >= 3 && !GENERIC.contains(&t.as_str())); + out.dedup(); + out +} + +/// The route a page file serves, or None for a file that isn't a page (or +/// a dynamic one, which has no address without data). +pub fn route_of(path: &str) -> Option { + let p = path.replace('\\', "/"); + let segs: Vec<&str> = p.split('/').collect(); + let name = *segs.last()?; + let stem = name.split('.').next().unwrap_or(name); + let ext = name.rsplit('.').next().unwrap_or(""); + if !["tsx", "jsx", "ts", "js", "mdx", "vue", "svelte"].contains(&ext) || is_test_file(&p) { + return None; + } + let route_from = |dirs: &[&str]| -> Option { + let mut parts = Vec::new(); + for d in dirs { + if d.starts_with('(') && d.ends_with(')') || d.starts_with('@') || d.starts_with('_') { + continue; + } + if d.contains('[') { + return None; + } + parts.push(*d); + } + Some(format!("/{}", parts.join("/"))) + }; + // App router: `app//page.tsx`. + if stem == "page" { + let at = segs.iter().rposition(|s| *s == "app")?; + return route_from(&segs[at + 1..segs.len() - 1]); + } + // Pages router: `pages//.tsx`. + let at = segs.iter().rposition(|s| *s == "pages")?; + if ["_app", "_document", "_error", "404", "500"].contains(&stem) + || segs[at + 1..].first() == Some(&"api") + || stem.contains('[') + { + return None; + } + let mut dirs: Vec<&str> = segs[at + 1..segs.len() - 1].to_vec(); + if stem != "index" { + dirs.push(stem); + } + route_from(&dirs) +} + +/// The pages to capture for the change: its changed pages first, then the +/// pages whose path shares the most words with the changed files, at most +/// [`MAX_PAGES`]; the home page when nothing names one. +pub fn routes(tree: &[String], changed: &[String]) -> Vec { + let mut out: Vec = Vec::new(); + for c in changed { + if let Some(r) = route_of(c) { + push_unique(&mut out, &r); + } + } + let want: Vec = changed + .iter() + .filter(|c| is_user_visible(c)) + .flat_map(|c| tokens(c)) + .collect(); + let mut scored: Vec<(usize, String)> = tree + .iter() + .filter_map(|p| { + let r = route_of(p)?; + let have = tokens(p); + let n = have.iter().filter(|t| want.contains(t)).count(); + (n > 0).then_some((n, r)) + }) + .collect(); + scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.len().cmp(&b.1.len()))); + for (_, r) in scored { + push_unique(&mut out, &r); + } + out.truncate(MAX_PAGES); + if out.is_empty() { + out.push("/".to_string()); + } + out +} + +/// The file name a page's capture is saved under (`join-desktop`). +pub fn shot_name(page: &str, width: &str) -> String { + let slug: String = page + .trim_matches('/') + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() { + c.to_ascii_lowercase() + } else { + '-' + } + }) + .collect(); + let slug = if slug.is_empty() { + "home".to_string() + } else { + slug + }; + format!("{slug}-{width}") +} + +/// The sandbox script that captures each page at both widths. It writes +/// each image base64-encoded (`.png.b64`) and `shots.json` (each +/// page's status and title) to `$CODERHELM_OUT`; a page that doesn't load +/// is recorded with its status, never retried into a pass. +pub fn capture_script(base: &str, pages: &[String]) -> String { + let base = base.trim_end_matches('/'); + let mut jobs = Vec::new(); + for p in pages { + for (width, (w, h)) in [("desktop", DESKTOP), ("phone", PHONE)] { + jobs.push(serde_json::json!({ + "page": p, + "width": width, + "w": w, + "h": h, + "url": format!("{base}{p}"), + "name": shot_name(p, width), + })); + } + } + let jobs = serde_json::to_string(&jobs).unwrap_or_else(|_| "[]".into()); + format!( + r#"import {{ chromium }} from 'playwright'; +import {{ writeFileSync }} from 'node:fs'; +const out = process.env.CODERHELM_OUT || '.'; +const jobs = {jobs}; +const results = []; +const browser = await chromium.launch(); +for (const j of jobs) {{ + const page = await browser.newPage({{ viewport: {{ width: j.w, height: j.h }} }}); + let status = 0, title = '', error = ''; + try {{ + const res = await page.goto(j.url, {{ waitUntil: 'networkidle', timeout: 45000 }}); + status = res ? res.status() : 0; + title = await page.title(); + if (status > 0 && status < 400) {{ + const png = await page.screenshot({{ fullPage: false }}); + writeFileSync(`${{out}}/${{j.name}}.png.b64`, png.toString('base64')); + }} + }} catch (e) {{ error = String(e).slice(0, 300); }} + results.push({{ page: j.page, width: j.width, name: j.name, status, title, error }}); + await page.close(); +}} +await browser.close(); +writeFileSync(`${{out}}/shots.json`, JSON.stringify(results)); +"# + ) +} + +/// The command that runs [`capture_script`] (saved as `capture.mjs`). +pub fn capture_command() -> String { + format!( + "npm init -y >/dev/null 2>&1; npm i --no-save --no-audit --no-fund playwright@{PLAYWRIGHT} >/dev/null 2>&1 && npx --no-install playwright install --with-deps chromium >/dev/null 2>&1 && node capture.mjs" + ) +} + +/// Hosts the capture needs besides the preview's: the package registry and +/// the browser download. +pub const CAPTURE_HOSTS: &[&str] = &[ + "registry.npmjs.org", + "cdn.playwright.dev", + "playwright.download.prss.microsoft.com", + "playwright.azureedge.net", +]; + +/// One page's capture as `shots.json` reports it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)] +#[serde(default)] +pub struct Captured { + pub page: String, + pub width: String, + pub name: String, + pub status: u16, + pub title: String, + pub error: String, +} + +/// Why no page was captured, from the capture's report: a login wall, a +/// page that didn't load, or nothing at all. None when one was. +pub fn why_no_shot(report: &[Captured]) -> Option { + if report.iter().any(|c| (1..400).contains(&c.status)) { + return None; + } + if report.iter().any(|c| c.status == 401 || c.status == 403) { + return Some("the preview asks for a login, so its pages couldn't be captured".into()); + } + if let Some(c) = report.iter().find(|c| c.status >= 400) { + return Some(format!( + "the preview answered {} for `{}`, so it couldn't be captured", + c.status, c.page + )); + } + if let Some(c) = report.iter().find(|c| !c.error.is_empty()) { + return Some(format!( + "the preview page `{}` didn't load ({})", + c.page, + crate::truncate_str(&c.error, 120) + )); + } + Some("the capture in the sandbox gave no result".into()) +} + +/// The repository's unit test command, from its tree: the runner its +/// config files name. Empty when none is known. +pub fn unit_cmd(tree: &[String]) -> String { + let has = |prefix: &str| { + tree.iter().any(|p| { + !p.contains("node_modules/") + && p.rsplit('/').next().is_some_and(|n| n.starts_with(prefix)) + }) + }; + if has("vitest.config.") || has("vitest.workspace.") { + "npx vitest run".into() + } else if has("jest.config.") { + "npx jest".into() + } else if has("pytest.ini") || has("conftest.py") { + "pytest".into() + } else if tree.iter().any(|p| p == "go.mod") { + "go test".into() + } else { + String::new() + } +} + +/// The commands that check the changed area by hand: the end-to-end specs +/// the change adds or updates, run against the preview, and the changed +/// unit tests. Empty when none is known. +pub fn how_to_check(changed: &[String], suite: Option<&Suite>, unit_cmd: &str) -> String { + let mut parts = Vec::new(); + if let Some(s) = suite { + let specs: Vec<&String> = changed + .iter() + .filter(|p| { + is_e2e_spec(p, s) + && (p.contains(".spec.") || p.contains(".cy.") || p.contains(".e2e.")) + }) + .take(3) + .collect(); + if !specs.is_empty() { + let rel: Vec = specs + .iter() + .map(|p| { + p.strip_prefix(&format!("{}/", s.dir)) + .unwrap_or(p) + .to_string() + }) + .collect(); + let dir = if s.dir.is_empty() { + String::new() + } else { + format!("cd {} && ", s.dir) + }; + let cmd = if s.runner == "cypress" { + format!("{dir}npx cypress run --spec {}", rel.join(",")) + } else { + format!("{dir}npx playwright test {}", rel.join(" ")) + }; + parts.push(format!("`{cmd}` against the preview")); + } + } + let unit: Vec<&String> = changed + .iter() + .filter(|p| { + is_test_file(p) + && !suite.is_some_and(|s| is_e2e_spec(p, s)) + && (p.contains(".test.") || p.contains(".spec.") || p.contains("_test.")) + }) + .take(4) + .collect(); + if !unit.is_empty() && !unit_cmd.trim().is_empty() { + parts.push(format!( + "`{} {}`", + unit_cmd.trim(), + unit.iter() + .map(|s| s.as_str()) + .collect::>() + .join(" ") + )); + } + parts.join(", then ") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(v: &[&str]) -> Vec { + v.iter().map(|x| x.to_string()).collect() + } + + /// A web repository whose preview deploy and preview end-to-end checks + /// run only with labels, as many monorepos gate them. + const PREVIEW_WF: &str = r#" +name: Preview +on: + pull_request: + types: [opened, synchronize, reopened, labeled] + paths: + - "apps/web/**" + - "packages/**" + - "!**/*.md" +jobs: + deploy_preview: + name: Deploy Preview Web App + if: >- + github.event.pull_request.draft != true && ( + contains(github.event.pull_request.labels.*.name, 'CI:E2E') || + contains(join(github.event.pull_request.labels.*.name, ','), 'E2E:')) + runs-on: ubuntu-latest + steps: + - run: echo deploy + e2e_preview: + name: E2E on preview + needs: deploy_preview + if: "!contains(github.event.pull_request.labels.*.name, 'CI:DEPLOY_STAGING')" + runs-on: ubuntu-latest + steps: + - run: echo e2e + cleanup: + name: Cleanup PR Preview + if: github.event.action == 'closed' + runs-on: ubuntu-latest + steps: + - run: echo bye +"#; + + const STAGING_WF: &str = r#" +name: Staging +on: + pull_request: + types: [labeled, synchronize] +jobs: + staging: + name: Deploy to Staging + if: contains(github.event.pull_request.labels.*.name, 'CI:DEPLOY_STAGING') + runs-on: ubuntu-latest + steps: + - run: echo staging + e2e_staging: + name: E2E after staging deploy + needs: staging + runs-on: ubuntu-latest + steps: + - run: echo e2e +"#; + + const PROD_WF: &str = r#" +name: Release +on: + push: + branches: [main] +jobs: + deploy: + name: Deploy to Production + runs-on: ubuntu-latest + steps: + - run: echo prod +"#; + + fn repo_labels() -> Vec { + s(&[ + "CI:E2E", + "CI:DEPLOY_STAGING", + "E2E:signup", + "E2E:checkout", + "E2E:account", + "bug", + ]) + } + + fn workflows() -> Vec<(String, String)> { + vec![ + (".github/workflows/preview.yml".into(), PREVIEW_WF.into()), + (".github/workflows/staging.yml".into(), STAGING_WF.into()), + (".github/workflows/release.yml".into(), PROD_WF.into()), + ] + } + + fn changed() -> Vec { + s(&[ + "apps/web/src/components/signup/use-signup-form.ts", + "apps/web/src/lib/validation-utils.ts", + "apps/web/src/test/lib/validation-utils.test.ts", + ]) + } + + #[test] + fn a_label_gated_preview_gets_its_label_and_the_matching_area() { + let (w, c, l) = (workflows(), changed(), repo_labels()); + let p = plan(&PlanInput { + workflows: &w, + changed: &c, + base: "main", + repo_labels: &l, + on_pr: &[], + preferred: &[], + areas: &[], + }); + let names: Vec<&str> = p.covers.iter().map(|c| c.check.as_str()).collect(); + assert_eq!(names, vec!["Deploy Preview Web App", "E2E on preview"]); + // The e2e area the changed paths name runs the change's own specs + // (before the label that runs every test); never the staging label, + // never an area the change doesn't touch. + assert_eq!(p.add, s(&["E2E:signup"])); + // Both skip drafts: they run once the pull request is ready, and + // are waited on as proof, never read as skipped for good. + assert_eq!( + p.draft_gated, + s(&["Deploy Preview Web App", "E2E on preview"]) + ); + assert!(!p.needs_push, "the workflow starts on `labeled`"); + assert!(p.blocked.is_empty(), "{:?}", p.blocked); + } + + #[test] + fn a_label_counts_from_the_next_push_when_the_workflow_ignores_labeled() { + let wf = PREVIEW_WF.replace(", labeled]", "]"); + let (w, c, l) = ( + vec![(".github/workflows/preview.yml".to_string(), wf)], + changed(), + repo_labels(), + ); + let p = plan(&PlanInput { + workflows: &w, + changed: &c, + base: "main", + repo_labels: &l, + on_pr: &[], + preferred: &[], + areas: &[], + }); + assert_eq!(p.add, s(&["E2E:signup"])); + assert!(p.needs_push); + } + + #[test] + fn the_test_map_names_the_area_even_before_its_label_exists() { + let (w, c) = (workflows(), changed()); + let l = s(&["CI:E2E", "CI:DEPLOY_STAGING"]); + let areas = s(&["onboarding"]); + let p = plan(&PlanInput { + workflows: &w, + changed: &c, + base: "main", + repo_labels: &l, + on_pr: &[], + preferred: &[], + areas: &areas, + }); + assert_eq!(p.add, s(&["E2E:onboarding"])); + } + + #[test] + fn a_change_outside_the_workflow_paths_has_no_preview_path() { + let (w, l) = (workflows(), repo_labels()); + let c = s(&["services/api/src/main.rs", "docs/readme.md"]); + let p = plan(&PlanInput { + workflows: &w, + changed: &c, + base: "main", + repo_labels: &l, + on_pr: &[], + preferred: &[], + areas: &[], + }); + assert!(!p.has_path()); + assert!(p.add.is_empty()); + } + + #[test] + fn labels_already_on_the_pull_request_are_not_added_again() { + let (w, c, l) = (workflows(), changed(), repo_labels()); + let on = s(&["CI:E2E"]); + let p = plan(&PlanInput { + workflows: &w, + changed: &c, + base: "main", + repo_labels: &l, + on_pr: &on, + preferred: &[], + areas: &[], + }); + assert!(p.add.is_empty(), "{:?}", p.add); + } + + #[test] + fn a_preview_that_needs_only_a_shared_environment_label_is_blocked_not_labelled() { + let wf = r#" +on: + pull_request: + types: [labeled] +jobs: + preview: + name: Deploy Preview + if: contains(github.event.pull_request.labels.*.name, 'deploy-staging') + runs-on: ubuntu-latest + steps: [{run: x}] +"#; + let w = vec![("p.yml".to_string(), wf.to_string())]; + let (c, l) = (changed(), s(&["deploy-staging"])); + let p = plan(&PlanInput { + workflows: &w, + changed: &c, + base: "main", + repo_labels: &l, + on_pr: &[], + preferred: &[], + areas: &[], + }); + assert!(p.add.is_empty()); + assert_eq!(p.blocked.len(), 1); + assert!( + p.blocked[0].contains("environment the team shares"), + "{}", + p.blocked[0] + ); + } + + #[test] + fn a_preview_deploy_label_is_not_a_shared_environment() { + assert!(!is_shared_env_label("CI:DEPLOY_PREVIEW")); + assert!(!is_shared_env_label("CI:E2E")); + assert!(is_shared_env_label("CI:DEPLOY_STAGING")); + assert!(is_shared_env_label("deploy")); + assert!(is_shared_env_label("release-prod")); + } + + #[test] + fn check_roles_read_from_their_names() { + assert_eq!(role_of("Deploy Preview Web App"), Role::Preview); + assert_eq!(role_of("E2E on preview"), Role::E2e); + assert_eq!(role_of("Cleanup PR Preview"), Role::Cleanup); + assert_eq!(role_of("Deploy to Staging"), Role::Staging); + assert_eq!(role_of("E2E after staging deploy"), Role::Staging); + assert_eq!(role_of("Deploy to Production"), Role::Production); + assert_eq!(role_of("Deploy Web App"), Role::Other); + assert_eq!(role_of("Test CloudFront Cache Behavior"), Role::Other); + assert_eq!(role_of("unit tests"), Role::Other); + } + + #[test] + fn a_skipped_preview_or_e2e_check_on_a_visible_change_is_a_gap() { + let checks = vec![ + ("Deploy Preview Web App".to_string(), Outcome::Skipped), + ("E2E on preview".to_string(), Outcome::Skipped), + ("Deploy to Staging".to_string(), Outcome::Skipped), + ("E2E after staging deploy".to_string(), Outcome::Skipped), + ("Cleanup PR Preview".to_string(), Outcome::Skipped), + ("Deploy to Production".to_string(), Outcome::Skipped), + ("unit tests".to_string(), Outcome::Passed), + ]; + // Even with no workflow read: the names say what they cover. + assert_eq!( + gaps(&checks, &[], true), + s(&["Deploy Preview Web App", "E2E on preview"]) + ); + // A change with no visible surface has no preview gap. + assert!(gaps(&checks, &[], false).is_empty()); + } + + #[test] + fn the_preview_is_ready_only_once_every_covering_check_passed() { + let r = |o| CheckResult { + name: "x".into(), + outcome: o, + url: String::new(), + }; + assert_eq!(progress(&[], true), Stage::Triggered); + assert_eq!(progress(&[r(Outcome::Skipped)], true), Stage::Triggered); + assert_eq!( + progress(&[r(Outcome::Passed), r(Outcome::Running)], true), + Stage::Deploying + ); + assert_eq!( + progress(&[r(Outcome::Passed), r(Outcome::Failed)], true), + Stage::Failed + ); + assert_eq!( + progress(&[r(Outcome::Passed), r(Outcome::Passed)], true), + Stage::Ready + ); + } + + #[test] + fn a_preview_address_is_found_in_deployments_and_text() { + let deps = vec![ + ( + "staging".to_string(), + "https://staging.example.com".to_string(), + ), + ( + "pr-12".to_string(), + "https://pr-12.preview-web.example.com".to_string(), + ), + ]; + assert_eq!( + url_from_deployments(&deps).as_deref(), + Some("https://pr-12.preview-web.example.com") + ); + assert_eq!( + url_in("Deployed to https://pr-7.preview-web.example.com/ (ready).").as_deref(), + Some("https://pr-7.preview-web.example.com/") + ); + assert_eq!(url_in("see https://example.com/docs"), None); + } + + #[test] + fn a_visible_change_needs_an_e2e_spec_in_a_repo_with_a_suite() { + let tree = s(&[ + "apps/web/e2e/playwright.config.ts", + "apps/web/e2e/tests/signup.spec.ts", + "apps/web/src/app/(marketing)/join/page.tsx", + "apps/web/src/app/account/page.tsx", + "apps/web/src/app/account/[id]/page.tsx", + ]); + let suite = e2e_suite(&tree).unwrap(); + assert_eq!(suite.dir, "apps/web/e2e"); + let need = e2e_need(&changed(), Some(&suite)); + assert!(need.missing(), "{need:?}"); + assert!(need.instruction().unwrap().contains("`apps/web/e2e/`")); + let mut with_spec = changed(); + with_spec.push("apps/web/e2e/tests/signup.spec.ts".into()); + assert!(!e2e_need(&with_spec, Some(&suite)).missing()); + // No suite, or nothing visible: nothing to write. + assert_eq!(e2e_need(&changed(), None), E2eNeed::NotNeeded); + assert_eq!( + e2e_need(&s(&["apps/web/src/lib/validation-utils.ts"]), Some(&suite)), + E2eNeed::NotNeeded + ); + } + + #[test] + fn pages_to_capture_come_from_the_page_files_the_change_relates_to() { + let tree = s(&[ + "apps/web/src/app/page.tsx", + "apps/web/src/app/(marketing)/signup/page.tsx", + "apps/web/src/app/account/page.tsx", + "apps/web/src/app/account/[id]/page.tsx", + "apps/web/src/pages/_app.tsx", + ]); + assert_eq!(routes(&tree, &changed()), s(&["/signup"])); + assert_eq!(route_of("apps/web/src/app/page.tsx").as_deref(), Some("/")); + assert_eq!(route_of("apps/web/src/app/account/[id]/page.tsx"), None); + assert_eq!( + route_of("web/pages/about/team.tsx").as_deref(), + Some("/about/team") + ); + assert_eq!(routes(&tree, &s(&["apps/web/src/styles/x.css"])), s(&["/"])); + } + + #[test] + fn the_capture_script_takes_each_page_at_desktop_and_phone_width() { + let js = capture_script("https://pr-1.preview-web.example.com/", &s(&["/signup"])); + assert!(js.contains("https://pr-1.preview-web.example.com/signup")); + assert!(js.contains("signup-desktop") && js.contains("signup-phone")); + assert!(js.contains("\"w\":390") && js.contains("\"w\":1280")); + let report = vec![Captured { + status: 401, + page: "/signup".into(), + ..Default::default() + }]; + assert!(why_no_shot(&report).unwrap().contains("login")); + let ok = vec![Captured { + status: 200, + ..Default::default() + }]; + assert_eq!(why_no_shot(&ok), None); + } + + #[test] + fn how_to_check_names_the_changed_specs_and_tests_never_a_bare_suite() { + let suite = Suite { + dir: "apps/web/e2e".into(), + runner: "playwright".into(), + }; + let mut c = changed(); + c.push("apps/web/e2e/tests/signup.spec.ts".into()); + let how = how_to_check(&c, Some(&suite), "npx vitest run"); + assert!( + how.contains("cd apps/web/e2e && npx playwright test tests/signup.spec.ts"), + "{how}" + ); + assert!(how.contains("npx vitest run apps/web/src/test/lib/validation-utils.test.ts")); + assert_ne!(how.trim(), "npm test"); + } + + #[test] + fn the_unit_runner_is_read_from_the_tree() { + assert_eq!( + unit_cmd(&s(&["apps/web/vitest.config.ts"])), + "npx vitest run" + ); + assert_eq!(unit_cmd(&s(&["jest.config.js"])), "npx jest"); + assert_eq!(unit_cmd(&s(&["README.md"])), ""); + } + + #[test] + fn globs_read_as_github_reads_them() { + assert!(glob("apps/web/**", "apps/web/src/a.ts")); + assert!(glob("**/*.md", "docs/a/b.md")); + assert!(glob("**/*.md", "b.md")); + assert!(!glob("apps/*", "apps/web/src/a.ts")); + assert!(glob("main", "main")); + assert!(glob("release/*", "release/1")); + } +} diff --git a/services/common/src/waiting_line.rs b/services/common/src/waiting_line.rs new file mode 100644 index 000000000..0403d2da6 --- /dev/null +++ b/services/common/src/waiting_line.rs @@ -0,0 +1,240 @@ +//! The one line at the top of a run page and its pull request: what the +//! run is waiting on, and whether the pull request is ready for review. +//! +//! A finished run's page once showed "completed" with a merge standing +//! code (`needs_person_approval`) and a paragraph about auto-merge +//! settings: nobody could tell at a glance that the pull request only +//! waited for a person's approving review, or that its checks had passed. +//! [`line`] builds the sentence from what CoderHelm records about the pull +//! request (`merge_standing`, `draft_hold`, the preview), so the run page +//! and the description say the same thing. + +use crate::draft_hold::{DraftHold, Kind}; +use crate::merge_standing::Standing; +use crate::preview::{Stage, State as Preview}; + +/// What [`line`] reads. +#[derive(Debug, Clone, Default)] +pub struct Inputs<'a> { + pub pr: u64, + pub standing: Option<&'a Standing>, + pub hold: Option<&'a DraftHold>, + pub preview: Option<&'a Preview>, + /// The repository's checks passed on the head (`ci_last` = passed). + pub checks_passed: bool, +} + +fn pr(n: u64) -> String { + if n > 0 { + format!("#{n}") + } else { + "the pull request".into() + } +} + +fn clause(s: &str) -> String { + let s = s.trim().trim_end_matches('.'); + let mut c = s.chars(); + match c.next() { + Some(f) if f.is_uppercase() && !c.clone().next().is_some_and(|n| n.is_uppercase()) => { + f.to_lowercase().collect::() + c.as_str() + } + _ => s.to_string(), + } +} + +/// What the pull request waits on, as "Waiting on: …." (or what happened +/// to it), from the draft hold first (it holds the pull request before +/// anything about merging), then the merge standing. +fn waiting(i: &Inputs) -> Option { + let n = pr(i.pr); + if let Some(h) = i.hold { + let what = h + .reasons + .first() + .map(|r| clause(&r.what)) + .unwrap_or_default(); + return Some(match h.kind { + Kind::Waiting => format!( + "Waiting on: {what} on {n} (CoderHelm checks again by itself and marks it ready)." + ), + Kind::Held => format!("Waiting on: a person, {n} stays a draft because {what}."), + Kind::Failed => { + format!("Waiting on: a person to mark {n} ready (CoderHelm couldn't: {what}).") + } + }); + } + let s = i.standing?; + Some(match s.code.as_str() { + "needs_person_approval" => format!( + "Waiting on: an approving review from a person on {n} (this repo requires one before CoderHelm merges)." + ), + "auto_merge_off" => format!( + "Waiting on: a person on your team to merge {n} (auto-merge is off for this repo)." + ), + "repo_requires_person_review" => format!( + "Waiting on: the branch rules on {n} (they require an approving review from a person, or another rule GitHub enforces)." + ), + "reviewing" => format!("Waiting on: CoderHelm's review of the head of {n}."), + "fixing_review" => format!("Waiting on: CoderHelm's fix round for its review of {n}."), + "review_changes_requested" => format!( + "Waiting on: a person, CoderHelm's review asks for changes on {n} it could not make (listed on the pull request)." + ), + "checks_running" => format!("Waiting on: the checks still running on {n}."), + "checks_failing" => format!("Waiting on: CoderHelm's fix for the failing checks on {n}."), + "conflict" => format!("Waiting on: CoderHelm resolving the conflict on {n}."), + "draft" => format!("Waiting on: {n} leaving draft (its description says why at the top)."), + "merging" => format!("Nothing: {n} is approved and CoderHelm merges it."), + "merged" => format!("Nothing: {n} is merged; CoderHelm watches the deploy."), + "closed" => format!("Nothing: {n} was closed without merging."), + _ => format!("Waiting on: {}", clause(&s.text)) + ".", + }) +} + +/// Whether the pull request is ready for review, and on what: its checks, +/// and its preview when the change has one. None while it is a draft, done +/// or not yet checked. +fn readiness(i: &Inputs) -> Option { + if i.hold.is_some() + || i.standing.is_some_and(|s| { + matches!( + s.code.as_str(), + "merged" | "closed" | "draft" | "checks_failing" | "checks_running" | "conflict" + ) + }) + { + return None; + } + let mut on: Vec<&str> = Vec::new(); + if i.checks_passed { + on.push("checks passed"); + } + match i.preview { + Some(p) if p.stage == Stage::Checked => on.push("preview checked"), + Some(p) if p.stage == Stage::Failed => { + return Some("Not ready for review: the preview checks failed.".into()); + } + Some(p) if p.pending() => { + return Some(format!( + "Not ready for review yet: {}.", + p.phrase().unwrap_or("preview deploying") + )); + } + Some(p) if p.stage == Stage::Blocked => { + return Some(format!( + "Ready for review without a preview: {}.", + clause(if p.why.is_empty() { + "its preview couldn't be started" + } else { + &p.why + }) + )); + } + _ => {} + } + if !i.checks_passed { + return None; + } + Some(format!("Ready for review: {}.", on.join(", "))) +} + +/// The line: "Waiting on: …. Ready for review: …." Empty when nothing is +/// known about the pull request. +pub fn line(i: &Inputs) -> String { + [waiting(i), readiness(i)] + .into_iter() + .flatten() + .collect::>() + .join(" ") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::merge_standing::{decide, Facts}; + + fn approval_standing() -> Standing { + decide( + "org/web", + &Facts { + head: "abc1234def".into(), + reviewer_on: true, + own_verdict: Some(("APPROVE".into(), "abc1234def".into())), + auto_merge: true, + require_human_approval: true, + ..Default::default() + }, + ) + } + + #[test] + fn needs_person_approval_reads_as_one_plain_line() { + let s = approval_standing(); + assert_eq!(s.code, "needs_person_approval"); + let p = Preview { + stage: Stage::Checked, + ..Default::default() + }; + let l = line(&Inputs { + pr: 42, + standing: Some(&s), + hold: None, + preview: Some(&p), + checks_passed: true, + }); + assert_eq!( + l, + "Waiting on: an approving review from a person on #42 (this repo requires one before CoderHelm merges). Ready for review: checks passed, preview checked." + ); + } + + #[test] + fn a_preview_still_deploying_is_not_called_ready() { + let s = approval_standing(); + let p = Preview { + stage: Stage::Deploying, + ..Default::default() + }; + let l = line(&Inputs { + pr: 42, + standing: Some(&s), + preview: Some(&p), + checks_passed: true, + ..Default::default() + }); + assert!( + l.ends_with("Not ready for review yet: preview deploying."), + "{l}" + ); + assert!(!l.contains("Ready for review:")); + } + + #[test] + fn a_draft_hold_comes_first() { + let h = DraftHold::new( + Kind::Waiting, + vec![crate::draft_hold::Reason::new( + "The preview checks are running", + "", + )], + 7, + "", + ) + .unwrap(); + let l = line(&Inputs { + pr: 7, + hold: Some(&h), + checks_passed: true, + ..Default::default() + }); + assert_eq!( + l, + "Waiting on: the preview checks are running on #7 (CoderHelm checks again by itself and marks it ready)." + ); + } + + #[test] + fn nothing_known_says_nothing() { + assert_eq!(line(&Inputs::default()), ""); + } +} diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 8bddd4fe2..a1701c4c2 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -1019,6 +1019,125 @@ pub struct RunMergeStanding { pub link: Option, } +/// One preview or end-to-end check on the head of the run's pull request. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct RunPreviewCheck { + /// The check's name, as GitHub shows it. + #[schema(example = "E2E on preview")] + pub name: String, + /// `passed`, `failed`, `running` or `skipped`. + #[schema(example = "passed")] + pub outcome: String, + /// The check's page on GitHub; empty when it has none. + #[schema(example = "https://github.com/acme/web/actions/runs/1/job/2")] + pub url: String, +} + +/// One page captured on the preview. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct RunPreviewShot { + /// The page's path on the preview. + #[schema(example = "/signup")] + pub page: String, + /// `desktop` or `phone`. + #[schema(example = "desktop")] + pub width: String, + /// The image's address. + #[schema( + example = "https://github.com/acme/web/blob/abc/pr-1/abc/signup-desktop.png?raw=true" + )] + pub src: String, +} + +/// Where the preview of the run's pull request head stands +/// (`common::preview`). +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct RunPreview { + /// `not_needed`, `triggered`, `deploying`, `ready`, `checked`, + /// `failed` or `blocked`. + #[schema(example = "checked")] + pub stage: String, + /// The preview's address; empty when it isn't known. + #[schema(example = "https://pr-1.preview-web.example.com")] + pub url: String, + /// Labels CoderHelm added to start the preview and its end-to-end checks. + #[schema(example = json!(["E2E:signup"]))] + pub labels_added: Vec, + /// The preview and end-to-end checks that cover the change, on the head. + #[schema(example = json!([{"name": "E2E on preview", "outcome": "passed", "url": "https://github.com/acme/web/actions/runs/1/job/2"}]))] + pub checks: Vec, + /// The changed pages captured on the preview, at desktop and phone width. + #[schema(example = json!([{"page": "/signup", "width": "desktop", "src": "https://github.com/acme/web/blob/abc/pr-1/abc/signup-desktop.png?raw=true"}]))] + pub shots: Vec, + /// Why there is no preview or no capture, one line; empty otherwise. + #[schema(example = "")] + pub why: String, + /// The change alters what a person sees in a repository with an + /// end-to-end suite, so it needs an end-to-end spec. + #[schema(example = true)] + pub e2e_required: bool, + /// The change adds or updates an end-to-end spec. + #[schema(example = true)] + pub e2e_covered: bool, +} + +fn preview_of(item: &run_search::Item) -> Option { + let st = item + .get(common::preview::FIELD) + .and_then(|v| v.as_s().ok()) + .and_then(|s| common::preview::State::from_json(s))?; + let word = |v: serde_json::Value| v.as_str().unwrap_or("").to_string(); + Some(RunPreview { + stage: word(serde_json::to_value(st.stage).unwrap_or_default()), + url: st.url, + labels_added: st.labels_added, + checks: st + .checks + .into_iter() + .map(|c| RunPreviewCheck { + name: c.name, + outcome: word(serde_json::to_value(c.outcome).unwrap_or_default()), + url: c.url, + }) + .collect(), + shots: st + .shots + .into_iter() + .map(|s| RunPreviewShot { + page: s.page, + width: s.width, + src: s.src, + }) + .collect(), + why: st.why, + e2e_required: st.e2e_required, + e2e_covered: st.e2e_covered, + }) +} + +/// What the run's pull request waits on, in one line, from what the run +/// records (`common::waiting_line`). None before it has a pull request. +fn waiting_line_of(item: &run_search::Item) -> Option { + let s = |k: &str| item.get(k).and_then(|v| v.as_s().ok()).cloned(); + let pr = item + .get("pr_number") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .filter(|n| *n > 0)?; + let standing = s(common::merge_standing::FIELD) + .and_then(|j| common::merge_standing::Standing::from_json(&j)); + let hold = common::draft_hold::DraftHold::of_item(item); + let preview = s(common::preview::FIELD).and_then(|j| common::preview::State::from_json(&j)); + let line = common::waiting_line::line(&common::waiting_line::Inputs { + pr, + standing: standing.as_ref(), + hold: hold.as_ref(), + preview: preview.as_ref(), + checks_passed: s("ci_last").as_deref() == Some("passed"), + }); + (!line.is_empty()).then_some(line) +} + fn merge_standing_of(item: &run_search::Item) -> Option { let s = item .get(common::merge_standing::FIELD) @@ -1296,6 +1415,18 @@ pub struct Run { /// at the pull request. #[schema(example = json!(null))] pub merge_standing: Option, + /// What the run's pull request waits on, in one plain line, and + /// whether it is ready for review: "Waiting on: an approving review from + /// a person on #12 (this repo requires one before CoderHelm merges). + /// Ready for review: checks passed, preview checked." Built from + /// `merge_standing`, `draft_hold` and `preview`. Null before the run + /// has a pull request. + #[schema(example = json!(null))] + pub waiting_line: Option, + /// Where the preview of the pull request's head stands: its checks, + /// address and captured pages. Null when nothing was recorded. + #[schema(example = json!(null))] + pub preview: Option, /// The CI checks on the head of the run's open pull request, read from /// GitHub (reused for up to a minute). Null when the run has no open /// pull request or GitHub can't be read. @@ -1896,6 +2027,8 @@ fn run_of( }, draft_hold: draft_hold_of(item), merge_standing: merge_standing_of(item), + waiting_line: waiting_line_of(item), + preview: preview_of(item), checks: None, pr_review: None, pr_review_comments: None, diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 2c2dab564..374129aaf 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -2701,11 +2701,14 @@ impl GitHubClient { }), }) .collect(); + // An empty base: a tree of only these entries. + let body = if base_tree.is_empty() { + serde_json::json!({"tree": entries}) + } else { + serde_json::json!({"base_tree": base_tree, "tree": entries}) + }; let t = self - .post( - &format!("{API_BASE}/repos/{owner}/{repo}/git/trees"), - &serde_json::json!({"base_tree": base_tree, "tree": entries}), - ) + .post(&format!("{API_BASE}/repos/{owner}/{repo}/git/trees"), &body) .await?; t["sha"] .as_str() @@ -2730,6 +2733,91 @@ impl GitHubClient { .await } + /// The address each deployment of `sha` reports, as (environment, url): + /// the newest status of each deployment that has one. + pub async fn deployment_urls( + &self, + owner: &str, + repo: &str, + sha: &str, + ) -> Result, Box> { + let deps = self + .get(&format!( + "{API_BASE}/repos/{owner}/{repo}/deployments?sha={sha}&per_page=10" + )) + .await?; + let mut out = Vec::new(); + for d in deps.as_array().into_iter().flatten().take(10) { + let (Some(id), env) = (d["id"].as_u64(), d["environment"].as_str().unwrap_or("")) + else { + continue; + }; + let st = self + .get(&format!( + "{API_BASE}/repos/{owner}/{repo}/deployments/{id}/statuses?per_page=5" + )) + .await?; + if let Some(url) = st + .as_array() + .into_iter() + .flatten() + .filter_map(|s| { + s["environment_url"] + .as_str() + .or_else(|| s["target_url"].as_str()) + }) + .find(|u| u.starts_with("https://")) + { + out.push((env.to_string(), url.to_string())); + } + } + Ok(out) + } + + /// Points a ref outside `refs/heads/` (no workflow starts on it) at + /// `sha`, creating it when it doesn't exist. Only for CoderHelm's own + /// refs, such as the one its pull request screenshots are kept on. + pub async fn set_own_ref( + &self, + owner: &str, + repo: &str, + name: &str, + sha: &str, + ) -> Result<(), Box> { + let name = name.trim_start_matches("refs/"); + if name.starts_with("heads/") || name.starts_with("tags/") || !name.contains('/') { + return Err( + format!("`refs/{name}` is not a ref CoderHelm keeps its own files on").into(), + ); + } + let patched = self + .patch( + &format!("{API_BASE}/repos/{owner}/{repo}/git/refs/{name}"), + &serde_json::json!({"sha": sha, "force": true}), + ) + .await; + if patched.is_ok() { + return Ok(()); + } + self.post( + &format!("{API_BASE}/repos/{owner}/{repo}/git/refs"), + &serde_json::json!({"ref": format!("refs/{name}"), "sha": sha}), + ) + .await + .map(|_| ()) + } + + /// The commit a ref outside `refs/heads/` points at, if it exists. + pub async fn own_ref(&self, owner: &str, repo: &str, name: &str) -> Option { + let name = name.trim_start_matches("refs/"); + self.get(&format!("{API_BASE}/repos/{owner}/{repo}/git/ref/{name}")) + .await + .ok()? + .pointer("/object/sha")? + .as_str() + .map(str::to_string) + } + /// Moves `branch` forward to `to` only if it still points at `lease` and /// `to` contains it: never a force push, so nothing on the branch is /// rewritten. `false` (nothing moved) when someone pushed since; an error diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index 90620c741..8ed0fe504 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -554,6 +554,10 @@ struct RunBits { convention_evidence: String, /// The ticket's page in its tracker, when it is known. ticket_url: String, + /// Where the head's preview stands (`preview_state`). + preview: Option, + /// What the pull request waits on, one line (`waiting_line`). + waiting: String, } impl Gathered { @@ -586,7 +590,7 @@ impl Gathered { title: self.run.title.clone(), url: self.run.ticket_url.clone(), }); - super::description_facts::facts(&super::description_facts::Inputs { + let mut f = super::description_facts::facts(&super::description_facts::Inputs { head: self.head(), body, files: &self.files, @@ -610,7 +614,11 @@ impl Gathered { .into_iter() .collect(), repo_url: self.pr["base"]["repo"]["html_url"].as_str().unwrap_or(""), - }) + }); + let preview = self.run.preview.as_ref().filter(|p| p.head == self.head()); + super::description_facts::with_preview(&mut f, preview); + f.waiting = self.run.waiting.clone(); + f } } @@ -668,11 +676,37 @@ async fn run_bits( convention_note: get(CONVENTION_NOTE), convention_evidence: get(CONVENTION_EVIDENCE), ticket_url, + preview: common::preview::State::from_json(&get(common::preview::FIELD)), + waiting: waiting_of(&item, number), }, run_id, ) } +/// What a run's pull request waits on, from what the run records +/// (`common::waiting_line`). +pub fn waiting_of( + item: &std::collections::HashMap, + number: u64, +) -> String { + let get = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let standing = common::merge_standing::Standing::from_json(&get(common::merge_standing::FIELD)); + let hold = common::draft_hold::DraftHold::of_item(item); + let preview = common::preview::State::from_json(&get(common::preview::FIELD)); + common::waiting_line::line(&common::waiting_line::Inputs { + pr: number, + standing: standing.as_ref(), + hold: hold.as_ref(), + preview: preview.as_ref(), + checks_passed: get("ci_last") == "passed", + }) +} + /// Reads what a build needs: the pull request, its diff, the head's checks /// and the run behind it. async fn gather( @@ -941,6 +975,22 @@ pub fn fresh_base(body: &str) -> String { .join("\n") } +/// [`rebuild`] for a run's pull request, its ticket read from the run: +/// something the description shows changed without a push (the preview's +/// checks, its captured pages). +pub async fn rebuild_run( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + run_id: &str, + owner: &str, + repo: &str, + number: u64, +) -> Reconciled { + let ticket = run_ticket(state, team_id, run_id).await; + rebuild(state, github, team_id, owner, repo, number, &ticket).await +} + /// [`reconcile`] for a run's pull request, its ticket read from the run. pub async fn reconcile_run( state: &WorkerState, diff --git a/services/worker/src/passes/description_facts.rs b/services/worker/src/passes/description_facts.rs index 685613e03..f5755ba3b 100644 --- a/services/worker/src/passes/description_facts.rs +++ b/services/worker/src/passes/description_facts.rs @@ -460,6 +460,34 @@ pub fn facts(i: &Inputs<'_>) -> Facts { f } +/// The head's preview in the facts: its state, its address, the commands +/// that check the changed area, and each check that covers the change and +/// didn't run, as something not verified yet (never as evidence). +pub fn with_preview(f: &mut Facts, preview: Option<&common::preview::State>) { + let Some(p) = preview else { + return; + }; + f.preview = Some(p.clone()); + if p.url.starts_with("https://") { + f.preview_url = p.url.clone(); + } + if !p.how_to_check.trim().is_empty() { + f.how_to_check = p.how_to_check.clone(); + } + for g in common::pr_facts::preview_gaps(f) { + f.unverified.push(Unverified { + what: format!("`{g}` on this head"), + why: "it covers this change and hasn't run yet; CoderHelm starts it on the preview and reads its result".into(), + }); + } + if p.e2e_required && !p.e2e_covered { + f.unverified.push(Unverified { + what: "an end-to-end spec for the change a person sees".into(), + why: "the repository has an end-to-end suite and the change adds no spec to it; CoderHelm writes one".into(), + }); + } +} + /// A description in its final shape, the facts it shows and what the check /// corrected on the way. #[derive(Debug, Clone)] @@ -568,7 +596,14 @@ pub fn shape_for( &earlier, if own.is_empty() { from_title } else { own }, ); - facts.how_to_check = first(&slots.check, &prior.check, check_of(&checked)); + // The commands read from the change itself (its specs and tests) come + // before any written one: a bare suite command never stands for them. + let computed = std::mem::take(&mut facts.how_to_check); + facts.how_to_check = if computed.trim().is_empty() { + first(&slots.check, &prior.check, check_of(&checked)) + } else { + computed + }; let checked = pr_reader::without_sections(&checked, &slots.drop); // 3. The visible part, the generated blocks below it and the steps and // evidence, from the facts; the written text goes in the first fold. diff --git a/services/worker/src/passes/description_goldens/before_rewritten.md b/services/worker/src/passes/description_goldens/before_rewritten.md index 518785b4d..51fe6538e 100644 --- a/services/worker/src/passes/description_goldens/before_rewritten.md +++ b/services/worker/src/passes/description_goldens/before_rewritten.md @@ -50,6 +50,8 @@ Adds the warning rule. Full test evidence +How to check: `npm test -- hero-block-validation`. + Every check on this head: - [`Lint and typecheck`](https://ci.example.com/Lint-and-typecheck): passed - [`Unit tests`](https://ci.example.com/Unit-tests): passed diff --git a/services/worker/src/passes/description_goldens/ui_change.md b/services/worker/src/passes/description_goldens/ui_change.md index 875fe6d47..68cf9b25f 100644 --- a/services/worker/src/passes/description_goldens/ui_change.md +++ b/services/worker/src/passes/description_goldens/ui_change.md @@ -50,6 +50,8 @@ On d78bb24 (head of this PR): Full test evidence +How to check: `npm test -- hero-block-validation`. + Every check on this head: - [`Lint and typecheck`](https://ci.example.com/Lint-and-typecheck): passed - [`Unit tests`](https://ci.example.com/Unit-tests): passed diff --git a/services/worker/src/passes/habits_check.rs b/services/worker/src/passes/habits_check.rs index 08d0ca8ce..9ae18da7e 100644 --- a/services/worker/src/passes/habits_check.rs +++ b/services/worker/src/passes/habits_check.rs @@ -90,6 +90,12 @@ pub struct PrFacts { /// Dependents the plan updates that the branch doesn't touch. #[serde(default)] pub not_updated: Vec, + /// The change alters what a person sees in a repository with an + /// end-to-end suite and adds or updates no spec in it: the line the + /// coder acts on (`common::preview::E2eNeed::instruction`). Empty when + /// no spec is needed or one is there. + #[serde(default)] + pub e2e_missing: String, } /// Why the check didn't give a result. @@ -441,6 +447,54 @@ fn repro_waived(plan: &PlanResult) -> bool { .is_some_and(|d| !d.habits.repro.not_feasible.trim().is_empty()) } +/// The line for a change no changed test proves. +pub const UNPROVEN: &str = "No changed test fails without the change, so nothing proves it. Write a test that fails on the base code and passes with the change (a unit test, or an end-to-end spec when the behaviour is what a person sees in the browser), through code that exists on the base."; + +/// Whether the change's tests prove nothing: test files were changed with +/// the code, and none fails without the change. A new feature's test that +/// can't build without the new code covers it; a bug fix's must show the +/// failure. Not when the plan says no failing test can be written. +pub fn unproven(f: &PrFacts, plan: &PlanResult) -> bool { + if f.tests.is_empty() || repro_waived(plan) { + return false; + } + let proven = f.tests.iter().any(|t| { + t.verdict == Verdict::Proven || (!f.bug && t.verdict == Verdict::FailsBeforeAsserting) + }); + !proven +} + +/// The progress note for the check's result: "passed" only when a changed +/// test proves the change (or none needs to) and nothing blocks. +pub fn verdict_note(f: &PrFacts, plan: &PlanResult, blocking: &[String]) -> String { + let proven = f + .tests + .iter() + .filter(|t| t.verdict == Verdict::Proven) + .count(); + let counts = format!( + "{proven} of {} changed test file(s) fail without the change and pass with it", + f.tests.len() + ); + if unproven(f, plan) { + let why = if f.tests.iter().all(|t| t.verdict == Verdict::NotRun) { + "no test could be run both ways here" + } else { + "nothing proves the change" + }; + return format!("Tests and scope check not passed: {counts}; {why}. Listed under Open items until a test that fails without the change is added."); + } + if !blocking.is_empty() { + return format!( + "Tests and scope check not passed: {counts}; {} item(s) open", + blocking.len() + ); + } + format!( + "Tests and scope check passed: {counts}; no file changed outside the plan without a reason" + ) +} + /// What the coder must fix, one line each. Empty when the change holds. pub fn blocking(f: &PrFacts, plan: &PlanResult) -> Vec { let mut out = Vec::new(); @@ -466,6 +520,14 @@ pub fn blocking(f: &PrFacts, plan: &PlanResult) -> Vec { _ => {} } } + // Nothing proves the change: changed tests ran both ways and not one + // fails without it. A passing count of zero is never a pass. + if unproven(f, plan) && f.tests.iter().any(|t| t.verdict != Verdict::NotRun) { + out.push(UNPROVEN.to_string()); + } + if !f.e2e_missing.is_empty() { + out.push(f.e2e_missing.clone()); + } if f.bug && f.tests.is_empty() && !repro_waived(plan) && f.no_tests.contains("no test file") { out.push("This is a bug fix and the change has no test that fails without it. Add the test that reproduces the reported failure (it must fail on the base code and pass with the fix).".to_string()); } @@ -497,7 +559,11 @@ pub fn fix_feedback(lines: &[String]) -> String { /// What is still open after the fix rounds, for Open items. pub fn open_findings(f: &PrFacts, plan: &PlanResult) -> Vec { - blocking(f, plan) + let mut lines = blocking(f, plan); + if unproven(f, plan) && !lines.iter().any(|l| l == UNPROVEN) { + lines.push(UNPROVEN.to_string()); + } + lines .into_iter() .map(|l| { let (point, settle) = if l.contains("no task of the plan") { @@ -510,6 +576,11 @@ pub fn open_findings(f: &PrFacts, plan: &PlanResult) -> Vec { "Dependent not updated", "CoderHelm updates it in its next round on this pull request.", ) + } else if l.contains("no end-to-end spec there covers it") { + ( + "No end-to-end test for a visible change", + "CoderHelm writes the spec in its next round on this pull request and runs it on the preview.", + ) } else { ( "Test doesn't prove the change", @@ -923,6 +994,31 @@ pub async fn gate( outcome } +/// The missing end-to-end spec's line for a change a person sees in the +/// browser, read from the changed paths and the repository's tree (its +/// e2e suite). Empty when none is needed, one is there, or the tree +/// can't be read. +async fn e2e_missing(w: &super::proof::Work<'_>, paths: &[String]) -> String { + if !paths.iter().any(|p| common::preview::is_user_visible(p)) { + return String::new(); + } + let tree: Vec = match w + .github + .get_tree(&w.msg.repo_owner, &w.msg.repo_name, w.branch) + .await + { + Ok(t) => t.into_iter().map(|e| e.path).collect(), + Err(e) => { + warn!(run_id = w.run_id, error = %e, "Could not read the tree for the e2e suite"); + return String::new(); + } + }; + let suite = common::preview::e2e_suite(&tree); + common::preview::e2e_need(paths, suite.as_ref()) + .instruction() + .unwrap_or_default() +} + /// A bench for a step with no time for the sandbox: nothing runs, and each /// test says so. struct NoTime; @@ -986,7 +1082,7 @@ async fn check_and_fix( branch: w.branch, }; let bench: &dyn Bench = if short { &NoTime } else { &sandbox }; - let facts = check_once( + let mut facts = check_once( bench, &diff, w.plan, @@ -995,6 +1091,7 @@ async fn check_and_fix( &evidence.notes, ) .await; + facts.e2e_missing = e2e_missing(w, &paths).await; let blocking = blocking(&facts, w.plan); info!( run_id = w.run_id, @@ -1004,20 +1101,12 @@ async fn check_and_fix( rounds = w.ledger.update(|l| l.habits.rounds), "Check of the change against the plan's habits complete" ); - let proven = facts - .tests - .iter() - .filter(|t| t.verdict == Verdict::Proven) - .count(); if blocking.is_empty() { super::add_progress_note( w.state, &w.msg.team_id, w.run_id, - &format!( - "Tests and scope check passed: {proven} of {} changed test file(s) fail without the change and pass with it; no file changed outside the plan without a reason", - facts.tests.len() - ), + &verdict_note(&facts, w.plan, &blocking), ) .await; return Ok(Some(facts)); @@ -1212,6 +1301,73 @@ mod tests { assert_eq!(runs[2], run(2, "No test files found")); } + /// A run's check once read "passed: 0 of 6 changed test file(s) fail + /// without the change": six tests, none proving anything, called a + /// pass. Zero is never a pass. + #[tokio::test] + async fn six_changed_tests_none_failing_without_the_change_is_not_passed() { + let p = plan(TASKS, TicketIntent::Bug, Habits::default()); + let six: Vec = (1..=6).map(|i| format!("src/cart/t{i}.test.ts")).collect(); + let mut paths: Vec<&str> = six.iter().map(String::as_str).collect(); + paths.push("src/cart/total.ts"); + let bench = Fake(Ok(Runs { + with: vec![run(0, ""); 6], + without: vec![run(0, ""); 6], + })); + let f = check_once(&bench, &diff(&paths), &p, "acme/shop-api", &[], "").await; + assert_eq!(f.tests.len(), 6); + assert!(unproven(&f, &p)); + let b = blocking(&f, &p); + assert!(b.contains(&UNPROVEN.to_string()), "{b:?}"); + let note = verdict_note(&f, &p, &b); + assert!( + note.starts_with("Tests and scope check not passed: 0 of 6"), + "{note}" + ); + assert!(!note.contains("check passed")); + // A feature's own tests too: the gap is closed by writing one that + // fails without the change. + let feature = plan(TASKS, TicketIntent::Feature, Habits::default()); + assert!(blocking(&f, &feature).contains(&UNPROVEN.to_string())); + } + + #[tokio::test] + async fn tests_that_could_not_run_both_ways_are_not_a_pass_either() { + let p = plan(TASKS, TicketIntent::Bug, Habits::default()); + let bench = Fake(Err("the sandbox gave no result".into())); + let d = diff(&["src/cart/total.ts", "src/cart/total.test.ts"]); + let f = check_once(&bench, &d, &p, "acme/shop-api", &[], "").await; + // No fix round can make the sandbox run: open, never "passed". + assert!(!blocking(&f, &p).contains(&UNPROVEN.to_string())); + assert!(verdict_note(&f, &p, &[]).starts_with("Tests and scope check not passed")); + assert!(open_findings(&f, &p) + .iter() + .any(|o| o.point == "Test doesn't prove the change")); + } + + #[tokio::test] + async fn a_visible_change_with_no_e2e_spec_goes_back_to_the_coder() { + let p = plan(TASKS, TicketIntent::Feature, Habits::default()); + let mut f = PrFacts::default(); + let suite = common::preview::Suite { + dir: "e2e".into(), + runner: "playwright".into(), + }; + f.e2e_missing = common::preview::e2e_need( + &["web/src/components/cart/total.tsx".to_string()], + Some(&suite), + ) + .instruction() + .unwrap(); + let b = blocking(&f, &p); + assert_eq!(b.len(), 1); + assert!(b[0].contains("no end-to-end spec there covers it")); + assert_eq!( + open_findings(&f, &p)[0].point, + "No end-to-end test for a visible change" + ); + } + #[tokio::test] async fn a_test_that_passes_either_way_goes_back_to_the_coder() { let p = plan(TASKS, TicketIntent::Bug, Habits::default()); @@ -1223,8 +1379,9 @@ mod tests { let f = check_once(&bench, &d, &p, "acme/shop-api", &[], "").await; assert_eq!(f.tests[0].verdict, Verdict::PassesEitherWay); let b = blocking(&f, &p); - assert_eq!(b.len(), 1); + assert_eq!(b.len(), 2); assert!(b[0].contains("passes with the change taken out")); + assert_eq!(b[1], UNPROVEN); assert!(fix_feedback(&b).contains("Do not delete or skip a test")); let open = open_findings(&f, &p); assert_eq!(open[0].point, "Test doesn't prove the change"); diff --git a/services/worker/src/passes/host_steps_readers.rs b/services/worker/src/passes/host_steps_readers.rs index a66e8b966..980410687 100644 --- a/services/worker/src/passes/host_steps_readers.rs +++ b/services/worker/src/passes/host_steps_readers.rs @@ -66,6 +66,7 @@ mod tests { ("common/src/setup/facts.rs", "gathers the facts setup/ai.rs reads (routed)"), ("common/src/skill_apply.rs", "fits team standards into a reader's prompt; each reader is routed"), ("common/src/tool_registry.rs", "tool risk table"), + ("common/src/preview.rs", "names the conventions an end-to-end spec follows in a line the coder (routed) reads; runs nothing"), ("common/src/agent_policy/registry.rs", "tool risk table"), ("common/src/agent_policy/model.rs", "records an admin's accepted sandbox host"), ("common/src/agent_policy/sandbox.rs", "suggests sandbox hosts from AGENTS.md for an admin to accept; runs nothing"), diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index ac6edb113..75912a68f 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -212,14 +212,17 @@ pub async fn run( repo_instructions }; let instructions_block = super::format_instructions_block(trimmed_instructions); - let tests_block = + let tests_block = format!( + "{}{}", if super::review_pr::tests_required(state, &msg.team_id, &msg.repo_owner, &msg.repo_name) .await { super::TESTS_REQUIRED_CODER_SECTION } else { "" - }; + }, + super::E2E_CODER_SECTION + ); // The team's instructions are never trimmed: they are its working rules. // What outcomes taught the coder here (lessons naming what people // changed, and the prompt variant its bandit picked) sits with the @@ -229,7 +232,7 @@ pub async fn run( &msg.repo_name, &format!("{rules_block}{instructions_block}{}", msg.coder_learning), &msg.team_instructions, - tests_block, + &tests_block, ); let feedback_section = match review_feedback { diff --git a/services/worker/src/passes/incidents/aj_coder_habits.rs b/services/worker/src/passes/incidents/aj_coder_habits.rs index 3473639ab..8c64b77b0 100644 --- a/services/worker/src/passes/incidents/aj_coder_habits.rs +++ b/services/worker/src/passes/incidents/aj_coder_habits.rs @@ -192,7 +192,10 @@ async fn a_test_that_passes_without_the_fix_and_a_stray_file_go_back_to_the_code let f = habits_check::check_once(&both_pass, &first, &p, OWN, &[], "Evidence: none needed").await; let blocking = habits_check::blocking(&f, &p); - assert_eq!(blocking.len(), 3, "{blocking:?}"); + // Plus: no changed test fails without the change, so nothing proves + // it (`habits_check::UNPROVEN`): never a pass. + assert_eq!(blocking.len(), 4, "{blocking:?}"); + assert!(blocking.contains(&habits_check::UNPROVEN.to_string())); let feedback = habits_check::fix_feedback(&blocking); assert!(feedback.contains("`src/cart/total.test.ts` passes with the change taken out")); assert!(feedback.contains("`src/utils/format.ts` was changed and is no task of the plan")); diff --git a/services/worker/src/passes/incidents/ax_github_budget.rs b/services/worker/src/passes/incidents/ax_github_budget.rs index 652ad845e..5d76a354a 100644 --- a/services/worker/src/passes/incidents/ax_github_budget.rs +++ b/services/worker/src/passes/incidents/ax_github_budget.rs @@ -384,7 +384,7 @@ fn the_watch_costs_nothing_while_nothing_changed_and_picks_the_round_back_up() { ); assert!( look.find("resume_after_limit(").unwrap() - < look.find("decide(&c.status, &seen, &c.marks)").unwrap() + < look.find("decide_all(&c.status, &seen, &c.marks)").unwrap() ); // Once per round: claimed against when that round stopped. let done = Marks { diff --git a/services/worker/src/passes/incidents/bu_web_change_unchecked.rs b/services/worker/src/passes/incidents/bu_web_change_unchecked.rs new file mode 100644 index 000000000..4949b53e7 --- /dev/null +++ b/services/worker/src/passes/incidents/bu_web_change_unchecked.rs @@ -0,0 +1,270 @@ +//! bu. A run opened a pull request on a web app and called it ready with +//! nothing looked at in a browser. The repository's preview deploy and its +//! preview end-to-end checks skip drafts and run on a label; the +//! description was written while the pull request was a draft, so every +//! deploy and end-to-end check on the head read "skipped (its conditions +//! left this PR out)", next to passing unit tests. It said "No screenshot: +//! CoderHelm had no runnable preview", gave `npm test` as the way to check +//! it, and the tests check passed on "0 of 6 changed test files fail +//! without the change". The run page only said `needs_person_approval`. +//! +//! Guarantee, all read from the repository and the run's records: +//! - the preview and end-to-end jobs that cover the change, and the labels +//! that start them, come from the workflow files (`common::preview`); +//! a draft is marked ready for the checks that skip drafts and is ready +//! only once they pass (`ready::decide`); +//! - a skipped check that covers the change is a gap CoderHelm closes, +//! never evidence (`pr_facts`); +//! - the changed pages are captured at desktop and phone width once the +//! preview is up (`preview::capture`), and "How to check" names the +//! changed specs and tests; +//! - zero tests failing without the change is never a pass +//! (`habits_check::unproven`); +//! - the run page and the description say in one line what the pull +//! request waits on (`common::waiting_line`). + +use common::pr_facts::{CheckFact, Facts, FileChange, Outcome}; +use common::preview::{self as pv, Stage}; + +const WORKFLOW: &str = r#" +name: Deploy Preview +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review, labeled, closed] + branches: [main] +jobs: + deploy_preview: + name: Deploy Preview App + if: >- + github.event.action != 'closed' && + github.event.pull_request.draft != true && + (github.event.action != 'labeled' || + github.event.label.name == 'CI:PREVIEW' || + github.event.label.name == 'CI:E2E' || + startsWith(github.event.label.name, 'E2E:')) + runs-on: ubuntu-latest + steps: [{run: deploy}] + e2e_preview: + name: E2E on preview + needs: deploy_preview + if: >- + (contains(github.event.pull_request.labels.*.name, 'CI:E2E') || + contains(join(github.event.pull_request.labels.*.name, ','), 'E2E:')) && + !contains(github.event.pull_request.labels.*.name, 'CI:STAGING') + runs-on: ubuntu-latest + steps: [{run: e2e}] + cleanup: + name: Cleanup PR Preview + if: github.event.action == 'closed' + runs-on: ubuntu-latest + steps: [{run: bye}] +"#; + +fn s(v: &[&str]) -> Vec { + v.iter().map(|x| x.to_string()).collect() +} + +fn changed() -> Vec { + s(&[ + "apps/web/src/components/signup/use-signup-form.ts", + "apps/web/src/lib/validation.ts", + "apps/web/src/test/lib/validation.test.ts", + ]) +} + +#[test] +fn the_workflows_say_which_labels_start_the_preview_and_its_e2e() { + let w = vec![( + ".github/workflows/preview.yml".to_string(), + WORKFLOW.to_string(), + )]; + let c = changed(); + let labels = s(&[ + "CI:PREVIEW", + "CI:E2E", + "CI:STAGING", + "E2E:signup", + "E2E:billing", + ]); + let p = pv::plan(&pv::PlanInput { + workflows: &w, + changed: &c, + base: "main", + repo_labels: &labels, + on_pr: &[], + preferred: &[], + areas: &[], + }); + assert_eq!( + p.add, + s(&["E2E:signup"]), + "the change's own area, never staging" + ); + assert_eq!(p.draft_gated, s(&["Deploy Preview App", "E2E on preview"])); + // The test map names the area when the repository keeps one. + let areas = s(&["signup"]); + let mapped = pv::plan(&pv::PlanInput { + workflows: &w, + changed: &c, + base: "main", + repo_labels: &s(&["CI:E2E"]), + on_pr: &[], + preferred: &[], + areas: &areas, + }); + assert_eq!(mapped.add, s(&["E2E:signup"])); +} + +fn facts(preview: Option) -> Facts { + Facts { + head: "abc1234def".into(), + files: changed() + .into_iter() + .map(|path| FileChange { + path, + status: "modified".into(), + previous: String::new(), + changed: 4, + }) + .collect(), + files_complete: true, + checks_read: true, + checks: vec![ + CheckFact { + name: "Unit tests".into(), + outcome: Outcome::Passed, + url: String::new(), + }, + CheckFact { + name: "Deploy Preview App".into(), + outcome: Outcome::DidNotRun, + url: String::new(), + }, + CheckFact { + name: "E2E on preview".into(), + outcome: Outcome::DidNotRun, + url: String::new(), + }, + CheckFact { + name: "Deploy to Staging".into(), + outcome: Outcome::DidNotRun, + url: String::new(), + }, + ], + preview, + ..Default::default() + } +} + +#[test] +fn a_skipped_preview_check_is_a_gap_never_evidence() { + let f = facts(None); + assert_eq!( + common::pr_facts::preview_gaps(&f), + s(&["Deploy Preview App", "E2E on preview"]) + ); + let b = common::pr_facts::body_of(&f, &[]); + assert!(b.evidence.contains(&format!( + "`Deploy Preview App`: {}", + common::pr_facts::GAP_WORDS + ))); + assert!(!b + .evidence + .contains("`E2E on preview`: skipped (its conditions left this PR out)")); + // A staging deploy is not this pull request's to start. + assert!(b + .evidence + .contains("`Deploy to Staging`: skipped (its conditions left this PR out)")); +} + +#[test] +fn the_pages_are_shown_at_both_widths_once_the_preview_is_checked() { + let st = pv::State { + head: "abc1234def".into(), + stage: Stage::Checked, + url: "https://pr-1.preview-web.example.com".into(), + shots: vec![ + pv::Shot { + page: "/signup".into(), + width: "desktop".into(), + src: "https://github.com/org/web/blob/c1/pr-1/abc/signup-desktop.png?raw=true" + .into(), + }, + pv::Shot { + page: "/signup".into(), + width: "phone".into(), + src: "https://github.com/org/web/blob/c1/pr-1/abc/signup-phone.png?raw=true".into(), + }, + ], + ..Default::default() + }; + let b = common::pr_facts::body_of(&facts(Some(st)), &[]); + match b.screens { + Some(common::pr_body::Screens::Pages(p)) => { + assert_eq!(p.len(), 1); + assert!(p[0].1.ends_with("signup-desktop.png?raw=true")); + assert!(p[0].2.ends_with("signup-phone.png?raw=true")); + } + other => panic!("pages expected, got {other:?}"), + } + assert!(b + .evidence + .contains("Preview: https://pr-1.preview-web.example.com")); + // Still deploying: it says so, never "no runnable preview". + let deploying = pv::State { + head: "abc1234def".into(), + stage: Stage::Deploying, + ..Default::default() + }; + let b = common::pr_facts::body_of(&facts(Some(deploying)), &[]); + let Some(common::pr_body::Screens::Missing(why)) = b.screens else { + panic!("a line expected"); + }; + assert!(why.contains("still deploying"), "{why}"); +} + +#[test] +fn how_to_check_is_the_changed_specs_and_tests() { + let suite = pv::Suite { + dir: "apps/web/e2e".into(), + runner: "playwright".into(), + }; + let mut c = changed(); + c.push("apps/web/e2e/tests/signup.spec.ts".into()); + let how = pv::how_to_check(&c, Some(&suite), "npx vitest run"); + assert!( + how.contains("npx playwright test tests/signup.spec.ts"), + "{how}" + ); + assert!(how.contains("apps/web/src/test/lib/validation.test.ts")); +} + +#[test] +fn the_run_page_says_what_it_waits_on_in_one_line() { + let standing = common::merge_standing::decide( + "org/web", + &common::merge_standing::Facts { + head: "abc1234def".into(), + reviewer_on: true, + own_verdict: Some(("APPROVE".into(), "abc1234def".into())), + auto_merge: true, + require_human_approval: true, + ..Default::default() + }, + ); + let preview = pv::State { + stage: Stage::Checked, + ..Default::default() + }; + let line = common::waiting_line::line(&common::waiting_line::Inputs { + pr: 42, + standing: Some(&standing), + hold: None, + preview: Some(&preview), + checks_passed: true, + }); + assert_eq!( + line, + "Waiting on: an approving review from a person on #42 (this repo requires one before CoderHelm merges). Ready for review: checks passed, preview checked." + ); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 0849ab389..5148e3b6f 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -59,6 +59,7 @@ mod bq_upstream_read_not_guessed; mod br_description_writer_upgrade; mod bs_cut_plan_revision; mod bt_proof_answer_closes; +mod bu_web_change_unchecked; mod c_codegen_egress; mod d_echoed_markers; mod e_large_generated_output; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 60ce9fec3..346b52a78 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1342,6 +1342,7 @@ mod pr_holder; pub mod pr_outcomes; mod pr_risk; pub mod pr_watch; +pub mod preview; mod proof; pub mod quarantine; pub mod quarantine_work; @@ -9969,6 +9970,19 @@ config values, dependency bumps or generated files.\n\ - Never weaken, skip, or delete an existing test to make it pass; fix the code, or update the \ test only when the behavior change is intended.\n"; +/// Coding-agent instructions in every repository: a change a person sees in +/// the browser, in a repository with an end-to-end suite, carries a spec. +/// The rule is enforced in code (the Tests and scope check, the reviewer's +/// required finding and the ready decision, all from +/// `common::preview::e2e_need`); this tells the coder before it is asked. +pub(crate) const E2E_CODER_SECTION: &str = "\n\n## End-to-end tests for what a person sees\n\ +When the change alters what a person sees or does in the browser (a page, a form, a message, a \ +flow) and the repository has an end-to-end suite (a Playwright or Cypress config), write or update \ +an end-to-end spec in that suite for the new behaviour, in this same branch. Follow the suite's own \ +conventions: its folder, page objects and fixtures, tags and area labels, its test map, and the \ +AGENTS.md / CLAUDE.md files next to it. The spec must fail without the change and pass with it; \ +CoderHelm runs it on the pull request's preview. Unit tests alone don't cover a change a person sees.\n"; + pub(crate) fn attr_s(val: &str) -> aws_sdk_dynamodb::types::AttributeValue { aws_sdk_dynamodb::types::AttributeValue::S(val.to_string()) } diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 61eff2771..40e1dedf3 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -289,6 +289,16 @@ pub async fn run( } else { "" }; + // Every repository: a change a person sees, where the repository has an + // end-to-end suite, plans its spec (enforced after the build by + // `common::preview::e2e_need`). + let tests_block = format!( + "{tests_block}\n\n## End-to-end tests\n\ + When the change alters what a person sees in the browser and the repository has an \ + end-to-end suite, tasks.md MUST include a task that writes or updates the end-to-end spec \ + for the new behaviour, at its exact path in the suite, following the suite's conventions \ + (page objects, tags, area labels, test map)." + ); let system = format!( "You are the planning engineer for the {owner}/{repo} repository. {stance}\ Research the codebase using the provided tools, then generate an implementation plan \ diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 1b8dbcfd0..3fe4de8b2 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -86,6 +86,11 @@ pub struct Seen { pub reviewer_on: bool, /// CoderHelm's latest review verdict and the commit it is on. pub own_verdict: Option<(String, String)>, + /// The head's preview isn't settled (`preview::settled`): its checks + /// are to be started, read or its pages captured. Decided per look, + /// never kept in the probe. + #[serde(skip)] + pub preview_due: bool, } /// What the last look read from GitHub, kept on the run (`watch_probe`): @@ -191,6 +196,11 @@ pub enum Act { /// Run again the round GitHub's rate limit ended (the round's record, /// by when it stopped): `resume::resume_limit_ended`. ResumeRound(String), + /// Start, read or capture the head's preview (`preview::advance`, + /// `preview::capture`): a skipped preview or end-to-end check that + /// covers the change is closed by CoderHelm, also on pull requests + /// whose run finished before this existed. + Preview, } impl Act { @@ -204,6 +214,9 @@ impl Act { Act::FixFindings => Some((Marks::FINDINGS, seen.head.clone())), Act::WatchDeploy => Some((Marks::DEPLOY, seen.merge_sha.clone())), Act::ResumeRound(at) => Some((Marks::LIMIT, at.clone())), + // Done on every look until the head's preview is settled; each + // step of it is idempotent per head (`preview_state`). + Act::Preview => None, } } } @@ -268,6 +281,35 @@ pub fn decide(status: &str, seen: &Seen, marks: &Marks) -> Act { } } +/// [`decide`], then the preview when nothing else is needed: a conflict, +/// red checks and the review come first, the preview never waits behind +/// nothing. +pub fn decide_all(status: &str, seen: &Seen, marks: &Marks) -> Act { + match decide(status, seen, marks) { + Act::Nothing if watched(status) && seen.open && !seen.merged && seen.preview_due => { + Act::Preview + } + a => a, + } +} + +/// Whether the head's preview needs a look: the change's recorded state is +/// of another head or not settled. A look that read nothing new (`fresh` +/// false) leaves a pending preview to the next change on the pull request. +pub fn preview_due(stored: &str, head: &str, fresh: bool) -> bool { + if head.is_empty() { + return false; + } + match common::preview::State::from_json(stored) { + None => true, + Some(st) if st.head != head => true, + Some(st) if super::preview::settled(&st, head) => false, + // Ready: its pages are captured now, whatever else changed. + Some(st) if st.stage == common::preview::Stage::Ready => true, + Some(_) => fresh, + } +} + /// 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, @@ -315,6 +357,26 @@ pub struct Candidate { pub writer: String, /// When the run last changed (RFC 3339). pub updated_at: String, + /// The head's preview as last recorded (`preview_state`), "" when none. + pub preview: String, + /// Why the pull request is still a draft, as recorded (`draft_hold`). + pub hold: Option, + /// The repository's checks passed on the head (`ci_last`). + pub checks_passed: bool, +} + +impl Candidate { + /// What the pull request waits on with `standing` (`waiting_line`). + pub fn waiting_line(&self, standing: Option<&Standing>) -> String { + let preview = common::preview::State::from_json(&self.preview); + common::waiting_line::line(&common::waiting_line::Inputs { + pr: self.pr, + standing, + hold: self.hold.as_ref(), + preview: preview.as_ref(), + checks_passed: self.checks_passed, + }) + } } pub fn candidate_of(item: &HashMap) -> Option { @@ -358,6 +420,9 @@ pub fn candidate_of(item: &HashMap) -> Option .unwrap_or_default(), writer: s(DESCRIPTION_WRITER), updated_at: s("updated_at"), + preview: s(common::preview::FIELD), + hold: common::draft_hold::DraftHold::of_item(item), + checks_passed: s("ci_last") == "passed", }; (pr > 0 && c.installation_id > 0 && !c.team_id.is_empty() && !c.run_id.is_empty()).then_some(c) } @@ -614,6 +679,7 @@ async fn perform( .await; match act { Act::Nothing => Performed::Settled, + Act::Preview => preview(state, github, c).await, Act::ResolveConflict => super::resume::start_conflict_round( state, &c.team_id, @@ -700,6 +766,58 @@ async fn perform( } } +/// Captures at most one preview per process at a time: a capture runs a +/// sandbox build for minutes, and a sweep looks at many pull requests. +static CAPTURING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Moves the head's preview on: starts its checks, reads them, captures +/// the pages once it is up. When what the description or the ready +/// decision reads changed, the description is rebuilt and the ready +/// decision asked again. +async fn preview(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> Performed { + let Ok(pr) = github.get_pull_request(&c.owner, &c.repo, c.pr).await else { + return Performed::NotStarted; + }; + let p = super::preview::Pr { + team_id: &c.team_id, + run_id: &c.run_id, + owner: &c.owner, + repo: &c.repo, + number: c.pr, + }; + let before = common::preview::State::from_json(&c.preview); + let Some(mut st) = super::preview::advance(state, github, p, &pr).await else { + return Performed::NotStarted; + }; + if st.stage == common::preview::Stage::Ready + && !CAPTURING.swap(true, std::sync::atomic::Ordering::SeqCst) + { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(9 * 60); + super::preview::capture(state, github, p, &mut st, Some(deadline)).await; + CAPTURING.store(false, std::sync::atomic::Ordering::SeqCst); + } + let moved = before.as_ref().is_none_or(|b| { + b.head != st.head || b.stage != st.stage || b.shots != st.shots || b.checks != st.checks + }); + if moved { + info!(run_id = %c.run_id, pr = c.pr, stage = ?st.stage, "PR watch: the preview moved; the description follows"); + super::description::rebuild_run( + state, github, &c.team_id, &c.run_id, &c.owner, &c.repo, c.pr, + ) + .await; + super::ready::request_for( + state, + &c.team_id, + c.installation_id, + &c.owner, + &c.repo, + c.pr, + ) + .await; + } + Performed::Settled +} + /// Asks for CoderHelm's review of the head. async fn review_head(state: &WorkerState, c: &Candidate, head: &str) -> Performed { (!matches!( @@ -831,10 +949,14 @@ pub async fn look(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> (seen, validators) } }; + let mut seen = seen; + seen.preview_due = seen.open && preview_due(&c.preview, &seen.head, kept.is_none()); let mut act = resume_after_limit(&c.status, &seen, &c.marks, &c.limit_ended) - .unwrap_or_else(|| decide(&c.status, &seen, &c.marks)); + .unwrap_or_else(|| decide_all(&c.status, &seen, &c.marks)); let mut performed = Performed::NotStarted; - if let Some((field, value)) = act.claim(&seen) { + if act == Act::Preview { + performed = perform(state, github, c, &seen, &act).await; + } else if let Some((field, value)) = act.claim(&seen) { if !claim(state, c, field, &value).await { act = Act::Nothing; } else { @@ -863,6 +985,7 @@ pub async fn look(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> kept.as_ref().map(|p| p.human_approved), ) .await; + let open = seen.open; let probe = match kept { // Unchanged: the probe stands as it is. Some(_) => None, @@ -878,7 +1001,17 @@ pub async fn look(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> ) } }; + // The description's top line says what the pull request waits on: + // rebuilt when that changed. + let was = c.waiting_line(Standing::from_json(&c.standing).as_ref()); + let now = c.waiting_line(Some(&s)); record_look(state, c, Some(&s), probe.as_deref()).await; + if was != now && open && act != Act::Preview { + super::description::rebuild_run( + state, github, &c.team_id, &c.run_id, &c.owner, &c.repo, c.pr, + ) + .await; + } act } @@ -1176,6 +1309,51 @@ mod tests { } } + /// A finished run's pull request whose preview checks were skipped + /// (its run ended before CoderHelm started previews) is picked back + /// up: once nothing else is needed, the watch starts its preview, + /// reads it and captures its pages, on every look until it is settled. + #[test] + fn an_unchecked_preview_is_picked_up_after_the_run_ended() { + let mut seen = open(); + seen.preview_due = preview_due("", &seen.head, true); + assert!(seen.preview_due); + assert_eq!( + decide_all("completed", &seen, &Marks::default()), + Act::Preview + ); + // A conflict or red checks come first. + let mut red = seen.clone(); + red.failing = vec!["test".into()]; + assert!(matches!( + decide_all("completed", &red, &Marks::default()), + Act::FixCi(_) + )); + // Settled on this head: nothing; a new head: again. + let done = common::preview::State { + head: seen.head.clone(), + stage: common::preview::Stage::Checked, + ..Default::default() + } + .to_json(); + assert!(!preview_due(&done, &seen.head, true)); + assert!(preview_due(&done, "another", false)); + // Pending and nothing new on the pull request: the next change. + let pending = common::preview::State { + head: seen.head.clone(), + stage: common::preview::Stage::Deploying, + ..Default::default() + } + .to_json(); + assert!(!preview_due(&pending, &seen.head, false)); + assert!(preview_due(&pending, &seen.head, true)); + // Never for a run still in flight. + assert_eq!( + decide_all("running", &seen, &Marks::default()), + Act::Nothing + ); + } + #[test] fn a_settled_pull_request_needs_nothing() { assert_eq!( diff --git a/services/worker/src/passes/preview.rs b/services/worker/src/passes/preview.rs new file mode 100644 index 000000000..3b7fe5a81 --- /dev/null +++ b/services/worker/src/passes/preview.rs @@ -0,0 +1,677 @@ +//! The preview of a pull request's head, checked the way a person checks a +//! web change: start the repository's own preview deploy and end-to-end +//! checks on it, wait for them, then capture the changed pages at desktop +//! and phone width and put them in the description. +//! +//! The rules are `common::preview`'s, read from the repository itself; +//! this module reads GitHub, adds what starts the checks, runs the capture +//! in the sandbox, keeps the images on a ref of CoderHelm's own and records +//! the [`State`] on the run (`preview_state`), where the description, the +//! ready decision, the run page and the pull request watch read it. +//! +//! - [`advance`] is called by the pull request watch on every look at a +//! finished run's open pull request (and so for runs that finished +//! before this existed), and by the ready decision: it adds the labels +//! the workflows need (only labels the team's settings allow, never a +//! shared environment's), starts a workflow that counts labels only from +//! a push with an empty commit on CoderHelm's own branch, and reads the +//! covering checks' results and the preview's address. +//! - [`capture`] runs once the preview is up and its end-to-end checks +//! passed, in a step of the watch: a failed capture says why in one line +//! and is never retried into a pass. + +use aws_sdk_dynamodb::types::AttributeValue; +use base64::Engine as _; +use common::preview::{self as pv, CheckResult, Outcome, Shot, Stage, State}; +use tracing::{info, warn}; + +use super::attr_s; +use crate::clients::github::{GitEntry, GitHubClient}; +use crate::WorkerState; + +/// The ref the screenshots are kept on: outside `refs/heads/`, so no +/// workflow starts on it and no branch list shows it. +pub const SHOTS_REF: &str = "refs/coderhelm/screenshots"; +/// Workflow files read at most. +const MAX_WORKFLOWS: usize = 40; + +/// The pull request the preview is of. +#[derive(Debug, Clone, Copy)] +pub struct Pr<'a> { + pub team_id: &'a str, + pub run_id: &'a str, + pub owner: &'a str, + pub repo: &'a str, + pub number: u64, +} + +/// The state recorded on the run. +pub async fn load(state: &WorkerState, team_id: &str, run_id: &str) -> Option { + if run_id.is_empty() { + return None; + } + 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", pv::FIELD) + .send() + .await + .ok()? + .item?; + State::from_json(item.get(pv::FIELD)?.as_s().ok()?) +} + +async fn save(state: &WorkerState, p: Pr<'_>, st: &State) { + if p.run_id.is_empty() { + return; + } + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(p.team_id)) + .key("run_id", attr_s(p.run_id)) + .update_expression("SET #f = :v") + .condition_expression("attribute_exists(run_id)") + .expression_attribute_names("#f", pv::FIELD) + .expression_attribute_values(":v", AttributeValue::S(st.to_json())) + .send() + .await + { + warn!(run_id = p.run_id, error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "Could not record the preview's state"); + } +} + +/// A state that needs nothing more on its head. +pub fn settled(st: &State, head: &str) -> bool { + st.head == head + && matches!( + st.stage, + Stage::NotNeeded | Stage::Checked | Stage::Blocked | Stage::Failed + ) +} + +fn outcome_of(run: &serde_json::Value) -> Outcome { + match (run["status"].as_str(), run["conclusion"].as_str()) { + (Some("completed"), Some("success")) => Outcome::Passed, + (Some("completed"), Some("skipped" | "neutral")) => Outcome::Skipped, + (Some("completed"), _) => Outcome::Failed, + _ => Outcome::Running, + } +} + +/// The covering checks' newest runs on the head, and the preview address +/// any of them printed. +fn covering_results( + runs: &serde_json::Value, + covers: &[pv::Covering], +) -> (Vec, Option) { + // The newest run of each covering check that ran: a check skipped on + // the draft and run once it was ready reads as run, and a later event + // that skips it (another label added) doesn't undo a run. + let mut newest: Vec<(&str, &serde_json::Value)> = Vec::new(); + for r in runs["check_runs"].as_array().into_iter().flatten() { + let name = r["name"].as_str().unwrap_or(""); + if !pv::is_covering(covers, name) { + continue; + } + let rank = |x: &serde_json::Value| { + ( + outcome_of(x) != Outcome::Skipped, + x["started_at"].as_str().unwrap_or("").to_string(), + ) + }; + match newest.iter_mut().find(|(n, _)| *n == name) { + Some(slot) if rank(r) > rank(slot.1) => slot.1 = r, + Some(_) => {} + None => newest.push((name, r)), + } + } + let mut out: Vec = Vec::new(); + let mut url = None; + for (name, r) in newest { + if url.is_none() { + url = [ + r["output"]["summary"].as_str(), + r["output"]["text"].as_str(), + r["details_url"].as_str(), + ] + .into_iter() + .flatten() + .find_map(pv::url_in); + } + out.push(CheckResult { + name: name.to_string(), + outcome: outcome_of(r), + url: r["html_url"].as_str().unwrap_or("").to_string(), + }); + } + (out, url) +} + +/// The workflow files at `git_ref`, with their text. +async fn workflows( + gh: &GitHubClient, + owner: &str, + repo: &str, + git_ref: &str, +) -> Vec<(String, String)> { + let Ok(entries) = gh + .list_directory(owner, repo, ".github/workflows", git_ref) + .await + else { + return Vec::new(); + }; + let mut out = Vec::new(); + for e in entries + .into_iter() + .filter(|e| e.path.ends_with(".yml") || e.path.ends_with(".yaml")) + .take(MAX_WORKFLOWS) + { + if let Ok(text) = gh.read_file(owner, repo, &e.path, git_ref).await { + out.push((e.path, text)); + } + } + out +} + +/// The test map's areas that cover the changed paths. +async fn map_areas( + gh: &GitHubClient, + owner: &str, + repo: &str, + git_ref: &str, + tree: &[String], + changed: &[String], +) -> Vec { + let Some(path) = common::e2e::coverage::TEST_MAP_PATHS + .iter() + .find(|p| tree.iter().any(|t| t == *p)) + else { + return Vec::new(); + }; + let Some(map) = gh + .read_file(owner, repo, path, git_ref) + .await + .ok() + .and_then(|t| common::e2e::coverage::parse_test_map(&t)) + else { + return Vec::new(); + }; + let mut out: Vec = Vec::new(); + for c in changed { + for a in map.areas_for(c) { + if !out.contains(&a.name) { + out.push(a.name.clone()); + } + } + } + out +} + +/// Pushes an empty commit on CoderHelm's own branch, so a workflow that +/// reads labels only on a push sees the labels just added. Never moves a +/// branch someone pushed to since. +async fn nudge(gh: &GitHubClient, owner: &str, repo: &str, branch: &str, head: &str) -> bool { + let Ok((tree, _)) = gh.commit_tree_parents(owner, repo, head).await else { + return false; + }; + let Ok(sha) = gh + .put_commit( + owner, + repo, + "Start the preview checks with the labels they need", + &tree, + &[head.to_string()], + ) + .await + else { + return false; + }; + gh.fast_forward(owner, repo, branch, head, &sha) + .await + .unwrap_or(false) +} + +/// Reads where the preview of the pull request's head stands, starts what +/// the repository's workflows need to run it, and records it. `pr` is the +/// pull request as GitHub returns it. None when it couldn't be read. +pub async fn advance( + state: &WorkerState, + gh: &GitHubClient, + p: Pr<'_>, + pr: &serde_json::Value, +) -> Option { + let head = pr["head"]["sha"].as_str().unwrap_or("").to_string(); + let base = pr["base"]["ref"].as_str().unwrap_or("main").to_string(); + let branch = pr["head"]["ref"].as_str().unwrap_or("").to_string(); + let draft = pr["draft"].as_bool().unwrap_or(false); + if head.is_empty() || pr["state"].as_str() != Some("open") { + return None; + } + let prior = load(state, p.team_id, p.run_id).await; + if let Some(st) = prior.as_ref().filter(|st| settled(st, &head)) { + return Some(st.clone()); + } + let same_head = prior.as_ref().filter(|st| st.head == head); + let changed: Vec = gh + .compare_files_with_patches(p.owner, p.repo, &base, &head) + .await + .ok()? + .into_iter() + .filter(|(_, status, _)| status != "removed") + .map(|(path, _, _)| path) + .collect(); + let mut st = State { + head: head.clone(), + labels_added: same_head + .map(|s| s.labels_added.clone()) + .unwrap_or_default(), + ..Default::default() + }; + if !changed.iter().any(|c| pv::is_user_visible(c)) { + st.why = "the change has no page a person sees".into(); + save(state, p, &st).await; + return Some(st); + } + let tree: Vec = gh + .get_tree(p.owner, p.repo, &head) + .await + .map(|t| t.into_iter().map(|e| e.path).collect()) + .unwrap_or_default(); + let suite = pv::e2e_suite(&tree); + let need = pv::e2e_need(&changed, suite.as_ref()); + if let pv::E2eNeed::Required { covered, .. } = &need { + st.e2e_required = true; + st.e2e_covered = *covered; + } + st.how_to_check = pv::how_to_check(&changed, suite.as_ref(), &pv::unit_cmd(&tree)); + let wfs = workflows(gh, p.owner, p.repo, &head).await; + let areas = map_areas(gh, p.owner, p.repo, &head, &tree, &changed).await; + let repo_labels: Vec = gh + .list_repo_labels(p.owner, p.repo) + .await + .map(|v| v.into_iter().map(|(n, _)| n).collect()) + .unwrap_or_default(); + let preferred = super::review_pr::named_labels(state, p.team_id, p.owner, p.repo).await; + let on_pr = super::skipped_checks::labels_of(pr); + let plan = pv::plan(&pv::PlanInput { + workflows: &wfs, + changed: &changed, + base: &base, + repo_labels: &repo_labels, + on_pr: &on_pr, + preferred: &preferred, + areas: &areas, + }); + st.covers = plan.covers.clone(); + st.draft_gated = plan.draft_gated.clone(); + if !plan.has_path() { + st.stage = Stage::Blocked; + st.why = + "the repository has no preview deploy for this change, so no page could be captured" + .into(); + save(state, p, &st).await; + return Some(st); + } + // Start what the workflows need: once per label per head. + let mut add = Vec::new(); + for l in &plan.add { + if st.labels_added.iter().any(|a| a.eq_ignore_ascii_case(l)) { + continue; + } + if super::review_pr::may_add_label(state, p.team_id, p.owner, p.repo, l).await { + add.push(l.clone()); + } + } + let mut blocked = plan.blocked.clone(); + if !add.is_empty() { + match gh.add_labels(p.owner, p.repo, p.number, &add).await { + Ok(_) => { + info!(pr = p.number, labels = ?add, "Added the labels that start the preview and its end-to-end checks"); + st.labels_added.extend(add.iter().cloned()); + if plan.needs_push && !draft && !branch.is_empty() { + let pushed = nudge(gh, p.owner, p.repo, &branch, &head).await; + info!( + pr = p.number, + pushed, "Pushed an empty commit so the labels count" + ); + } + } + Err(e) => { + warn!(pr = p.number, error = %e, "Could not add the preview labels"); + blocked.push(format!( + "CoderHelm couldn't add {} ({})", + add.join(", "), + common::truncate_str(&e.to_string(), 120) + )); + } + } + } + let not_allowed: Vec<&String> = plan + .add + .iter() + .filter(|l| { + !st.labels_added.iter().any(|a| a.eq_ignore_ascii_case(l)) + && !on_pr.iter().any(|o| o.eq_ignore_ascii_case(l)) + }) + .collect(); + if !not_allowed.is_empty() && add.is_empty() { + blocked.push(format!( + "the team's label settings don't let CoderHelm add {}", + not_allowed + .iter() + .map(|l| format!("`{l}`")) + .collect::>() + .join(", ") + )); + } + let runs = gh + .list_check_runs_for_ref(p.owner, p.repo, &head) + .await + .unwrap_or_default(); + let (results, url) = covering_results(&runs, &plan.covers); + st.checks = results; + let triggered = !st.labels_added.is_empty() || draft; + st.stage = pv::progress(&st.checks, triggered); + let none_ran = st.checks.iter().all(|c| c.outcome == Outcome::Skipped); + if none_ran && !blocked.is_empty() && st.labels_added.is_empty() && !draft { + st.stage = Stage::Blocked; + st.why = blocked.join("; "); + } + st.url = match url { + Some(u) => u, + None if matches!(st.stage, Stage::Ready | Stage::Deploying) => gh + .deployment_urls(p.owner, p.repo, &head) + .await + .ok() + .and_then(|d| pv::url_from_deployments(&d)) + .unwrap_or_default(), + None => String::new(), + }; + // Captured on this head already: it stays checked. + if st.stage == Stage::Ready { + if let Some(prev) = same_head.filter(|s| !s.shots.is_empty() || s.stage == Stage::Checked) { + st.shots = prev.shots.clone(); + st.why = prev.why.clone(); + st.stage = Stage::Checked; + } + } + save(state, p, &st).await; + Some(st) +} + +/// Captures the changed pages on the preview at desktop and phone width, +/// keeps the images on [`SHOTS_REF`] and records them. Only once the +/// preview is up and its end-to-end checks passed; whatever happens, the +/// state ends checked, with the pages or the one line saying why not. +pub async fn capture( + state: &WorkerState, + gh: &GitHubClient, + p: Pr<'_>, + st: &mut State, + deadline: Option, +) { + if st.stage != Stage::Ready { + return; + } + st.stage = Stage::Checked; + if st.url.is_empty() { + st.why = "the preview's address wasn't in its deploy's output or deployments, so its pages couldn't be captured".into(); + save(state, p, st).await; + return; + } + let host = st.url["https://".len()..] + .split('/') + .next() + .unwrap_or("") + .to_string(); + let base = format!("https://{host}"); + let tree: Vec = gh + .get_tree(p.owner, p.repo, &st.head) + .await + .map(|t| t.into_iter().map(|e| e.path).collect()) + .unwrap_or_default(); + let changed = changed_of(gh, p).await; + let pages = pv::routes(&tree, &changed); + let script = pv::capture_script(&base, &pages); + let source = match super::skill_run::pack(&[("capture.mjs".to_string(), script)]) { + Ok(b) => b, + Err(e) => { + st.why = format!("the capture couldn't be packed ({e})"); + save(state, p, st).await; + return; + } + }; + 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, p.team_id).await); + let key = format!( + "{}-shots-{}", + p.run_id, + st.head.get(..12).unwrap_or(&st.head) + ); + let mut hosts: Vec = pv::CAPTURE_HOSTS.iter().map(|h| h.to_string()).collect(); + hosts.push(host); + let cmd = pv::capture_command(); + let out = sandbox + .run_script( + crate::clients::sandbox::ScriptRun { + key: &key, + source, + cmd: &cmd, + secret: None, + hosts, + }, + deadline, + ) + .await; + let out = match out { + Ok(o) if o.ran => o, + Ok(o) => { + st.why = format!( + "the capture didn't run in the sandbox ({})", + common::truncate_str(o.output.lines().next().unwrap_or(""), 120) + ); + save(state, p, st).await; + return; + } + Err(e) => { + st.why = format!("the sandbox couldn't run the capture ({e})"); + save(state, p, st).await; + return; + } + }; + let report: Vec = out + .files + .iter() + .find(|(n, _)| n.ends_with("shots.json")) + .and_then(|(_, b)| serde_json::from_str(b).ok()) + .unwrap_or_default(); + if let Some(why) = pv::why_no_shot(&report) { + st.why = why; + save(state, p, st).await; + return; + } + match keep_images(gh, p, &st.head, &report, &out.files).await { + Ok(shots) if !shots.is_empty() => { + info!( + pr = p.number, + shots = shots.len(), + "Captured the changed pages on the preview" + ); + st.shots = shots; + st.why.clear(); + } + Ok(_) => st.why = "the capture brought back no image".into(), + Err(e) => { + st.why = format!( + "the pages were captured but couldn't be kept on the repository ({})", + common::truncate_str(&e.to_string(), 120) + ) + } + } + save(state, p, st).await; +} + +async fn changed_of(gh: &GitHubClient, p: Pr<'_>) -> Vec { + let Ok(pr) = gh.get_pull_request(p.owner, p.repo, p.number).await else { + return Vec::new(); + }; + let (Some(base), Some(head)) = (pr["base"]["ref"].as_str(), pr["head"]["sha"].as_str()) else { + return Vec::new(); + }; + gh.compare_files_with_patches(p.owner, p.repo, base, head) + .await + .map(|v| v.into_iter().map(|(p, _, _)| p).collect()) + .unwrap_or_default() +} + +/// Writes the captured images in one commit on [`SHOTS_REF`] (on top of +/// the ones kept before) and returns each page's image address. +async fn keep_images( + gh: &GitHubClient, + p: Pr<'_>, + head: &str, + report: &[pv::Captured], + files: &[(String, String)], +) -> Result, Box> { + let short = head.get(..12).unwrap_or(head); + let mut entries: Vec<(String, Option)> = Vec::new(); + let mut shots: Vec<(Shot, String)> = Vec::new(); + for c in report.iter().filter(|c| (1..400).contains(&c.status)) { + let Some((_, b64)) = files + .iter() + .find(|(n, _)| n.ends_with(&format!("{}.png.b64", c.name))) + else { + continue; + }; + let clean: String = b64.chars().filter(|c| !c.is_whitespace()).collect(); + let bytes = base64::engine::general_purpose::STANDARD.decode(clean)?; + let path = format!("pr-{}/{short}/{}.png", p.number, c.name); + let sha = gh.put_blob(p.owner, p.repo, &bytes).await?; + entries.push(( + path.clone(), + Some(GitEntry { + mode: "100644".into(), + kind: "blob".into(), + sha, + }), + )); + shots.push(( + Shot { + page: c.page.clone(), + width: c.width.clone(), + src: String::new(), + }, + path, + )); + } + if entries.is_empty() { + return Ok(Vec::new()); + } + let parent = gh.own_ref(p.owner, p.repo, SHOTS_REF).await; + let base_tree = match &parent { + Some(c) => gh.commit_tree_parents(p.owner, p.repo, c).await?.0, + None => String::new(), + }; + let tree = gh.put_tree(p.owner, p.repo, &base_tree, &entries).await?; + let commit = gh + .put_commit( + p.owner, + p.repo, + &format!("Screenshots of #{} at {short}", p.number), + &tree, + &parent.into_iter().collect::>(), + ) + .await?; + gh.set_own_ref(p.owner, p.repo, SHOTS_REF, &commit).await?; + Ok(shots + .into_iter() + .map(|(mut s, path)| { + s.src = format!( + "https://github.com/{}/{}/blob/{commit}/{path}?raw=true", + p.owner, p.repo + ); + s + }) + .collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn covering_runs_are_read_with_the_preview_address_they_print() { + let runs = serde_json::json!({"check_runs": [ + {"name": "Deploy Preview Web App", "status": "completed", "conclusion": "success", + "html_url": "https://github.com/o/r/runs/1", + "output": {"summary": "Preview at https://pr-9.preview-web.example.com"}}, + {"name": "E2E on preview", "status": "in_progress", "conclusion": null, + "html_url": "https://github.com/o/r/runs/2", "output": {}}, + {"name": "unit tests", "status": "completed", "conclusion": "success", "output": {}} + ]}); + let covers = vec![ + pv::Covering { + check: "Deploy Preview Web App".into(), + ..Default::default() + }, + pv::Covering { + check: "E2E on preview".into(), + ..Default::default() + }, + ]; + let (r, url) = covering_results(&runs, &covers); + assert_eq!(r.len(), 2); + assert_eq!(r[0].outcome, Outcome::Passed); + assert_eq!(r[1].outcome, Outcome::Running); + assert_eq!(url.as_deref(), Some("https://pr-9.preview-web.example.com")); + assert_eq!(pv::progress(&r, true), Stage::Deploying); + } + + #[test] + fn a_check_skipped_on_the_draft_and_run_once_ready_reads_as_run() { + let runs = serde_json::json!({"check_runs": [ + {"name": "E2E on preview", "status": "completed", "conclusion": "skipped", + "started_at": "2026-01-01T10:00:00Z", "output": {}}, + {"name": "E2E on preview", "status": "completed", "conclusion": "success", + "started_at": "2026-01-01T10:20:00Z", "output": {}}, + {"name": "E2E on preview", "status": "completed", "conclusion": "skipped", + "started_at": "2026-01-01T10:40:00Z", "output": {}} + ]}); + let covers = vec![pv::Covering { + check: "E2E on preview".into(), + ..Default::default() + }]; + let (r, _) = covering_results(&runs, &covers); + assert_eq!(r.len(), 1); + assert_eq!(r[0].outcome, Outcome::Passed); + } + + #[test] + fn a_settled_head_is_not_read_again_but_a_new_head_is() { + let st = State { + head: "abc".into(), + stage: Stage::Checked, + ..Default::default() + }; + assert!(settled(&st, "abc")); + assert!(!settled(&st, "def")); + let pending = State { + head: "abc".into(), + stage: Stage::Deploying, + ..Default::default() + }; + assert!(!settled(&pending, "abc")); + } +} diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index e5f44b12c..809c4ceda 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -180,8 +180,21 @@ pub struct Facts { /// Its CI fix loop found every failing check failing on the base branch /// too (`ci_end` = `red_on_base`): not this change's failure. pub red_on_base: bool, + /// The head's preview (`preview::advance`): a web change is ready only + /// once its preview deploy and end-to-end checks passed on it, and only + /// with an end-to-end spec when the repository has a suite. + pub preview: Option, } +/// The hold for a change a person sees that has no end-to-end spec in a +/// repository with a suite. +pub const E2E_MISSING: &str = + "The change alters what a person sees and adds no end-to-end spec to the repository's suite"; + +/// What a draft waits for while its preview checks run. +pub const PREVIEW_WAIT: &str = + "the preview deploy and its end-to-end checks are running on this head"; + impl Ci { /// A check failed on the head (not merely running or missing). pub fn failing(&self) -> bool { @@ -433,6 +446,53 @@ pub fn decide(f: &Facts) -> Decision { } } } + // A web change: its preview checks are proof like any other, and a + // visible change needs its end-to-end spec. + if let Some(p) = f + .preview + .as_ref() + .filter(|p| f.head.is_empty() || p.head == f.head) + { + use common::preview::{Outcome as PvOutcome, Stage}; + if p.e2e_required && !p.e2e_covered { + reasons.push(Reason::new( + E2E_MISSING, + "CoderHelm writes the spec in its next round on this branch (its Tests and scope check sends it back), runs it on the preview, and marks the pull request ready once it passes.", + )); + } + match p.stage { + Stage::Failed => { + let failed: Vec = p + .checks + .iter() + .filter(|c| c.outcome == PvOutcome::Failed) + .map(|c| c.name.clone()) + .collect(); + reasons.push(Reason::new( + format!("The preview checks failed: {}", check_names(&failed)), + "CoderHelm fixes the cause like any failing check and pushes; the preview runs again on the new head.", + )); + } + Stage::Triggered | Stage::Deploying => { + let not_run: Vec = p + .draft_gated + .iter() + .filter(|g| { + !p.checks + .iter() + .any(|c| &c.name == *g && c.outcome != PvOutcome::Skipped) + }) + .cloned() + .collect(); + if f.draft && !not_run.is_empty() { + runs_when_ready.extend(not_run); + } else { + proof_wait.get_or_insert_with(|| PREVIEW_WAIT.to_string()); + } + } + _ => {} + } + } // A security fix leaves draft on green CI only. let (sec_hold, sec_wait) = security_ci(f); if let Some(r) = sec_hold { @@ -999,6 +1059,7 @@ async fn gather(ctx: &Ctx<'_>) -> Result { f.feature = super::feature::ready_hold(ctx.state, gh, ctx.team_id, ctx.owner, ctx.repo, ctx.pr) .await; + f.preview = preview_of(ctx, &pr).await; } // The description as it is now (the link check may have rewritten it). let pr = read_pr().await?; @@ -1054,6 +1115,30 @@ async fn gather(ctx: &Ctx<'_>) -> Result { Ok(f) } +/// The head's preview, moved on now (`preview::advance`): its labels added, +/// its checks read. None for a pull request no run of CoderHelm's opened. +async fn preview_of(ctx: &Ctx<'_>, pr: &serde_json::Value) -> Option { + let run_id = if ctx.run_id.is_empty() { + super::review_pr::lookup_run_by_pr(ctx.state, ctx.team_id, ctx.owner, ctx.repo, ctx.pr) + .await? + } else { + ctx.run_id.clone() + }; + super::preview::advance( + ctx.state, + ctx.github, + super::preview::Pr { + team_id: ctx.team_id, + run_id: &run_id, + owner: ctx.owner, + repo: ctx.repo, + number: ctx.pr, + }, + pr, + ) + .await +} + /// Whether the run's CI fix loop ended because every failing check fails on /// the base branch too. async fn red_on_base(ctx: &Ctx<'_>) -> bool { @@ -1082,6 +1167,27 @@ async fn red_on_base(ctx: &Ctx<'_>) -> bool { .is_some_and(|e| e == "red_on_base") } +/// Asks for the ready decision of a pull request again, now: the preview's +/// checks it waits on moved (`preview`). +pub async fn request_for( + state: &WorkerState, + team_id: &str, + installation_id: u64, + owner: &str, + repo: &str, + pr_number: u64, +) -> bool { + let m = MarkReadyMessage { + team_id: team_id.to_string(), + installation_id, + repo_owner: owner.to_string(), + repo_name: repo.to_string(), + pr_number, + ..Default::default() + }; + send(state, &m, 0).await +} + /// Asks for the ready decision of a PR again, now: CoderHelm's review of its /// head just gave the verdict the decision waited for. pub async fn request(state: &WorkerState, msg: &crate::models::ReviewMessage) { @@ -2109,6 +2215,78 @@ mod tests { } } + fn preview(stage: common::preview::Stage) -> common::preview::State { + common::preview::State { + head: "abc".into(), + stage, + draft_gated: vec!["Deploy Preview".into(), "E2E on preview".into()], + ..Default::default() + } + } + + /// A web change was once marked ready with its preview deploy and + /// preview end-to-end checks skipped (they skip drafts), and nothing + /// waited for them. Now the draft is marked ready for them and stays + /// "being proven" until they pass. + #[test] + fn a_draft_web_change_is_proven_on_its_preview_before_it_is_ready() { + let f = Facts { + head: "abc".into(), + preview: Some(preview(common::preview::Stage::Triggered)), + ..green_approved() + }; + let d = decide(&f); + let Decision::Proving { why, reasons } = &d else { + panic!("proving expected, got {d:?}"); + }; + assert!(reasons.is_empty()); + assert!( + why.contains("`Deploy Preview`") && why.contains("`E2E on preview`"), + "{why}" + ); + // Marked ready and still deploying: it waits, never plain ready. + let running = Facts { + draft: false, + body: PROVING_MARK.into(), + preview: Some(preview(common::preview::Stage::Deploying)), + ..f.clone() + }; + assert_eq!( + decide(&running), + Decision::Proving { + why: PREVIEW_WAIT.into(), + reasons: Vec::new() + } + ); + // Checked: ready. + let checked = Facts { + preview: Some(preview(common::preview::Stage::Checked)), + ..running.clone() + }; + assert!(matches!(decide(&checked), Decision::Ready { .. })); + } + + #[test] + fn a_visible_change_with_no_e2e_spec_is_not_ready() { + let mut p = preview(common::preview::Stage::Checked); + p.e2e_required = true; + let f = Facts { + head: "abc".into(), + preview: Some(p.clone()), + ..green_approved() + }; + let Decision::Held { reasons } = decide(&f) else { + panic!("held expected"); + }; + assert!(reasons[0].what.starts_with(E2E_MISSING)); + p.e2e_covered = true; + let ok = Facts { + preview: Some(p), + ..f + }; + assert!(matches!(decide(&ok), Decision::Ready { .. })); + } + /// A security fix whose CI the fix loop couldn't get green (it handed /// the pull request off): it stays a draft, and the hold names the /// failing checks at the top of the description. diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 9cb34cdb0..2c8f19a6f 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -3357,6 +3357,28 @@ async fn run_once( "Findings held to the repository's required rules" ); } + // A change a person sees, in a repository with an end-to-end suite, + // carries a spec for it: a finding by rule, read from the paths and the + // tree, whatever the model said. + if changed_list + .iter() + .any(|p| common::preview::is_user_visible(p)) + { + if let Ok(tree) = github + .get_tree(&msg.repo_owner, &msg.repo_name, &head_sha) + .await + { + let tree: Vec = tree.into_iter().map(|e| e.path).collect(); + if let Some(f) = super::review_rules::e2e_finding(&changed_list, &tree) { + info!( + pr = msg.pr_number, + "A visible change with no end-to-end spec: must fix" + ); + findings.retain(|x| x.title != f.title); + findings.push(f); + } + } + } review_agent::enforce_source_data_override(&mut findings); // A request to test something by hand is a note, never a block. review_agent::enforce_manual_checks_are_notes(&mut findings); diff --git a/services/worker/src/passes/review_rules.rs b/services/worker/src/passes/review_rules.rs index 6273eab9d..ec61b6a29 100644 --- a/services/worker/src/passes/review_rules.rs +++ b/services/worker/src/passes/review_rules.rs @@ -41,6 +41,34 @@ use super::review_agent::Finding; pub const TESTS_RULE: &str = "tests with behavior changes (this repository's \"Require tests\" setting)"; +/// The rule every repository with an end-to-end suite has: a change a +/// person sees in the browser carries a spec for it. +pub const E2E_RULE: &str = "an end-to-end spec with every change a person sees in the browser (the repository has an end-to-end suite)"; + +/// The review's finding for a change a person sees that adds no +/// end-to-end spec to the repository's suite, from the changed paths and +/// the repository's tree alone. It blocks by rule (`mandatory`): the fix +/// round writes the spec. None when no spec is needed or one is there. +pub fn e2e_finding(changed: &[String], tree: &[String]) -> Option { + let suite = common::preview::e2e_suite(tree); + let need = common::preview::e2e_need(changed, suite.as_ref()); + let body = need.instruction()?; + let common::preview::E2eNeed::Required { visible, .. } = &need else { + return None; + }; + Some(Finding { + file: visible.first().cloned().unwrap_or_default(), + severity: "blocking".into(), + category: "tests".into(), + title: "No end-to-end spec for a change a person sees".into(), + body, + evidence: Some("verified-defect".into()), + caused_by_diff: Some(true), + required: Some(E2E_RULE.to_string()), + ..Default::default() + }) +} + /// Why a required rule broken blocks. pub const REQUIRED_WHY: &str = "a rule this repository requires is broken"; /// Why a failing check blocks. @@ -572,6 +600,9 @@ pub fn mandatory_label(f: &Finding) -> Option { REQUIRED_WHY if f.required.as_deref() == Some(TESTS_RULE) => { "Blocking (required: tests)".to_string() } + REQUIRED_WHY if f.required.as_deref() == Some(E2E_RULE) => { + "Blocking (required: end-to-end test)".to_string() + } REQUIRED_WHY => "Blocking (required rule)".to_string(), FAILING_CHECK_WHY => "Blocking (failing check)".to_string(), MAIN_PATH_WHY if f.evidence() == super::review_agent::Evidence::VerifiedDefect => { @@ -595,6 +626,42 @@ pub fn settles(thread_body: &str, status: &str) -> bool { } } +#[cfg(test)] +mod e2e_rule_tests { + use super::*; + + fn s(v: &[&str]) -> Vec { + v.iter().map(|x| x.to_string()).collect() + } + + /// A visible web change with no new or updated e2e spec, in a + /// repository with a suite, is a must-fix finding the fix round acts + /// on; nothing after it makes it a note. + #[test] + fn a_visible_change_with_no_e2e_spec_requests_changes() { + let tree = s(&["e2e/playwright.config.ts", "e2e/tests/cart.spec.ts"]); + let changed = s(&[ + "web/src/components/cart/Total.tsx", + "web/src/components/cart/Total.test.tsx", + ]); + let f = e2e_finding(&changed, &tree).expect("a finding"); + assert_eq!(f.severity, "blocking"); + assert_eq!(mandatory(&f), Some(REQUIRED_WHY)); + assert_eq!( + mandatory_label(&f).as_deref(), + Some("Blocking (required: end-to-end test)") + ); + assert!(f.body.contains("`e2e/`")); + // With a spec, or with no suite, nothing is asked. + let mut with_spec = changed.clone(); + with_spec.push("e2e/tests/cart.spec.ts".into()); + assert!(e2e_finding(&with_spec, &tree).is_none()); + assert!(e2e_finding(&changed, &s(&["README.md"])).is_none()); + // A change nobody sees needs none. + assert!(e2e_finding(&s(&["web/src/lib/money.ts"]), &tree).is_none()); + } +} + #[cfg(test)] mod tests { use super::*; From 59bb525de658ca019297a6045c6d4f87e6f0709a Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 16 Nov 2026 14:45:26 -0500 Subject: [PATCH 2/4] Failures are read from their report, checks are named by the job that covers the change, outside pages are probed - common::e2e::failure_read: a failed end-to-end check is read from the e2e workflow's comment on the pull request, its annotations, then its job log, before anything is said about it; "couldn't be read" only when all are empty. Whether the change caused it comes from the same check on the base branch and the specs the change touched. The preview state records each failure, the description says it, and a line claiming an unread log is dropped while a report exists. - common::ci_cover maps the changed paths to the jobs that run on them (paths filters, branches, working-directory). "How to check" and Open items come from that mapping; a check command aimed at a folder the change doesn't touch is dropped, and "no CI job covers this change" is said when none does. - common::e2e::probe and the coder's probe_page tool: an outside page is loaded with Playwright in the sandbox and its test ids and JSON fields recorded under .coderhelm/probes/. The review requests changes on a new or changed e2e file whose selectors or fields on an outside origin no probe observed. --- services/common/src/ci_cover.rs | 278 ++++++++++++++ services/common/src/e2e/failure_read.rs | 342 ++++++++++++++++++ services/common/src/e2e/mod.rs | 2 + services/common/src/e2e/probe.rs | 299 +++++++++++++++ services/common/src/lib.rs | 1 + services/common/src/preview.rs | 7 + services/worker/src/clients/github.rs | 22 ++ .../worker/src/passes/description_facts.rs | 74 ++++ services/worker/src/passes/feedback.rs | 1 + services/worker/src/passes/implement.rs | 1 + .../incidents/bu_web_change_unchecked.rs | 69 ++++ services/worker/src/passes/mod.rs | 6 +- services/worker/src/passes/pr_watch.rs | 6 +- services/worker/src/passes/preview.rs | 135 ++++++- services/worker/src/passes/review_pr.rs | 99 ++++- services/worker/src/passes/review_rules.rs | 37 ++ services/worker/src/passes/web_check.rs | 105 ++++++ 17 files changed, 1461 insertions(+), 23 deletions(-) create mode 100644 services/common/src/ci_cover.rs create mode 100644 services/common/src/e2e/failure_read.rs create mode 100644 services/common/src/e2e/probe.rs diff --git a/services/common/src/ci_cover.rs b/services/common/src/ci_cover.rs new file mode 100644 index 000000000..794f4cf51 --- /dev/null +++ b/services/common/src/ci_cover.rs @@ -0,0 +1,278 @@ +//! Which CI job covers the changed code. +//! +//! A web pull request's Open items once told a reader to run `npm test` in +//! an unrelated serverless function's folder: the line came from the list +//! of every workflow in the repository, not from the jobs that test the +//! changed package. [`covering_jobs`] maps the changed paths to the jobs +//! that run on them (the workflow's `paths` filters and branches, and each +//! job's `working-directory`), [`line`] says which job checks the change or +//! that none does, and [`command_fits`] rejects a check command aimed at a +//! folder the change doesn't touch. "How to check" and Open items are built +//! from this mapping, never from a repository-wide list. + +use serde::{Deserialize, Serialize}; + +/// One CI job that runs on the changed code. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CoveringJob { + pub workflow: String, + /// The check's name (the job's `name`, else its key). + pub check: String, + /// The folder its steps run in; "" for the repository's root. + pub dir: String, + /// The test-like commands it runs, as written. + pub commands: Vec, +} + +fn s(v: Option<&serde_yaml::Value>) -> String { + v.and_then(|x| x.as_str()).unwrap_or("").trim().to_string() +} + +fn norm_dir(d: &str) -> String { + d.trim() + .trim_start_matches("./") + .trim_end_matches('/') + .to_string() +} + +/// A command that runs tests, lint or type checks. +pub fn is_check_command(cmd: &str) -> bool { + let c = cmd.to_ascii_lowercase(); + [ + " test", + "test ", + "vitest", + "jest", + "pytest", + "playwright", + "cypress", + "lint", + "tsc", + "typecheck", + "type-check", + "cargo test", + "go test", + ] + .iter() + .any(|w| c.contains(w)) +} + +/// Whether a changed path lies in `dir` ("" is the whole repository). +fn under(dir: &str, path: &str) -> bool { + dir.is_empty() || path == dir || path.starts_with(&format!("{dir}/")) +} + +/// The jobs of pull request workflows that run on the changed paths. A +/// job whose steps run in a folder covers only changes in that folder; a +/// job at the root covers the change when its workflow starts for it. +pub fn covering_jobs( + workflows: &[(String, String)], + changed: &[String], + base: &str, +) -> Vec { + let mut out = Vec::new(); + for (path, yaml) in workflows { + if !crate::preview::triggers(yaml).applies(changed, base) { + continue; + } + let Ok(v) = serde_yaml::from_str::(yaml) else { + continue; + }; + let wf_dir = s(v + .get("defaults") + .and_then(|d| d.get("run")) + .and_then(|r| r.get("working-directory"))); + let Some(jobs) = v.get("jobs").and_then(|j| j.as_mapping()) else { + continue; + }; + for (k, job) in jobs { + let Some(id) = k.as_str() else { continue }; + let name = s(job.get("name")); + let check = if name.is_empty() || name.contains("${{") { + id.to_string() + } else { + name + }; + let job_dir = s(job + .get("defaults") + .and_then(|d| d.get("run")) + .and_then(|r| r.get("working-directory"))); + let mut dirs: Vec = Vec::new(); + let mut commands: Vec = Vec::new(); + for step in job + .get("steps") + .and_then(|x| x.as_sequence()) + .into_iter() + .flatten() + { + let run = s(step.get("run")); + if run.is_empty() || !is_check_command(&run) { + continue; + } + let step_dir = s(step.get("working-directory")); + let dir = [&step_dir, &job_dir, &wf_dir] + .into_iter() + .find(|d| !d.is_empty() && !d.contains("${{")) + .map(|d| norm_dir(d)) + .unwrap_or_default(); + // `cd && …` in the command itself. + let dir = cd_dir(&run).unwrap_or(dir); + if !dirs.contains(&dir) { + dirs.push(dir); + } + commands.push(run.lines().next().unwrap_or("").trim().to_string()); + } + if commands.is_empty() { + continue; + } + if let Some(dir) = dirs.iter().find(|d| changed.iter().any(|c| under(d, c))) { + out.push(CoveringJob { + workflow: path.clone(), + check: check.clone(), + dir: dir.clone(), + commands, + }); + } + } + } + out +} + +/// The folder a command `cd`s into first, if any. +fn cd_dir(cmd: &str) -> Option { + let t = cmd.trim(); + let rest = t.strip_prefix("cd ")?; + let dir = rest + .split(|c: char| c.is_whitespace() || c == '&' || c == ';') + .next()? + .trim_matches(['\'', '"']); + (!dir.is_empty() && !dir.contains('$')).then(|| norm_dir(dir)) +} + +/// The folders a command names to run in: `cd X`, `--prefix X`, +/// `--dir X`, `-C X`, `--filter ./X`, `working-directory: X`. +pub fn command_dirs(cmd: &str) -> Vec { + let mut out = Vec::new(); + let toks: Vec<&str> = cmd + .split(|c: char| c.is_whitespace() || c == '&' || c == ';' || c == '`') + .filter(|t| !t.is_empty()) + .collect(); + for (i, t) in toks.iter().enumerate() { + let next = toks.get(i + 1).map(|n| n.trim_matches(['\'', '"'])); + let dir = match *t { + "cd" | "--prefix" | "--dir" | "-C" | "--cwd" | "working-directory:" => next, + "--filter" => next.filter(|n| n.starts_with("./")), + _ => None, + }; + if let Some(d) = dir.filter(|d| !d.is_empty() && *d != "." && !d.contains('$')) { + let d = norm_dir(d); + if !out.contains(&d) { + out.push(d); + } + } + } + out +} + +/// Whether a check command fits the change: every folder it names to run +/// in holds a changed path. A command naming no folder runs at the root +/// and fits. +pub fn command_fits(cmd: &str, changed: &[String]) -> bool { + command_dirs(cmd) + .iter() + .all(|d| changed.iter().any(|c| under(d, c))) +} + +/// The line that names the CI job checking the change, or says none does. +pub fn line(jobs: &[CoveringJob]) -> String { + if jobs.is_empty() { + return "No CI job covers this change: no pull request workflow runs tests on the changed paths".into(); + } + let parts: Vec = jobs + .iter() + .take(3) + .map(|j| { + let at = if j.dir.is_empty() { + String::new() + } else { + format!(" in `{}`", j.dir) + }; + format!( + "`{}`{at} runs `{}`", + j.check, + j.commands.first().map(String::as_str).unwrap_or("") + ) + }) + .collect(); + format!("CI checks this change: {}", parts.join("; ")) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn v(x: &[&str]) -> Vec { + x.iter().map(|s| s.to_string()).collect() + } + + const WEB: &str = r#" +name: Web +on: + pull_request: + paths: ["apps/web/**"] +jobs: + unit: + name: Web unit tests + defaults: + run: + working-directory: apps/web + steps: + - run: npm ci + - run: npm test +"#; + + const FUNCTION: &str = r#" +name: Function +on: + pull_request: +jobs: + fn_tests: + name: Function tests + steps: + - run: npm ci + working-directory: lambda/uploader + - run: npm test + working-directory: lambda/uploader +"#; + + fn wfs() -> Vec<(String, String)> { + vec![ + ("web.yml".into(), WEB.into()), + ("fn.yml".into(), FUNCTION.into()), + ] + } + + /// A web change's Open items once cited `npm test` in an unrelated + /// function's folder. The job that covers the change is the web one. + #[test] + fn the_job_that_tests_the_changed_package_is_named_never_another_folders() { + let changed = v(&["apps/web/src/components/form.tsx"]); + let jobs = covering_jobs(&wfs(), &changed, "main"); + assert_eq!(jobs.len(), 1, "{jobs:?}"); + assert_eq!(jobs[0].check, "Web unit tests"); + assert_eq!(jobs[0].dir, "apps/web"); + assert!(line(&jobs).contains("`Web unit tests` in `apps/web` runs `npm test`")); + assert!(!command_fits("cd lambda/uploader && npm test", &changed)); + assert!(!command_fits("npm --prefix lambda/uploader test", &changed)); + assert!(command_fits("cd apps/web && npm test", &changed)); + assert!(command_fits("npm test", &changed)); + } + + #[test] + fn a_change_no_job_tests_says_so() { + let changed = v(&["docs/guide.md"]); + let jobs = covering_jobs(&wfs(), &changed, "main"); + assert!(jobs.is_empty()); + assert!(line(&jobs).starts_with("No CI job covers this change")); + } +} diff --git a/services/common/src/e2e/failure_read.rs b/services/common/src/e2e/failure_read.rs new file mode 100644 index 000000000..1ba1f85e5 --- /dev/null +++ b/services/common/src/e2e/failure_read.rs @@ -0,0 +1,342 @@ +//! What a failed end-to-end run says, read before anything is written +//! about it. +//! +//! A pull request once said CoderHelm "couldn't read the log" of a failed +//! end-to-end run while the workflow's own comment on the pull request +//! named the failing test and its error. The rules: +//! +//! - [`read`] takes every source there is (the e2e workflow's comment on +//! the pull request, the check run's annotations, the job's log) and +//! returns the failing tests and the error from the first that names +//! them. It returns [`Unreadable`] only when every source is empty: "the +//! log couldn't be read" can't be said while a comment or an annotation +//! exists. +//! - [`cause`] says whether this pull request caused it: the same check +//! failing on the base branch is not this change's; a failing spec the +//! change touched, or a check that passes on the base, is. + +use serde::{Deserialize, Serialize}; + +/// What there is to read about one failed check. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Sources { + /// The comment the e2e workflow posted on the pull request. + pub comment: String, + /// The check run's annotations: (path, title, message). + pub annotations: Vec<(String, String, String)>, + /// The tail of the job's log. + pub log: String, +} + +impl Sources { + pub fn is_empty(&self) -> bool { + self.comment.trim().is_empty() && self.annotations.is_empty() && self.log.trim().is_empty() + } +} + +/// Every source was empty: the only time a failure may be called unread. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Unreadable; + +/// Whether this pull request caused the failure. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "kind", content = "why")] +pub enum Cause { + ThisChange(String), + NotThisChange(String), + Unknown(String), +} + +/// A failed end-to-end check, as its own report says. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FailureRead { + pub check: String, + /// The failing tests, as the report names them (`file › title`). + pub tests: Vec, + /// The first error line. + pub error: String, + /// Where it was read: `comment`, `annotations` or `log`. + pub source: String, + pub cause: Cause, +} + +impl FailureRead { + /// One line for the pull request. + pub fn line(&self) -> String { + let tests = if self.tests.is_empty() { + String::new() + } else { + format!( + ": {}", + self.tests + .iter() + .take(3) + .map(|t| format!("`{t}`")) + .collect::>() + .join(", ") + ) + }; + let err = if self.error.is_empty() { + String::new() + } else { + format!(" ({})", crate::truncate_str(&self.error, 160)) + }; + let cause = match &self.cause { + Cause::ThisChange(w) => format!("This change caused it: {w}"), + Cause::NotThisChange(w) => format!("Not this change's: {w}"), + Cause::Unknown(w) => format!("Whether this change caused it isn't known yet: {w}"), + }; + format!( + "`{}` failed{tests}{err}, read from its {}. {cause}.", + self.check, self.source + ) + } +} + +/// A failing test named in a report line: Playwright's `✘ … › file:line › +/// title`, a numbered `1) [project] › …`, or Cypress' `1) suite title`. +fn test_of(line: &str) -> Option { + let t = line.trim(); + let t = t + .trim_start_matches(['✘', '×', '✗', '-', '*', ' ']) + .trim_start_matches(|c: char| c.is_ascii_digit()) + .trim_start_matches([')', '.', ' ']); + if !t.contains(" › ") && !t.contains(" > ") { + return None; + } + let sep = if t.contains(" › ") { " › " } else { " > " }; + let parts: Vec<&str> = t + .split(sep) + .map(str::trim) + .filter(|p| !p.starts_with('[') && !p.is_empty()) + .collect(); + let file = parts + .iter() + .find(|p| p.contains(".spec.") || p.contains(".test.") || p.contains(".cy."))?; + let file = file.split(':').next().unwrap_or(file); + let title = parts + .last() + .filter(|l| !l.contains(file)) + .copied() + .unwrap_or(""); + Some(if title.is_empty() { + file.to_string() + } else { + format!("{file} › {title}") + }) +} + +fn error_of(text: &str) -> String { + text.lines() + .map(str::trim) + .find(|l| { + let low = l.to_ascii_lowercase(); + low.starts_with("error:") + || low.starts_with("timeouterror") + || low.starts_with("expect(") + || low.contains("assertionerror") + || low.starts_with("expected") + }) + .map(|l| l.replace('`', "'")) + .unwrap_or_default() +} + +fn tests_in(text: &str) -> Vec { + let mut out: Vec = Vec::new(); + for l in text.lines() { + let low = l.to_ascii_lowercase(); + // Passing lines and the summary don't name failures. + if low.contains("✓") || low.contains(" passed") || low.contains("flaky") { + continue; + } + if let Some(t) = test_of(l) { + if !out.contains(&t) { + out.push(t); + } + } + } + out +} + +/// The failing tests and error, from the first source that names them. +pub fn read(check: &str, s: &Sources) -> Result { + if s.is_empty() { + return Err(Unreadable); + } + let make = |tests: Vec, error: String, source: &str| FailureRead { + check: check.to_string(), + tests, + error, + source: source.to_string(), + cause: Cause::Unknown("not decided yet".into()), + }; + let from_comment = (tests_in(&s.comment), error_of(&s.comment)); + if !from_comment.0.is_empty() || !from_comment.1.is_empty() { + return Ok(make( + from_comment.0, + from_comment.1, + "comment on the pull request", + )); + } + if !s.annotations.is_empty() { + let mut tests = Vec::new(); + let mut error = String::new(); + for (path, title, message) in &s.annotations { + let named = test_of(title).unwrap_or_else(|| { + if path.is_empty() { + title.clone() + } else { + format!("{path} › {title}") + } + }); + if !named.trim().is_empty() && !tests.contains(&named) { + tests.push(named); + } + if error.is_empty() { + error = error_of(message); + if error.is_empty() { + error = message.lines().next().unwrap_or("").trim().to_string(); + } + } + } + return Ok(make(tests, error, "check annotations")); + } + if !s.log.trim().is_empty() { + return Ok(make(tests_in(&s.log), error_of(&s.log), "job log")); + } + // A comment that names nothing is still read: it is quoted as is. + Ok(make( + Vec::new(), + s.comment + .lines() + .find(|l| !l.trim().is_empty()) + .unwrap_or("") + .trim() + .to_string(), + "comment on the pull request", + )) +} + +/// Whether the pull request caused it: `base_failed` is the same check's +/// result on the base branch's head (None when it didn't run there). +pub fn cause(f: &FailureRead, changed: &[String], base_failed: Option) -> Cause { + if base_failed == Some(true) { + return Cause::NotThisChange(format!("`{}` fails on the base branch too", f.check)); + } + let touched: Vec<&String> = f + .tests + .iter() + .filter(|t| { + let file = t.split(" › ").next().unwrap_or(t); + changed + .iter() + .any(|c| c.ends_with(file) || file.ends_with(c.as_str())) + }) + .collect(); + if let Some(t) = touched.first() { + return Cause::ThisChange(format!( + "the failing spec `{t}` is one this change adds or edits" + )); + } + if base_failed == Some(false) { + return Cause::ThisChange(format!( + "`{}` passes on the base branch and fails with this change", + f.check + )); + } + Cause::Unknown(format!( + "`{}` hasn't run on the base branch to compare", + f.check + )) +} + +/// Text that says a failure couldn't be read: refused while the failure +/// has a comment, an annotation or a log to read. +pub fn says_unreadable(text: &str) -> bool { + let t = text.to_ascii_lowercase(); + [ + "couldn't read the log", + "could not read the log", + "couldn't read its log", + "could not read its log", + "log couldn't be read", + "log could not be read", + "log isn't readable", + "couldn't read the e2e", + "could not read the e2e", + ] + .iter() + .any(|p| t.contains(p)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const COMMENT: &str = "## E2E results\n\n❌ 1 failed, 41 passed\n\n 1) [chromium] › tests/checkout/registration.spec.ts:88:7 › Camp registration › pays with a saved card\n\n Error: expect(locator).toBeVisible() failed\n Locator: getByTestId('payment-confirmation')\n"; + + /// A pull request said it couldn't read the log while the e2e + /// workflow's comment named the failing test and its error. + #[test] + fn the_comment_names_the_failing_test_and_its_error() { + let s = Sources { + comment: COMMENT.into(), + ..Default::default() + }; + let f = read("E2E on preview", &s).unwrap(); + assert_eq!( + f.tests, + vec!["tests/checkout/registration.spec.ts › pays with a saved card".to_string()] + ); + assert!(f.error.starts_with("Error: expect(locator).toBeVisible()")); + assert_eq!(f.source, "comment on the pull request"); + // "Unreadable" only when there is nothing at all. + assert_eq!(read("x", &Sources::default()), Err(Unreadable)); + assert!(says_unreadable( + "CoderHelm couldn't read the log of this run" + )); + } + + #[test] + fn annotations_are_read_when_there_is_no_comment() { + let s = Sources { + annotations: vec![( + "e2e/tests/login.spec.ts".into(), + "[chromium] › tests/login.spec.ts:12:5 › Login › shows an error".into(), + "Error: Timed out 5000ms waiting for expect(locator).toHaveText()".into(), + )], + ..Default::default() + }; + let f = read("E2E", &s).unwrap(); + assert_eq!(f.source, "check annotations"); + assert_eq!( + f.tests, + vec!["tests/login.spec.ts › shows an error".to_string()] + ); + assert!(f.error.contains("Timed out")); + } + + #[test] + fn the_cause_comes_from_the_base_and_the_changed_specs() { + let f = read( + "E2E on preview", + &Sources { + comment: COMMENT.into(), + ..Default::default() + }, + ) + .unwrap(); + let none: Vec = Vec::new(); + assert!(matches!( + cause(&f, &none, Some(true)), + Cause::NotThisChange(_) + )); + assert!(matches!( + cause(&f, &none, Some(false)), + Cause::ThisChange(_) + )); + assert!(matches!(cause(&f, &none, None), Cause::Unknown(_))); + let changed = vec!["e2e/tests/checkout/registration.spec.ts".to_string()]; + assert!(matches!(cause(&f, &changed, None), Cause::ThisChange(_))); + } +} diff --git a/services/common/src/e2e/mod.rs b/services/common/src/e2e/mod.rs index 80c5ae11b..860bc20da 100644 --- a/services/common/src/e2e/mod.rs +++ b/services/common/src/e2e/mod.rs @@ -37,6 +37,7 @@ pub mod ci_setup; pub mod coverage; pub mod detect; pub mod failure; +pub mod failure_read; pub mod fix_guard; pub mod fix_ticket; pub mod flake; @@ -45,6 +46,7 @@ pub mod messages; pub mod model; pub mod owners; pub mod parse; +pub mod probe; pub mod quarantine; pub mod report_source; pub mod signature; diff --git a/services/common/src/e2e/probe.rs b/services/common/src/e2e/probe.rs new file mode 100644 index 000000000..8c3ec4aa2 --- /dev/null +++ b/services/common/src/e2e/probe.rs @@ -0,0 +1,299 @@ +//! End-to-end tests against a page another company serves are built from +//! what that page really has. +//! +//! A spec once clicked test ids and read JSON fields of a payment vendor's +//! page that nobody had looked at: they didn't exist, and the run said the +//! test "covered" the checkout. The rules: +//! +//! - [`probe_script`] loads the page in the sandbox with Playwright and +//! lists its test ids (`data-testid`, `data-test`, `data-cy`, also inside +//! frames) and the field names of the JSON it fetches; the coder's +//! `probe_page` tool runs it and the record is committed in the +//! repository ([`record_path`]) and quoted in the pull request. +//! - [`unprobed`] is the gate: a new or changed end-to-end file that +//! reaches an outside origin (a host other than the team's own) may use +//! only test ids and JSON fields a probe of that origin observed. Any +//! other is a must-fix finding of the review. + +use serde::{Deserialize, Serialize}; + +/// What a probe of one page saw. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ProbeRecord { + /// The page's host. + pub origin: String, + pub url: String, + /// When it was probed (RFC 3339). + pub at: String, + /// Test ids on the page and in its frames. + pub testids: Vec, + /// Field names of the JSON responses it fetched (dotted paths). + pub json_fields: Vec, +} + +/// Where a probe of `host` is kept in the repository. +pub fn record_path(host: &str) -> String { + let safe: String = host + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '.' || c == '-' { + c + } else { + '-' + } + }) + .collect(); + format!(".coderhelm/probes/{safe}.json") +} + +/// Whether a path is a probe record. +pub fn is_record(path: &str) -> bool { + path.starts_with(".coderhelm/probes/") && path.ends_with(".json") +} + +/// The sandbox script that probes `url`: it writes `probe.json` (a +/// [`ProbeRecord`]) to `$CODERHELM_OUT`. +pub fn probe_script(url: &str) -> String { + let url = serde_json::to_string(url).unwrap_or_else(|_| "\"\"".into()); + format!( + r#"import {{ chromium }} from 'playwright'; +import {{ writeFileSync }} from 'node:fs'; +const out = process.env.CODERHELM_OUT || '.'; +const url = {url}; +const fields = new Set(); +const walk = (v, p, d) => {{ + if (d > 4 || v === null || typeof v !== 'object') return; + for (const [k, x] of Object.entries(Array.isArray(v) ? (v[0] ? {{ '0': v[0] }} : {{}}) : v)) {{ + const key = Array.isArray(v) ? p : (p ? `${{p}}.${{k}}` : k); + if (!Array.isArray(v)) fields.add(key); + walk(x, key, d + 1); + }} +}}; +const browser = await chromium.launch(); +const page = await browser.newPage(); +page.on('response', async (r) => {{ + try {{ + if ((r.headers()['content-type'] || '').includes('json')) walk(await r.json(), '', 0); + }} catch (e) {{}} +}}); +await page.goto(url, {{ waitUntil: 'networkidle', timeout: 45000 }}); +const ids = new Set(); +for (const f of page.frames()) {{ + try {{ + const got = await f.$$eval('[data-testid],[data-test],[data-cy],[data-test-id]', (els) => + els.map((e) => e.getAttribute('data-testid') || e.getAttribute('data-test') || e.getAttribute('data-cy') || e.getAttribute('data-test-id'))); + got.forEach((x) => x && ids.add(x)); + }} catch (e) {{}} +}} +await browser.close(); +writeFileSync(`${{out}}/probe.json`, JSON.stringify({{ + origin: new URL(url).host, url, at: new Date().toISOString(), + testids: [...ids].sort(), json_fields: [...fields].sort(), +}}, null, 2)); +"# + ) +} + +/// The quoted value of every `name('…')` call in `code`. +fn calls(code: &str, name: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = code; + while let Some(i) = rest.find(name) { + let after = &rest[i + name.len()..]; + rest = after; + let Some(q) = after + .chars() + .next() + .filter(|c| matches!(c, '\'' | '"' | '`')) + else { + continue; + }; + if let Some(end) = after[1..].find(q) { + out.push(after[1..1 + end].to_string()); + } + } + out +} + +/// The test ids a piece of end-to-end code uses. +pub fn selectors_in(code: &str) -> Vec { + let mut out: Vec = calls(code, "getByTestId("); + for attr in ["data-testid=", "data-test=", "data-cy=", "data-test-id="] { + out.extend(calls(code, attr)); + } + out.sort(); + out.dedup(); + out +} + +/// The JSON fields a piece of end-to-end code asserts on +/// (`toHaveProperty('a.b')`). +pub fn fields_in(code: &str) -> Vec { + let mut out = calls(code, "toHaveProperty("); + out.sort(); + out.dedup(); + out +} + +/// The https hosts a piece of code reaches that aren't the team's own +/// (`own` hosts and their subdomains, previews included). +pub fn outside_origins(code: &str, own: &[String]) -> Vec { + let mut out: Vec = Vec::new(); + for (i, _) in code.match_indices("https://") { + let host: String = code[i + 8..] + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) + .collect::() + .to_ascii_lowercase(); + if host.is_empty() || !host.contains('.') { + continue; + } + let ours = own.iter().any(|o| { + let o = o.to_ascii_lowercase(); + host == o || host.ends_with(&format!(".{o}")) + }) || host.contains("preview") + || host.contains("localhost") + || host.ends_with("example.com"); + if !ours && !out.contains(&host) { + out.push(host); + } + } + out +} + +/// A new or changed e2e file's selectors or fields no probe observed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Unprobed { + pub path: String, + pub origin: String, + pub missing: Vec, +} + +impl Unprobed { + /// The review finding's text. + pub fn body(&self) -> String { + format!( + "`{}` drives `{}`, a page another company serves, with {} that no probe of that page observed. Probe it first with the `probe_page` tool (on the preview or the vendor's URL), commit the record at `{}`, quote what it found in the pull request, and build the spec from the test ids and fields that are really there.", + self.path, + self.origin, + self.missing + .iter() + .map(|m| format!("`{m}`")) + .collect::>() + .join(", "), + record_path(&self.origin) + ) + } +} + +/// The gate: for each changed e2e file (path, its text at the head, its +/// added lines) that reaches an outside origin, the test ids and fields in +/// its added lines that no probe of that origin observed. +pub fn unprobed( + files: &[(String, String, String)], + probes: &[ProbeRecord], + own: &[String], +) -> Vec { + let mut out = Vec::new(); + for (path, full, added) in files { + let origins = outside_origins(full, own); + if origins.is_empty() { + continue; + } + let used: Vec = selectors_in(added) + .into_iter() + .chain(fields_in(added)) + .collect(); + if used.is_empty() { + continue; + } + for origin in origins { + let seen: Vec<&ProbeRecord> = probes + .iter() + .filter(|p| p.origin.eq_ignore_ascii_case(&origin)) + .collect(); + let missing: Vec = used + .iter() + .filter(|u| { + !seen.iter().any(|p| { + p.testids.iter().any(|t| t == *u) || p.json_fields.iter().any(|f| f == *u) + }) + }) + .cloned() + .collect(); + if !missing.is_empty() { + out.push(Unprobed { + path: path.clone(), + origin, + missing, + }); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const PAGE_OBJECT: &str = r#" +export class VendorCheckout { + url = 'https://checkout.vendor-pay.test/session'; + async pay() { + await this.page.frameLocator('iframe').getByTestId('card-number').fill('4111'); + await this.page.getByTestId('pay-button').click(); + expect(await res.json()).toHaveProperty('payment.status'); + } +} +"#; + + #[test] + fn selectors_on_an_outside_page_must_have_been_observed() { + let files = vec![( + "e2e/pages/vendor-checkout.ts".to_string(), + PAGE_OBJECT.to_string(), + PAGE_OBJECT.to_string(), + )]; + let own = vec!["web.example.org".to_string()]; + // No probe at all: every selector and field is unobserved. + let u = unprobed(&files, &[], &own); + assert_eq!(u.len(), 1); + assert_eq!(u[0].origin, "checkout.vendor-pay.test"); + assert_eq!( + u[0].missing, + vec!["card-number", "pay-button", "payment.status"] + ); + assert!(u[0] + .body() + .contains(".coderhelm/probes/checkout.vendor-pay.test.json")); + // A probe that saw two of them: the third is still flagged. + let probe = ProbeRecord { + origin: "checkout.vendor-pay.test".into(), + testids: vec!["card-number".into(), "submit".into()], + json_fields: vec!["payment.status".into()], + ..Default::default() + }; + let u = unprobed(&files, std::slice::from_ref(&probe), &own); + assert_eq!(u[0].missing, vec!["pay-button"]); + // Everything observed: nothing to flag. + let full = ProbeRecord { + testids: vec!["card-number".into(), "pay-button".into()], + ..probe + }; + assert!(unprobed(&files, &[full], &own).is_empty()); + } + + #[test] + fn the_teams_own_pages_and_previews_need_no_probe() { + let code = "await page.goto('https://pr-3.preview-web.example.org/');\nawait page.getByTestId('x').click();"; + let files = vec![( + "e2e/a.spec.ts".to_string(), + code.to_string(), + code.to_string(), + )]; + assert!(unprobed(&files, &[], &["example.org".to_string()]).is_empty()); + assert!(probe_script("https://a.test/x").contains("probe.json")); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index b0305d4c3..1e7625f4f 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -156,6 +156,7 @@ pub mod knowledge; // Reading the team's repositories for Chat (overview, files, search). pub mod repo_read; // The test that every model call site is a metered helper +pub mod ci_cover; #[cfg(test)] mod model_call_sites; /// Which pull requests CoderHelm may push to, edit or close: its own. diff --git a/services/common/src/preview.rs b/services/common/src/preview.rs index b63cbf5ed..5544cacaa 100644 --- a/services/common/src/preview.rs +++ b/services/common/src/preview.rs @@ -676,6 +676,13 @@ pub struct State { pub draft_gated: Vec, /// The commands that check the changed area ([`how_to_check`]). pub how_to_check: String, + /// The CI jobs that run on the changed paths (`crate::ci_cover`): + /// "How to check" and Open items name these, never another folder's. + pub ci_jobs: Vec, + /// The failed end-to-end checks on the head, each as its own report + /// says (`crate::e2e::failure_read`), with whether this change caused + /// it. + pub failures: Vec, } impl State { diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 374129aaf..eabbcc8ab 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -4418,6 +4418,28 @@ impl GitHubClient { // ─── Check runs ───────────────────────────────────────────── + /// One check run's annotations, as (path, title, message). + pub async fn check_run_annotation_list( + &self, + owner: &str, + repo: &str, + check_run_id: u64, + ) -> Result, Box> { + let v = self + .get(&format!( + "{API_BASE}/repos/{owner}/{repo}/check-runs/{check_run_id}/annotations?per_page=50" + )) + .await?; + Ok(v.as_array() + .into_iter() + .flatten() + .map(|a| { + let t = |k: &str| a[k].as_str().unwrap_or("").to_string(); + (t("path"), t("title"), t("message")) + }) + .collect()) + } + /// Download check run / action job logs. pub async fn get_check_run_logs( &self, diff --git a/services/worker/src/passes/description_facts.rs b/services/worker/src/passes/description_facts.rs index f5755ba3b..79623c156 100644 --- a/services/worker/src/passes/description_facts.rs +++ b/services/worker/src/passes/description_facts.rs @@ -486,6 +486,78 @@ pub fn with_preview(f: &mut Facts, preview: Option<&common::preview::State>) { why: "the repository has an end-to-end suite and the change adds no spec to it; CoderHelm writes one".into(), }); } + scope_to_change(f); +} + +/// The backticked check commands a line names. +fn commands_in(text: &str) -> Vec { + text.split('`') + .skip(1) + .step_by(2) + .filter(|c| common::ci_cover::is_check_command(c)) + .map(str::to_string) + .collect() +} + +/// Holds "How to check" and Open items to the change: a check command +/// aimed at a folder the change doesn't touch is dropped (the CI job that +/// covers the change, or "no CI job covers this", is said instead), and a +/// failed end-to-end check is said from its own report, never "couldn't be +/// read" while it has one (`common::ci_cover`, `common::e2e::failure_read`). +pub fn scope_to_change(f: &mut Facts) { + let Some(p) = f.preview.clone() else { + return; + }; + let changed: Vec = f.files.iter().map(|x| x.path.clone()).collect(); + let fits = |t: &str| { + commands_in(t) + .iter() + .all(|c| common::ci_cover::command_fits(c, &changed)) + }; + let before = f.open.len() + f.unverified.len(); + f.open.retain(|o| fits(&o.text)); + f.unverified.retain(|u| fits(&u.what) && fits(&u.why)); + if !p.failures.is_empty() { + let unread = |t: &str| common::e2e::failure_read::says_unreadable(t); + f.open.retain(|o| !unread(&o.text)); + f.unverified.retain(|u| !unread(&u.what) && !unread(&u.why)); + } + let dropped = before != f.open.len() + f.unverified.len(); + if !fits(&f.how_to_check) { + f.how_to_check = match p.ci_jobs.first() { + Some(j) => { + let cmd = j.commands.first().cloned().unwrap_or_default(); + if j.dir.is_empty() { + format!("`{cmd}`") + } else { + format!("`cd {} && {cmd}`", j.dir) + } + } + None => String::new(), + }; + } + let ci = common::ci_cover::line(&p.ci_jobs); + if !f.evidence.contains(&ci) { + f.evidence.push(ci.clone()); + } + if dropped && p.ci_jobs.is_empty() && !f.notes.contains(&format!("{ci}.")) { + f.notes.push(format!("{ci}.")); + } + for r in &p.failures { + let line = r.line(); + if !f.evidence.contains(&line) { + f.evidence.push(line.clone()); + } + let what = format!("`{}` on this head", r.check); + if matches!(r.cause, common::e2e::failure_read::Cause::ThisChange(_)) + && !f.unverified.iter().any(|u| u.what == what) + { + f.unverified.push(Unverified { + what, + why: "it fails because of this change (its report says why); CoderHelm fixes it like any failing check".into(), + }); + } + } } /// A description in its final shape, the facts it shows and what the check @@ -604,6 +676,8 @@ pub fn shape_for( } else { computed }; + // Open items were read again from the text: held to the change again. + scope_to_change(&mut facts); let checked = pr_reader::without_sections(&checked, &slots.drop); // 3. The visible part, the generated blocks below it and the steps and // evidence, from the facts; the written text goes in the first fold. diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 2b6dbea85..ba32a647a 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -891,6 +891,7 @@ Rules: format!("{}/{}#{}", msg.repo_owner, msg.repo_name, msg.pr_number), ); tools.push(super::web_check::tool()); + tools.push(super::web_check::probe_tool()); full_system.push_str(&web.prompt_section()); let ops = super::ops_tools::OpsTools::load( state, diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 75912a68f..f71fe1e3a 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -700,6 +700,7 @@ pub async fn run( ), ); tools.push(super::web_check::tool()); + tools.push(super::web_check::probe_tool()); full_system.push_str(&web.prompt_section()); full_system.push_str(super::link_checks::CODER_NOTE); let ops = super::ops_tools::OpsTools::load( diff --git a/services/worker/src/passes/incidents/bu_web_change_unchecked.rs b/services/worker/src/passes/incidents/bu_web_change_unchecked.rs index 4949b53e7..f84446789 100644 --- a/services/worker/src/passes/incidents/bu_web_change_unchecked.rs +++ b/services/worker/src/passes/incidents/bu_web_change_unchecked.rs @@ -268,3 +268,72 @@ fn the_run_page_says_what_it_waits_on_in_one_line() { "Waiting on: an approving review from a person on #42 (this repo requires one before CoderHelm merges). Ready for review: checks passed, preview checked." ); } + +/// The same review, a second pull request: its Open items told a reader to +/// run `npm test` in an unrelated function's folder, and it said the e2e +/// log couldn't be read while the e2e workflow's comment named the failing +/// test. "How to check" and Open items come from the jobs that test the +/// changed paths; a failure is said from its own report. +#[test] +fn open_items_name_the_job_that_covers_the_change_and_failures_are_read() { + use common::e2e::failure_read as fr; + use common::pr_facts::{Closer, OpenItem}; + let jobs = common::ci_cover::covering_jobs( + &[( + "web.yml".to_string(), + "on:\n pull_request:\n paths: ['apps/web/**']\njobs:\n unit:\n name: Web unit tests\n defaults:\n run:\n working-directory: apps/web\n steps:\n - run: npm test\n".to_string(), + )], + &changed(), + "main", + ); + let mut failure = fr::read( + "E2E on preview", + &fr::Sources { + comment: "1 failed\n 1) [chromium] › tests/signup.spec.ts:9:3 › Signup › shows the age error\n Error: expect(locator).toBeVisible() failed".into(), + ..Default::default() + }, + ) + .unwrap(); + failure.cause = fr::cause(&failure, &changed(), Some(false)); + let st = pv::State { + head: "abc1234def".into(), + stage: Stage::Failed, + ci_jobs: jobs, + failures: vec![failure], + ..Default::default() + }; + let mut f = facts(None); + f.open = vec![ + OpenItem { + text: "Run `cd services/uploader-fn && npm test` before merge".into(), + closer: Closer::CoderHelm, + }, + OpenItem { + text: "CoderHelm couldn't read the log of the E2E run".into(), + closer: Closer::CoderHelm, + }, + OpenItem { + text: "Run `cd apps/web && npm test`".into(), + closer: Closer::CoderHelm, + }, + ]; + f.how_to_check = "`cd services/uploader-fn && npm test`".into(); + crate::passes::description_facts::with_preview(&mut f, Some(&st)); + let texts: Vec<&str> = f.open.iter().map(|o| o.text.as_str()).collect(); + assert_eq!(texts, vec!["Run `cd apps/web && npm test`"]); + assert_eq!(f.how_to_check, "`cd apps/web && npm test`"); + assert!(f + .evidence + .iter() + .any(|e| e.contains("`Web unit tests` in `apps/web` runs `npm test`"))); + let read = f + .evidence + .iter() + .find(|e| e.starts_with("`E2E on preview` failed")) + .expect("the failure, read"); + assert!( + read.contains("tests/signup.spec.ts › shows the age error"), + "{read}" + ); + assert!(read.contains("This change caused it"), "{read}"); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 346b52a78..456a62a82 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -9981,7 +9981,11 @@ flow) and the repository has an end-to-end suite (a Playwright or Cypress config an end-to-end spec in that suite for the new behaviour, in this same branch. Follow the suite's own \ conventions: its folder, page objects and fixtures, tags and area labels, its test map, and the \ AGENTS.md / CLAUDE.md files next to it. The spec must fail without the change and pass with it; \ -CoderHelm runs it on the pull request's preview. Unit tests alone don't cover a change a person sees.\n"; +CoderHelm runs it on the pull request's preview. Unit tests alone don't cover a change a person sees. \ +Assert what the person sees. Before writing selectors or reading JSON of a page another company serves \ +(a payment form, a sign-in widget), probe it with `probe_page` (on the preview or the vendor's URL), commit \ +the record it returns, quote the test ids and fields you use in the pull request, and use only those: the \ +review flags any it can't find in a probe.\n"; pub(crate) fn attr_s(val: &str) -> aws_sdk_dynamodb::types::AttributeValue { aws_sdk_dynamodb::types::AttributeValue::S(val.to_string()) diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 3fe4de8b2..a4ec08c70 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -950,7 +950,11 @@ pub async fn look(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> } }; let mut seen = seen; - seen.preview_due = seen.open && preview_due(&c.preview, &seen.head, kept.is_none()); + seen.preview_due = seen.open + && (preview_due(&c.preview, &seen.head, kept.is_none()) + || common::preview::State::from_json(&c.preview).is_some_and(|st| { + st.head == seen.head && super::preview::unread_failure(&st, &seen.failing) + })); let mut act = resume_after_limit(&c.status, &seen, &c.marks, &c.limit_ended) .unwrap_or_else(|| decide_all(&c.status, &seen, &c.marks)); let mut performed = Performed::NotStarted; diff --git a/services/worker/src/passes/preview.rs b/services/worker/src/passes/preview.rs index 3b7fe5a81..889e5fa13 100644 --- a/services/worker/src/passes/preview.rs +++ b/services/worker/src/passes/preview.rs @@ -86,6 +86,15 @@ async fn save(state: &WorkerState, p: Pr<'_>, st: &State) { } } +/// An end-to-end check failing on the head whose report the state hasn't +/// read: it is read before anything is said about it. +pub fn unread_failure(st: &State, failing: &[String]) -> bool { + failing + .iter() + .filter(|f| pv::role_of(f) == pv::Role::E2e) + .any(|f| !st.failures.iter().any(|r| &r.check == f)) +} + /// A state that needs nothing more on its head. pub fn settled(st: &State, head: &str) -> bool { st.head == head @@ -237,6 +246,101 @@ async fn nudge(gh: &GitHubClient, owner: &str, repo: &str, branch: &str, head: & .unwrap_or(false) } +/// Each failed end-to-end check on the head, read from its own report +/// before anything is said about it: the e2e workflow's comment on the +/// pull request, the check's annotations, the job's log +/// (`common::e2e::failure_read`), with whether this change caused it (the +/// same check on the base branch's head). +async fn read_failures( + gh: &GitHubClient, + p: Pr<'_>, + base: &str, + runs: &serde_json::Value, + changed: &[String], +) -> Vec { + use common::e2e::failure_read as fr; + let failed: Vec<&serde_json::Value> = runs["check_runs"] + .as_array() + .into_iter() + .flatten() + .filter(|r| outcome_of(r) == Outcome::Failed) + .filter(|r| pv::role_of(r["name"].as_str().unwrap_or("")) == pv::Role::E2e) + .take(3) + .collect(); + if failed.is_empty() { + return Vec::new(); + } + let comments = gh + .list_issue_comments(p.owner, p.repo, p.number) + .await + .unwrap_or_default(); + let base_runs = match gh.get_ref(p.owner, p.repo, base).await { + Ok(sha) => gh + .list_check_runs_for_ref(p.owner, p.repo, &sha) + .await + .unwrap_or_default(), + Err(_) => serde_json::Value::Null, + }; + let mut out = Vec::new(); + for r in failed { + let name = r["name"].as_str().unwrap_or("").to_string(); + let id = r["id"].as_u64().unwrap_or(0); + let comment = comments + .iter() + .rev() + .filter(|c| c["user"]["type"].as_str() == Some("Bot")) + .filter_map(|c| c["body"].as_str()) + .find(|b| { + let l = b.to_ascii_lowercase(); + (l.contains(&name.to_ascii_lowercase()) + || l.contains("e2e") + || l.contains("playwright") + || l.contains("end-to-end")) + && (l.contains("fail") || l.contains('✘') || l.contains('❌')) + }) + .unwrap_or("") + .to_string(); + let annotations = if id > 0 { + gh.check_run_annotation_list(p.owner, p.repo, id) + .await + .unwrap_or_default() + } else { + Vec::new() + }; + let log = if id > 0 && comment.is_empty() && annotations.is_empty() { + gh.get_check_run_logs(p.owner, p.repo, id) + .await + .map(|l| { + let lines: Vec<&str> = l.lines().collect(); + lines[lines.len().saturating_sub(300)..].join("\n") + }) + .unwrap_or_default() + } else { + String::new() + }; + let sources = fr::Sources { + comment, + annotations, + log, + }; + let Ok(mut read) = fr::read(&name, &sources) else { + // Nothing at all to read: said as such, and only then. + continue; + }; + let base_failed = base_runs["check_runs"] + .as_array() + .into_iter() + .flatten() + .filter(|b| b["name"].as_str() == Some(name.as_str())) + .map(outcome_of) + .find(|o| matches!(o, Outcome::Passed | Outcome::Failed)) + .map(|o| o == Outcome::Failed); + read.cause = fr::cause(&read, changed, base_failed); + out.push(read); + } + out +} + /// Reads where the preview of the pull request's head stands, starts what /// the repository's workflows need to run it, and records it. `pr` is the /// pull request as GitHub returns it. None when it couldn't be read. @@ -255,7 +359,22 @@ pub async fn advance( } let prior = load(state, p.team_id, p.run_id).await; if let Some(st) = prior.as_ref().filter(|st| settled(st, &head)) { - return Some(st.clone()); + // Settled, unless an end-to-end check failed since and its report + // hasn't been read. + let runs = gh + .list_check_runs_for_ref(p.owner, p.repo, &head) + .await + .unwrap_or_default(); + let failing: Vec = runs["check_runs"] + .as_array() + .into_iter() + .flatten() + .filter(|r| outcome_of(r) == Outcome::Failed) + .filter_map(|r| r["name"].as_str().map(str::to_string)) + .collect(); + if !unread_failure(st, &failing) { + return Some(st.clone()); + } } let same_head = prior.as_ref().filter(|st| st.head == head); let changed: Vec = gh @@ -273,6 +392,15 @@ pub async fn advance( .unwrap_or_default(), ..Default::default() }; + // The CI jobs that test the changed paths, for every change: "How to + // check" and Open items name these, never another folder's job. + let wfs = workflows(gh, p.owner, p.repo, &head).await; + st.ci_jobs = common::ci_cover::covering_jobs(&wfs, &changed, &base); + let runs = gh + .list_check_runs_for_ref(p.owner, p.repo, &head) + .await + .unwrap_or_default(); + st.failures = read_failures(gh, p, &base, &runs, &changed).await; if !changed.iter().any(|c| pv::is_user_visible(c)) { st.why = "the change has no page a person sees".into(); save(state, p, &st).await; @@ -290,7 +418,6 @@ pub async fn advance( st.e2e_covered = *covered; } st.how_to_check = pv::how_to_check(&changed, suite.as_ref(), &pv::unit_cmd(&tree)); - let wfs = workflows(gh, p.owner, p.repo, &head).await; let areas = map_areas(gh, p.owner, p.repo, &head, &tree, &changed).await; let repo_labels: Vec = gh .list_repo_labels(p.owner, p.repo) @@ -370,10 +497,6 @@ pub async fn advance( .join(", ") )); } - let runs = gh - .list_check_runs_for_ref(p.owner, p.repo, &head) - .await - .unwrap_or_default(); let (results, url) = covering_results(&runs, &plan.covers); st.checks = results; let triggered = !st.labels_added.is_empty() || draft; diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 2c8f19a6f..cf6a9dd47 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -170,6 +170,64 @@ pub(crate) async fn named_labels( .unwrap_or_default() } +/// The review's findings for changed end-to-end files that drive another +/// company's page with test ids or JSON fields no probe recorded in the +/// repository (`common::e2e::probe`) observed. +async fn probe_gaps( + state: &WorkerState, + github: &GitHubClient, + (team_id, owner, repo): (&str, &str, &str), + head_sha: &str, + compare: &serde_json::Value, + tree: &[String], +) -> Vec { + let suite = common::preview::e2e_suite(tree); + let mut files = Vec::new(); + for f in compare["files"].as_array().into_iter().flatten().take(60) { + let path = f["filename"].as_str().unwrap_or(""); + let is_e2e = match &suite { + Some(s) => common::preview::is_e2e_spec(path, s), + None => path.contains("e2e/") || path.contains(".spec.") || path.contains(".cy."), + }; + if !is_e2e || f["status"].as_str() == Some("removed") { + continue; + } + let added: String = f["patch"] + .as_str() + .unwrap_or("") + .lines() + .filter(|l| l.starts_with('+') && !l.starts_with("+++")) + .map(|l| &l[1..]) + .collect::>() + .join("\n"); + if added.is_empty() { + continue; + } + let full = github + .read_file(owner, repo, path, head_sha) + .await + .unwrap_or_else(|_| added.clone()); + files.push((path.to_string(), full, added)); + } + if files.is_empty() { + return Vec::new(); + } + let mut probes = Vec::new(); + for p in tree + .iter() + .filter(|p| common::e2e::probe::is_record(p)) + .take(20) + { + if let Ok(text) = github.read_file(owner, repo, p, head_sha).await { + if let Ok(r) = serde_json::from_str::(&text) { + probes.push(r); + } + } + } + let own = super::web_check::team_domains(state, team_id).await; + super::review_rules::probe_findings(&common::e2e::probe::unprobed(&files, &probes, &own)) +} + /// True when the repo turned on "Require tests" (and review isn't off/killed). /// The same switch makes the reviewer block untested behavior changes and makes /// CoderHelm's own coding passes write those tests. @@ -3360,23 +3418,34 @@ async fn run_once( // A change a person sees, in a repository with an end-to-end suite, // carries a spec for it: a finding by rule, read from the paths and the // tree, whatever the model said. - if changed_list - .iter() - .any(|p| common::preview::is_user_visible(p)) + if let Ok(tree) = github + .get_tree(&msg.repo_owner, &msg.repo_name, &head_sha) + .await { - if let Ok(tree) = github - .get_tree(&msg.repo_owner, &msg.repo_name, &head_sha) - .await + let tree: Vec = tree.into_iter().map(|e| e.path).collect(); + if let Some(f) = super::review_rules::e2e_finding(&changed_list, &tree) { + info!( + pr = msg.pr_number, + "A visible change with no end-to-end spec: must fix" + ); + findings.retain(|x| x.title != f.title); + findings.push(f); + } + // End-to-end code against another company's page: only test ids + // and fields a probe of that page observed. + for f in probe_gaps( + state, + &github, + (&msg.team_id, &msg.repo_owner, &msg.repo_name), + &head_sha, + &compare, + &tree, + ) + .await { - let tree: Vec = tree.into_iter().map(|e| e.path).collect(); - if let Some(f) = super::review_rules::e2e_finding(&changed_list, &tree) { - info!( - pr = msg.pr_number, - "A visible change with no end-to-end spec: must fix" - ); - findings.retain(|x| x.title != f.title); - findings.push(f); - } + info!(pr = msg.pr_number, file = %f.file, "End-to-end selectors no probe observed: must fix"); + findings.retain(|x| x.title != f.title || x.file != f.file); + findings.push(f); } } review_agent::enforce_source_data_override(&mut findings); diff --git a/services/worker/src/passes/review_rules.rs b/services/worker/src/passes/review_rules.rs index ec61b6a29..292455cba 100644 --- a/services/worker/src/passes/review_rules.rs +++ b/services/worker/src/passes/review_rules.rs @@ -69,6 +69,28 @@ pub fn e2e_finding(changed: &[String], tree: &[String]) -> Option { }) } +/// The rule that end-to-end code against another company's page uses only +/// what a probe of that page observed. +pub const PROBE_RULE: &str = "end-to-end selectors and JSON fields on another company's page come from a probe of that page (`probe_page`)"; + +/// The review's findings for end-to-end code that uses test ids or JSON +/// fields of an outside page no probe observed (`common::e2e::probe`). +pub fn probe_findings(gaps: &[common::e2e::probe::Unprobed]) -> Vec { + gaps.iter() + .map(|g| Finding { + file: g.path.clone(), + severity: "blocking".into(), + category: "tests".into(), + title: format!("Selectors on `{}` that no probe observed", g.origin), + body: g.body(), + evidence: Some("verified-defect".into()), + caused_by_diff: Some(true), + required: Some(PROBE_RULE.to_string()), + ..Default::default() + }) + .collect() +} + /// Why a required rule broken blocks. pub const REQUIRED_WHY: &str = "a rule this repository requires is broken"; /// Why a failing check blocks. @@ -630,6 +652,21 @@ pub fn settles(thread_body: &str, status: &str) -> bool { mod e2e_rule_tests { use super::*; + #[test] + fn unobserved_outside_selectors_are_a_must_fix() { + let code = + "const url = 'https://pay.vendor.test/s';\nawait page.getByTestId('pay-now').click();"; + let gaps = common::e2e::probe::unprobed( + &[("e2e/pages/pay.ts".into(), code.into(), code.into())], + &[], + &["web.example.org".into()], + ); + let f = probe_findings(&gaps); + assert_eq!(f.len(), 1); + assert_eq!(mandatory(&f[0]), Some(REQUIRED_WHY)); + assert!(f[0].body.contains("`pay-now`")); + } + fn s(v: &[&str]) -> Vec { v.iter().map(|x| x.to_string()).collect() } diff --git a/services/worker/src/passes/web_check.rs b/services/worker/src/passes/web_check.rs index c1c8cf573..8bf0a75bd 100644 --- a/services/worker/src/passes/web_check.rs +++ b/services/worker/src/passes/web_check.rs @@ -70,6 +70,37 @@ const SOURCE_NAME: &str = "Public page check"; pub const SETTINGS_SK: &str = "REVIEW_CONFIG#GLOBAL"; pub const SETTINGS_ATTR: &str = common::web_domains::ATTR; +/// Probes a page before end-to-end code is written against it. +pub const PROBE_TOOL: &str = "probe_page"; + +/// The coder's probe of a page another company serves (a payment form, a +/// sign-in widget), or of the preview: it loads the page with Playwright +/// in the sandbox and returns its test ids and the field names of the JSON +/// it fetches, as a record to commit (`common::e2e::probe`). Selectors and +/// fields no probe observed are a must-fix finding of the review. +pub fn probe_tool() -> ToolDefinition { + ToolDefinition { + name: PROBE_TOOL.to_string(), + description: format!( + "Load a page in a real browser (Playwright, in the sandbox) and list what is really \ + there: every test id (data-testid, data-test, data-cy, also inside frames) and the \ + field names of the JSON responses it fetches. Use it BEFORE writing end-to-end \ + selectors or reading JSON fields of a page another company serves (or a page on \ + the preview), and build the spec only from what it found. Commit the record it \ + returns at `{}`, and quote what it found in the pull request. Only hosts this run \ + may check are allowed.", + common::e2e::probe::record_path("") + ), + input_schema: json!({ + "type": "object", + "properties": { + "url": { "type": "string", "description": "The https page to probe" } + }, + "required": ["url"] + }), + } +} + pub fn tool() -> ToolDefinition { ToolDefinition { name: TOOL.to_string(), @@ -996,6 +1027,13 @@ impl WebCheck { name: &str, input: &Value, ) -> Option { + if name == PROBE_TOOL { + let gate = RepoGate { + web: self, + search: github, + }; + return Some(self.probe(state, &gate, input).await); + } if name != TOOL { return None; } @@ -1006,6 +1044,73 @@ impl WebCheck { Some(self.run_urls(state, &gate, &Net, input).await) } + /// Runs [`probe_tool`]: the page's host must be one this run may check. + async fn probe(&self, state: &WorkerState, gate: &dyn HostGate, input: &Value) -> String { + let url = input["url"].as_str().unwrap_or("").trim().to_string(); + let (parsed, host) = match vet_url(&url) { + Ok(v) => v, + Err(CheckError::Refused(m)) | Err(CheckError::Failed(m)) => { + return format!("{url}: refused: {m}") + } + }; + if !gate.allowed(&host).await { + return format!( + "{url}: refused: `{host}` isn't a host this run may load (name it in the work at hand, or it must be used in the team's repositories)" + ); + } + let source = match super::skill_run::pack(&[( + "probe.mjs".to_string(), + common::e2e::probe::probe_script(parsed.as_str()), + )]) { + Ok(b) => b, + Err(e) => return format!("The probe couldn't be packed: {e}"), + }; + 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, &self.team_id).await); + let mut hosts: Vec = common::preview::CAPTURE_HOSTS + .iter() + .map(|h| h.to_string()) + .collect(); + hosts.push(host.clone()); + let cmd = common::preview::capture_command().replace("capture.mjs", "probe.mjs"); + let key = format!("probe-{}", uuid::Uuid::new_v4().simple()); + let out = sandbox + .run_script( + crate::clients::sandbox::ScriptRun { + key: &key, + source, + cmd: &cmd, + secret: None, + hosts, + }, + None, + ) + .await; + let record = match out { + Ok(o) => match o.files.iter().find(|(n, _)| n.ends_with("probe.json")) { + Some((_, body)) => body.clone(), + None => { + return format!( + "{url}: the probe gave no record ({})", + common::truncate_str(o.output.lines().last().unwrap_or(""), 200) + ) + } + }, + Err(e) => return format!("{url}: the sandbox couldn't run the probe ({e})"), + }; + format!( + "Probe of {url}. Commit this record at `{}` and quote the test ids and fields you use in the pull request; write selectors and field reads only from it:\n{}", + common::e2e::probe::record_path(&host), + common::truncate_str(&record, 12_000) + ) + } + async fn run_urls( &self, state: &WorkerState, From 133a84908a2b58c84bf27d1c64919754aab12eab Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 16 Nov 2026 18:46:36 -0500 Subject: [PATCH 3/4] The coder plans, builds and is reviewed as the smallest change the ticket asks for Explore before planning (the ticket's own names are searched and handed to the planner), five required plan sections (Reuse, Must not change, Measure first, Smallest change, Proof) with a gate that sends back parallel structures, widening the ticket doesn't ask for, unmeasured outside pages and test-for-product flips; a coder guard that needs a search and a reuse list before the first write and refuses a twin of an existing map or helper; a diff check after the build and in the review for parallel structures, deletes or overwrites where the base only added, log level changes, unasked reporting, oversized tests and invented payloads; and data rules that ask for skip reporting only when the ticket does. --- docs/coder-loop.md | 127 ++ docs/incidents.md | 1 + services/worker/src/passes/explore_guard.rs | 231 ++++ .../worker/src/passes/feature/data_rules.rs | 34 +- services/worker/src/passes/feature/mod.rs | 6 + services/worker/src/passes/habits_check.rs | 73 +- services/worker/src/passes/implement.rs | 66 +- .../passes/incidents/bx_smallest_change.rs | 269 ++++ services/worker/src/passes/incidents/mod.rs | 1 + services/worker/src/passes/minimal_change.rs | 1091 +++++++++++++++++ services/worker/src/passes/mod.rs | 3 + services/worker/src/passes/plan.rs | 52 +- services/worker/src/passes/plan_shape.rs | 607 +++++++++ services/worker/src/passes/review_pr.rs | 83 ++ services/worker/src/passes/review_rules.rs | 86 ++ 15 files changed, 2713 insertions(+), 17 deletions(-) create mode 100644 docs/coder-loop.md create mode 100644 services/worker/src/passes/explore_guard.rs create mode 100644 services/worker/src/passes/incidents/bx_smallest_change.rs create mode 100644 services/worker/src/passes/minimal_change.rs create mode 100644 services/worker/src/passes/plan_shape.rs diff --git a/docs/coder-loop.md b/docs/coder-loop.md new file mode 100644 index 000000000..db9a47af7 --- /dev/null +++ b/docs/coder-loop.md @@ -0,0 +1,127 @@ +# The coder's loop + +How CoderHelm turns a ticket into a change: explore, measure, plan the smallest +change, implement, review it against the ticket, prove it. Each step has a check +in code, so the loop holds whatever the model writes. + +## Why + +Two pull requests show what went wrong. + +- **A data-pipeline ticket** asked to link four camps to a second sport. The plan + added a second map and helpers beside the existing overrides map, and made an + insert-only link sync replace and delete links. The build added warnings, three + counters and a log level change in shared code, plus a 432-line test with fake + hooks and an invented payload. The right change was four map entries, an insert + that does nothing on conflict, and one small test. +- **A web ticket's** end-to-end tests for a vendor's embedded portal were rewritten + three times, each time on a guess about the vendor's page. When a criterion met + the vendor's behaviour, the test was changed instead of the page. + +The causes were in the loop, not only in prompt wording: + +- The planner was told to use "2-4 tool calls" on a simple ticket and not to read + whole files. It never saw the map it should have extended. +- The data rules told every change that touched a pipeline to add counters and a + warning for each skip, and a fix round enforced it. +- Nothing compared the diff with the ticket. The scope checks compared files with + the plan, and the plan was already too wide. +- Nothing stopped the coder writing before it searched, or adding a twin of a + structure that was already there. +- Outside pages were never measured, and nothing caught a test bent to a vendor + against a criterion. + +## The loop + +1. **Explore.** Before the planner runs, the worker searches the repository for the + ticket's own names (backticked code, identifiers, quoted names, capitalised + names) and gives the planner the hits (`plan_shape::existing_for_ticket`). + The planner is told to read the structure it extends in full, along with its + writers and readers. + +2. **Measure.** The plan has a `## Measure first` section listing every outside + system the change or its tests rest on, and how each was measured: `probe_page` + for a page (from #734), a read-only lookup for data, or `None`. A plan for a + ticket about an embed, vendor, portal, webhook or partner that measured nothing + is sent back. + +3. **Plan the smallest change.** design.md has five sections: + - `## Reuse` + - `## Must not change` + - `## Measure first` + - `## Smallest change` + - `## Proof` + + `plan_shape::plan_gaps` sends the plan back when a section is missing. It also + sends it back when the plan: + - adds a name parallel to one it reuses or one the search found; + - deletes, overwrites, upserts or prunes when the ticket asks for none of that; + - changes logging or adds reporting the ticket doesn't ask for; + - would change a test to match an outside system while the ticket's acceptance + criteria say what the product must do. + + Whatever is still open after the one send-back stays on the decision. + +4. **Implement.** In the coder's tool loop (`explore_guard`): + - The first write of a build is refused until a search has run and the write + names what it reuses (`reuses`). + - An edit that adds a top-level map, helper or config beside a similar existing + one is refused unless it says why (`why_new`). + + Both are kept as evidence lines. The coder's prompt carries the same rules + (`SMALLEST_CHANGE_RULES`). The data rules ask for reporting on a skip only when + the ticket asks for it. + +5. **Review against the ticket.** After the build, the habits check reads the diff + against the base and the ticket (`minimal_change::check`). It flags: + - parallel structures; + - deleting or overwriting semantics where the base only added; + - log level changes; + - new counters and log calls nobody asked for; + - tests out of proportion to the code; + - large fake payloads with no probe record. + + Each goes to the fix round as "make it smaller". A `Wider than the ticket: + : ` line keeps an item, except deletes and invented payloads: only + the ticket can ask for those. The reviewer runs the same check. Deletes, an + unobserved payload, and a test assertion flipped to an outside page's + behaviour against an acceptance criterion are required findings + (`review_rules::SMALLEST_RULE`). + +6. **Prove.** Each new or changed test runs in the sandbox with and without the + change (`habits_check`). A test the runner finds nothing in goes back to the + coder, and the coder quotes the run's output in its Evidence. End-to-end code + against another company's page uses only what a probe observed (#734). + +## What is deterministic + +Everything above except the model's own writing: the searches, section checks, +word checks, definition parsing, diff checks and refusals are plain code with unit +tests. `incidents::bx_smallest_change` replays both pull requests through the plan +gate, the coder's guard, the habits check and the reviewer. The plans and diffs +as they were are sent back; the small ones pass. + +## Sources + +- Claude Code best practices: explore, then plan, then code; give the agent a way + to verify; review against the spec. https://code.claude.com/docs/en/best-practices +- Claude prompting best practices: the minimum complexity the task needs; don't + touch code you weren't asked to change; tests check correctness and don't define + the solution. + https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices +- Building effective agents: ground truth from the environment at each step; tools + that are hard to misuse. https://www.anthropic.com/engineering/building-effective-agents +- SWE-agent: search tools, a bounded file viewer, and edits checked as they are + made. https://arxiv.org/abs/2405.15793 +- OpenHands: agents that browse and run code in a sandbox to see the real system. + https://arxiv.org/abs/2407.16741 +- Agentless: find the files, then the functions, then the lines, before editing; + keep only reproduction tests that fail on the original code. + https://arxiv.org/abs/2407.01489 +- Aider: a repository map so the model reuses what exists; edits that send only + the changed parts. https://aider.chat/docs/repomap.html, + https://aider.chat/docs/more/edit-formats.html +- Google engineering practices: one self-contained change per CL; reviewers look + for over-engineering and features nobody asked for. + https://google.github.io/eng-practices/review/developer/small-cls.html, + https://google.github.io/eng-practices/review/reviewer/looking-for.html diff --git a/docs/incidents.md b/docs/incidents.md index 42d96bcc4..bd5617ce1 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -98,6 +98,7 @@ pipeline still calls it there. | br. `br_description_writer_upgrade` | After the description writer was upgraded (a final review in the one save, the repository's template as the structure), a pull request opened the day before kept its old text: six checks "Not run: still running when this was written", the file to read first and the way back said twice, filler and a raw page id. Its head had not moved and its checked text was unchanged, so its stamp said current and nothing rebuilt it. | The stamp names the writer version (`description::WRITER`, raised with every change to what a description says or how it is laid out); a description built by another writer, or before the version, is not current. The pull request watch's sweep catches up open pull requests CoderHelm opened, whatever the age of their run: a few per team each sweep (`pr_watch::CATCH_UP_PER_TEAM`), inside its GitHub budget, each rebuilt once and marked on its run. A description still wholly CoderHelm's is built again from the facts of the head alone: nothing of the old text is kept, not even in a fold, except a line that closes an issue. A description with no CoderHelm stamp, or whose checked text a person changed, is left as it is. | | bs. `bs_cut_plan_revision` | A ticket with a long history was planned, and the plan check sent the plan back with two open items. The revision reached the output limit partway through its last block. The planner was told the coder's note ("make a change in small edit_file calls"), wrote only its decision block again, and the worker read only that last turn: no tasks, no design. The run failed with "empty or malformed plan ... retry the run" and the first plan was thrown away. | A planner's cut answer is continued where it stopped and read together with what came before the cut, file by file (`plan_sections`). A cut turn's note fits its loop: the coder's edit note only where there are edit tools, the planner's "continue the document" note, a shorter answer for everyone else. A revision that comes back empty, cut off or malformed never replaces a valid file, and a send-back asks for only the files that change. Files still missing are asked for alone, twice at most, the second with a larger output budget. A plan still not usable is planned again in a fresh step, then reported as CoderHelm's own failure, saying what it lacked. No run tells a person to retry it. | | bt. `bt_proof_answer_closes` | A security update's own review asked for proof of the build and unit tests on the head. The fix rounds changed no code: the second ran every check on the head, all passing, and one runtime check it started was cut short by the step's time. The ledger counted that as a block, the round pushed nothing so no review read the head again, and the draft was held for a person ("Fix them on the branch, or remove a finding") while the merge standing said no person was needed. | A round that pushed nothing is read by a review of the same head, with the round's account in the reviewer's context, and a finding answered with proof closes there. A command, check or codegen a step is too short to start is owed: the pass continues in a fresh step that runs it first, and a round cut short by time is never a block. Nothing on CoderHelm's side holds a draft for a person: what is left after every approach is listed as CoderHelm's note and the pull request goes ready, with CoderHelm's verdict kept so nothing merges over it. A stuck run is sent back to its review on the next look of the ready sweep or the pull request's watch. | +| bx. `bx_smallest_change` | A ticket asked to link four camps to a second sport. The plan added a second map and helpers beside the existing overrides map and made an insert-only link sync replace and delete links; the build added warnings, three counters and a log level change in shared code (the data rules asked for reporting on any skip) and a 432-line test with fake hooks and an invented payload. A web ticket's vendor end-to-end tests were rewritten three times on guesses, and a criterion ("no double scrollbars") was met by changing the test to expect the vendor's behaviour instead of changing the page. | The ticket's own words are searched before planning and the hits go to the planner. The plan writes Reuse, Must not change, Measure first, Smallest change and Proof, and is sent back when it proposes a structure parallel to an existing one, deletes or overwrites the ticket doesn't ask for, logging or reporting changes, outside-page behaviour with nothing measured, or a test change where a criterion says the product must change (`plan_shape`). The coder's first write follows a search and names what it reuses; an edit adding a twin of an existing map or helper is refused without a reason (`explore_guard`). After the build a diff wider than its ticket goes back to be made smaller (`minimal_change` in the habits check); deletes where the base only added, and a payload no probe observed, have no excuse but the ticket. Reporting on a skip is asked for only when the ticket asks. The reviewer finds the same, and a test bent to an outside page against a criterion is a required finding. | ## Adding a case diff --git a/services/worker/src/passes/explore_guard.rs b/services/worker/src/passes/explore_guard.rs new file mode 100644 index 000000000..3a2bf262b --- /dev/null +++ b/services/worker/src/passes/explore_guard.rs @@ -0,0 +1,231 @@ +//! Explore before the first edit; extend what exists instead of adding a +//! twin beside it. +//! +//! A build once wrote a second overrides map and two helpers next to the +//! map that already did the job, in its first edit, without one search. +//! In the coder's loop now: +//! +//! - **The first write of a build names what it reuses.** It carries +//! [`REUSES_INPUT`]: the existing maps, helpers, config and tests the +//! change extends, by path, or `none: searched `; and a search +//! (`search_code`, a graph lookup, a `grep`) has run in the round. Until +//! both hold, the write is refused with what to do. The list is kept as +//! the coder's evidence (`Reuses: ...`). +//! - **A new map, helper or config beside an existing equivalent is +//! refused** ([`ExploreGuard::check_edit`]): an edit whose new top-level +//! definition parallels one already in the file (`minimal_change`) needs +//! [`WHY_NEW_INPUT`], saying why the existing one can't hold the change. +//! The reason is kept as the habits check's line `Wider than the ticket:`. +//! +//! The refusals are the same every time; no count of tries opens them. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; + +use super::minimal_change; + +/// The write tools' field naming what the change reuses. +pub const REUSES_INPUT: &str = "reuses"; +/// The write tools' field saying why a parallel structure is needed. +pub const WHY_NEW_INPUT: &str = "why_new"; + +/// The tools that count as a search of the code. +pub fn is_search(tool: &str, input: &serde_json::Value) -> bool { + match tool { + "search_code" | "find_references" | "find_symbol" | "find_definition" | "who_calls" + | "code_graph" => true, + "bash" => input + .get("command") + .and_then(|c| c.as_str()) + .is_some_and(|c| { + let c = c.trim_start(); + ["grep ", "rg ", "git grep", "ag ", "find "] + .iter() + .any(|p| c.starts_with(p) || c.contains(&format!("| {p}"))) + }), + t => t.starts_with("graph_") || t.contains("search"), + } +} + +fn text_input<'a>(input: &'a serde_json::Value, key: &str) -> Option<&'a str> { + input + .get(key) + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty()) +} + +/// The schema fields the write tools take for the guard. +pub fn offer_fields(schema: &mut serde_json::Value) { + if let Some(props) = schema.get_mut("properties").and_then(|p| p.as_object_mut()) { + props.insert( + REUSES_INPUT.to_string(), + serde_json::json!({ + "type": "string", + "description": "Required on the first write of a build: the existing maps, helpers, constants, config and tests this change extends, each with its path (found by search_code), or `none: searched `." + }), + ); + props.insert( + WHY_NEW_INPUT.to_string(), + serde_json::json!({ + "type": "string", + "description": "Only when this edit adds a map, helper or config next to an existing similar one: why the existing one can't hold the change." + }), + ); + } +} + +/// The guard of one coder round. +#[derive(Debug, Default)] +pub struct ExploreGuard { + /// The round must name what it reuses before its first write. + require: bool, + searched: AtomicBool, + reuses: Mutex>, + kept: Mutex>, +} + +impl ExploreGuard { + /// A build round: the first write names what it reuses. + pub fn for_build() -> Self { + Self { + require: true, + ..Default::default() + } + } + + /// A fix round: the parallel check only. + pub fn for_fix() -> Self { + Self::default() + } + + /// Records a tool call the coder made. + pub fn saw(&self, tool: &str, input: &serde_json::Value) { + if is_search(tool, input) { + self.searched.store(true, Ordering::Relaxed); + } + } + + /// Whether a write may go ahead: `Err` is the refusal the coder reads. + pub fn check_first_write(&self, input: &serde_json::Value) -> Result<(), String> { + if !self.require || self.reuses.lock().unwrap().is_some() { + return Ok(()); + } + let searched = self.searched.load(Ordering::Relaxed); + match (searched, text_input(input, REUSES_INPUT)) { + (true, Some(r)) => { + *self.reuses.lock().unwrap() = Some(r.to_string()); + Ok(()) + } + (false, _) => Err(format!( + "Not written: search before the first edit. Run `search_code` for the ticket's names and for the kind of structure you are about to add (a map, a helper, a config key, a test of the same code), read what it finds, then write again with `{REUSES_INPUT}` naming what you extend, by path." + )), + (true, None) => Err(format!( + "Not written: the first write of a build names what it reuses. Call it again with `{REUSES_INPUT}`: the existing maps, helpers, config and tests this change extends, each with its path, or `none: searched `." + )), + } + } + + /// Whether an edit of an existing file may add the definitions it adds: + /// one parallel to an existing definition in the file needs a reason. + pub fn check_edit( + &self, + path: &str, + old: &str, + new: &str, + input: &serde_json::Value, + ) -> Result<(), String> { + let pairs = minimal_change::parallel_in_edit(path, old, new); + if pairs.is_empty() { + return Ok(()); + } + if let Some(why) = text_input(input, WHY_NEW_INPUT) { + self.kept + .lock() + .unwrap() + .push((path.to_string(), why.to_string())); + return Ok(()); + } + let list = pairs + .iter() + .map(|(n, e)| format!("`{}` next to the existing `{}`", n.name, e.name)) + .collect::>() + .join(", "); + Err(format!( + "Not written: this edit adds {list} in `{path}`. Extend the existing one instead (add the entries, or a parameter to the helper). If a separate one is really needed, call again with `{WHY_NEW_INPUT}` saying why the existing one can't hold the change." + )) + } + + /// The coder's evidence lines: what it reuses, and each kept parallel + /// with its reason (read by the habits check). + pub fn evidence_lines(&self) -> String { + let mut out = String::new(); + if let Some(r) = self.reuses.lock().unwrap().as_ref() { + out.push_str(&format!("Reuses: {r}\n")); + } + for (p, why) in self.kept.lock().unwrap().iter() { + out.push_str(&format!("Wider than the ticket: {p}: {why}\n")); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn the_first_write_follows_a_search_and_names_what_it_reuses() { + let g = ExploreGuard::for_build(); + let w = json!({"path": "dags/camps.py"}); + assert!(g + .check_first_write(&w) + .unwrap_err() + .contains("search before the first edit")); + g.saw("read_file", &json!({})); + assert!(g.check_first_write(&w).is_err()); + g.saw("bash", &json!({"command": "grep -rn OVERRIDES dags"})); + assert!(g.check_first_write(&w).unwrap_err().contains("`reuses`")); + let named = json!({"path": "dags/camps.py", "reuses": "`CAMP_OVERRIDES` in dags/camps.py"}); + assert!(g.check_first_write(&named).is_ok()); + // Later writes go ahead. + assert!(g.check_first_write(&w).is_ok()); + assert!(g.evidence_lines().starts_with("Reuses: `CAMP_OVERRIDES`")); + // A fix round asks for none of it. + assert!(ExploreGuard::for_fix().check_first_write(&w).is_ok()); + } + + #[test] + fn a_twin_beside_the_existing_map_needs_a_reason() { + let g = ExploreGuard::for_fix(); + let old = "CAMP_SPORT_OVERRIDES = {\n \"a\": [\"x\"],\n}\n"; + let twin = format!("{old}CAMP_SWIM_SPORT_OVERRIDES = {{\n}}\n"); + let e = g + .check_edit("dags/camps.py", old, &twin, &json!({})) + .unwrap_err(); + assert!( + e.contains("`CAMP_SWIM_SPORT_OVERRIDES` next to the existing `CAMP_SPORT_OVERRIDES`") + ); + // Entries in the existing map are the change it should make. + let entries = old.replace("}\n", " \"b\": [\"x\", \"swimming\"],\n}\n"); + assert!(g + .check_edit("dags/camps.py", old, &entries, &json!({})) + .is_ok()); + // A stated reason is let through and kept. + assert!(g + .check_edit( + "dags/camps.py", + old, + &twin, + &json!({"why_new": "a different key type"}) + ) + .is_ok()); + assert!(g + .evidence_lines() + .contains("Wider than the ticket: dags/camps.py: a different key type")); + let mut schema = json!({"type": "object", "properties": {}}); + offer_fields(&mut schema); + assert!(schema["properties"]["reuses"].is_object()); + } +} diff --git a/services/worker/src/passes/feature/data_rules.rs b/services/worker/src/passes/feature/data_rules.rs index fac28621b..d6f47a3a7 100644 --- a/services/worker/src/passes/feature/data_rules.rs +++ b/services/worker/src/passes/feature/data_rules.rs @@ -59,10 +59,11 @@ find any other path that makes the same choice (full and incremental, batch and and live) and name it with its ordering key under `### Same selection elsewhere` (or what you \ searched when none exists). Both paths use the identical ordering key, tie-breaks and null \ handling included; plan a test with ties and nulls in both modes.\n\ -- Unexpected data: records without the expected shape are collected and reported in ONE warning \ -per run naming their ids (deduplicated, capped), with counts in the run's summary; never a log \ -line per row and never a silent skip. Expected exclusions are counted, not warned. Where the \ -repository or the team's instructions already set a format, follow it.\n\ +- Unexpected data: a record the change skips is handled the way the surrounding code already \ +handles a skipped record. Plan new reporting (ONE warning per run naming the ids, counts in the \ +run's summary) only when the ticket asks for it; never a log line per row, never a change to \ +existing log levels. Where the repository or the team's instructions already set a format, \ +follow it.\n\ - Real data: when the change affects stored data and a read-only data source is connected, plan \ to read the records the ticket names and the edge cases the change touches (ties, nulls, missing \ records) before and after, for the pull request's Verification section.\n"; @@ -72,7 +73,7 @@ pub const CODER_RULES: &str = " ## Changes to stored data (every change that reads or writes it) - Cursor columns: when you change how a timestamp, sequence or version column is written (set it conditionally, stop advancing it, move it back), first search for every reader of that column: SQL `MAX(col)`, `GREATEST(... col ...)`, `WHERE col >`, `ORDER BY col`, and code that compares it. List them in your notes. Keep the column advancing (`GREATEST(existing, new)`), even when another column must stay stable, and add a test proving it still advances. - Same selection everywhere: when code picks a winner, latest or first among rows and another path makes the same choice (full and incremental sync, batch and stream, backfill and live), use the identical ordering key in both, tie-breaks and null handling included (a shared function where you can). Add a test with ties and nulls that both modes pass. -- Unexpected data: collect records that don't have the expected shape and report them in ONE warning per run naming their ids (deduplicated, capped), with counts in the run's summary. Never a log line per row, never a silent `continue`. Expected exclusions (filtered-out categories) are counted, not warned. Follow the repository's or team's format when one is set. +- Unexpected data: a record your change skips is handled the way the surrounding code already handles a skipped record. Add reporting (ONE warning per run naming the ids, counts in the run's summary) only when the ticket asks for it. Never a log line per row, and never change an existing log level. Follow the repository's or team's format when one is set. "; /// A code or SQL file whose lines count. @@ -939,6 +940,11 @@ pub struct Facts { pub others: Vec, pub skips: Vec, pub reports_once: bool, + /// The ticket asks for no reporting: a skip follows the surrounding + /// code's own handling, and only a log line per row is a problem (a + /// change once grew counters, a warning and a log level change in + /// shared code for a four-entry fix, to settle this item). + pub quiet_skips: bool, /// The test text the diff adds ([`tests_added`]). pub tests: String, } @@ -1104,7 +1110,7 @@ pub fn items(f: &Facts, text: &str) -> Vec { .filter(|s| !s.counted) .map(|s| format!("`{}`: `{}`", s.path, s.line)) .collect(); - if !silent.is_empty() { + if !silent.is_empty() && !f.quiet_skips { problems.push(format!("skipped silently: {}", shown(&silent))); } let per_row: Vec = f @@ -1116,7 +1122,7 @@ pub fn items(f: &Facts, text: &str) -> Vec { if !per_row.is_empty() { problems.push(format!("a log line per row: {}", shown(&per_row))); } - if f.skips.iter().any(|s| s.collected) && !f.reports_once { + if f.skips.iter().any(|s| s.collected) && !f.reports_once && !f.quiet_skips { problems .push("records are collected but no single WARNING per run names them".to_string()); } @@ -1566,6 +1572,20 @@ mod tests { let per_row = vec![file("pipeline/sync_items.py", PER_ROW)]; let it = items(&Facts::from_diff(&per_row), ""); assert!(it[0].detail.contains("a log line per row"), "{it:?}"); + // A ticket that asks for no reporting: the skip follows the + // surrounding code; only a log line per row is still a problem. + let quiet = Facts { + quiet_skips: true, + ..Facts::from_diff(&silent) + }; + assert_eq!(items(&quiet, "")[0].status, Status::Pass); + let quiet_per_row = Facts { + quiet_skips: true, + ..Facts::from_diff(&per_row) + }; + assert!(items(&quiet_per_row, "")[0] + .detail + .contains("a log line per row")); let once = vec![file("pipeline/sync_items.py", ONCE)]; let f = Facts::from_diff(&once); assert!(f.reports_once); diff --git a/services/worker/src/passes/feature/mod.rs b/services/worker/src/passes/feature/mod.rs index af86bf712..faf9d42aa 100644 --- a/services/worker/src/passes/feature/mod.rs +++ b/services/worker/src/passes/feature/mod.rs @@ -399,6 +399,12 @@ async fn data_facts( ) -> data_rules::Facts { let (owner, repo, base) = (&w.msg.repo_owner, &w.msg.repo_name, &w.msg.base_branch); let mut facts = data_rules::Facts::from_diff(files); + // A skip follows the surrounding code unless the ticket asks for + // reporting (`minimal_change`). + facts.quiet_skips = !crate::passes::minimal_change::ticket_asks( + &format!("{}\n{}", w.msg.title, w.msg.body), + crate::passes::minimal_change::REPORT_ASKS, + ); let mut cols: Vec = Vec::new(); for c in facts.writes.iter().map(|x| x.column.clone()) { if !cols.contains(&c) { diff --git a/services/worker/src/passes/habits_check.rs b/services/worker/src/passes/habits_check.rs index 9ae18da7e..24a5931f3 100644 --- a/services/worker/src/passes/habits_check.rs +++ b/services/worker/src/passes/habits_check.rs @@ -96,6 +96,13 @@ pub struct PrFacts { /// no spec is needed or one is there. #[serde(default)] pub e2e_missing: String, + /// Where the change is wider than its ticket and the coder gave no + /// reason it may keep (`minimal_change`): a parallel structure, + /// deleting or overwriting where the code only added, a log level, + /// reporting nobody asked for, tests out of proportion, a payload + /// nobody observed. + #[serde(default)] + pub wider: Vec, } /// Why the check didn't give a result. @@ -528,6 +535,21 @@ pub fn blocking(f: &PrFacts, plan: &PlanResult) -> Vec { if !f.e2e_missing.is_empty() { out.push(f.e2e_missing.clone()); } + // A test that never ran proves nothing, whatever CI says later. + for t in f + .tests + .iter() + .filter(|t| t.verdict == Verdict::NotRun && t.detail.contains("found no tests")) + { + out.push(format!( + "`{}`: {}. Make it run under the repository's test command, run it, and quote its output in your Evidence.", + t.path, t.detail + )); + } + // The change is held to the ticket: smaller, not wider. + for w in &f.wider { + out.push(w.instruction()); + } if f.bug && f.tests.is_empty() && !repro_waived(plan) && f.no_tests.contains("no test file") { out.push("This is a bug fix and the change has no test that fails without it. Add the test that reproduces the reported failure (it must fail on the base code and pass with the fix).".to_string()); } @@ -548,7 +570,7 @@ pub fn blocking(f: &PrFacts, plan: &PlanResult) -> Vec { /// The fix round's instructions. pub fn fix_feedback(lines: &[String]) -> String { format!( - "The check after the build ran each new or changed test with and without your change, and compared the changed files with the plan. Fix every item:\n{}\nDo not delete or skip a test to settle an item.", + "The check after the build ran each new or changed test with and without your change, compared the changed files with the plan, and compared the change with the ticket. Fix every item; where the change is wider than the ticket, make it smaller:\n{}\nDo not delete or skip a test to settle an item.", lines .iter() .map(|l| format!("- {l}")) @@ -566,7 +588,13 @@ pub fn open_findings(f: &PrFacts, plan: &PlanResult) -> Vec { lines .into_iter() .map(|l| { - let (point, settle) = if l.contains("no task of the plan") { + let wider = f.wider.iter().find(|w| w.instruction() == l); + let (point, settle) = if let Some(w) = wider { + ( + w.point(), + "CoderHelm makes the change smaller in its next round on this pull request.", + ) + } else if l.contains("no task of the plan") { ( "Changed outside the plan", "CoderHelm restores it or records why the change needs it in its next round on this pull request.", @@ -1019,6 +1047,46 @@ async fn e2e_missing(w: &super::proof::Work<'_>, paths: &[String]) -> String { .unwrap_or_default() } +/// Where the change is wider than its ticket (`minimal_change`), read +/// against the base text of the changed code files and the ticket's own +/// words, less what the coder's notes keep with a reason. +async fn wider( + w: &super::proof::Work<'_>, + diff: &Diff, + notes: &str, +) -> Vec { + let (owner, repo) = (&w.msg.repo_owner, &w.msg.repo_name); + let mut base = Vec::new(); + for (path, _, _) in diff + .iter() + .filter(|(p, s, _)| s == "modified" && !is_test_path(p)) + .take(12) + { + if let Ok(text) = w + .github + .read_file(owner, repo, path, &w.msg.base_branch) + .await + { + base.push((path.clone(), text)); + } + } + let has_probe = match w.github.get_tree(owner, repo, w.branch).await { + Ok(t) => t.iter().any(|e| common::e2e::probe::is_record(&e.path)), + Err(_) => false, + }; + let ticket = format!( + "{}\n{}{}", + w.msg.title, + w.msg.body, + common::run_questions::answers_note(&w.msg.answers) + ); + let found = super::minimal_change::check(diff, &base, &ticket, has_probe); + super::minimal_change::standing(&found, notes) + .into_iter() + .cloned() + .collect() +} + /// A bench for a step with no time for the sandbox: nothing runs, and each /// test says so. struct NoTime; @@ -1092,6 +1160,7 @@ async fn check_and_fix( ) .await; facts.e2e_missing = e2e_missing(w, &paths).await; + facts.wider = wider(w, &diff, &evidence.notes).await; let blocking = blocking(&facts, w.plan); info!( run_id = w.run_id, diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index f71fe1e3a..5f4ee304b 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -499,6 +499,21 @@ pub async fn run( all_tools() }; + // The build searches before its first write and names what it reuses; + // every round explains a new structure beside an existing one + // (`explore_guard`). + let explore = if round_for == super::write_guard::RoundFor::Build { + super::explore_guard::ExploreGuard::for_build() + } else { + super::explore_guard::ExploreGuard::for_fix() + }; + for t in tools + .iter_mut() + .filter(|t| matches!(t.name.as_str(), "write_file" | "edit_file" | "batch_write")) + { + super::explore_guard::offer_fields(&mut t.input_schema); + } + // A bounded round's write tools take the reason for an edit outside // its files. if scope_guard.bounded() { @@ -837,6 +852,7 @@ pub async fn run( codegen_cmd, codegen_env, scope_guard, + explore, run_id: run_id.map(|s| s.to_string()), node_version, terraform_version, @@ -1286,6 +1302,12 @@ pub async fn run( lines if lines.is_empty() => closing.trim().to_string(), lines => format!("{}\n{lines}", closing.trim()), }; + // What the build reused, and each structure it kept beside an existing + // one with why (the habits check reads these lines). + let notes = match executor.write_executor.explore.evidence_lines() { + lines if lines.is_empty() => notes, + lines => format!("{notes}\n{}", lines.trim_end()), + }; Ok(ImplementResult { files_modified: files, timed_out, @@ -1380,10 +1402,11 @@ pub(super) fn task_prompt(p: &TaskPrompt) -> String { {design}{continuation}{openspec}{files_hint}{feedback}{issue} ## Instructions — SIMPLE CHANGE -Go DIRECTLY to the target files listed in the OpenSpec. -- Use `read_file_lines` on the exact section, make the change with `edit_file`, done. +Go to the target files listed in the OpenSpec. +- `search_code` once for the structure the change extends (the map, helper or query the plan names under Reuse), read that section, make the change with `edit_file`, done. - Use `edit_file` for modifying existing files (search/replace). Only use `write_file` for new files. -- You should need 2-5 tool calls total, plus any lookups the rules below call for. +- You should need 3-6 tool calls total, plus any lookups the rules below call for. +{smallest} - Only implement the listed tasks. Do not add extras. - Write each file as soon as its change is done; never hold finished changes back for one write at the end. - NEVER leave placeholder text like TODO, FIXME, REPLACE_ME, or stub implementations. Every line you write must be complete, working code. @@ -1402,6 +1425,7 @@ Go DIRECTLY to the target files listed in the OpenSpec. evidence_output = super::proof::EVIDENCE_OUTPUT, proof_rules = super::proof::CODER_RULES, data_rules = super::feature::data_rules::CODER_RULES, + smallest = SMALLEST_CHANGE_RULES, ) } else { format!( @@ -1422,6 +1446,7 @@ Go DIRECTLY to the target files listed in the OpenSpec. - {commit} - {evidence_output} - Only implement the listed tasks. Do not add extras. +{smallest} {proof_rules}{data_rules}{schema_rules}"#, number = p.number, title = p.title, @@ -1435,10 +1460,18 @@ Go DIRECTLY to the target files listed in the OpenSpec. proof_rules = super::proof::CODER_RULES, data_rules = super::feature::data_rules::CODER_RULES, schema_rules = SCHEMA_CHANGE_RULES, + smallest = SMALLEST_CHANGE_RULES, ) } } +/// The smallest change, as the coder's loop and the habits check hold it +/// (`explore_guard`, `minimal_change`). +pub(crate) const SMALLEST_CHANGE_RULES: &str = "- The smallest change that does the ticket: before the first write, `search_code` for the structure you would add and pass `reuses` naming what you extend. Add entries to the existing map, a parameter to the existing helper, a key to the existing config; never a second one beside it. +- Never widen behaviour past the ticket: an insert-only path stays insert-only (no `DELETE`, no `ON CONFLICT DO UPDATE`, no replacing sync), log levels and shared logging stay as they are, and no counters or reports the ticket doesn't ask for. +- Tests sized to the change: the new behaviour and that nothing else changed, through the real entry point. Never invent another system's payload, page or test ids: probe it (`probe_page`) or reuse an existing fixture. Run the tests and quote their output in your Evidence. +- When an acceptance criterion and an outside system disagree, change the product so the criterion holds; never change the test to expect the outside behaviour without the measured reason."; + /// What a change to a table's schema, constraints, ids or stored data must /// do before it is written. Each rule is a way such a change shipped broken. const SCHEMA_CHANGE_RULES: &str = " @@ -1970,6 +2003,8 @@ struct WriteToolExecutor<'a> { /// Which existing files the round may edit, by what it is for /// (`write_guard`). No boundary on the build and a person's ask. scope_guard: super::write_guard::ScopeGuard, + /// Search before the first write; no twin beside an existing structure. + explore: super::explore_guard::ExploreGuard, /// Node major version to switch the sandbox to (None -> buildspec default). node_version: Option, /// Exact Terraform version the sandbox installs (None when the repo has @@ -2018,9 +2053,18 @@ impl<'a> ToolExecutor for WriteToolExecutor<'a> { name: &str, input: &serde_json::Value, ) -> Result> { + self.explore.saw(name, input); if name == "bash" { return Box::pin(self.bash(input)).await; } + if matches!(name, "write_file" | "edit_file" | "batch_write") { + if let Err(refusal) = self.explore.check_first_write(input) { + note(LogOutcome::soft_fail( + "not written: search and name what it reuses first", + )); + return Ok(json!(refusal)); + } + } let out = self.execute_tool(name, input).await; let out = match out { Ok(serde_json::Value::String(text)) if is_write_tool(name) => { @@ -2315,6 +2359,12 @@ impl<'a> WriteToolExecutor<'a> { ))); return Ok(json!(refusal)); } + if let Err(refusal) = self.explore.check_edit(path, old, content, input) { + note(LogOutcome::soft_fail( + "not written: a twin of an existing structure", + )); + return Ok(json!(refusal)); + } if let Some(problem) = validate_edit_safety(old, content, path) { note(LogOutcome::soft_fail("rejected: it would gut the file")); return Ok(json!(format!( @@ -2448,6 +2498,16 @@ impl<'a> WriteToolExecutor<'a> { Read the file again and retry with a corrected edit." ))); } + // A new map or helper beside an existing equivalent. + if let Err(refusal) = + self.explore + .check_edit(path, &original_content, &content, input) + { + note(LogOutcome::soft_fail( + "not edited: a twin of an existing structure", + )); + return Ok(json!(refusal)); + } // Deletion guardrail: reject edits that gut the file if let Some(problem) = validate_edit_safety(&original_content, &content, path) { note(LogOutcome::soft_fail("rejected: it would gut the file")); diff --git a/services/worker/src/passes/incidents/bx_smallest_change.rs b/services/worker/src/passes/incidents/bx_smallest_change.rs new file mode 100644 index 000000000..5926e2811 --- /dev/null +++ b/services/worker/src/passes/incidents/bx_smallest_change.rs @@ -0,0 +1,269 @@ +//! bx. Two pull requests did far more than their tickets, and guessed +//! where they should have measured. +//! +//! A data-pipeline ticket asked to link four full-day camps to Swimming as +//! well as their own sport. The plan added a second overrides map and two +//! helpers beside the existing `CAMP_MULTI_SPORT_OVERRIDES`, and switched +//! the insert-only link sync to a replacing upsert that deleted links +//! nobody asked about. The build added warnings, three summary counters +//! and an INFO-to-DEBUG change in shared code (the data rules' "report +//! unexpected data once per run" item asked for them on a four-entry fix), +//! and a 432-line test with fake hooks and an invented payload. The right +//! change: four map entries; an insert with `ON CONFLICT DO NOTHING` in the +//! three write branches; one small test. +//! +//! A web ticket embedded a vendor's booking portal in a frame. Its vendor +//! end-to-end tests were rewritten three times on guesses (no inner +//! scroll, a click that adds to an order, invented test ids), and when the +//! criterion "no double scrollbars on desktop" met the vendor's behaviour, +//! the test was changed to expect the vendor's behaviour instead of the +//! page losing its footer and bottom padding. +//! +//! Guarantee: the plan writes Reuse, Must not change, Measure first, +//! Smallest change and Proof, and is sent back when it proposes a +//! structure parallel to an existing one, deleting or overwriting the +//! ticket doesn't ask for, logging changes, reporting, assertions about an +//! outside page with nothing measured, or a test change where a criterion +//! says the product must change (`plan_shape`). The coder's first write +//! follows a search and names what it reuses, and an edit that adds a twin +//! of an existing map or helper is refused without a reason +//! (`explore_guard`). After the build, a diff wider than its ticket goes +//! back to the coder to be made smaller, deletes where the base only added +//! with no excuse but the ticket (`minimal_change`, `habits_check`); the +//! reviewer finds the same, and a test bent to an outside page against a +//! criterion is a required finding (`review_rules`). + +use crate::passes::explore_guard::ExploreGuard; +use crate::passes::habits_check::{self, PrFacts}; +use crate::passes::minimal_change::{self, Kind}; +use crate::passes::plan::PlanResult; +use crate::passes::plan_shape; +use crate::passes::review_rules; +use serde_json::json; + +const MAP_FILE: &str = "dags/camps/sports.py"; +const SYNC_FILE: &str = "dags/camps/sync_links.py"; + +const CAMP_TICKET: &str = "Link four full-day camps to Swimming\n\nThese full-day camps should show under Swimming as well as their own sport: \"Aqua Day Camp\", \"Swim and Sail\", \"Pool Explorers\", \"Splash Week\"."; + +const PORTAL_TICKET: &str = "Embed the booking portal on the camps page\n\nShow the vendor's booking portal in an iframe on the camps page.\n\nAcceptance criteria:\n- The portal loads inside the page\n- No double scrollbars on desktop\n"; + +const BASE_MAP: &str = "CAMP_MULTI_SPORT_OVERRIDES = {\n \"sports academy break camp\": [\"multi-sport\"],\n}\n\n\ndef get_camp_multi_sport_names(name):\n return CAMP_MULTI_SPORT_OVERRIDES.get(name.lower(), [])\n"; + +const BASE_SYNC: &str = "def write_links(cur, camp_id, sports):\n for sport_id in sports:\n cur.execute(\n \"INSERT INTO camp_sports (camp_id, sport_id) VALUES (%s, %s) ON CONFLICT DO NOTHING\",\n (camp_id, sport_id),\n )\n"; + +fn plan(design: &str, tasks: &str) -> PlanResult { + PlanResult { + design: design.into(), + tasks: tasks.into(), + ..Default::default() + } +} + +/// The plan the run wrote for the camps ticket, in its shape. +fn camps_plan_before() -> PlanResult { + plan( + "## Approach\nAdd `CAMP_SWIMMING_OVERRIDES` and `get_camp_swimming_names` to hold the swimming links. \ + The link sync upserts each camp's links and deletes stale ones so the table matches. \ + Report skipped camps once per run with summary counters, and move the per-record INFO log to debug.\n", + &format!("- [ ] {MAP_FILE}: add the swimming map and helper\n- [ ] {SYNC_FILE}: replace links per camp\n- [ ] tests/test_sync_links.py: cover the sync"), + ) +} + +/// The small, correct plan. +fn camps_plan_after() -> PlanResult { + plan( + "## Reuse\n- `CAMP_MULTI_SPORT_OVERRIDES` and `get_camp_multi_sport_names` in dags/camps/sports.py\n\n\ + ## Must not change\nNo deletes: existing links stay. Logging and the other pipelines stay as they are.\n\n\ + ## Measure first\nNone: the change stays inside this repository.\n\n\ + ## Smallest change\n4 entries in `CAMP_MULTI_SPORT_OVERRIDES`; in the 3 write branches insert links for \ + `get_camp_multi_sport_names` with ON CONFLICT DO NOTHING.\n\n\ + ## Proof\nOne test: the 4 names get Swimming and their own sport, others only their own, nothing deleted.\n", + &format!("- [ ] {MAP_FILE}: 4 entries\n- [ ] {SYNC_FILE}: insert the extra links\n- [ ] tests/test_sports.py: one test"), + ) +} + +fn portal_plan_before() -> PlanResult { + plan( + "## Reuse\n- `CampsPage` in web/src/pages/camps.tsx\n\n## Must not change\nThe header.\n\n\ + ## Measure first\nThe vendor portal renders in an iframe with no inner scroll; clicking a camp adds it to the order summary.\n\n\ + ## Smallest change\nAn iframe block on the camps page.\n\n\ + ## Proof\ne2e spec for the portal. If the frame scrolls, update the test to match the vendor.\n", + "- [ ] web/src/pages/camps.tsx: embed\n- [ ] e2e/portal.spec.ts: spec", + ) +} + +fn portal_plan_after() -> PlanResult { + plan( + "## Reuse\n- `CampsPage` in web/src/pages/camps.tsx and its layout\n\n## Must not change\nThe header and other pages.\n\n\ + ## Measure first\nprobe_page on the portal at 1280x900: the embed script caps the frame at the window height below its top (663px) and the portal scrolls inside it; every camp button is disabled until registration opens; weeks are `program-portals-segment-tag-guest-N`.\n\n\ + ## Smallest change\nAn iframe block on the camps page; drop the footer and bottom padding there so the frame fills the window, as the vendor's embed docs recommend.\n\n\ + ## Proof\nOne e2e spec from the probe record: the page itself has no scrollbar at 1280x900, the frame is 663px, week tags are listed.\n", + "- [ ] web/src/pages/camps.tsx: embed, no footer\n- [ ] e2e/portal.spec.ts: spec from the probe", + ) +} + +#[test] +fn the_plans_are_sent_back_until_they_are_the_small_change() { + let existing = vec!["CAMP_MULTI_SPORT_OVERRIDES".to_string()]; + // Before: the camps plan has no sections, a parallel map, a replacing + // sync, a log change and reporting. + let g = plan_shape::plan_gaps(&camps_plan_before(), CAMP_TICKET, false, &existing); + let all = g.join("\n"); + assert!(all.contains("lacks `## Reuse`"), "{all}"); + assert!( + all.contains("`CAMP_SWIMMING_OVERRIDES` next to the existing `CAMP_MULTI_SPORT_OVERRIDES`"), + "{all}" + ); + assert!(all.contains("delete or overwrite"), "{all}"); + assert!(all.contains("changes logging"), "{all}"); + assert!(all.contains("adds reporting"), "{all}"); + // After: nothing to send back. + assert!(plan_shape::plan_gaps(&camps_plan_after(), CAMP_TICKET, false, &existing).is_empty()); + // The portal plan guessed the outside page and planned to bend the + // test to the vendor against a criterion. + let g = plan_shape::plan_gaps(&portal_plan_before(), PORTAL_TICKET, false, &[]); + let all = g.join("\n"); + assert!(all.contains("plans no measurement"), "{all}"); + assert!( + all.contains("product change that meets the criterion first"), + "{all}" + ); + assert!(plan_shape::plan_gaps(&portal_plan_after(), PORTAL_TICKET, false, &[]).is_empty()); + // The planner is told the sections, and the ticket's own words are + // searched before it plans. + assert!(plan_shape::PLANNER.contains("## Must not change")); + let terms = plan_shape::ticket_terms("Link four full-day camps to Swimming", CAMP_TICKET); + assert!(terms.contains(&"Swimming".to_string()), "{terms:?}"); + assert!(terms.contains(&"Aqua Day Camp".to_string()), "{terms:?}"); +} + +#[test] +fn the_coder_searches_first_and_never_adds_a_twin() { + let g = ExploreGuard::for_build(); + let twin = format!( + "{BASE_MAP}\nCAMP_SWIMMING_OVERRIDES = {{\n \"aqua day camp\": [\"swimming\"],\n}}\n" + ); + // The run's first write came before any search. + let first = json!({"path": MAP_FILE, "edits": []}); + assert!(g.check_first_write(&first).is_err()); + g.saw("search_code", &json!({"query": "Swimming"})); + let named = + json!({"path": MAP_FILE, "reuses": "`CAMP_MULTI_SPORT_OVERRIDES` in dags/camps/sports.py"}); + assert!(g.check_first_write(&named).is_ok()); + // A second map beside the first is refused; entries in it are not. + assert!(g.check_edit(MAP_FILE, BASE_MAP, &twin, &named).is_err()); + let entries = BASE_MAP.replace( + " \"sports academy break camp\": [\"multi-sport\"],\n", + " \"sports academy break camp\": [\"multi-sport\"],\n \"aqua day camp\": [\"swimming\", \"sailing\"],\n", + ); + assert!(g.check_edit(MAP_FILE, BASE_MAP, &entries, &named).is_ok()); +} + +fn diff_before() -> Vec<(String, String, String)> { + let map = "@@ -1,3 +1,14 @@\n CAMP_MULTI_SPORT_OVERRIDES = {\n+CAMP_SWIMMING_OVERRIDES = {\n+ \"aqua day camp\": [\"swimming\"],\n+}\n+def get_camp_swimming_names(name):\n+ return CAMP_SWIMMING_OVERRIDES.get(name.lower(), [])\n"; + let sync = "@@ -1,6 +1,20 @@\n def write_links(cur, camp_id, sports):\n- for sport_id in sports:\n+ cur.execute(\"DELETE FROM camp_sports WHERE camp_id = %s AND NOT (sport_id = ANY(%s))\", (camp_id, sports))\n+ for sport_id in sports:\n cur.execute(\n- \"INSERT INTO camp_sports (camp_id, sport_id) VALUES (%s, %s) ON CONFLICT DO NOTHING\",\n+ \"INSERT INTO camp_sports (camp_id, sport_id) VALUES (%s, %s) ON CONFLICT (camp_id, sport_id) DO UPDATE SET sport_id = EXCLUDED.sport_id\",\n+ linked += 1\n+ skipped += 1\n+ log.warning(\"skipped camps: %s\", skipped_ids)\n"; + let log = "@@ -1,3 +1,3 @@\n-logger.setLevel(logging.INFO)\n+logger.setLevel(logging.DEBUG)\n"; + let test: String = std::iter::once("+class FakePostgresHook:\n".to_string()) + .chain((0..16).map(|i| format!("+ \"camp_field_{i}\": \"value\",\n"))) + .chain((0..420).map(|i| format!("+ assert rows[{i}]\n"))) + .collect(); + vec![ + (MAP_FILE.into(), "modified".into(), map.into()), + (SYNC_FILE.into(), "modified".into(), sync.into()), + ("dags/common/logs.py".into(), "modified".into(), log.into()), + ("tests/test_sync_links.py".into(), "added".into(), test), + ] +} + +fn diff_after() -> Vec<(String, String, String)> { + let map = "@@ -1,3 +1,7 @@\n CAMP_MULTI_SPORT_OVERRIDES = {\n \"sports academy break camp\": [\"multi-sport\"],\n+ \"aqua day camp\": [\"swimming\", \"sailing\"],\n+ \"swim and sail\": [\"swimming\", \"sailing\"],\n+ \"pool explorers\": [\"swimming\", \"multi-sport\"],\n+ \"splash week\": [\"swimming\", \"multi-sport\"],\n }\n"; + let sync = "@@ -1,6 +1,11 @@\n def write_links(cur, camp_id, sports):\n- for sport_id in sports:\n+ for sport_id in sports + extra_sports(camp_name):\n cur.execute(\n \"INSERT INTO camp_sports (camp_id, sport_id) VALUES (%s, %s) ON CONFLICT DO NOTHING\",\n"; + let test: String = (0..24) + .map(|i| format!("+ assert links[{i}]\n")) + .collect(); + vec![ + (MAP_FILE.into(), "modified".into(), map.into()), + (SYNC_FILE.into(), "modified".into(), sync.into()), + ("tests/test_sports.py".into(), "added".into(), test), + ] +} + +#[test] +fn the_wider_diff_goes_back_and_the_small_one_passes() { + let base = vec![ + (MAP_FILE.to_string(), BASE_MAP.to_string()), + (SYNC_FILE.to_string(), BASE_SYNC.to_string()), + ]; + let found = minimal_change::check(&diff_before(), &base, CAMP_TICKET, false); + let kinds: Vec = found.iter().map(|w| w.kind).collect(); + for k in [ + Kind::Parallel, + Kind::Replacing, + Kind::LogLevel, + Kind::Reporting, + Kind::TestSize, + Kind::InventedPayload, + ] { + assert!(kinds.contains(&k), "{k:?} not found in {found:?}"); + } + // The habits check's fix round gets each as a line to make smaller; + // a reason excuses neither the deletes nor the invented payload. + let notes = format!( + "Wider than the ticket: {SYNC_FILE}: keeps the table in step\nWider than the ticket: tests/test_sync_links.py: thorough" + ); + let facts = PrFacts { + wider: minimal_change::standing(&found, ¬es) + .into_iter() + .cloned() + .collect(), + ..Default::default() + }; + let lines = habits_check::blocking(&facts, &PlanResult::default()); + assert!( + lines + .iter() + .any(|l| l.contains("deletes or overwrites stored data")), + "{lines:?}" + ); + assert!( + lines.iter().any(|l| l.contains("payload nobody observed")), + "{lines:?}" + ); + assert!(habits_check::fix_feedback(&lines).contains("make it smaller")); + let open = habits_check::open_findings(&facts, &PlanResult::default()); + assert!(open + .iter() + .any(|f| f.point == "Deletes or overwrites where the code only added")); + // The reviewer finds the same; the deletes block by rule. + let review = review_rules::wider_findings(&found); + let deletes = review + .iter() + .find(|f| f.title == "Deletes or overwrites where the code only added") + .unwrap(); + assert_eq!( + review_rules::mandatory(deletes), + Some(review_rules::REQUIRED_WHY) + ); + // The right change passes every check. + assert!( + minimal_change::check(&diff_after(), &base, CAMP_TICKET, false).is_empty(), + "{:?}", + minimal_change::check(&diff_after(), &base, CAMP_TICKET, false) + ); +} + +#[test] +fn a_test_bent_to_the_vendor_against_a_criterion_is_a_required_finding() { + let patch = "@@ -10,4 +10,4 @@\n const frame = page.frameLocator('iframe');\n- expect(await pageScrolls(page)).toBe(false);\n+ expect(await pageScrolls(page)).toBe(true);\n"; + let criteria = crate::passes::stop_judge::acceptance(PORTAL_TICKET); + let flips = minimal_change::vendor_flips("e2e/portal.spec.ts", patch, true, &criteria); + assert_eq!(flips.len(), 1); + assert_eq!(flips[0].criterion, "No double scrollbars on desktop"); + let f = review_rules::vendor_flip_findings(&flips); + assert_eq!( + review_rules::mandatory(&f[0]), + Some(review_rules::REQUIRED_WHY) + ); + assert!(f[0].body.contains("Change the product side first")); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 5148e3b6f..6fd2c090e 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -60,6 +60,7 @@ mod br_description_writer_upgrade; mod bs_cut_plan_revision; mod bt_proof_answer_closes; mod bu_web_change_unchecked; +mod bx_smallest_change; mod c_codegen_egress; mod d_echoed_markers; mod e_large_generated_output; diff --git a/services/worker/src/passes/minimal_change.rs b/services/worker/src/passes/minimal_change.rs new file mode 100644 index 000000000..3220ced36 --- /dev/null +++ b/services/worker/src/passes/minimal_change.rs @@ -0,0 +1,1091 @@ +//! The change is the smallest one that does what the ticket asks. +//! +//! A ticket asked to link four camps to a second sport. The pull request +//! added a second map and helpers beside the existing overrides map, turned +//! an insert-only link sync into a replacing upsert that deleted links +//! nobody asked to delete, added warnings, three summary counters and a log +//! level change in code other pipelines share, and a 432-line test with +//! fake hooks and a payload nobody had seen. The right change was four map +//! entries, an insert that does nothing on conflict in the three write +//! branches, and one small test. +//! +//! Each way the change grew is read here from the diff, with no model: +//! +//! - **A parallel structure** ([`Kind::Parallel`]): a new top-level map, +//! list, constant table or helper whose name shares its words with an +//! existing one in the same file (or another changed file). Extend the +//! existing one. +//! - **Replacing where the base was additive** ([`Kind::Replacing`]): the +//! diff adds deleting or overwriting semantics (`DELETE`, `ON CONFLICT DO +//! UPDATE`, `TRUNCATE TABLE`, `REPLACE INTO`, an ORM delete) the base +//! didn't have there. It blocks unless the ticket asks to delete, replace +//! or overwrite; no reason in the coder's notes excuses it. +//! - **A log level changed** ([`Kind::LogLevel`]): the same log line or +//! logger setting at another level. Other code reads those logs. +//! - **Reporting nobody asked for** ([`Kind::Reporting`]): new counters and +//! log calls in a change whose ticket asks for no report, count or log. +//! - **A test out of proportion** ([`Kind::TestSize`]): many more test +//! lines than changed code lines. +//! - **An invented outside payload** ([`Kind::InventedPayload`]): a test +//! that fakes an outside call with a large payload literal while no probe +//! record (`common::e2e::probe`) shows what the outside system returns. +//! +//! The coder may keep a [`Kind::Parallel`], [`Kind::LogLevel`], +//! [`Kind::Reporting`] or [`Kind::TestSize`] item by saying why on a line +//! `Wider than the ticket: : ` in its notes ([`reasons`]). +//! +//! [`vendor_flips`] is the reviewer's check for a test assertion changed to +//! match another company's page while an acceptance criterion of the ticket +//! says otherwise: the product side changes first. + +use serde::{Deserialize, Serialize}; + +use super::feature::reuse::{name_similarity, name_words}; + +/// Changed files: (path, status, patch), as the compare API gives them. +pub type Diff = [(String, String, String)]; + +/// How a change grew past its ticket. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + Parallel, + Replacing, + LogLevel, + Reporting, + TestSize, + InventedPayload, +} + +/// One way the change is wider than its ticket. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Widening { + pub kind: Kind, + pub path: String, + /// What the diff shows, in a few words (names, the line). + pub what: String, +} + +impl Widening { + /// The heading a report shows it under. + pub fn point(&self) -> &'static str { + match self.kind { + Kind::Parallel => "A parallel structure next to an existing one", + Kind::Replacing => "Deletes or overwrites where the code only added", + Kind::LogLevel => "A log level changed", + Kind::Reporting => "Reporting the ticket doesn't ask for", + Kind::TestSize => "A test out of proportion to the change", + Kind::InventedPayload => "A test payload nobody observed", + } + } + + /// Whether a reason in the coder's notes may keep it. + pub fn excusable(&self) -> bool { + !matches!(self.kind, Kind::Replacing | Kind::InventedPayload) + } + + /// What the coder is told to do, one line. + pub fn instruction(&self) -> String { + let why = if self.excusable() { + format!( + " If the ticket truly needs it, say why on a line `Wider than the ticket: {}: `.", + self.path + ) + } else { + String::new() + }; + let what = match self.kind { + Kind::Parallel => format!( + "`{}` adds {}. Extend the existing one (add the entries or the parameter there) and remove the new one.", + self.path, self.what + ), + Kind::Replacing => format!( + "`{}` now deletes or overwrites stored data ({}) where the base only added, and the ticket doesn't ask for that. Keep the write additive (insert, `ON CONFLICT DO NOTHING`) and remove the delete or overwrite.", + self.path, self.what + ), + Kind::LogLevel => format!( + "`{}` changes a log level ({}). Other code and people read those logs; put it back.", + self.path, self.what + ), + Kind::Reporting => format!( + "`{}` adds reporting the ticket doesn't ask for ({}). Remove the new counters and log lines; follow how the surrounding code already handles the case.", + self.path, self.what + ), + Kind::TestSize => format!( + "The tests are {} for this change. Cut them to the cases the ticket names: the new behaviour and that nothing else changed, through the code's real entry point.", + self.what + ), + Kind::InventedPayload => format!( + "`{}` fakes an outside call with a payload nobody observed ({}). Build the fixture from a real response (probe it, or copy an existing fixture in the repository), or test the change below the outside call.", + self.path, self.what + ), + }; + format!("{what}{why}") + } +} + +// ── Words ────────────────────────────────────────────────────────────────── + +/// Whether the ticket's words ask for any of `words`. +pub fn ticket_asks(ticket: &str, words: &[&str]) -> bool { + let t = ticket.to_lowercase(); + words.iter().any(|w| t.contains(w)) +} + +/// Ticket words that ask to delete, replace or overwrite. +pub const REPLACE_ASKS: &[&str] = &[ + "delete", + "remove", + "replace", + "overwrite", + "prune", + "purge", + "clean up", + "cleanup", + "dedup", + "upsert", + "update existing", + "resync", + "re-sync", + "truncate", + "unlink", + "no longer", + "drop ", +]; + +/// Ticket words that ask about logging. +pub const LOG_ASKS: &[&str] = &["log", "verbose", "noisy", "debug"]; + +/// Ticket words that ask for reporting. +pub const REPORT_ASKS: &[&str] = &[ + "report", "count", "metric", "summary", "warn", "alert", "log", "monitor", "observab", +]; + +const OUTSIDE_LINE: &str = "wider than the ticket:"; + +/// The coder's reasons for keeping a wider change, from its notes +/// (`Wider than the ticket: : `). +pub fn reasons(notes: &str) -> Vec<(String, String)> { + notes + .lines() + .filter_map(|l| { + let l = l.trim().trim_start_matches(['-', '*']).trim(); + let at = l.to_ascii_lowercase().find(OUTSIDE_LINE)?; + let rest = l[at + OUTSIDE_LINE.len()..].trim(); + let (path, why) = rest.split_once(": ")?; + let path = path.trim().trim_matches('`').trim(); + let why = why.trim(); + (!path.is_empty() && !why.is_empty()).then(|| (path.to_string(), why.to_string())) + }) + .collect() +} + +// ── Files and lines ──────────────────────────────────────────────────────── + +fn is_test(path: &str) -> bool { + super::habits::is_test_path(path) + || path.to_ascii_lowercase().contains("/e2e/") + || path.to_ascii_lowercase().starts_with("e2e/") + || path.contains("/fixtures/") + || path.contains("/__fixtures__/") + || path.contains("/testdata/") +} + +fn code_file(path: &str) -> bool { + let l = path.to_lowercase(); + [ + ".sql", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".py", ".rb", ".go", ".rs", ".kt", ".java", + ".cs", ".php", ".scala", + ] + .iter() + .any(|e| l.ends_with(e)) + && !l.contains(".d.ts") + && !l.contains("/generated/") +} + +fn ext(path: &str) -> &str { + path.rsplit('.').next().unwrap_or("") +} + +/// A patch's added (`+`) or removed (`-`) lines, without headers. +fn lines_of(patch: &str, sign: char) -> Vec<&str> { + let header = if sign == '+' { "+++" } else { "---" }; + patch + .lines() + .filter(|l| l.starts_with(sign) && !l.starts_with(header)) + .map(|l| &l[1..]) + .collect() +} + +/// A patch's unchanged context lines. +fn context_of(patch: &str) -> Vec<&str> { + patch + .lines() + .filter(|l| l.starts_with(' ')) + .map(|l| &l[1..]) + .collect() +} + +fn non_blank(lines: &[&str]) -> usize { + lines.iter().filter(|l| !l.trim().is_empty()).count() +} + +// ── Definitions ──────────────────────────────────────────────────────────── + +/// What a top-level definition is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DefKind { + /// A map, list, set or object literal: a lookup table or config. + Table, + /// A function or method at the top level. + Function, +} + +/// A top-level definition. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Def { + pub name: String, + pub kind: DefKind, +} + +fn ident(s: &str) -> Option { + let n: String = s + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$') + .collect(); + (n.len() >= 3 && !n.chars().next().is_some_and(|c| c.is_ascii_digit())).then_some(n) +} + +fn table_value(v: &str) -> bool { + let v = v.trim_start(); + [ + "{", + "[", + "(", + "dict(", + "frozenset(", + "set(", + "mappingproxytype(", + "new map", + "new set", + "object.freeze(", + "map[", + "phf_map!", + "hashmap", + "btreemap", + "&[", + ] + .iter() + .any(|p| v.to_lowercase().starts_with(p)) +} + +/// The definition a line makes at the top level of a file, by language. +/// Indented lines (inside a class or function) define nothing here. +pub fn top_level_def(line: &str, path: &str) -> Option { + if line.starts_with([' ', '\t']) || line.trim().is_empty() { + return None; + } + let l = line.trim_end(); + match ext(path) { + "py" => { + if let Some(r) = l + .strip_prefix("def ") + .or_else(|| l.strip_prefix("async def ")) + { + return ident(r).map(|name| Def { + name, + kind: DefKind::Function, + }); + } + let (lhs, rhs) = l.split_once('=')?; + if rhs.starts_with('=') || lhs.contains('(') { + return None; + } + let name = ident(lhs.split(':').next()?.trim())?; + table_value(rhs).then_some(Def { + name, + kind: DefKind::Table, + }) + } + "ts" | "tsx" | "js" | "jsx" | "mjs" | "cjs" => { + let r = l.strip_prefix("export ").unwrap_or(l); + let r = r.strip_prefix("default ").unwrap_or(r); + let r = r.strip_prefix("async ").unwrap_or(r); + if let Some(f) = r.strip_prefix("function ") { + return ident(f.trim_start_matches('*').trim_start()).map(|name| Def { + name, + kind: DefKind::Function, + }); + } + let decl = ["const ", "let ", "var "] + .iter() + .find_map(|k| r.strip_prefix(k))?; + let name = ident(decl)?; + let rhs = decl.split_once('=')?.1.trim_start(); + let rhs_l = rhs.to_lowercase(); + if rhs_l.starts_with("(") && (rhs_l.contains("=>") || rhs_l.starts_with("(async")) + || rhs_l.starts_with("async") + || rhs_l.starts_with("function") + { + return Some(Def { + name, + kind: DefKind::Function, + }); + } + table_value(rhs).then_some(Def { + name, + kind: DefKind::Table, + }) + } + "rs" => { + let r = l + .strip_prefix("pub(crate) ") + .or_else(|| l.strip_prefix("pub(super) ")) + .or_else(|| l.strip_prefix("pub ")) + .unwrap_or(l); + let r = r.strip_prefix("async ").unwrap_or(r); + if let Some(f) = r.strip_prefix("fn ") { + return ident(f).map(|name| Def { + name, + kind: DefKind::Function, + }); + } + let decl = ["static ", "const "] + .iter() + .find_map(|k| r.strip_prefix(k))?; + let name = ident(decl)?; + let (ty, rhs) = decl.split_once('=').unwrap_or((decl, "")); + let ty = ty.to_lowercase(); + (ty.contains("map") || ty.contains('[') || ty.contains("set") || table_value(rhs)) + .then_some(Def { + name, + kind: DefKind::Table, + }) + } + "go" => { + if let Some(f) = l.strip_prefix("func ") { + return ident(f).map(|name| Def { + name, + kind: DefKind::Function, + }); + } + let decl = l.strip_prefix("var ")?; + let name = ident(decl)?; + let rhs = decl.split_once('=')?.1; + table_value(rhs).then_some(Def { + name, + kind: DefKind::Table, + }) + } + "rb" => { + let (lhs, rhs) = l.split_once('=')?; + let name = ident(lhs.trim())?; + (name + .chars() + .all(|c| c.is_ascii_uppercase() || c == '_' || c.is_ascii_digit()) + && table_value(rhs)) + .then_some(Def { + name, + kind: DefKind::Table, + }) + } + _ => None, + } +} + +/// Every top-level definition in `text`. +pub fn defs(text: &str, path: &str) -> Vec { + text.lines() + .filter_map(|l| top_level_def(l, path)) + .collect() +} + +/// Whether a new definition parallels an existing one: the same kind, and +/// names that share at least two words and half of the smaller name's. +pub fn parallels(new: &Def, old: &Def) -> bool { + if new.kind != old.kind || new.name == old.name { + return false; + } + let a = name_words(&new.name); + let b = name_words(&old.name); + let shared = a.iter().filter(|w| b.contains(w)).count(); + let smaller = a.len().min(b.len()).max(1); + shared >= 2 && shared * 2 >= smaller && name_similarity(&new.name, &old.name) >= 0.34 +} + +/// The new definitions of an edit that parallel one already in the file, +/// as (new, existing). An existing one the edit removes was renamed, not +/// paralleled. +pub fn parallel_in_edit(path: &str, old: &str, new: &str) -> Vec<(Def, Def)> { + let before = defs(old, path); + let after = defs(new, path); + let mut out = Vec::new(); + for d in after + .iter() + .filter(|d| !before.iter().any(|b| b.name == d.name)) + { + if let Some(e) = before + .iter() + .filter(|b| after.iter().any(|a| a.name == b.name)) + .find(|b| parallels(d, b)) + { + out.push((d.clone(), e.clone())); + } + } + out +} + +/// The parallel structures a diff adds: new top-level definitions next to +/// a similar existing one in the same file's base (`base`, by path) or its +/// patch's context, or in another changed file's base. +pub fn parallel_structures(diff: &Diff, base: &[(String, String)]) -> Vec { + let mut out = Vec::new(); + for (path, status, patch) in diff { + if status == "removed" || !code_file(path) || is_test(path) { + continue; + } + let removed: Vec = lines_of(patch, '-') + .into_iter() + .filter_map(|l| top_level_def(l, path)) + .collect(); + let mut existing: Vec = base + .iter() + .filter(|(p, _)| p == path) + .flat_map(|(_, t)| defs(t, path)) + .collect(); + existing.extend( + context_of(patch) + .into_iter() + .filter_map(|l| top_level_def(l, path)), + ); + existing.retain(|e| !removed.iter().any(|r| r.name == e.name)); + for d in lines_of(patch, '+') + .into_iter() + .filter_map(|l| top_level_def(l, path)) + { + if existing.iter().any(|e| e.name == d.name) { + continue; + } + if let Some(e) = existing.iter().find(|e| parallels(&d, e)) { + let what = format!("`{}` next to the existing `{}`", d.name, e.name); + if !out.iter().any(|w: &Widening| w.what == what) { + out.push(Widening { + kind: Kind::Parallel, + path: path.clone(), + what, + }); + } + } + } + } + out +} + +// ── Replacing semantics ──────────────────────────────────────────────────── + +/// Statements that delete or overwrite stored rows, with how a report +/// names each. +const REPLACING: &[(&str, &str)] = &[ + ("do update", "`ON CONFLICT DO UPDATE`"), + ("on_conflict_do_update", "`on_conflict_do_update`"), + ("delete from", "`DELETE FROM`"), + ("truncate table", "`TRUNCATE TABLE`"), + ("insert or replace", "`INSERT OR REPLACE`"), + ("replace into", "`REPLACE INTO`"), + ("when matched then update", "`MERGE ... UPDATE`"), + ("when matched then delete", "`MERGE ... DELETE`"), + ( + "when not matched by source", + "`MERGE ... NOT MATCHED BY SOURCE`", + ), + (".delete()", "an ORM delete"), + ("delete_many(", "`delete_many`"), + ("destroy_all", "`destroy_all`"), + ("bulk_delete", "a bulk delete"), + ("drop table", "`DROP TABLE`"), +]; + +fn count(lines: &[&str], token: &str) -> usize { + lines + .iter() + .filter(|l| { + let t = l.trim_start(); + !(t.starts_with("--") || t.starts_with('#') || t.starts_with("//")) + }) + .map(|l| l.to_lowercase().matches(token).count()) + .sum() +} + +/// Deleting or overwriting statements the diff adds where its base had +/// none of that kind: an insert-only path made replacing. +pub fn replacing(diff: &Diff, base: &[(String, String)]) -> Vec { + let mut out = Vec::new(); + for (path, status, patch) in diff { + if status == "removed" || !code_file(path) || is_test(path) { + continue; + } + let added = lines_of(patch, '+'); + let removed = lines_of(patch, '-'); + let base_text = base + .iter() + .find(|(p, _)| p == path) + .map(|(_, t)| t.as_str()); + let mut found = Vec::new(); + for (token, name) in REPLACING { + let a = count(&added, token); + if a == 0 || a <= count(&removed, token) { + continue; + } + // The base file had none of it: the path was additive. In a new + // file every one is new. + let had = base_text + .map(|t| t.to_lowercase().matches(token).count()) + .unwrap_or_else(|| count(&context_of(patch), token)); + if status == "added" || had == 0 { + found.push(*name); + } + } + if !found.is_empty() { + out.push(Widening { + kind: Kind::Replacing, + path: path.clone(), + what: found.join(", "), + }); + } + } + out +} + +// ── Logging and reporting ────────────────────────────────────────────────── + +const LEVELS: &[&str] = &[ + "warning", "critical", "debug", "info", "warn", "error", "fatal", "trace", +]; + +fn level_free(line: &str) -> String { + let mut s = line.trim().to_lowercase(); + for l in LEVELS { + s = s.replace(l, ""); + } + s +} + +fn has_level(line: &str) -> bool { + let l = line.to_lowercase(); + LEVELS.iter().any(|w| l.contains(w)) + && (l.contains("log") || l.contains("!(") || l.contains("setlevel") || l.contains("level")) +} + +/// Log lines and logger settings the diff keeps but moves to another level. +pub fn log_levels(diff: &Diff) -> Vec { + let mut out = Vec::new(); + for (path, status, patch) in diff { + if status == "removed" || is_test(path) { + continue; + } + let removed: Vec<&str> = lines_of(patch, '-') + .into_iter() + .filter(|l| has_level(l)) + .collect(); + for a in lines_of(patch, '+').into_iter().filter(|l| has_level(l)) { + if let Some(r) = removed.iter().find(|r| { + level_free(r) == level_free(a) && r.trim().to_lowercase() != a.trim().to_lowercase() + }) { + out.push(Widening { + kind: Kind::LogLevel, + path: path.clone(), + what: format!( + "`{}` became `{}`", + common::truncate_str(r.trim(), 80), + common::truncate_str(a.trim(), 80) + ), + }); + break; + } + } + } + out +} + +fn is_counter(line: &str) -> bool { + let l = line.to_lowercase().replace(' ', ""); + l.contains("+=1") + || l.contains("++;") + || l.contains(".inc(") + || l.contains("counter(") + || l.contains("fetch_add(") +} + +fn is_log_call(line: &str) -> bool { + let l = line.trim_start().to_lowercase(); + [ + "logger.", + "logging.", + "log.", + "self.log.", + "warn!(", + "info!(", + "debug!(", + "console.warn(", + "console.info(", + "console.debug(", + "warnings.warn(", + ] + .iter() + .any(|p| l.starts_with(p) || l.contains(&format!(" {p}")) || l.contains(&format!("({p}"))) +} + +/// New counters and log calls in non-test code: (counters, log calls). +pub fn reporting_added(diff: &Diff) -> Vec<(String, usize, usize)> { + diff.iter() + .filter(|(p, s, _)| s != "removed" && code_file(p) && !is_test(p)) + .map(|(p, _, patch)| { + let added = lines_of(patch, '+'); + let removed = lines_of(patch, '-'); + let counters = added.iter().filter(|l| is_counter(l)).count(); + let logs = added.iter().filter(|l| is_log_call(l)).count(); + let was_counters = removed.iter().filter(|l| is_counter(l)).count(); + let was_logs = removed.iter().filter(|l| is_log_call(l)).count(); + ( + p.clone(), + counters.saturating_sub(was_counters), + logs.saturating_sub(was_logs), + ) + }) + .filter(|(_, c, l)| *c > 0 || *l > 0) + .collect() +} + +/// Reporting the diff adds that the ticket doesn't ask for: two or more new +/// counters, a counter and a log call, or three or more log calls in a file. +pub fn reporting(diff: &Diff) -> Vec { + reporting_added(diff) + .into_iter() + .filter(|(_, c, l)| *c >= 2 || (*c >= 1 && *l >= 1) || *l >= 3) + .map(|(path, c, l)| Widening { + kind: Kind::Reporting, + path, + what: format!("{c} new counter(s), {l} new log call(s)"), + }) + .collect() +} + +// ── Tests ────────────────────────────────────────────────────────────────── + +/// Added test lines against added code lines: a test of more than 200 +/// lines and twice the code, or more than 120 lines and four times it. +pub fn test_size(diff: &Diff) -> Vec { + let mut tests = 0; + let mut code = 0; + let mut biggest = (String::new(), 0usize); + for (path, status, patch) in diff { + if status == "removed" { + continue; + } + let n = non_blank(&lines_of(patch, '+')); + if is_test(path) { + tests += n; + if n > biggest.1 { + biggest = (path.clone(), n); + } + } else if code_file(path) { + code += n; + } + } + let out_of_proportion = (tests > 200 && tests > 2 * code) || (tests > 120 && tests > 4 * code); + if !out_of_proportion { + return Vec::new(); + } + vec![Widening { + kind: Kind::TestSize, + path: biggest.0, + what: format!("{tests} added lines against {code} lines of changed code"), + }] +} + +const FAKES: &[&str] = &[ + "class fake", + "class mock", + "class stub", + "magicmock(", + "mock.patch(", + "@patch(", + "monkeypatch.setattr(", + "responses.add(", + "nock(", + "route.fulfill(", + "jest.mock(", + "vi.mock(", + "mockresolvedvalue(", + "mockreturnvalue(", + "httpretty.register_uri(", + "requests_mock", +]; + +fn payload_key(line: &str) -> bool { + let t = line.trim_start(); + let Some(q) = t.chars().next().filter(|c| matches!(c, '"' | '\'')) else { + return false; + }; + let rest = &t[1..]; + let Some(end) = rest.find(q) else { + return false; + }; + let key = &rest[..end]; + !key.is_empty() + && key + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')) + && rest[end + 1..].trim_start().starts_with(':') +} + +/// Tests that fake an outside call with a large payload literal (twelve or +/// more keys), or add a JSON fixture of that size, while no probe record +/// shows what the outside system returns. +pub fn invented_payloads(diff: &Diff, has_probe: bool) -> Vec { + if has_probe { + return Vec::new(); + } + let mut out = Vec::new(); + for (path, status, patch) in diff { + if status == "removed" || !is_test(path) { + continue; + } + let added = lines_of(patch, '+'); + let keys = added.iter().filter(|l| payload_key(l)).count(); + let low = added.join("\n").to_lowercase(); + let fakes = FAKES.iter().filter(|f| low.contains(*f)).count(); + let fixture = path.ends_with(".json") && status == "added"; + if keys >= 12 && (fakes > 0 || fixture) { + out.push(Widening { + kind: Kind::InventedPayload, + path: path.clone(), + what: format!( + "{keys} payload keys{}", + if fakes > 0 { + format!(" behind {fakes} kind(s) of fake") + } else { + " in a new fixture".to_string() + } + ), + }); + } + } + out +} + +// ── The check ────────────────────────────────────────────────────────────── + +/// Everything a diff adds past its ticket. `base` holds the base text of +/// changed files where read; `ticket` is the ticket's own words (title, +/// body, people's answers); `has_probe` says a probe record is in the tree. +pub fn check( + diff: &Diff, + base: &[(String, String)], + ticket: &str, + has_probe: bool, +) -> Vec { + let mut out = parallel_structures(diff, base); + if !ticket_asks(ticket, REPLACE_ASKS) { + out.extend(replacing(diff, base)); + } + if !ticket_asks(ticket, LOG_ASKS) { + out.extend(log_levels(diff)); + } + if !ticket_asks(ticket, REPORT_ASKS) { + out.extend(reporting(diff)); + } + out.extend(test_size(diff)); + out.extend(invented_payloads(diff, has_probe)); + out +} + +/// What still stands after the coder's reasons: an excusable item with a +/// reason for its path is kept as said, the rest go back. +pub fn standing<'a>(found: &'a [Widening], notes: &str) -> Vec<&'a Widening> { + let why = reasons(notes); + found + .iter() + .filter(|w| !(w.excusable() && why.iter().any(|(p, _)| p.trim() == w.path.trim()))) + .collect() +} + +// ── Test assertions changed to match another company's page ──────────────── + +/// An assertion a test change flipped to what an outside page does, while +/// an acceptance criterion of the ticket says otherwise. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VendorFlip { + pub path: String, + pub removed: String, + pub added: String, + pub criterion: String, +} + +impl VendorFlip { + /// The review finding's text. + pub fn body(&self) -> String { + format!( + "`{}` changes `{}` to `{}`, matching what the outside page does, while the ticket's acceptance criterion says \"{}\". Change the product side first (the layout around the frame, the page's own code, the vendor's documented embed options) so the criterion holds, and keep the assertion. Change the test only when the product can't meet the criterion, with the measured reason in the plan and the pull request.", + self.path, + common::truncate_str(self.removed.trim(), 120), + common::truncate_str(self.added.trim(), 120), + self.criterion + ) + } +} + +/// The subject of an `expect(...)` and the rest of the assertion. +fn assertion(line: &str) -> Option<(String, String)> { + let at = line.find("expect(")?; + let rest = &line[at + 7..]; + let mut depth = 1; + for (i, c) in rest.char_indices() { + match c { + '(' => depth += 1, + ')' => { + depth -= 1; + if depth == 0 { + return Some(( + rest[..i].trim().to_string(), + rest[i + 1..].trim().to_string(), + )); + } + } + _ => {} + } + } + None +} + +/// Assertions a patch changed: a removed and an added `expect` on the same +/// subject with another matcher or value. +pub fn assertion_flips(patch: &str) -> Vec<(String, String)> { + let removed: Vec<&str> = lines_of(patch, '-'); + let mut out = Vec::new(); + for a in lines_of(patch, '+') { + let Some((sa, ra)) = assertion(a) else { + continue; + }; + if let Some(r) = removed + .iter() + .find(|r| assertion(r).is_some_and(|(sr, rr)| sr == sa && rr != ra)) + { + out.push((r.to_string(), a.to_string())); + } + } + out +} + +const CODE_WORDS: &[&str] = &[ + "expect", + "await", + "const", + "locator", + "frame", + "frames", + "tobe", + "true", + "false", + "toequal", + "page", + "getbytestid", + "evaluate", + "document", + "window", + "toBeVisible", + "tohave", +]; + +fn stems(text: &str) -> Vec { + text.split(|c: char| !c.is_ascii_alphanumeric()) + .flat_map(name_words) + .filter(|w| w.len() >= 5 && !CODE_WORDS.iter().any(|c| c.eq_ignore_ascii_case(w))) + .map(|w| w.chars().take(5).collect()) + .collect() +} + +/// The vendor flips in a changed test file: `outside` says the file drives +/// another company's page; each flipped assertion is matched to the +/// acceptance criterion it shares words with. +pub fn vendor_flips( + path: &str, + patch: &str, + outside: bool, + criteria: &[String], +) -> Vec { + if !outside || criteria.is_empty() { + return Vec::new(); + } + let mut out = Vec::new(); + for (removed, added) in assertion_flips(patch) { + let words = stems(&format!("{removed} {added}")); + let best = criteria + .iter() + .map(|c| { + let cw = stems(c); + (words.iter().filter(|w| cw.contains(w)).count(), c) + }) + .filter(|(n, _)| *n > 0) + .max_by_key(|(n, _)| *n); + if let Some((_, c)) = best { + out.push(VendorFlip { + path: path.to_string(), + removed, + added, + criterion: c.clone(), + }); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn d(path: &str, status: &str, patch: &str) -> (String, String, String) { + (path.into(), status.into(), patch.into()) + } + + #[test] + fn definitions_by_language() { + let py = + "CAMP_MULTI_SPORT_OVERRIDES = {\ndef get_camp_multi_sport_names(name):\n X = {}"; + let got = defs(py, "dags/camps.py"); + assert_eq!(got.len(), 2); + assert_eq!(got[0].kind, DefKind::Table); + assert_eq!(got[1].kind, DefKind::Function); + let ts = "export const SPORT_MAP: Record = {\nexport function sportFor(x) {\nconst handler = async (e) => {"; + let got = defs(ts, "src/a.ts"); + assert_eq!( + got.iter().map(|d| d.name.as_str()).collect::>(), + vec!["SPORT_MAP", "sportFor", "handler"] + ); + let rs = "pub const RULES: &[&str] = &[\npub(crate) fn rules_for() {}"; + assert_eq!(defs(rs, "a.rs").len(), 2); + } + + #[test] + fn a_second_map_next_to_the_first_is_a_parallel_structure() { + let base = vec![( + "dags/camps.py".to_string(), + "CAMP_MULTI_SPORT_OVERRIDES = {\n \"a\": [\"Soccer\"],\n}\n\ndef get_camp_multi_sport_names(name):\n return CAMP_MULTI_SPORT_OVERRIDES.get(name, [])\n".to_string(), + )]; + let patch = "@@ -1,3 +1,9 @@\n CAMP_MULTI_SPORT_OVERRIDES = {\n+CAMP_SWIMMING_OVERRIDES = {\n+ \"b\": [\"Swimming\"],\n+}\n+def get_camp_swimming_names(name):\n+ return CAMP_SWIMMING_OVERRIDES.get(name, [])\n"; + let w = parallel_structures(&[d("dags/camps.py", "modified", patch)], &base); + assert_eq!(w.len(), 2, "{w:?}"); + assert!(w[0].what.contains("CAMP_SWIMMING_OVERRIDES")); + assert!(w[0].what.contains("CAMP_MULTI_SPORT_OVERRIDES")); + assert!(w[1].what.contains("get_camp_multi_sport_names")); + // Four new entries in the existing map are no new structure. + let small = "@@ -1,3 +1,7 @@\n CAMP_MULTI_SPORT_OVERRIDES = {\n+ \"c\": [\"Swimming\", \"Tennis\"],\n"; + assert!(parallel_structures(&[d("dags/camps.py", "modified", small)], &base).is_empty()); + // A rename is not a parallel. + let rename = "-CAMP_MULTI_SPORT_OVERRIDES = {\n+CAMP_SPORT_OVERRIDES = {\n"; + assert!(parallel_structures(&[d("dags/camps.py", "modified", rename)], &base).is_empty()); + } + + #[test] + fn insert_only_made_replacing_blocks_unless_asked() { + let patch = "- ON CONFLICT (camp_id, sport_id) DO NOTHING\n+ ON CONFLICT (camp_id, sport_id) DO UPDATE SET sport_id = EXCLUDED.sport_id\n+DELETE FROM camp_sports WHERE camp_id = %s AND sport_id <> ALL(%s)\n"; + let base = vec![( + "dags/sync.py".to_string(), + "INSERT INTO camp_sports VALUES (%s, %s) ON CONFLICT (camp_id, sport_id) DO NOTHING" + .to_string(), + )]; + let diff = [d("dags/sync.py", "modified", patch)]; + let w = check( + &diff, + &base, + "Link these four camps to Swimming as well", + false, + ); + let r: Vec<&Widening> = w.iter().filter(|w| w.kind == Kind::Replacing).collect(); + assert_eq!(r.len(), 1); + assert!(r[0].what.contains("DO UPDATE") && r[0].what.contains("DELETE FROM")); + assert!(!r[0].excusable()); + assert!(standing(&w, "Wider than the ticket: dags/sync.py: cleaner").len() == w.len()); + // A ticket that asks to remove stale links may. + assert!( + check(&diff, &base, "Remove links that no longer apply", false) + .iter() + .all(|w| w.kind != Kind::Replacing) + ); + // An additive insert is fine. + let add = "+ INSERT INTO camp_sports VALUES (%s, %s) ON CONFLICT DO NOTHING\n"; + assert!(replacing(&[d("dags/sync.py", "modified", add)], &base).is_empty()); + } + + #[test] + fn log_levels_and_new_reporting() { + let patch = "-logger.setLevel(logging.INFO)\n+logger.setLevel(logging.DEBUG)\n+ skipped += 1\n+ linked += 1\n+ log.warning(\"skipped %s\", ids)\n"; + let diff = [d("dags/common/log.py", "modified", patch)]; + let w = check(&diff, &[], "Link four camps to Swimming", false); + assert!(w.iter().any(|w| w.kind == Kind::LogLevel), "{w:?}"); + assert!(w.iter().any(|w| w.kind == Kind::Reporting), "{w:?}"); + // A reason keeps an excusable item. + let kept = standing( + &w, + "Wider than the ticket: dags/common/log.py: the ticket's comment asks for the count", + ); + assert!(kept.is_empty()); + // A ticket that asks for logging gets it. + assert!(check(&diff, &[], "Log how many camps were skipped", false).is_empty()); + // One new log line in a change is ordinary. + let one = [d("a.py", "modified", "+ log.info(\"done\")\n")]; + assert!(reporting(&one).is_empty()); + } + + #[test] + fn tests_in_proportion_and_payloads_observed() { + let code: String = (0..20).map(|i| format!("+ x{i} = 1\n")).collect(); + let test: String = (0..430).map(|i| format!("+ assert y{i}\n")).collect(); + let diff = [ + d("dags/sync.py", "modified", &code), + d("tests/test_sync.py", "added", &test), + ]; + let w = test_size(&diff); + assert_eq!(w.len(), 1); + assert!(w[0].what.contains("430 added lines against 20")); + let small: String = (0..30).map(|i| format!("+ assert y{i}\n")).collect(); + assert!(test_size(&[ + d("dags/sync.py", "modified", &code), + d("tests/test_sync.py", "added", &small) + ]) + .is_empty()); + + let payload: String = std::iter::once("+class FakeVendorHook:\n".to_string()) + .chain((0..14).map(|i| format!("+ \"field_{i}\": \"v\",\n"))) + .collect(); + let diff = [d("tests/test_sync.py", "added", &payload)]; + assert_eq!(invented_payloads(&diff, false).len(), 1); + assert!(invented_payloads(&diff, true).is_empty()); + } + + #[test] + fn a_test_flipped_to_the_vendor_while_a_criterion_says_otherwise() { + let patch = "- expect(await frameScrolls(page)).toBe(false);\n+ expect(await frameScrolls(page)).toBe(true);\n"; + let criteria = vec![ + "The portal loads inside the page".to_string(), + "No double scrollbars on desktop".to_string(), + ]; + let f = vendor_flips("e2e/portal.spec.ts", patch, true, &criteria); + assert_eq!(f.len(), 1); + assert_eq!(f[0].criterion, "No double scrollbars on desktop"); + assert!(f[0].body().contains("Change the product side first")); + // Our own page, or no criterion, is a test's own business. + assert!(vendor_flips("e2e/portal.spec.ts", patch, false, &criteria).is_empty()); + assert!(vendor_flips("e2e/portal.spec.ts", patch, true, &[]).is_empty()); + } + + #[test] + fn an_edit_that_adds_a_parallel_helper() { + let old = "SPORT_OVERRIDES = {\n}\ndef sport_overrides_for(n):\n pass\n"; + let new = format!("{old}SWIM_SPORT_OVERRIDES = {{\n}}\n"); + let p = parallel_in_edit("a.py", old, &new); + assert_eq!(p.len(), 1); + assert_eq!(p[0].1.name, "SPORT_OVERRIDES"); + assert!(parallel_in_edit("a.py", old, old).is_empty()); + } +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 456a62a82..9e125977e 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1276,6 +1276,7 @@ pub mod e2e; pub mod e2e_attribution; pub mod e2e_setup; pub mod email_events; +mod explore_guard; pub mod feature; pub mod feedback; pub mod file_claims; @@ -1315,6 +1316,7 @@ mod log_fix_checks; #[cfg(test)] mod log_fix_eval; pub mod log_look; +pub mod minimal_change; pub mod model_check; #[cfg(test)] mod model_route_eval; @@ -1335,6 +1337,7 @@ pub(crate) mod plan_coverage; pub mod plan_execute; mod plan_judge; pub(crate) mod plan_sections; +mod plan_shape; /// Plugin runs, publishing, source sync and results. pub mod plugins; mod pr; diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 40e1dedf3..02f257073 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -305,11 +305,12 @@ pub async fn run( that CoderHelm carries out to the end, verification included.\n\n\ You have access to these repos:\n{repos_list}\n\n\ All tools default to {owner}/{repo} when the `repo` parameter is omitted. \ - To explore another repo, pass `repo` as `owner/name` (e.g. `\"{default_repo}\"`).{cross_repo}{instructions_block}{team_block}{tests_block}{feature_block}", + To explore another repo, pass `repo` as `owner/name` (e.g. `\"{default_repo}\"`).{cross_repo}{instructions_block}{team_block}{tests_block}{feature_block}{smallest}", owner = msg.repo_owner, repo = msg.repo_name, stance = super::ownership::planner_stance(), feature_block = super::feature::planner_block(intent), + smallest = super::plan_shape::PLANNER, cross_repo = if team_repos.len() > 1 { super::cross_repo::PLANNER_LINE } else { @@ -321,10 +322,10 @@ pub async fn run( "simple" => { r#"## Complexity: SIMPLE (1-3 files) -This is a simple change. Be extremely efficient: -- Use 1-2 `search_code` calls to locate the relevant file(s) and line numbers -- Use `read_file_lines` on the specific section (max 100 lines), NOT whole files -- You should need 2-4 tool calls total, then output the plan +This is a simple change. Be efficient, but read what the change extends: +- Use `search_code` to locate the relevant file(s), and once more for the structure the change would add (an existing map, helper or config that already does part of it) +- Use `read_file_lines` on that structure in full (the whole map, function or query) and on its writers +- You should need 3-6 tool calls, then output the plan - The plan usually has 1-2 tasks; when the change needs more files, list every one"# } "medium" => { @@ -833,6 +834,18 @@ Then the ```fix_location.json block described above."#, state, }; + // Explore before planning: what the ticket's own words find in the + // repository goes to the planner with the ticket, so the plan extends + // it (a plan once added a second map beside the one it needed). + let found = super::plan_shape::existing_for_ticket( + &executor.read_only, + &default_repo, + &msg.title, + &msg.body, + ) + .await; + let existing_names = super::plan_shape::existing_names(&found); + let prompt = format!("{prompt}{}", super::plan_shape::existing_block(&found)); let mut content_blocks = vec![serde_json::json!({"type": "text", "text": prompt})]; for img in &msg.image_attachments { if let Some(b64) = @@ -934,6 +947,19 @@ Then the ```fix_location.json block described above."#, // reuse and the closest sibling. let feature_gaps = super::feature::plan_gaps(&draft, intent, &ticket_history.prior); back.extend(feature_gaps.iter().cloned()); + // The smallest correct change (see plan_shape): its five sections, no + // parallel structure, no widening the ticket doesn't ask for, outside + // systems measured, the product changed before a test. + let ticket_words = format!( + "{}\n{}{}", + msg.title, + msg.body, + common::run_questions::answers_note(&msg.answers) + ); + let is_feature = intent == super::triage::TicketIntent::Feature; + let shape_gaps = + super::plan_shape::plan_gaps(&draft, &ticket_words, is_feature, &existing_names); + back.extend(shape_gaps.iter().cloned()); // A decision that stops without a fix names the one step a person takes. back.extend(super::fix_location::next_step_gaps(draft.fix.as_ref())); // What a careful engineer settles before code (see habits): the worker @@ -1419,6 +1445,22 @@ Then the ```fix_location.json block described above."#, } } } + if !shape_gaps.is_empty() { + let left = super::plan_shape::plan_gaps(&files, &ticket_words, is_feature, &existing_names); + if !left.is_empty() { + warn!(ticket_id = %msg.ticket_id, gaps = ?left, "Plan is still not the smallest change after one send-back"); + super::add_progress_note( + state, + &msg.team_id, + run_id, + &format!("Plan check (smallest change): {}", left.join(" ")), + ) + .await; + if let Some(d) = files.fix.as_mut() { + d.open_gaps.extend(left); + } + } + } // The habits, read again on the plan as it now stands (a revision names // new files and new names to search for). { diff --git a/services/worker/src/passes/plan_shape.rs b/services/worker/src/passes/plan_shape.rs new file mode 100644 index 000000000..9afb98573 --- /dev/null +++ b/services/worker/src/passes/plan_shape.rs @@ -0,0 +1,607 @@ +//! The plan is the smallest correct change, and says so in five sections. +//! +//! Two plans went wrong before a line was written. One, for linking four +//! camps to a second sport, planned a new map and helpers beside the +//! existing overrides map and a sync that "replaces" links, so the build +//! deleted links nobody asked about. The other, for embedding a vendor's +//! portal, planned end-to-end assertions about the vendor's page from +//! guesses, and when the vendor's page broke a criterion ("no double +//! scrollbars") it planned to change the test instead of the page. +//! +//! Each plan now writes, in design.md: +//! +//! - [`REUSE`]: the existing maps, helpers, config and tests it extends, +//! by path (found by search; the worker also hands the planner what the +//! ticket's own words find, [`existing_block`]); +//! - [`MUST_NOT_CHANGE`]: behaviour that stays as it is (no deletes where +//! the code only adds, shared logging, other pipelines); +//! - [`MEASURE_FIRST`]: what outside systems it measures before writing +//! against them (a `probe_page` record, a lookup), or that there are none; +//! - [`SMALLEST_CHANGE`]: the change in a few lines, and why nothing +//! smaller does it; +//! - [`PROOF`]: the one test (or the check) that shows it, in proportion. +//! +//! [`plan_gaps`] holds the draft to them and rejects a plan that proposes a +//! structure parallel to one it names under Reuse, replacing or deleting +//! semantics or log changes the ticket doesn't ask for, assertions about an +//! outside page with nothing measured, or a test change where a criterion +//! says the product must change. What is missing goes back to the planner +//! in the plan's one send-back. + +use super::cross_repo::RepoSearch; +use super::feature::reuse::section; +use super::minimal_change::{self, Def, DefKind}; +use super::plan::PlanResult; + +pub const REUSE: &str = super::feature::reuse::REUSE_HEADING; +pub const MUST_NOT_CHANGE: &str = "## Must not change"; +pub const MEASURE_FIRST: &str = "## Measure first"; +pub const SMALLEST_CHANGE: &str = "## Smallest change"; +pub const PROOF: &str = "## Proof"; + +/// What the planner is told, for every ticket kind. +pub const PLANNER: &str = "\n\n## The smallest correct change (CoderHelm checks these)\n\ +Before you plan, read the code the change extends: the whole map, function or query, and its \ +writers and readers. Then write these sections in design.md:\n\ +- `## Reuse`: the existing maps, helpers, constants, config and tests this change extends, each \ +with its path (search the ticket's names and the structure you would add). Add entries to an \ +existing map or a parameter to an existing helper; never a second map or helper beside it.\n\ +- `## Must not change`: what stays as it is. A path that only inserts keeps only inserting (no \ +`DELETE`, no `ON CONFLICT DO UPDATE`, no replacing sync) unless the ticket asks for it; log \ +levels, shared logging and other pipelines stay untouched; no new counters or reports the \ +ticket doesn't ask for.\n\ +- `## Measure first`: every outside system the change or its tests rest on (a vendor page or \ +embed, an API, a webhook payload) and how you measure it before writing against it: the \ +`probe_page` tool for a page (its test ids, sizes, what is enabled), a read-only lookup for \ +data. Write `None: the change stays inside this repository` when there are none. Never plan \ +selectors, fields or behaviour of another company's system from a guess.\n\ +- `## Smallest change`: the change in a few lines (for example \"4 entries in \ +`CAMP_OVERRIDES`; an insert with `ON CONFLICT DO NOTHING` in the 3 write branches\"), and why \ +nothing smaller does it.\n\ +- `## Proof`: the one test or check that shows it, sized to the change: the new behaviour and \ +that nothing else changed, through the real entry point, with real or probed data. When an \ +acceptance criterion and an outside system disagree, plan the product change that meets the \ +criterion first; a test is changed to match the outside system only with the measured reason.\n"; + +fn names_something(s: &str) -> bool { + s.contains('`') + || s.split_whitespace() + .any(|t| t.contains('/') && !t.contains("://")) + || s.to_lowercase().contains("searched") + || s.to_lowercase().contains("none") +} + +fn stops(files: &PlanResult) -> bool { + let t = files.tasks.trim_start(); + t.is_empty() || t.starts_with("NO_CHANGES_NEEDED") || t.starts_with("CLARIFICATION_NEEDED") +} + +/// Backticked identifiers in `text` (names of code, not paths or prose). +fn backticked(text: &str) -> Vec { + let mut out = Vec::new(); + for (i, part) in text.split('`').enumerate() { + if i % 2 == 0 { + continue; + } + let p = part.trim().trim_end_matches("()"); + let ok = p.len() >= 4 + && p.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + && (p.contains('_') || p.chars().skip(1).any(|c| c.is_ascii_uppercase())); + if ok && !out.iter().any(|o| o == p) { + out.push(p.to_string()); + } + } + out +} + +fn as_def(name: &str) -> Def { + let table = name + .chars() + .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'); + Def { + name: name.to_string(), + kind: if table { + DefKind::Table + } else { + DefKind::Function + }, + } +} + +const NEW_STRUCTURE: &[&str] = &[ + "new map", + "new dict", + "new mapping", + "separate map", + "separate mapping", + "separate dict", + "parallel map", + "second map", + "new lookup", + "new override", + "new constant", + "new helper", + "new config", +]; + +const REPLACING_WORDS: &[&str] = &[ + "upsert", + "do update", + "delete ", + "deletes ", + "deleting", + "replace the", + "replaces the", + "replacing", + "overwrite", + "truncate", + "prune", + "purge", + "remove stale", + "removes stale", + "sync removals", +]; + +const LOG_WORDS: &[&str] = &[ + "log level", + "to debug", + "to info", + "setlevel", + "info to debug", + "debug to info", +]; + +const REPORT_WORDS: &[&str] = &[ + "summary counter", + "counters", + "count of skipped", + "warning per run", + "report the skipped", + "report skipped", +]; + +const OUTSIDE_WORDS: &[&str] = &[ + "iframe", + "embed", + "vendor", + "third-party", + "third party", + "portal", + "widget", + "webhook", + "external api", + "partner", +]; + +const MEASURED_WORDS: &[&str] = &[ + "probe", + "measured", + "observed", + "lookup", + "looked up", + "fetched", + "curl", + "none:", + "none.", +]; + +const TEST_TO_VENDOR: &[&str] = &[ + "update the test to match", + "update the tests to match", + "change the test to", + "change the assertion", + "adjust the assertion", + "relax the assertion", + "expect the vendor", + "accept the vendor", + "match the vendor", + "match the portal", +]; + +/// The plan's words that propose things, without its Must not change +/// section (where "no deletes" is said). +fn proposing_text(files: &PlanResult) -> String { + let design = match section(&files.design, MUST_NOT_CHANGE) { + Some(s) => files.design.replace(s, ""), + None => files.design.clone(), + }; + format!("{}\n{}\n{}", files.proposal, design, files.tasks).to_lowercase() +} + +fn found<'a>(text: &str, words: &'a [&str]) -> Option<&'a str> { + words.iter().find(|w| text.contains(*w)).copied() +} + +/// What a draft misses or proposes past its ticket, one line each for the +/// send-back. `ticket` is the ticket's own words (title, body, answers); +/// `is_feature` skips the Reuse section, which the new-feature rules +/// already ask for; `existing` holds names the worker found for the +/// ticket's words. +pub fn plan_gaps( + files: &PlanResult, + ticket: &str, + is_feature: bool, + existing: &[String], +) -> Vec { + if stops(files) { + return Vec::new(); + } + let mut out = Vec::new(); + let design = &files.design; + let mut need = vec![MUST_NOT_CHANGE, MEASURE_FIRST, SMALLEST_CHANGE, PROOF]; + if !is_feature { + need.insert(0, REUSE); + } + let missing: Vec<&str> = need + .into_iter() + .filter(|h| !section(design, h).is_some_and(|s| !s.trim().is_empty())) + .collect(); + if !missing.is_empty() { + out.push(format!( + "design.md lacks {}. Write each: Reuse (existing structures by path), Must not change, Measure first (outside systems and how they are measured, or `None`), Smallest change (the change in a few lines), Proof (the one test or check).", + missing + .iter() + .map(|h| format!("`{h}`")) + .collect::>() + .join(", ") + )); + } + let reuse = section(design, REUSE).unwrap_or(""); + if !reuse.trim().is_empty() && !names_something(reuse) { + out.push(format!( + "`{REUSE}` names no existing structure. Search the ticket's names and the structure you would add, and list what you extend by path, or say what you searched." + )); + } + let text = proposing_text(files); + // A new structure beside an existing one. + let mut known: Vec = backticked(reuse); + known.extend(existing.iter().cloned()); + let proposed: Vec = backticked(&format!("{}\n{}", files.tasks, files.design)) + .into_iter() + .filter(|n| !known.contains(n)) + .collect(); + let mut parallel: Vec<(String, String)> = Vec::new(); + for p in &proposed { + if let Some(k) = known + .iter() + .find(|k| minimal_change::parallels(&as_def(p), &as_def(k))) + { + parallel.push((p.clone(), k.clone())); + } + } + if let Some((p, k)) = parallel.first() { + out.push(format!( + "The plan adds `{p}` next to the existing `{k}`. Extend `{k}` (add the entries or a parameter there) instead of a parallel structure." + )); + } else if let Some(w) = found(&text, NEW_STRUCTURE) { + if !known.is_empty() { + out.push(format!( + "The plan proposes a {w} while `{REUSE}` names `{}`. Extend the existing one, or say under `{SMALLEST_CHANGE}` why it can't hold this.", + known[0] + )); + } + } + if !minimal_change::ticket_asks(ticket, minimal_change::REPLACE_ASKS) { + if let Some(w) = found(&text, REPLACING_WORDS) { + out.push(format!( + "The plan would delete or overwrite (\"{}\") but the ticket asks for no deletes or replacements. Keep the write additive (insert, `ON CONFLICT DO NOTHING`) and list the existing rows under `{MUST_NOT_CHANGE}`.", + w.trim() + )); + } + } + if !minimal_change::ticket_asks(ticket, minimal_change::LOG_ASKS) { + if let Some(w) = found(&text, LOG_WORDS) { + out.push(format!( + "The plan changes logging (\"{}\") the ticket doesn't ask about. Leave log levels and shared logging as they are.", + w.trim() + )); + } + } + if !minimal_change::ticket_asks(ticket, minimal_change::REPORT_ASKS) { + if let Some(w) = found(&text, REPORT_WORDS) { + out.push(format!( + "The plan adds reporting (\"{}\") the ticket doesn't ask for. Leave it out.", + w.trim() + )); + } + } + let ticket_l = ticket.to_lowercase(); + let outside = found(&ticket_l, OUTSIDE_WORDS).or_else(|| found(&text, OUTSIDE_WORDS)); + if let Some(w) = outside { + let measured = section(design, MEASURE_FIRST) + .map(|s| found(&s.to_lowercase(), MEASURED_WORDS).is_some()) + .unwrap_or(false); + if !measured { + out.push(format!( + "The change rests on an outside system (\"{w}\") and `{MEASURE_FIRST}` plans no measurement. Probe it first (`probe_page` for a page: its test ids, frame size and scrolling, what is enabled; a read-only lookup for data) and plan the code and tests from what it shows." + )); + } + let criteria = super::stop_judge::acceptance(ticket); + if !criteria.is_empty() { + if let Some(w) = found(&text, TEST_TO_VENDOR) { + out.push(format!( + "The plan would change a test to match the outside system (\"{w}\") while the ticket's criteria say what the product must do. Plan the product change that meets the criterion first; change the test only with the measured reason it can't." + )); + } + } + } + out +} + +// ── What the ticket's words find, before the plan ────────────────────────── + +const STOP: &[&str] = &[ + "The", + "This", + "That", + "These", + "Those", + "When", + "Then", + "Given", + "And", + "But", + "For", + "With", + "From", + "Add", + "Make", + "Update", + "Change", + "Fix", + "Remove", + "Link", + "Please", + "Should", + "Acceptance", + "Criteria", + "Ticket", + "Summary", + "Description", + "Steps", + "Expected", + "Actual", +]; + +/// The search terms a ticket's own words give: code names in backticks, +/// identifiers, quoted names and capitalised names mid-sentence, at most +/// six, the most specific first. +pub fn ticket_terms(title: &str, body: &str) -> Vec { + let text = format!("{title}\n{body}"); + let mut ids: Vec = backticked(&text); + for w in text.split(|c: char| c.is_whitespace() || matches!(c, ',' | ';' | '(' | ')' | ':')) { + let w = w.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '_'); + let id = w.len() >= 5 + && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + && (w.contains('_') || w.chars().skip(1).any(|c| c.is_ascii_uppercase())) + && w.chars().any(|c| c.is_ascii_lowercase() || c == '_'); + if id && !ids.iter().any(|i| i == w) { + ids.push(w.to_string()); + } + } + let mut quoted = Vec::new(); + for q in ['"', '\u{201c}'] { + let close = if q == '"' { '"' } else { '\u{201d}' }; + let mut rest = text.as_str(); + while let Some(i) = rest.find(q) { + let after = &rest[i + q.len_utf8()..]; + let Some(j) = after.find(close) else { break }; + let s = after[..j].trim(); + if (3..=40).contains(&s.len()) && !s.contains('\n') && !quoted.iter().any(|x| x == s) { + quoted.push(s.to_string()); + } + rest = &after[j + close.len_utf8()..]; + } + } + let mut proper = Vec::new(); + for sentence in text.split(['.', '\n', '!', '?']) { + for (i, w) in sentence.split_whitespace().enumerate() { + let w = w.trim_matches(|c: char| !c.is_ascii_alphanumeric()); + if i > 0 + && w.len() >= 4 + && w.chars().next().is_some_and(|c| c.is_ascii_uppercase()) + && w.chars().skip(1).all(|c| c.is_ascii_lowercase()) + && !STOP.contains(&w) + && !proper.iter().any(|p| p == w) + { + proper.push(w.to_string()); + } + } + } + ids.into_iter() + .chain(quoted) + .chain(proper) + .take(6) + .collect() +} + +/// What the ticket's words find in the repository, as (term, hits), at +/// most eight hits a term. +pub async fn existing_for_ticket( + search: &dyn RepoSearch, + repo: &str, + title: &str, + body: &str, +) -> Vec<(String, Vec)> { + let mut out = Vec::new(); + for t in ticket_terms(title, body) { + if let Ok(hits) = search.search(repo, &t).await { + if !hits.is_empty() { + out.push((t, hits.into_iter().take(8).collect())); + } + } + } + out +} + +/// The top-level names the hits show (maps, helpers), for the plan gate. +pub fn existing_names(found: &[(String, Vec)]) -> Vec { + let mut out: Vec = Vec::new(); + for (_, hits) in found { + for h in hits { + let path = h.lines().next().unwrap_or(""); + for line in h.lines().skip(1) { + // A match may carry its line number: `12: CODE`. + let line = match line.split_once(": ") { + Some((n, l)) if n.trim().chars().all(|c| c.is_ascii_digit()) => l, + _ => line, + }; + if let Some(d) = minimal_change::top_level_def(line, path) { + if !out.contains(&d.name) { + out.push(d.name); + } + } + } + } + } + out +} + +/// The planner's block for what the ticket's words found: read these +/// first, and extend them. +pub fn existing_block(found: &[(String, Vec)]) -> String { + if found.is_empty() { + return String::new(); + } + let mut s = String::from( + "\n\n## Existing code the ticket's words find (read it before planning)\nCoderHelm searched the repository for the ticket's own names. Read each hit that the change touches in full (the whole map, function or query) and extend it; list it under `## Reuse`.\n", + ); + for (term, hits) in found { + s.push_str(&format!("\n### `{term}`\n")); + for h in hits { + s.push_str(&format!("- {}\n", common::truncate_str(h.trim(), 300))); + } + } + s +} + +#[cfg(test)] +mod tests { + use super::*; + + fn plan(design: &str, tasks: &str) -> PlanResult { + PlanResult { + proposal: String::new(), + design: design.into(), + tasks: tasks.into(), + spec: String::new(), + ..Default::default() + } + } + + const GOOD: &str = "## Reuse\n- `CAMP_MULTI_SPORT_OVERRIDES` and `get_camp_multi_sport_names` in dags/camps/sports.py\n\n## Must not change\nNo deletes: existing links stay. Logging stays as it is.\n\n## Measure first\nNone: the change stays inside this repository.\n\n## Smallest change\n4 entries in `CAMP_MULTI_SPORT_OVERRIDES`; in the 3 write branches insert links for `get_camp_multi_sport_names` with ON CONFLICT DO NOTHING.\n\n## Proof\nOne test: the 4 names get Swimming and their own sport, others only their own, nothing deleted.\n"; + + #[test] + fn the_small_plan_passes() { + let p = plan( + GOOD, + "- [ ] dags/camps/sports.py: add 4 entries\n- [ ] tests/test_sports.py: one test", + ); + assert!(plan_gaps( + &p, + "Link four camps to Swimming as well as their sport", + false, + &[] + ) + .is_empty()); + } + + #[test] + fn missing_sections_go_back() { + let p = plan("## Overview\nstuff", "- [ ] a.py: x"); + let g = plan_gaps(&p, "x", false, &[]); + assert_eq!(g.len(), 1); + for h in [ + REUSE, + MUST_NOT_CHANGE, + MEASURE_FIRST, + SMALLEST_CHANGE, + PROOF, + ] { + assert!(g[0].contains(h), "{h}"); + } + // A plan that stops plans nothing. + assert!(plan_gaps(&plan("", "NO_CHANGES_NEEDED: done"), "x", false, &[]).is_empty()); + } + + #[test] + fn a_parallel_map_and_a_replacing_sync_are_rejected() { + let design = GOOD.replace( + "## Smallest change\n", + "## Smallest change\nAdd `CAMP_SWIMMING_OVERRIDES` and `get_camp_swimming_names`; the sync upserts links and deletes stale ones. Change the INFO log to debug.\n", + ); + let g = plan_gaps( + &plan(&design, "- [ ] dags/camps/sports.py: x"), + "Link four camps to Swimming", + false, + &[], + ); + assert!( + g.iter().any(|l| l.contains( + "`CAMP_SWIMMING_OVERRIDES` next to the existing `CAMP_MULTI_SPORT_OVERRIDES`" + )), + "{g:?}" + ); + assert!(g.iter().any(|l| l.contains("delete or overwrite")), "{g:?}"); + assert!(g.iter().any(|l| l.contains("changes logging")), "{g:?}"); + } + + #[test] + fn an_outside_page_is_measured_and_the_product_changes_first() { + let design = GOOD.replace( + "None: the change stays inside this repository.", + "The vendor portal is loaded in an iframe; we assume it has no inner scroll.", + ) + "\nIf the vendor scrolls, update the test to match the vendor.\n"; + let ticket = "Embed the booking portal.\n\nAcceptance criteria:\n- No double scrollbars on desktop\n"; + let g = plan_gaps( + &plan(&design, "- [ ] e2e/portal.spec.ts: x"), + ticket, + false, + &[], + ); + assert!( + g.iter().any(|l| l.contains("plans no measurement")), + "{g:?}" + ); + assert!( + g.iter() + .any(|l| l.contains("product change that meets the criterion first")), + "{g:?}" + ); + let measured = design + .replace( + "we assume it has no inner scroll", + "probe_page measured the frame and its test ids", + ) + .replace( + "If the vendor scrolls, update the test to match the vendor.", + "", + ); + assert!(plan_gaps( + &plan(&measured, "- [ ] e2e/portal.spec.ts: x"), + ticket, + false, + &[] + ) + .is_empty()); + } + + #[test] + fn the_tickets_words_become_searches() { + let t = ticket_terms( + "Link full-day camps to Swimming", + "These camps should also show under Swimming: \"Aqua Day Camp\", \"Swim Week\". See `CAMP_MULTI_SPORT_OVERRIDES`.", + ); + assert_eq!(t[0], "CAMP_MULTI_SPORT_OVERRIDES"); + assert!(t.contains(&"Aqua Day Camp".to_string())); + assert!(t.contains(&"Swimming".to_string())); + let names = existing_names(&[( + "Swimming".into(), + vec!["dags/camps/sports.py\nCAMP_MULTI_SPORT_OVERRIDES = {".into()], + )]); + assert_eq!(names, vec!["CAMP_MULTI_SPORT_OVERRIDES"]); + assert!( + existing_block(&[("Swimming".into(), vec!["dags/a.py".into()])]).contains("## Reuse") + ); + } +} diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index cf6a9dd47..8432275a8 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -228,6 +228,72 @@ async fn probe_gaps( super::review_rules::probe_findings(&common::e2e::probe::unprobed(&files, &probes, &own)) } +/// The review's findings for a change wider than its ticket +/// (`minimal_change`) and for test assertions changed to match another +/// company's page against an acceptance criterion. `ticket` is the +/// ticket's words the review has (its context and the PR body). +async fn smallest_change_gaps( + state: &WorkerState, + github: &GitHubClient, + (team_id, owner, repo): (&str, &str, &str), + head_sha: &str, + compare: &serde_json::Value, + tree: &[String], + ticket: &str, +) -> Vec { + let files: Vec<(String, String, String)> = compare["files"] + .as_array() + .into_iter() + .flatten() + .take(80) + .map(|f| { + ( + f["filename"].as_str().unwrap_or("").to_string(), + f["status"].as_str().unwrap_or("").to_string(), + f["patch"].as_str().unwrap_or("").to_string(), + ) + }) + .filter(|(p, _, _)| !p.is_empty()) + .collect(); + let mut base = Vec::new(); + if let Some(sha) = compare["merge_base_commit"]["sha"].as_str() { + for (p, _, _) in files + .iter() + .filter(|(p, s, _)| s == "modified" && !super::habits::is_test_path(p)) + .take(12) + { + if let Ok(text) = github.read_file(owner, repo, p, sha).await { + base.push((p.clone(), text)); + } + } + } + let has_probe = tree.iter().any(|p| common::e2e::probe::is_record(p)); + let mut out = super::review_rules::wider_findings(&super::minimal_change::check( + &files, &base, ticket, has_probe, + )); + let criteria = super::stop_judge::acceptance(ticket); + if !criteria.is_empty() { + let own = super::web_check::team_domains(state, team_id).await; + let mut flips = Vec::new(); + for (path, _, patch) in files.iter().filter(|(p, s, patch)| { + s != "removed" && super::habits::is_test_path(p) && patch.contains("expect(") + }) { + let full = github + .read_file(owner, repo, path, head_sha) + .await + .unwrap_or_else(|_| patch.clone()); + let outside = !common::e2e::probe::outside_origins(&full, &own).is_empty() + || full.contains("frameLocator(") + || full.contains("contentFrame("); + flips.extend(super::minimal_change::vendor_flips( + path, patch, outside, &criteria, + )); + } + out.extend(super::review_rules::vendor_flip_findings(&flips)); + } + out +} + /// True when the repo turned on "Require tests" (and review isn't off/killed). /// The same switch makes the reviewer block untested behavior changes and makes /// CoderHelm's own coding passes write those tests. @@ -3447,6 +3513,23 @@ async fn run_once( findings.retain(|x| x.title != f.title || x.file != f.file); findings.push(f); } + // The change does what its ticket asks and no more, and a test is + // never bent to another company's page against a criterion. + for f in smallest_change_gaps( + state, + &github, + (&msg.team_id, &msg.repo_owner, &msg.repo_name), + &head_sha, + &compare, + &tree, + &format!("{ticket_context}\n{pr_body}"), + ) + .await + { + info!(pr = msg.pr_number, file = %f.file, title = %f.title, "Wider than the ticket: must fix"); + findings.retain(|x| x.title != f.title || x.file != f.file); + findings.push(f); + } } review_agent::enforce_source_data_override(&mut findings); // A request to test something by hand is a note, never a block. diff --git a/services/worker/src/passes/review_rules.rs b/services/worker/src/passes/review_rules.rs index 292455cba..4248bcbd0 100644 --- a/services/worker/src/passes/review_rules.rs +++ b/services/worker/src/passes/review_rules.rs @@ -91,6 +91,57 @@ pub fn probe_findings(gaps: &[common::e2e::probe::Unprobed]) -> Vec { .collect() } +/// The rule every change is held to: it does what its ticket asks and no +/// more (`minimal_change`). +pub const SMALLEST_RULE: &str = "the change does what the ticket asks and no more: no deletes or overwrites where the code only added, no test payload nobody observed, no test changed to match another company's page against an acceptance criterion"; + +/// The review's findings for a change wider than its ticket. Deleting or +/// overwriting where the base only added, and a payload nobody observed, +/// block by rule; the rest block as verified defects the fix round makes +/// smaller. +pub fn wider_findings(found: &[super::minimal_change::Widening]) -> Vec { + use super::minimal_change::Kind; + found + .iter() + .map(|w| Finding { + file: w.path.clone(), + severity: "blocking".into(), + category: match w.kind { + Kind::TestSize | Kind::InventedPayload => "tests", + Kind::Replacing => "data", + _ => "scope", + } + .into(), + title: w.point().to_string(), + body: w.instruction(), + evidence: Some("verified-defect".into()), + caused_by_diff: Some(true), + required: (!w.excusable()).then(|| SMALLEST_RULE.to_string()), + ..Default::default() + }) + .collect() +} + +/// The review's findings for test assertions changed to match another +/// company's page while an acceptance criterion says otherwise: the +/// product changes first. +pub fn vendor_flip_findings(flips: &[super::minimal_change::VendorFlip]) -> Vec { + flips + .iter() + .map(|f| Finding { + file: f.path.clone(), + severity: "blocking".into(), + category: "tests".into(), + title: "A test changed to the outside page's behaviour against a criterion".into(), + body: f.body(), + evidence: Some("verified-defect".into()), + caused_by_diff: Some(true), + required: Some(SMALLEST_RULE.to_string()), + ..Default::default() + }) + .collect() +} + /// Why a required rule broken blocks. pub const REQUIRED_WHY: &str = "a rule this repository requires is broken"; /// Why a failing check blocks. @@ -625,6 +676,9 @@ pub fn mandatory_label(f: &Finding) -> Option { REQUIRED_WHY if f.required.as_deref() == Some(E2E_RULE) => { "Blocking (required: end-to-end test)".to_string() } + REQUIRED_WHY if f.required.as_deref() == Some(SMALLEST_RULE) => { + "Blocking (required: the ticket's scope)".to_string() + } REQUIRED_WHY => "Blocking (required rule)".to_string(), FAILING_CHECK_WHY => "Blocking (failing check)".to_string(), MAIN_PATH_WHY if f.evidence() == super::review_agent::Evidence::VerifiedDefect => { @@ -652,6 +706,38 @@ pub fn settles(thread_body: &str, status: &str) -> bool { mod e2e_rule_tests { use super::*; + #[test] + fn wider_than_the_ticket_and_vendor_flips_are_findings() { + use crate::passes::minimal_change::{Kind, VendorFlip, Widening}; + let f = wider_findings(&[ + Widening { + kind: Kind::Replacing, + path: "dags/sync.py".into(), + what: "`DELETE FROM`".into(), + }, + Widening { + kind: Kind::Parallel, + path: "dags/camps.py".into(), + what: "`A_MAP` next to the existing `B_MAP`".into(), + }, + ]); + assert_eq!(mandatory(&f[0]), Some(REQUIRED_WHY)); + assert_eq!( + mandatory_label(&f[0]).as_deref(), + Some("Blocking (required: the ticket's scope)") + ); + assert!(f[1].required.is_none()); + assert_eq!(f[1].severity, "blocking"); + let v = vendor_flip_findings(&[VendorFlip { + path: "e2e/portal.spec.ts".into(), + removed: "expect(x).toBe(false)".into(), + added: "expect(x).toBe(true)".into(), + criterion: "No double scrollbars on desktop".into(), + }]); + assert_eq!(mandatory(&v[0]), Some(REQUIRED_WHY)); + assert!(v[0].body.contains("No double scrollbars")); + } + #[test] fn unobserved_outside_selectors_are_a_must_fix() { let code = From ffa9b8ddbbe1afe5c4b6116774f3727354d27589 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 16 Nov 2026 20:33:19 -0500 Subject: [PATCH 4/4] Reused helpers state what they do to stored rows; the test environment is installed once per run The plan check reads each helper named under Reuse and calls it insert only or replacing (a DELETE, ON CONFLICT DO UPDATE, a delete then an insert, a relation .set). A replacing helper the plan doesn't say replaces, or one reused on a path that only inserts today when the ticket asks for no replacement, sends the plan back. The first round reads how the repository's CI installs and runs its tests, records it on the run, and every later sandbox build of every round and the proof step restores the cached install instead of installing again. The coder is told the environment is ready and how the tests run. --- docs/coder-loop.md | 20 +- docs/incidents.md | 2 +- services/common/src/lib.rs | 1 + services/common/src/test_env.rs | 575 ++++++++++++++++++ services/worker/src/clients/sandbox.rs | 43 +- services/worker/src/passes/implement.rs | 29 +- .../passes/incidents/bx_smallest_change.rs | 57 ++ services/worker/src/passes/minimal_change.rs | 128 ++++ services/worker/src/passes/mod.rs | 1 + services/worker/src/passes/plan.rs | 28 +- services/worker/src/passes/plan_shape.rs | 156 ++++- services/worker/src/passes/preview.rs | 2 +- services/worker/src/passes/test_bug.rs | 16 +- services/worker/src/passes/test_setup.rs | 107 ++++ 14 files changed, 1154 insertions(+), 11 deletions(-) create mode 100644 services/common/src/test_env.rs create mode 100644 services/worker/src/passes/test_setup.rs diff --git a/docs/coder-loop.md b/docs/coder-loop.md index db9a47af7..ff5270cc0 100644 --- a/docs/coder-loop.md +++ b/docs/coder-loop.md @@ -60,6 +60,14 @@ The causes were in the loop, not only in prompt wording: - would change a test to match an outside system while the ticket's acceptance criteria say what the product must do. + The Reuse section also says, for each helper that writes data, whether it + only inserts or replaces and deletes. The worker reads each reused helper's + body (`minimal_change::write_semantics`: a `DELETE`, an `ON CONFLICT DO + UPDATE`, a delete-then-insert, a relation `.set(`). A plan that reuses a + replacing helper on a path that only inserts today is sent back unless the + ticket asks to replace. The camps run's plan named the right map, then + reused the link helper that deletes every link it isn't given. + Whatever is still open after the one send-back stays on the decision. 4. **Implement.** In the coder's tool loop (`explore_guard`): @@ -88,7 +96,17 @@ The causes were in the loop, not only in prompt wording: behaviour against an acceptance criterion are required findings (`review_rules::SMALLEST_RULE`). -6. **Prove.** Each new or changed test runs in the sandbox with and without the +6. **Prove.** + The first round works out how the repository's CI installs and + runs its tests (`common::test_env`: the test job's working folder, Python + and Node versions, install steps and test steps). It records this on the + run (`test_setup`). Every sandbox build of every later round, and the proof + step's runs, restore that install from a cache named by the install steps + and the manifests' blob ids. Only the first build installs and saves it. + The coder is told the environment is ready and how the tests run. One run + reinstalled its dependencies eighteen times, about 25 minutes of builds. + + Each new or changed test runs in the sandbox with and without the change (`habits_check`). A test the runner finds nothing in goes back to the coder, and the coder quotes the run's output in its Evidence. End-to-end code against another company's page uses only what a probe observed (#734). diff --git a/docs/incidents.md b/docs/incidents.md index bd5617ce1..cc795ced0 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -98,7 +98,7 @@ pipeline still calls it there. | br. `br_description_writer_upgrade` | After the description writer was upgraded (a final review in the one save, the repository's template as the structure), a pull request opened the day before kept its old text: six checks "Not run: still running when this was written", the file to read first and the way back said twice, filler and a raw page id. Its head had not moved and its checked text was unchanged, so its stamp said current and nothing rebuilt it. | The stamp names the writer version (`description::WRITER`, raised with every change to what a description says or how it is laid out); a description built by another writer, or before the version, is not current. The pull request watch's sweep catches up open pull requests CoderHelm opened, whatever the age of their run: a few per team each sweep (`pr_watch::CATCH_UP_PER_TEAM`), inside its GitHub budget, each rebuilt once and marked on its run. A description still wholly CoderHelm's is built again from the facts of the head alone: nothing of the old text is kept, not even in a fold, except a line that closes an issue. A description with no CoderHelm stamp, or whose checked text a person changed, is left as it is. | | bs. `bs_cut_plan_revision` | A ticket with a long history was planned, and the plan check sent the plan back with two open items. The revision reached the output limit partway through its last block. The planner was told the coder's note ("make a change in small edit_file calls"), wrote only its decision block again, and the worker read only that last turn: no tasks, no design. The run failed with "empty or malformed plan ... retry the run" and the first plan was thrown away. | A planner's cut answer is continued where it stopped and read together with what came before the cut, file by file (`plan_sections`). A cut turn's note fits its loop: the coder's edit note only where there are edit tools, the planner's "continue the document" note, a shorter answer for everyone else. A revision that comes back empty, cut off or malformed never replaces a valid file, and a send-back asks for only the files that change. Files still missing are asked for alone, twice at most, the second with a larger output budget. A plan still not usable is planned again in a fresh step, then reported as CoderHelm's own failure, saying what it lacked. No run tells a person to retry it. | | bt. `bt_proof_answer_closes` | A security update's own review asked for proof of the build and unit tests on the head. The fix rounds changed no code: the second ran every check on the head, all passing, and one runtime check it started was cut short by the step's time. The ledger counted that as a block, the round pushed nothing so no review read the head again, and the draft was held for a person ("Fix them on the branch, or remove a finding") while the merge standing said no person was needed. | A round that pushed nothing is read by a review of the same head, with the round's account in the reviewer's context, and a finding answered with proof closes there. A command, check or codegen a step is too short to start is owed: the pass continues in a fresh step that runs it first, and a round cut short by time is never a block. Nothing on CoderHelm's side holds a draft for a person: what is left after every approach is listed as CoderHelm's note and the pull request goes ready, with CoderHelm's verdict kept so nothing merges over it. A stuck run is sent back to its review on the next look of the ready sweep or the pull request's watch. | -| bx. `bx_smallest_change` | A ticket asked to link four camps to a second sport. The plan added a second map and helpers beside the existing overrides map and made an insert-only link sync replace and delete links; the build added warnings, three counters and a log level change in shared code (the data rules asked for reporting on any skip) and a 432-line test with fake hooks and an invented payload. A web ticket's vendor end-to-end tests were rewritten three times on guesses, and a criterion ("no double scrollbars") was met by changing the test to expect the vendor's behaviour instead of changing the page. | The ticket's own words are searched before planning and the hits go to the planner. The plan writes Reuse, Must not change, Measure first, Smallest change and Proof, and is sent back when it proposes a structure parallel to an existing one, deletes or overwrites the ticket doesn't ask for, logging or reporting changes, outside-page behaviour with nothing measured, or a test change where a criterion says the product must change (`plan_shape`). The coder's first write follows a search and names what it reuses; an edit adding a twin of an existing map or helper is refused without a reason (`explore_guard`). After the build a diff wider than its ticket goes back to be made smaller (`minimal_change` in the habits check); deletes where the base only added, and a payload no probe observed, have no excuse but the ticket. Reporting on a skip is asked for only when the ticket asks. The reviewer finds the same, and a test bent to an outside page against a criterion is a required finding. | +| bx. `bx_smallest_change` | A ticket asked to link four camps to a second sport. The plan added a second map and helpers beside the existing overrides map and made an insert-only link sync replace and delete links; the build added warnings, three counters and a log level change in shared code (the data rules asked for reporting on any skip) and a 432-line test with fake hooks and an invented payload. A web ticket's vendor end-to-end tests were rewritten three times on guesses, and a criterion ("no double scrollbars") was met by changing the test to expect the vendor's behaviour instead of changing the page. | The ticket's own words are searched before planning and the hits go to the planner. The plan writes Reuse, Must not change, Measure first, Smallest change and Proof, and is sent back when it proposes a structure parallel to an existing one, deletes or overwrites the ticket doesn't ask for, logging or reporting changes, outside-page behaviour with nothing measured, or a test change where a criterion says the product must change (`plan_shape`). The coder's first write follows a search and names what it reuses; an edit adding a twin of an existing map or helper is refused without a reason (`explore_guard`). After the build a diff wider than its ticket goes back to be made smaller (`minimal_change` in the habits check); deletes where the base only added, and a payload no probe observed, have no excuse but the ticket. Reporting on a skip is asked for only when the ticket asks. The reviewer finds the same, and a test bent to an outside page against a criterion is a required finding. The plan says what each reused helper does to stored rows, read from its body, and reusing a replacing helper on a path that only inserts is sent back unless the ticket asks to replace. The test environment CI uses is found once per run, and every later sandbox build restores its cached install instead of installing again. | ## Adding a case diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 1e7625f4f..6e1e07406 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -282,6 +282,7 @@ pub mod stop_judge; pub mod stop_rules; /// A team's run and PR-reviewed counts, each added exactly once. pub mod team_counts; +pub mod test_env; pub mod ticket_comments; /// A ticket's comments as CoderHelm read them, and whether its work is done. pub mod ticket_state; diff --git a/services/common/src/test_env.rs b/services/common/src/test_env.rs new file mode 100644 index 000000000..59603fd5f --- /dev/null +++ b/services/common/src/test_env.rs @@ -0,0 +1,575 @@ +//! How a repository's CI installs and runs its tests, found once and reused +//! by every sandbox command of the run. +//! +//! A data-pipeline run reinstalled its test dependencies eighteen times in +//! one run, about 25 minutes of sandbox builds. Each round started over: it +//! ran the test file bare, read the CI workflow, then tried `pip install` +//! lines until one worked. Each sandbox command is a fresh build, so nothing +//! carried over. +//! +//! Now: +//! +//! - [`from_workflows`] reads the CI job that runs the tests: its working +//! directory, Python and Node versions, the install steps before its first +//! test step, the test steps, and the plain environment values it sets. +//! - [`TestEnv::fingerprint`] names that install, from its steps and the +//! dependency manifests' blob ids. A changed requirements or lock file is +//! a new fingerprint and a fresh install. +//! - [`TestEnv::wrap`] puts a command inside the environment. With a cached +//! environment (`ENV_CACHE_GET_URL`) it is restored, and a Python install is +//! not run again; without one the install runs once and the result is +//! saved (`ENV_CACHE_PUT_URL`) for every later command, round and proof +//! step of the run. Python installs go into one virtual environment and +//! Node package managers keep their download store there, so the archive +//! is one folder. +//! - [`TestEnv::coder_note`] tells the coder the environment is ready, so it +//! runs the tests directly instead of reinstalling. + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +/// Where the environment lives in the sandbox; a test may move it. +pub const ENV_ROOT: &str = "/tmp/coderhelm-env"; + +/// The printed lines that say what the wrapper did. +pub const RESTORED: &str = "===CODERHELM_ENV_RESTORED==="; +pub const INSTALLED: &str = "===CODERHELM_ENV_INSTALLED==="; +pub const SAVED: &str = "===CODERHELM_ENV_SAVED==="; + +/// The language whose packages the install fills. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + Python, + Node, + #[default] + Other, +} + +/// How the repository's CI installs and runs its tests. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct TestEnv { + /// The workflow and job it came from. + pub source: String, + /// The folder the steps run in; "" for the repository root. + pub dir: String, + pub kind: Kind, + pub python: String, + pub node: String, + /// Plain `NAME=value` settings of the job (never an expression). + pub env: Vec<(String, String)>, + pub install: Vec, + pub test: Vec, + /// Files whose content decides the install (requirements, locks). + pub manifests: Vec, +} + +const INSTALL_WORDS: &[&str] = &[ + "pip install", + "pip3 install", + "uv pip install", + "uv sync", + "poetry install", + "pipenv install", + "npm ci", + "npm install", + "pnpm install", + "yarn install", + "bun install", + "corepack enable", +]; + +const LOCKS: &[&str] = &[ + "requirements.txt", + "requirement.txt", + "requirements-dev.txt", + "constraints.txt", + "pyproject.toml", + "poetry.lock", + "uv.lock", + "Pipfile.lock", + "package.json", + "package-lock.json", + "pnpm-lock.yaml", + "yarn.lock", + "bun.lockb", +]; + +fn s(v: Option<&serde_yaml::Value>) -> String { + match v { + Some(serde_yaml::Value::String(x)) => x.trim().to_string(), + Some(serde_yaml::Value::Number(n)) => n.to_string(), + _ => String::new(), + } +} + +fn plain_env(v: Option<&serde_yaml::Value>) -> Vec<(String, String)> { + let mut out = Vec::new(); + if let Some(m) = v.and_then(|x| x.as_mapping()) { + for (k, val) in m { + let (k, val) = (s(Some(k)), s(Some(val))); + let safe_key = + !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); + let low = k.to_ascii_lowercase(); + let secretish = ["token", "secret", "password", "key", "auth"] + .iter() + .any(|w| low.contains(w)); + if safe_key && !secretish && !val.contains("${{") && !val.contains('\n') { + out.push((k, val)); + } + } + } + out +} + +fn lines_of(run: &str) -> Vec { + run.lines() + .map(str::trim) + .filter(|l| !l.is_empty() && !l.starts_with('#')) + .map(str::to_string) + .collect() +} + +fn is_install(line: &str) -> bool { + let l = line.to_ascii_lowercase(); + INSTALL_WORDS.iter().any(|w| l.contains(w)) +} + +/// Files an install line reads (`-r`, `-c`, `--constraint`, `--requirement`). +fn named_files(line: &str) -> Vec { + let t: Vec<&str> = line.split_whitespace().collect(); + let mut out = Vec::new(); + for (i, w) in t.iter().enumerate() { + let next = t.get(i + 1).map(|x| x.trim_matches(['"', '\''])); + match *w { + "-r" | "-c" | "--constraint" | "--requirement" => { + if let Some(f) = next.filter(|f| !f.contains("://") && !f.contains('$')) { + out.push(f.to_string()); + } + } + _ => {} + } + } + out +} + +fn join(dir: &str, f: &str) -> String { + let f = f.trim_start_matches("./"); + if dir.is_empty() || f.starts_with('/') { + f.to_string() + } else { + format!("{}/{f}", dir.trim_end_matches('/')) + } +} + +/// The repository's test environment, from its workflow files +/// (`(path, text)`): the first job with a test step, its setup before that +/// step, and its test steps. `None` when no job runs tests. +pub fn from_workflows(workflows: &[(String, String)], tree: &[String]) -> Option { + for (path, text) in workflows { + let Ok(doc) = serde_yaml::from_str::(text) else { + continue; + }; + let Some(jobs) = doc.get("jobs").and_then(|j| j.as_mapping()) else { + continue; + }; + for (name, job) in jobs { + let Some(steps) = job.get("steps").and_then(|x| x.as_sequence()) else { + continue; + }; + let mut env = TestEnv { + source: format!("{path} ({})", s(Some(name))), + dir: s(job + .get("defaults") + .and_then(|d| d.get("run")) + .and_then(|r| r.get("working-directory"))) + .trim_start_matches("./") + .trim_end_matches('/') + .to_string(), + env: plain_env(doc.get("env")), + ..Default::default() + }; + env.env.extend(plain_env(job.get("env"))); + let mut seen_test = false; + for step in steps { + let uses = s(step.get("uses")).to_ascii_lowercase(); + if uses.starts_with("actions/setup-python") { + env.python = s(step.get("with").and_then(|w| w.get("python-version"))); + } + if uses.starts_with("actions/setup-node") { + env.node = s(step.get("with").and_then(|w| w.get("node-version"))); + } + let run = s(step.get("run")); + if run.is_empty() || run.contains("${{") { + continue; + } + let dir = s(step.get("working-directory")) + .trim_start_matches("./") + .to_string(); + for line in lines_of(&run) { + let line = if dir.is_empty() { + line + } else { + format!("(cd {dir} && {line})") + }; + if crate::ci_cover::is_check_command(&line) && !is_install(&line) { + seen_test = true; + env.test.push(line); + env.env.extend(plain_env(step.get("env"))); + } else if is_install(&line) && !seen_test { + env.install.push(line); + } + } + } + if env.test.is_empty() { + continue; + } + let all = format!("{} {}", env.install.join(" "), env.test.join(" ")).to_lowercase(); + env.kind = if !env.python.is_empty() + || ["pip", "pytest", "python", "poetry", "uv "] + .iter() + .any(|w| all.contains(w)) + { + Kind::Python + } else if !env.node.is_empty() + || ["npm", "pnpm", "yarn", "npx", "vitest", "jest"] + .iter() + .any(|w| all.contains(w)) + { + Kind::Node + } else { + Kind::Other + }; + let mut manifests: Vec = env + .install + .iter() + .flat_map(|l| named_files(l)) + .map(|f| join(&env.dir, &f)) + .collect(); + for l in LOCKS { + let p = join(&env.dir, l); + if tree.iter().any(|t| t == &p) { + manifests.push(p); + } + } + manifests.sort(); + manifests.dedup(); + env.manifests = manifests; + env.env.sort(); + env.env.dedup(); + return Some(env); + } + } + None +} + +fn quote(s: &str) -> String { + format!("'{}'", s.replace('\'', "'\\''")) +} + +impl TestEnv { + /// The install's name: its steps, versions and the manifests' blob ids + /// (`shas`: `(path, blob sha)` from the tree at the head). + pub fn fingerprint(&self, shas: &[(String, String)]) -> String { + let mut h = Sha256::new(); + h.update(self.dir.as_bytes()); + h.update(self.python.as_bytes()); + h.update(self.node.as_bytes()); + for l in &self.install { + h.update(l.as_bytes()); + h.update(b"\n"); + } + for m in &self.manifests { + let sha = shas + .iter() + .find(|(p, _)| p == m) + .map(|(_, s)| s.as_str()) + .unwrap_or("-"); + h.update(format!("{m}={sha}\n").as_bytes()); + } + hex::encode(&h.finalize()[..12]) + } + + /// Whether a restored environment is complete: a Python install lives + /// whole in the virtual environment; a Node install keeps only the + /// package store there and runs again (fast, from the store). + pub fn restore_is_complete(&self) -> bool { + self.kind == Kind::Python + } + + fn activate(&self) -> String { + let mut out = vec![format!( + "export E=\"${{CODERHELM_ENV:-{ENV_ROOT}}}\"; mkdir -p \"$E\"" + )]; + for (k, v) in &self.env { + out.push(format!("export {k}={}", quote(v))); + } + match self.kind { + Kind::Python => { + if !self.python.is_empty() { + out.push(format!( + "(command -v pyenv >/dev/null 2>&1 && pyenv global {} >/dev/null 2>&1) || true", + quote(&self.python) + )); + } + out.push( + "[ -x \"$E/venv/bin/python\" ] || python3 -m venv \"$E/venv\"; . \"$E/venv/bin/activate\"" + .to_string(), + ); + } + Kind::Node => { + out.push( + "export npm_config_cache=\"$E/npm\" npm_config_store_dir=\"$E/pnpm-store\" YARN_CACHE_FOLDER=\"$E/yarn\"" + .to_string(), + ); + if !self.node.is_empty() { + out.push(format!( + "n {} >/dev/null 2>&1 || true; hash -r", + quote(&self.node) + )); + } + } + Kind::Other => {} + } + out.join("\n") + } + + /// `command` run inside the environment. The script restores the cached + /// environment when `ENV_CACHE_GET_URL` is set and fetches, installs + /// otherwise (or after a Node restore), saves a fresh install when + /// `ENV_CACHE_PUT_URL` is set, then runs `command` and exits with its + /// code. + pub fn wrap(&self, command: &str) -> String { + self.wrap_with(command, self.restore_is_complete()) + } + + /// [`Self::wrap`], saying whether a restored environment is complete. + pub fn wrap_with(&self, command: &str, complete: bool) -> String { + let install = if self.install.is_empty() { + "true".to_string() + } else { + self.install.join(" && ") + }; + let cd = if self.dir.is_empty() { + String::new() + } else { + format!("cd {} || exit 1\n", quote(&self.dir)) + }; + let complete = if complete { "1" } else { "" }; + format!( + r#"export E="${{CODERHELM_ENV:-{ENV_ROOT}}}"; mkdir -p "$E" +ROOT="$PWD" +RESTORED="" +if [ -n "$ENV_CACHE_GET_URL" ] && curl -fsS --retry 2 --noproxy "*" -o /tmp/coderhelm-env.tgz "$ENV_CACHE_GET_URL" 2>/dev/null && tar xzf /tmp/coderhelm-env.tgz -C "$E"; then + RESTORED=1; echo "{RESTORED}" +fi +{activate} +{cd}if [ -z "$RESTORED" ] || [ -z "{complete}" ]; then + ( {install} ) >/tmp/coderhelm-install.log 2>&1; ICODE=$?; tail -5 /tmp/coderhelm-install.log + if [ $ICODE -eq 0 ] && [ -z "$RESTORED" ]; then + echo "{INSTALLED}" + if [ -n "$ENV_CACHE_PUT_URL" ] && tar czf /tmp/coderhelm-env-out.tgz -C "$E" . && curl -fsS --retry 2 --noproxy "*" -T /tmp/coderhelm-env-out.tgz "$ENV_CACHE_PUT_URL"; then echo "{SAVED}"; fi + fi +fi +cd "$ROOT" +bash -c {cmd}"#, + activate = self.activate(), + cmd = quote(command), + ) + } + + /// What the coder is told: the environment is ready in every command, + /// and how the tests run. + pub fn coder_note(&self) -> String { + format!( + "\n\n## The test environment (from CI: {})\nEvery sandbox command you run starts with this repository's test environment installed (CoderHelm installs it once per run and reuses it in every round). Don't reinstall dependencies: run the tests directly{}:\n{}\n", + self.source, + if self.dir.is_empty() { + String::new() + } else { + format!(" from `{}`", self.dir) + }, + self.test + .iter() + .map(|t| format!("- `{t}`")) + .collect::>() + .join("\n") + ) + } + + /// One line for the run's notes. + pub fn summary(&self) -> String { + format!( + "Test environment from {}: install `{}`; tests `{}`", + self.source, + if self.install.is_empty() { + "nothing".to_string() + } else { + self.install.join(" && ") + }, + self.test.join(" && ") + ) + } +} + +/// The S3 key of a cached environment: one per team, repository and +/// fingerprint, so later rounds and runs of the same install reuse it. +pub fn cache_key(team: &str, repo: &str, fingerprint: &str) -> String { + let safe = |x: &str| -> String { + x.chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '-' { + c + } else { + '_' + } + }) + .collect() + }; + format!("env-cache/{}/{}/{fingerprint}.tgz", safe(team), safe(repo)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const PY: &str = r#" +name: Tests +on: [pull_request] +env: + PYTHONHASHSEED: "0" + GH_TOKEN: ${{ secrets.X }} +jobs: + tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - run: | + pip install 'apache-airflow[postgres]==2.10.3' -c dags/constraints-3.11.txt + pip install -r requirement.txt + - run: for t in tests/test_*.py; do python "$t" || exit 1; done + name: Run tests + - run: python -m pytest tests +"#; + + #[test] + fn the_test_job_is_read_from_ci() { + let tree = vec![ + "requirement.txt".to_string(), + "dags/constraints-3.11.txt".to_string(), + ]; + let e = + from_workflows(&[(".github/workflows/tests.yml".into(), PY.into())], &tree).unwrap(); + assert_eq!(e.kind, Kind::Python); + assert_eq!(e.python, "3.11"); + assert_eq!(e.install.len(), 2); + assert!(e.test.iter().any(|t| t.contains("pytest"))); + assert_eq!(e.env, vec![("PYTHONHASHSEED".to_string(), "0".to_string())]); + assert_eq!( + e.manifests, + vec!["dags/constraints-3.11.txt", "requirement.txt"] + ); + // A changed requirements file is a new install. + let a = e.fingerprint(&[("requirement.txt".into(), "aaa".into())]); + let b = e.fingerprint(&[("requirement.txt".into(), "bbb".into())]); + assert_ne!(a, b); + assert_eq!( + a, + e.fingerprint(&[("requirement.txt".into(), "aaa".into())]) + ); + assert!(e.coder_note().contains("Don't reinstall")); + assert!(cache_key("TEAM#x", "o/r", &a).starts_with("env-cache/TEAM_x/o_r/")); + } + + #[test] + fn a_node_job_with_a_working_directory() { + let wf = "jobs:\n web:\n defaults:\n run:\n working-directory: ./apps/web\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: 20\n - run: corepack enable && pnpm install --frozen-lockfile\n - run: pnpm vitest run\n"; + let e = from_workflows( + &[("ci.yml".into(), wf.into())], + &["apps/web/pnpm-lock.yaml".to_string()], + ) + .unwrap(); + assert_eq!(e.kind, Kind::Node); + assert_eq!(e.dir, "apps/web"); + assert_eq!(e.node, "20"); + assert_eq!(e.manifests, vec!["apps/web/pnpm-lock.yaml"]); + assert!(!e.restore_is_complete()); + assert!(e.wrap("pnpm vitest run").contains("cd 'apps/web'")); + // No job with a test step: nothing. + assert!(from_workflows( + &[( + "d.yml".into(), + "jobs:\n d:\n steps:\n - run: echo hi\n".into() + )], + &[] + ) + .is_none()); + } + + /// The second round restores the first round's install instead of + /// installing again. Runs the real script with bash, tar and curl (file + /// URLs stand in for the presigned ones). + #[test] + fn a_second_round_restores_instead_of_reinstalling() { + for tool in ["bash", "tar", "curl"] { + if std::process::Command::new(tool) + .arg("--version") + .output() + .is_err() + { + return; + } + } + let dir = std::env::temp_dir().join(format!("coderhelm-env-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("repo")).unwrap(); + let log = dir.join("installs.log"); + let cache = dir.join("cache.tgz"); + let env = TestEnv { + source: "ci.yml (tests)".into(), + kind: Kind::Other, + install: vec![format!( + "echo install >> {} && echo ready > \"$E/marker\"", + log.display() + )], + test: vec!["true".into()], + ..Default::default() + }; + // A complete restore (as for Python), without needing Python here. + let script = env.wrap_with("cat \"$E/marker\"", true); + let run = |get: Option<&std::path::Path>, put: Option<&std::path::Path>, env_root: &str| { + let mut c = std::process::Command::new("bash"); + c.arg("-c") + .arg(&script) + .current_dir(dir.join("repo")) + .env("CODERHELM_ENV", dir.join(env_root)); + match get { + Some(p) => c.env("ENV_CACHE_GET_URL", format!("file://{}", p.display())), + None => c.env_remove("ENV_CACHE_GET_URL"), + }; + match put { + Some(p) => c.env("ENV_CACHE_PUT_URL", format!("file://{}", p.display())), + None => c.env_remove("ENV_CACHE_PUT_URL"), + }; + let o = c.output().unwrap(); + String::from_utf8_lossy(&o.stdout).to_string() + }; + // Round one: nothing cached, so it installs and saves. + let first = run(None, Some(&cache), "env1"); + assert!(first.contains(INSTALLED), "{first}"); + assert!(first.contains(SAVED), "{first}"); + assert!(first.contains("ready"), "{first}"); + // Round two, a fresh build: restored, not installed again. + let second = run(Some(&cache), None, "env2"); + assert!(second.contains(RESTORED), "{second}"); + assert!(!second.contains(INSTALLED), "{second}"); + assert!(second.contains("ready"), "{second}"); + let installs = std::fs::read_to_string(&log).unwrap(); + assert_eq!(installs.lines().count(), 1, "installed {installs}"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/services/worker/src/clients/sandbox.rs b/services/worker/src/clients/sandbox.rs index 1f31e44f7..b88543577 100644 --- a/services/worker/src/clients/sandbox.rs +++ b/services/worker/src/clients/sandbox.rs @@ -471,6 +471,10 @@ pub struct SandboxClient<'a> { generator_hosts: Vec, /// The commands that run the repository's generators. generator_cmds: Vec, + /// The run's test environment and its install's cache key + /// (`common::test_env`): every check build runs inside it, restoring + /// the cached install or saving the first one. + test_env: Option<(common::test_env::TestEnv, String)>, } /// The allowlist one build gets: the team's list (None: the network is @@ -572,9 +576,44 @@ impl<'a> SandboxClient<'a> { egress: None, generator_hosts: Vec::new(), generator_cmds: Vec::new(), + test_env: None, } } + /// Runs every check build inside the run's test environment + /// (`passes::test_setup::for_run`), so no round installs it again. + pub fn with_test_env(mut self, env: Option<(common::test_env::TestEnv, String)>) -> Self { + self.test_env = env; + self + } + + /// The command a check build runs and the variable that restores or + /// saves the cached install: restore when it exists, save when not. + async fn in_test_env( + &self, + checks_cmd: &str, + ) -> Result<(String, Option), Box> + { + let Some((env, key)) = &self.test_env else { + return Ok((checks_cmd.to_string(), None)); + }; + let cached = self + .s3 + .head_object() + .bucket(self.bucket) + .key(key) + .send() + .await + .is_ok(); + let var = if cached { + env_var("ENV_CACHE_GET_URL", &self.presigned_get(key).await?)? + } else { + env_var("ENV_CACHE_PUT_URL", &self.presigned_put(key).await?)? + }; + info!(key = %key, cached, "sandbox: the run's test environment"); + Ok((env.wrap(checks_cmd), Some(var))) + } + /// Is the sandbox configured (both bucket and project set)? pub fn is_enabled(&self) -> bool { !self.bucket.is_empty() && !self.project.is_empty() @@ -1019,10 +1058,12 @@ impl<'a> SandboxClient<'a> { terraform_version: Option<&str>, deadline: Option, ) -> Result> { + let (cmd, cache) = self.in_test_env(checks_cmd).await?; let mut env = vec![ env_var("SANDBOX_GET_URL", &self.presigned_get(key).await?)?, - env_var("CHECKS_CMD", checks_cmd)?, + env_var("CHECKS_CMD", &cmd)?, ]; + env.extend(cache); env.extend(self.egress_env(Some(checks_cmd))?); // The buildspec switches Node to this via `n` before running checks, so // "green in the sandbox" tracks the repo's real toolchain (it defaults diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 5f4ee304b..2f428daf2 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -212,8 +212,26 @@ pub async fn run( repo_instructions }; let instructions_block = super::format_instructions_block(trimmed_instructions); + // How the repository's CI installs and runs its tests, found once per + // run and reused by every round's sandbox builds (`test_setup`). + let test_env = match run_id { + Some(rid) => { + super::test_setup::for_run( + state, + github, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + &msg.base_branch, + branch, + rid, + ) + .await + } + None => None, + }; let tests_block = format!( - "{}{}", + "{}{}{}", if super::review_pr::tests_required(state, &msg.team_id, &msg.repo_owner, &msg.repo_name) .await { @@ -221,7 +239,11 @@ pub async fn run( } else { "" }, - super::E2E_CODER_SECTION + super::E2E_CODER_SECTION, + test_env + .as_ref() + .map(|(e, _)| e.coder_note()) + .unwrap_or_default() ); // The team's instructions are never trimmed: they are its working rules. // What outcomes taught the coder here (lessons naming what people @@ -351,7 +373,8 @@ pub async fn run( &state.config.sandbox_bucket_name, &state.config.sandbox_project_name, ) - .with_egress(crate::agent::policy::sandbox_egress(state, &msg.team_id).await), + .with_egress(crate::agent::policy::sandbox_egress(state, &msg.team_id).await) + .with_test_env(test_env.clone()), ) } else { None diff --git a/services/worker/src/passes/incidents/bx_smallest_change.rs b/services/worker/src/passes/incidents/bx_smallest_change.rs index 5926e2811..19723484c 100644 --- a/services/worker/src/passes/incidents/bx_smallest_change.rs +++ b/services/worker/src/passes/incidents/bx_smallest_change.rs @@ -267,3 +267,60 @@ fn a_test_bent_to_the_vendor_against_a_criterion_is_a_required_finding() { ); assert!(f[0].body.contains("Change the product side first")); } + +/// The shape the data-pipeline run really had: its plan named the right +/// map, then reused the existing multi-sport link helper, which deletes +/// every link it isn't given, on a sync path that only inserted. The run +/// deleted links nobody asked about. The helper's body says what it does, +/// so the plan is sent back; the plan that inserts with `ON CONFLICT DO +/// NOTHING` and reuses only the read-only lookup passes. +#[test] +fn a_replacing_helper_reused_on_an_insert_only_path_is_sent_back() { + const HELPERS: &str = "CAMP_MULTI_SPORT_OVERRIDES = {\n \"sports academy break camp\": [\"multi-sport\"],\n}\n\n\ndef get_camp_multi_sport_names(name):\n return CAMP_MULTI_SPORT_OVERRIDES.get(name.lower(), [])\n\n\ndef upsert_multi_sport_links(cur, group_id, sport_ids):\n cur.execute(\"DELETE FROM camp_sports WHERE camp_id = %s AND NOT (sport_id = ANY(%s))\", (group_id, sport_ids))\n for sport_id in sport_ids:\n cur.execute(\"INSERT INTO camp_sports VALUES (%s, %s) ON CONFLICT DO NOTHING\", (group_id, sport_id))\n"; + let reuse_replacing = plan( + "## Reuse\n- `CAMP_MULTI_SPORT_OVERRIDES` and `upsert_multi_sport_links` in dags/camps/sports.py (the other two sources already use them)\n\n\ + ## Must not change\nSingle-sport camps.\n\n## Measure first\nNone: the change stays inside this repository.\n\n\ + ## Smallest change\n4 entries in `CAMP_MULTI_SPORT_OVERRIDES`; call `upsert_multi_sport_links` in the 3 write branches.\n\n\ + ## Proof\nOne test of the links per camp.\n", + &format!("- [ ] {MAP_FILE}: 4 entries\n- [ ] {SYNC_FILE}: link the extra sports\n- [ ] tests/test_sports.py: one test"), + ); + let sources = |p: &PlanResult| -> Vec<(String, String, String)> { + plan_shape::reused_functions(p) + .into_iter() + .map(|n| (n, MAP_FILE.to_string(), HELPERS.to_string())) + .collect() + }; + let planned = vec![ + (MAP_FILE.to_string(), HELPERS.to_string()), + (SYNC_FILE.to_string(), BASE_SYNC.to_string()), + ]; + let facts = plan_shape::write_facts(&sources(&reuse_replacing), &planned); + assert!(facts.path_inserts_only, "{facts:?}"); + let g = plan_shape::write_gaps(&reuse_replacing, CAMP_TICKET, &facts); + assert!( + g.iter() + .any(|l| l.contains("`upsert_multi_sport_links` without what it does to stored rows")), + "{g:?}" + ); + assert!( + g.iter() + .any(|l| l.contains("on a path that only inserts today")), + "{g:?}" + ); + // Saying it replaces isn't enough when the ticket asks for no + // replacement; a ticket that asks to replace the links may. + let said = plan( + &reuse_replacing.design.replace( + "(the other two sources already use them)", + "(it replaces a camp's links: DELETE then insert)", + ), + &reuse_replacing.tasks, + ); + let g = plan_shape::write_gaps(&said, CAMP_TICKET, &facts); + assert_eq!(g.len(), 1, "{g:?}"); + assert!(plan_shape::write_gaps(&said, "Replace each camp's sport links", &facts).is_empty()); + // The small plan reuses only the map and the read-only lookup. + let small = camps_plan_after(); + let facts = plan_shape::write_facts(&sources(&small), &planned); + assert!(plan_shape::write_gaps(&small, CAMP_TICKET, &facts).is_empty()); +} diff --git a/services/worker/src/passes/minimal_change.rs b/services/worker/src/passes/minimal_change.rs index 3220ced36..90eb458a0 100644 --- a/services/worker/src/passes/minimal_change.rs +++ b/services/worker/src/passes/minimal_change.rs @@ -556,6 +556,101 @@ pub fn replacing(diff: &Diff, base: &[(String, String)]) -> Vec { out } +// ── What a helper does to stored rows ────────────────────────────────────── + +/// What a function does to rows already stored. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Writes { + /// It adds rows and leaves existing ones as they are. + InsertOnly, + /// It deletes, overwrites or replaces existing rows; the statements + /// that show it. + Replacing(Vec), + /// It writes nothing the check can see. + None, +} + +const INSERTS: &[&str] = &[ + "insert into", + "do nothing", + "on_conflict_do_nothing", + "bulk_create(", + "insert_many(", + "insert_one(", + ".add(", + ".create(", + "get_or_create(", +]; + +/// The text of the top-level definition `name` in `text`: from its line to +/// the next top-level definition (or a line back at the left margin that +/// isn't a closing bracket or a decorator). +pub fn body_of(text: &str, path: &str, name: &str) -> Option { + let lines: Vec<&str> = text.lines().collect(); + let start = lines + .iter() + .position(|l| top_level_def(l, path).is_some_and(|d| d.name == name))?; + let mut out = vec![lines[start]]; + for l in &lines[start + 1..] { + let t = l.trim_start(); + let at_margin = !l.is_empty() && !l.starts_with([' ', '\t']); + if at_margin && !(t.starts_with('}') || t.starts_with(')') || t.starts_with(']')) { + break; + } + out.push(l); + } + Some(out.join("\n")) +} + +/// What a function body does to stored rows: deleting or overwriting +/// statements (or a delete followed by an insert, a `.set(` that replaces a +/// relation) make it replacing; an insert with none of them, insert only. +pub fn write_semantics(body: &str) -> Writes { + let lines: Vec<&str> = body + .lines() + .filter(|l| { + let t = l.trim_start(); + !(t.starts_with('#') || t.starts_with("//") || t.starts_with("--")) + }) + .collect(); + let low = lines.join("\n").to_lowercase(); + let mut how: Vec = REPLACING + .iter() + .filter(|(t, _)| low.contains(t)) + .map(|(_, n)| n.to_string()) + .collect(); + let writes_db = [ + "execute(", "query(", ".save(", "insert", "session.", "cursor", + ] + .iter() + .any(|w| low.contains(w)); + if low.contains(".set(") && writes_db { + how.push("a `.set(` that replaces a relation".to_string()); + } + let delete = low.find("delete ").or_else(|| low.find("delete(")); + let insert = low.rfind("insert"); + if let (Some(d), Some(i)) = (delete, insert) { + if d < i && !how.iter().any(|h| h.contains("DELETE")) { + how.push("a delete followed by an insert".to_string()); + } + } + if !how.is_empty() { + return Writes::Replacing(how); + } + if INSERTS.iter().any(|t| low.contains(t)) { + return Writes::InsertOnly; + } + Writes::None +} + +/// Whether the code paths in `texts` only insert: at least one insert and +/// no deleting or overwriting statement. +pub fn inserts_only(texts: &[&str]) -> bool { + let all = texts.join("\n"); + matches!(write_semantics(&all), Writes::InsertOnly) +} + // ── Logging and reporting ────────────────────────────────────────────────── const LEVELS: &[&str] = &[ @@ -1079,6 +1174,39 @@ mod tests { assert!(vendor_flips("e2e/portal.spec.ts", patch, true, &[]).is_empty()); } + #[test] + fn what_a_helper_does_to_existing_rows() { + let text = "def upsert_multi_sport_links(cur, group_id, sport_ids):\n cur.execute(\"DELETE FROM group_sport WHERE group_id = %s AND NOT (sport_id = ANY(%s))\", (group_id, sport_ids))\n for s in sport_ids:\n cur.execute(\"INSERT INTO group_sport VALUES (%s, %s) ON CONFLICT DO NOTHING\", (group_id, s))\n\n\ndef upsert_group_sport_link(cur, group_id, sport_id):\n cur.execute(\"INSERT INTO group_sport VALUES (%s, %s) ON CONFLICT DO NOTHING\", (group_id, sport_id))\n\n\ndef sport_names(name):\n return OVERRIDES.get(name, [])\n"; + let replacing = body_of(text, "a.py", "upsert_multi_sport_links").unwrap(); + assert!(!replacing.contains("def upsert_group_sport_link")); + assert_eq!( + write_semantics(&replacing), + Writes::Replacing(vec!["`DELETE FROM`".to_string()]) + ); + let insert = body_of(text, "a.py", "upsert_group_sport_link").unwrap(); + assert_eq!(write_semantics(&insert), Writes::InsertOnly); + let read = body_of(text, "a.py", "sport_names").unwrap(); + assert_eq!(write_semantics(&read), Writes::None); + assert!(inserts_only(&[&insert])); + assert!(!inserts_only(&[&insert, &replacing])); + // An upsert that overwrites, and a relation replaced with `.set(`. + assert!(matches!( + write_semantics("INSERT INTO t VALUES (1) ON CONFLICT (id) DO UPDATE SET v = 1"), + Writes::Replacing(_) + )); + assert!(matches!( + write_semantics("group.sports.set(ids)\ngroup.save()"), + Writes::Replacing(_) + )); + assert_eq!(write_semantics("cache.set(k, v)"), Writes::None); + // A TypeScript helper body ends at its closing brace. + let ts = "export function linkAll(db, ids) {\n return db.query('DELETE FROM l WHERE id = $1', ids);\n}\nexport const other = 1;\n"; + assert!(matches!( + write_semantics(&body_of(ts, "a.ts", "linkAll").unwrap()), + Writes::Replacing(_) + )); + } + #[test] fn an_edit_that_adds_a_parallel_helper() { let old = "SPORT_OVERRIDES = {\n}\ndef sport_overrides_for(n):\n pass\n"; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 9e125977e..fe08ff914 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1424,6 +1424,7 @@ pub(crate) mod terraform; mod test; pub mod test_bug; pub mod test_fix; +pub(crate) mod test_setup; pub mod ticket_base; pub mod ticket_comments; pub mod ticket_history; diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 02f257073..1566089a4 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -957,8 +957,23 @@ Then the ```fix_location.json block described above."#, common::run_questions::answers_note(&msg.answers) ); let is_feature = intent == super::triage::TicketIntent::Feature; - let shape_gaps = + let mut shape_gaps = super::plan_shape::plan_gaps(&draft, &ticket_words, is_feature, &existing_names); + // What the reused helpers do to stored rows, read from their bodies: a + // replacing helper on a path that only inserts deleted rows nobody asked + // about. + let write_facts = super::plan_shape::read_write_facts( + &executor.read_only, + github, + (&msg.repo_owner, &msg.repo_name, &msg.base_branch), + &draft, + ) + .await; + shape_gaps.extend(super::plan_shape::write_gaps( + &draft, + &ticket_words, + &write_facts, + )); back.extend(shape_gaps.iter().cloned()); // A decision that stops without a fix names the one step a person takes. back.extend(super::fix_location::next_step_gaps(draft.fix.as_ref())); @@ -1446,7 +1461,16 @@ Then the ```fix_location.json block described above."#, } } if !shape_gaps.is_empty() { - let left = super::plan_shape::plan_gaps(&files, &ticket_words, is_feature, &existing_names); + let mut left = + super::plan_shape::plan_gaps(&files, &ticket_words, is_feature, &existing_names); + let facts = super::plan_shape::read_write_facts( + &executor.read_only, + github, + (&msg.repo_owner, &msg.repo_name, &msg.base_branch), + &files, + ) + .await; + left.extend(super::plan_shape::write_gaps(&files, &ticket_words, &facts)); if !left.is_empty() { warn!(ticket_id = %msg.ticket_id, gaps = ?left, "Plan is still not the smallest change after one send-back"); super::add_progress_note( diff --git a/services/worker/src/passes/plan_shape.rs b/services/worker/src/passes/plan_shape.rs index 9afb98573..af70c4462 100644 --- a/services/worker/src/passes/plan_shape.rs +++ b/services/worker/src/passes/plan_shape.rs @@ -44,7 +44,10 @@ pub const PLANNER: &str = "\n\n## The smallest correct change (CoderHelm checks Before you plan, read the code the change extends: the whole map, function or query, and its \ writers and readers. Then write these sections in design.md:\n\ - `## Reuse`: the existing maps, helpers, constants, config and tests this change extends, each \ -with its path (search the ticket's names and the structure you would add). Add entries to an \ +with its path (search the ticket's names and the structure you would add). For each helper that \ +writes data, read its body and say what it does to rows already stored: `inserts only` or \ +`replaces/deletes` (a `DELETE`, an `ON CONFLICT DO UPDATE`, a delete-then-insert). A helper that \ +replaces is never reused on a path that only inserts unless the ticket asks to replace. Add entries to an \ existing map or a parameter to an existing helper; never a second map or helper beside it.\n\ - `## Must not change`: what stays as it is. A path that only inserts keeps only inserting (no \ `DELETE`, no `ON CONFLICT DO UPDATE`, no replacing sync) unless the ticket asks for it; log \ @@ -328,6 +331,157 @@ pub fn plan_gaps( out } +// ── What reused helpers do to stored rows ────────────────────────────────── + +/// A helper the plan reuses, and what it does to stored rows. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Helper { + pub name: String, + pub path: String, + pub writes: minimal_change::Writes, +} + +/// What the plan's reused helpers and the planned files do to stored rows. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct WriteFacts { + pub helpers: Vec, + /// The planned code files, without the reused helpers' own bodies, only + /// insert today. + pub path_inserts_only: bool, +} + +/// The function-like names under the plan's Reuse section. +pub fn reused_functions(files: &PlanResult) -> Vec { + let reuse = section(&files.design, REUSE).unwrap_or(""); + backticked(reuse) + .into_iter() + .filter(|n| n.chars().any(|c| c.is_ascii_lowercase())) + .collect() +} + +/// The facts from the helpers' sources (`(name, path, file text)`) and the +/// planned code files' base texts (`(path, text)`). +pub fn write_facts( + sources: &[(String, String, String)], + planned: &[(String, String)], +) -> WriteFacts { + let mut helpers = Vec::new(); + let mut bodies: Vec = Vec::new(); + for (name, path, text) in sources { + if let Some(body) = minimal_change::body_of(text, path, name) { + helpers.push(Helper { + name: name.clone(), + path: path.clone(), + writes: minimal_change::write_semantics(&body), + }); + bodies.push(body); + } + } + let rest: Vec = planned + .iter() + .map(|(_, t)| { + let mut t = t.clone(); + for b in &bodies { + t = t.replace(b.as_str(), ""); + } + t + }) + .collect(); + let refs: Vec<&str> = rest.iter().map(String::as_str).collect(); + WriteFacts { + helpers, + path_inserts_only: !refs.is_empty() && minimal_change::inserts_only(&refs), + } +} + +const SAYS_REPLACES: &[&str] = &["replace", "delete", "overwrite", "do update", "prune"]; + +/// What the plan misses about the rows its reused helpers touch: a +/// replacing helper the Reuse section doesn't say replaces, and a replacing +/// helper reused where the code only inserts, when the ticket asks for no +/// replacement. +pub fn write_gaps(files: &PlanResult, ticket: &str, facts: &WriteFacts) -> Vec { + if stops(files) { + return Vec::new(); + } + let reuse = section(&files.design, REUSE).unwrap_or("").to_lowercase(); + let mut out = Vec::new(); + for h in &facts.helpers { + let minimal_change::Writes::Replacing(how) = &h.writes else { + continue; + }; + let line = reuse + .lines() + .find(|l| l.contains(&h.name.to_lowercase())) + .unwrap_or(""); + if !SAYS_REPLACES.iter().any(|w| line.contains(w)) { + out.push(format!( + "`{REUSE}` names `{}` without what it does to stored rows: it replaces them ({}, in `{}`). Say so next to it.", + h.name, + how.join(", "), + h.path + )); + } + if facts.path_inserts_only + && !minimal_change::ticket_asks(ticket, minimal_change::REPLACE_ASKS) + { + out.push(format!( + "The plan reuses `{}`, which replaces stored rows ({}), on a path that only inserts today, and the ticket asks for no replacement. Keep the path additive: insert the new rows with `ON CONFLICT DO NOTHING` (or the insert-only helper the path already uses), and list the existing rows under `{MUST_NOT_CHANGE}`.", + h.name, + how.join(", ") + )); + } + } + out +} + +/// Reads the facts: each reused function's definition (found by search, +/// read at `base`) and the planned code files at `base`. +pub async fn read_write_facts( + search: &dyn RepoSearch, + github: &crate::clients::github::GitHubClient, + (owner, repo, base): (&str, &str, &str), + files: &PlanResult, +) -> WriteFacts { + let own = format!("{owner}/{repo}"); + let mut sources = Vec::new(); + for name in reused_functions(files).into_iter().take(6) { + let Ok(hits) = search.search(&own, &name).await else { + continue; + }; + let defining = hits.iter().find_map(|h| { + let path = h.lines().next()?.to_string(); + let defines = [ + format!("def {name}("), + format!("function {name}"), + format!("fn {name}"), + format!("const {name} ="), + ]; + h.lines() + .skip(1) + .any(|l| defines.iter().any(|d| l.contains(d.as_str()))) + .then_some(path) + }); + let Some(path) = defining else { + continue; + }; + if let Ok(text) = github.read_file(owner, repo, &path, base).await { + sources.push((name, path, text)); + } + } + let mut planned = Vec::new(); + for f in super::feature::plan_files::planned_files(&files.tasks) + .into_iter() + .filter(|f| !super::habits::is_test_path(&f.path)) + .take(8) + { + if let Ok(text) = github.read_file(owner, repo, &f.path, base).await { + planned.push((f.path.clone(), text)); + } + } + write_facts(&sources, &planned) +} + // ── What the ticket's words find, before the plan ────────────────────────── const STOP: &[&str] = &[ diff --git a/services/worker/src/passes/preview.rs b/services/worker/src/passes/preview.rs index 889e5fa13..3ee18abb0 100644 --- a/services/worker/src/passes/preview.rs +++ b/services/worker/src/passes/preview.rs @@ -163,7 +163,7 @@ fn covering_results( } /// The workflow files at `git_ref`, with their text. -async fn workflows( +pub(crate) async fn workflows( gh: &GitHubClient, owner: &str, repo: &str, diff --git a/services/worker/src/passes/test_bug.rs b/services/worker/src/passes/test_bug.rs index 1d7cf11f6..cd4d69a6f 100644 --- a/services/worker/src/passes/test_bug.rs +++ b/services/worker/src/passes/test_bug.rs @@ -80,7 +80,21 @@ impl Runner<'_> { &self.state.config.sandbox_bucket_name, &self.state.config.sandbox_project_name, ) - .with_egress(crate::agent::policy::sandbox_egress(self.state, self.team_id).await); + .with_egress(crate::agent::policy::sandbox_egress(self.state, self.team_id).await) + // The proof step runs in the run's test environment too. + .with_test_env( + super::test_setup::for_run( + self.state, + self.github, + self.team_id, + self.owner, + self.repo, + sha, + sha, + self.run_id, + ) + .await, + ); let source = sandbox .ensure_source(self.run_id, sha, || { self.github.download_tarball(self.owner, self.repo, sha) diff --git a/services/worker/src/passes/test_setup.rs b/services/worker/src/passes/test_setup.rs new file mode 100644 index 000000000..91bec4482 --- /dev/null +++ b/services/worker/src/passes/test_setup.rs @@ -0,0 +1,107 @@ +//! The run's test environment (`common::test_env`), found once and reused. +//! +//! The first round that has a sandbox reads the repository's CI workflows +//! and records how its tests install and run on the run, in the sandbox +//! bucket (`env-cache/runs/.json`), with one line in the run's notes. +//! Every later round, continuation and proof step reads that record instead +//! of working it out again. Each one names the install by its fingerprint, so +//! every sandbox build restores the cached install, or saves it when it is +//! the first (`SandboxClient::with_test_env`). + +use common::test_env::{self, TestEnv}; +use tracing::{info, warn}; + +use crate::clients::github::GitHubClient; +use crate::WorkerState; + +/// Where the run's record lives in the sandbox bucket. +pub fn record_key(run_id: &str) -> String { + let safe: String = run_id + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') + .collect(); + format!("env-cache/runs/{safe}.json") +} + +async fn read_record(state: &WorkerState, run_id: &str) -> Option { + let obj = state + .s3 + .get_object() + .bucket(&state.config.sandbox_bucket_name) + .key(record_key(run_id)) + .send() + .await + .ok()?; + let bytes = obj.body.collect().await.ok()?.into_bytes(); + serde_json::from_slice(&bytes).ok() +} + +async fn write_record(state: &WorkerState, run_id: &str, env: &TestEnv) { + let Ok(body) = serde_json::to_vec(env) else { + return; + }; + if let Err(e) = state + .s3 + .put_object() + .bucket(&state.config.sandbox_bucket_name) + .key(record_key(run_id)) + .body(aws_sdk_s3::primitives::ByteStream::from(body)) + .content_type("application/json") + .send() + .await + { + warn!(run_id, error = %e, "Could not record the run's test environment"); + } +} + +/// The run's test environment and the cache key of its install at +/// `git_ref`, or `None` without a sandbox or a CI job that runs tests. +#[allow(clippy::too_many_arguments)] +pub async fn for_run( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + owner: &str, + repo: &str, + base_branch: &str, + git_ref: &str, + run_id: &str, +) -> Option<(TestEnv, String)> { + if state.config.sandbox_bucket_name.is_empty() || state.config.sandbox_project_name.is_empty() { + return None; + } + let tree: Vec<(String, String)> = github + .get_tree(owner, repo, git_ref) + .await + .ok()? + .into_iter() + .filter(|e| e.entry_type == "blob") + .map(|e| (e.path, e.sha)) + .collect(); + let env = match read_record(state, run_id).await { + Some(env) => env, + None => { + let workflows = super::preview::workflows(github, owner, repo, base_branch).await; + let paths: Vec = tree.iter().map(|(p, _)| p.clone()).collect(); + let env = test_env::from_workflows(&workflows, &paths)?; + write_record(state, run_id, &env).await; + super::add_progress_note(state, team_id, run_id, &env.summary()).await; + env + } + }; + let fp = env.fingerprint(&tree); + let key = test_env::cache_key(team_id, &format!("{owner}/{repo}"), &fp); + info!(run_id, key = %key, "The run's test environment"); + Some((env, key)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_record_per_run() { + assert_eq!(record_key("01ABC"), "env-cache/runs/01ABC.json"); + assert_eq!(record_key("../x"), "env-cache/runs/x.json"); + } +}