From 1440aac0382aac7f366cc86c6f58cabb531ab800 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 16 Nov 2026 13:51:45 -0500 Subject: [PATCH 1/3] 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/3] 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 adff1fd78f44ffd971438f4cc2e73b6b654e27dd Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 16 Nov 2026 19:24:58 -0500 Subject: [PATCH 3/3] Answers on the ticket are decisions in every run; related tickets are checked before ready Every answer and instruction people wrote on the ticket counts in every run on it, whichever run handled it, and a description never lists an answered item as pending. The Jira app sends the ticket's linked tickets; their criteria reach the plan, and before the pull request is called ready each one, and each address a pull request closed in favor of it moved, is checked or listed as not covered with why. --- coderhelm-jira/src/index.js | 14 +- coderhelm-jira/src/related.js | 81 +++ coderhelm-jira/test/related.test.js | 37 + services/common/src/lib.rs | 6 + services/common/src/messages.rs | 6 + services/common/src/related_tickets.rs | 645 ++++++++++++++++++ services/common/src/ticket_decisions.rs | 560 +++++++++++++++ services/gateway/src/routes/jira_webhook.rs | 3 + services/worker/src/models.rs | 1 + services/worker/src/passes/description.rs | 15 + services/worker/src/passes/e2e.rs | 2 + services/worker/src/passes/e2e_attribution.rs | 1 + services/worker/src/passes/feedback.rs | 18 + services/worker/src/passes/implement.rs | 6 +- .../passes/incidents/bm_teams_never_cross.rs | 1 + .../incidents/bz_ticket_answer_decides.rs | 123 ++++ .../incidents/ca_related_ticket_covered.rs | 122 ++++ services/worker/src/passes/incidents/mod.rs | 2 + services/worker/src/passes/log_autofix.rs | 1 + services/worker/src/passes/mod.rs | 22 + services/worker/src/passes/plan.rs | 12 +- services/worker/src/passes/ready.rs | 43 ++ services/worker/src/passes/related.rs | 215 ++++++ services/worker/src/passes/resume.rs | 14 +- services/worker/src/passes/ticket_comments.rs | 48 ++ 25 files changed, 1991 insertions(+), 7 deletions(-) create mode 100644 coderhelm-jira/src/related.js create mode 100644 coderhelm-jira/test/related.test.js create mode 100644 services/common/src/related_tickets.rs create mode 100644 services/common/src/ticket_decisions.rs create mode 100644 services/worker/src/passes/incidents/bz_ticket_answer_decides.rs create mode 100644 services/worker/src/passes/incidents/ca_related_ticket_covered.rs create mode 100644 services/worker/src/passes/related.rs diff --git a/coderhelm-jira/src/index.js b/coderhelm-jira/src/index.js index 10ae86b45..d2daf3b23 100644 --- a/coderhelm-jira/src/index.js +++ b/coderhelm-jira/src/index.js @@ -7,6 +7,7 @@ const { GATEWAY_URL } = require("./gateway"); const { existingComments } = require("./comments"); const { postReply, parentIdOf } = require("./thread-reply"); const { versionFields } = require("./version"); +const { relatedTickets } = require("./related"); /** Jira's comment calls as the app, for a threaded reply (see thread-reply.js). */ const jiraComments = { @@ -23,6 +24,14 @@ const jiraComments = { // see whether Jira's comment events carry a parent id. let loggedCommentKeys = false; +/** A related ticket's summary, status and description, read as the app. */ +async function readRelatedIssue(key) { + const res = await api.asApp().requestJira(route`/rest/api/3/issue/${key}?fields=summary,description,status`); + if (!res.ok) return null; + const full = await res.json(); + return full.fields || null; +} + /** The parts of a Jira user CoderHelm keeps: account id, name, email. */ function jiraUser(u) { return { accountId: u.accountId, displayName: u.displayName, emailAddress: u.emailAddress }; @@ -188,7 +197,7 @@ exports.handler = async (event, context) => { let fields = {}; if (issue.id) { try { - const res = await api.asApp().requestJira(route`/rest/api/3/issue/${issue.id}?fields=summary,description,labels,assignee,reporter,creator,project,attachment,issuetype,comment`); + const res = await api.asApp().requestJira(route`/rest/api/3/issue/${issue.id}?fields=summary,description,labels,assignee,reporter,creator,project,attachment,issuetype,comment,issuelinks`); if (res.ok) { const full = await res.json(); fields = full.fields || {}; @@ -238,6 +247,9 @@ exports.handler = async (event, context) => { // What people already wrote on the ticket: the run that starts reads it // before it plans (the gateway keeps each comment once, by its id). comments: existingComments(fields), + // The tickets linked to this one and the ones its text names: their + // acceptance criteria are part of the change (see related.js). + related: await relatedTickets(issue.key, fields, readRelatedIssue), user: requester(event.atlassianId, fields), coderhelm: { repo_owner: repoOwner || undefined, diff --git a/coderhelm-jira/src/related.js b/coderhelm-jira/src/related.js new file mode 100644 index 000000000..41bf5f470 --- /dev/null +++ b/coderhelm-jira/src/related.js @@ -0,0 +1,81 @@ +/** + * The tickets related to the one CoderHelm works on: its issue links ("relates + * to", "blocks", "is cloned by") and the tickets its description names. Their + * acceptance criteria are part of the change, so the run reads them before it + * plans and checks them before the pull request is called ready. + * + * A pull request was once closed by a person who expected a linked ticket's + * pull request to cover it; that pull request had never read the linked + * ticket, and the button it was about still pointed to the old address. + */ + +/** The most related tickets sent with one ticket event. */ +const MAX_RELATED = 6; + +/** The most characters of one related ticket's description sent. */ +const MAX_BODY_CHARS = 8000; + +/** Ticket keys a text names (`ABC-123`), in order, without repeats. */ +function keysInText(text, own) { + const out = []; + const re = /(^|[^A-Za-z0-9-])([A-Z][A-Z0-9]+-\d+)(?![A-Za-z0-9])/g; + let m; + while ((m = re.exec(text || "")) !== null) { + const key = m[2]; + if (key !== own && !out.includes(key)) out.push(key); + } + return out; +} + +/** + * The related tickets' keys with how each relates, issue links first. + * @param {string} own The ticket's own key. + * @param {object} fields The ticket's fields (with `issuelinks` and `description`). + * @returns {{key: string, relation: string}[]} + */ +function relatedKeys(own, fields) { + const out = []; + for (const l of (fields && fields.issuelinks) || []) { + const other = l.outwardIssue || l.inwardIssue; + if (!other || !other.key || other.key === own) continue; + const type = l.type || {}; + const relation = (l.outwardIssue ? type.outward : type.inward) || type.name || "relates to"; + if (!out.some((r) => r.key === other.key)) out.push({ key: other.key, relation }); + } + const text = typeof fields?.description === "string" ? fields.description : JSON.stringify(fields?.description || ""); + for (const key of keysInText(text, own)) { + if (!out.some((r) => r.key === key)) out.push({ key, relation: "named in the ticket" }); + } + return out.slice(0, MAX_RELATED); +} + +/** + * Each related ticket with its summary, status and description (the + * gateway reads the description's words), read as the app. + * @param {string} own The ticket's own key. + * @param {object} fields The ticket's fields. + * @param {(key: string) => Promise} readIssue The issue's fields, or null. + */ +async function relatedTickets(own, fields, readIssue) { + const out = []; + for (const { key, relation } of relatedKeys(own, fields)) { + let f = null; + try { + f = await readIssue(key); + } catch (e) { + f = null; + } + if (!f) continue; + const body = typeof f.description === "string" ? f.description : JSON.stringify(f.description || ""); + out.push({ + key, + relation, + summary: f.summary || "", + status: (f.status && f.status.name) || "", + description: body.slice(0, MAX_BODY_CHARS), + }); + } + return out; +} + +module.exports = { keysInText, relatedKeys, relatedTickets, MAX_RELATED }; diff --git a/coderhelm-jira/test/related.test.js b/coderhelm-jira/test/related.test.js new file mode 100644 index 000000000..0901fb412 --- /dev/null +++ b/coderhelm-jira/test/related.test.js @@ -0,0 +1,37 @@ +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const { keysInText, relatedKeys, relatedTickets, MAX_RELATED } = require("../src/related"); + +test("keys named in a text, without the ticket's own", () => { + assert.deepEqual(keysInText("See ABC-2 and XY-3, not ABC-1 or abc-4. ABC-2 again.", "ABC-1"), ["ABC-2", "XY-3"]); +}); + +test("issue links come first, with how they relate, then keys in the description", () => { + const fields = { + issuelinks: [ + { type: { name: "Relates", inward: "relates to", outward: "relates to" }, outwardIssue: { key: "ABC-2" } }, + { type: { name: "Blocks", inward: "is blocked by", outward: "blocks" }, inwardIssue: { key: "ABC-3" } }, + ], + description: { type: "doc", content: [{ type: "text", text: "Also covers ABC-4 and ABC-2." }] }, + }; + assert.deepEqual(relatedKeys("ABC-1", fields), [ + { key: "ABC-2", relation: "relates to" }, + { key: "ABC-3", relation: "is blocked by" }, + { key: "ABC-4", relation: "named in the ticket" }, + ]); +}); + +test("each related ticket is read with its summary and description; an unreadable one is left out", async () => { + const fields = { issuelinks: [{ type: { outward: "relates to" }, outwardIssue: { key: "ABC-2" } }, { type: { outward: "relates to" }, outwardIssue: { key: "ABC-9" } }] }; + const read = async (key) => (key === "ABC-2" ? { summary: "Point the drawer button to the new page", status: { name: "Closed" }, description: "Acceptance criteria\n- The drawer Register button links to /new/register" } : null); + const got = await relatedTickets("ABC-1", fields, read); + assert.equal(got.length, 1); + assert.equal(got[0].key, "ABC-2"); + assert.equal(got[0].status, "Closed"); + assert.match(got[0].description, /links to \/new\/register/); +}); + +test("at most a handful are sent", () => { + const links = Array.from({ length: 10 }, (_, i) => ({ type: { outward: "relates to" }, outwardIssue: { key: `ABC-${i + 2}` } })); + assert.equal(relatedKeys("ABC-1", { issuelinks: links }).length, MAX_RELATED); +}); diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 1e7625f4f..b51b30ae2 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -232,6 +232,9 @@ pub mod problems; /// Where this deployment's dashboard and API are (links, redirects, webhooks). pub mod public_urls; pub mod registry_check; +/// Linked tickets and pull requests closed in favor of this one: their criteria are +/// part of the change and checked before it is called ready. +pub mod related_tickets; /// What CoderHelm says back to a person, written from the thread and the run's records. pub mod reply_compose; /// Who asked for a run: one identity per person, for per-person analytics. @@ -283,6 +286,9 @@ pub mod stop_rules; /// A team's run and PR-reviewed counts, each added exactly once. pub mod team_counts; pub mod ticket_comments; +/// What a person answered on the ticket is a decision in every run on it; a +/// description never lists an answered item as pending. +pub mod ticket_decisions; /// A ticket's comments as CoderHelm read them, and whether its work is done. pub mod ticket_state; /// A team's monthly token limits: new tokens, cache read, cache write. diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 4d494d418..941e0b017 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -1147,6 +1147,11 @@ pub struct TicketMessage { /// planner doesn't ask them again (see `run_questions`). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub answers: Vec, + /// The tickets linked to this one (Jira issue links, tickets its text + /// names), as the Jira app sends them: their acceptance criteria are + /// part of the change (`related_tickets`). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub related: Vec, /// The id the new run takes, when whoever sent the ticket named it /// first (answering on the dashboard links the asking run to the run /// that picks the answers up). A continuation keeps its own id. @@ -1253,6 +1258,7 @@ impl Default for TicketMessage { coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: None, } } diff --git a/services/common/src/related_tickets.rs b/services/common/src/related_tickets.rs new file mode 100644 index 000000000..7b946ef8b --- /dev/null +++ b/services/common/src/related_tickets.rs @@ -0,0 +1,645 @@ +//! The tickets and pull requests related to a run's ticket are part of its +//! work, and the pull request says which of their criteria it covers. +//! +//! The failure this was written for: a ticket's pull request was closed by +//! a person who expected another ticket's pull request to cover it (the +//! tickets were linked in Jira). That pull request never read the linked +//! ticket: the drawer's Register button still pointed to the old address +//! when it was called ready. +//! +//! Now: +//! +//! - The Jira app sends the ticket's issue links and the tickets its text +//! names, each with its summary and description ([`Related`]); the +//! gateway keeps them on the run's message. +//! - [`criteria`] reads a ticket's acceptance criteria from its text; the +//! planner is given every related ticket's ([`plan_note`]) and the run +//! keeps them ([`Criterion`]). +//! - A pull request closed in favor of this one (it links this pull +//! request and was closed without merging) brings its own change: +//! [`moved_links`] reads the addresses it replaced, and [`check_source`] +//! says whether this pull request's head made the same move. +//! - Before the pull request is called ready, each criterion is checked +//! where it can be: an address change on the head's files, a link on the +//! preview page ([`link_expectation`], [`check_page`]). One that can't be +//! checked is listed as not covered, with why. [`section`] is what the +//! description shows. + +use serde::{Deserialize, Serialize}; + +/// The marker of the description's related-tickets section. +pub const MARKER: &str = ""; + +/// A ticket related to the run's ticket, as the Jira app sends it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Related { + pub key: String, + /// How it relates ("relates to", "blocks", "is cloned by", "named in + /// the ticket"). + #[serde(default)] + pub relation: String, + #[serde(default)] + pub summary: String, + /// Its description as plain text. + #[serde(default)] + pub body: String, + #[serde(default)] + pub status: String, +} + +/// One acceptance criterion this pull request takes on from a related +/// ticket or a pull request closed in favor of it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Criterion { + /// Where it comes from: a ticket key or `#123`. + pub from: String, + pub text: String, +} + +/// What checking a criterion found. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum Verdict { + /// Covered, with what showed it. + Covered(String), + /// Not covered, with why (what was found, or why it couldn't be + /// checked). + NotCovered(String), +} + +/// The related tickets a Jira app event carries (`related`: key, +/// relation, summary, status, description as a document or text). +pub fn from_payload(payload: &serde_json::Value) -> Vec { + payload["related"] + .as_array() + .into_iter() + .flatten() + .filter_map(|r| { + let key = r["key"].as_str()?.trim().to_string(); + if key.is_empty() { + return None; + } + let s = |k: &str| r[k].as_str().unwrap_or("").trim().to_string(); + Some(Related { + key, + relation: s("relation"), + summary: s("summary"), + body: crate::jira_text::body_text(&r["description"]), + status: s("status"), + }) + }) + .take(8) + .collect() +} + +/// Ticket keys a text names (`ABC-123`), without `own` and without +/// repeats, in the order they appear. +pub fn keys_in_text(text: &str, own: &str) -> Vec { + let mut out: Vec = Vec::new(); + let b = text.as_bytes(); + let mut i = 0; + while i < b.len() { + let start_ok = i == 0 || !(b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'-'); + if start_ok && b[i].is_ascii_uppercase() { + let mut j = i; + while j < b.len() && (b[j].is_ascii_uppercase() || b[j].is_ascii_digit()) { + j += 1; + } + if j - i >= 2 && j < b.len() && b[j] == b'-' { + let mut k = j + 1; + while k < b.len() && b[k].is_ascii_digit() { + k += 1; + } + let end_ok = k == b.len() || !b[k].is_ascii_alphanumeric(); + if k > j + 1 && end_ok { + let key = &text[i..k]; + if !key.eq_ignore_ascii_case(own) && !out.iter().any(|o| o == key) { + out.push(key.to_string()); + } + i = k; + continue; + } + } + i = j.max(i + 1); + continue; + } + i += 1; + } + out +} + +fn is_heading(line: &str) -> bool { + let t = line.trim(); + t.starts_with('#') + || (t.starts_with("**") && t.ends_with("**")) + || (t.ends_with(':') && t.len() < 60 && !t.starts_with('-') && !t.starts_with('*')) +} + +fn criteria_heading(line: &str) -> bool { + let t = line.to_ascii_lowercase(); + t.contains("acceptance criteria") + || t.contains("acceptance criterion") + || t.contains("definition of done") + || t.trim() + .trim_start_matches('#') + .trim() + .trim_end_matches(':') + == "ac" +} + +fn item(line: &str) -> Option<&str> { + let t = line.trim_start(); + for p in ["- [ ] ", "- [x] ", "- ", "* ", "+ ", "• "] { + if let Some(r) = t.strip_prefix(p) { + return Some(r.trim()); + } + } + let d = t.chars().take_while(|c| c.is_ascii_digit()).count(); + if d > 0 && (t[d..].starts_with(". ") || t[d..].starts_with(") ")) { + return Some(t[d + 2..].trim()); + } + None +} + +/// A ticket's acceptance criteria: the items under its "Acceptance +/// criteria" (or "Definition of done") heading. With no such heading, the +/// items of its text when it is a list of what must be true, else nothing. +pub fn criteria(text: &str) -> Vec { + let lines: Vec<&str> = text.lines().collect(); + let mut out = Vec::new(); + if let Some(at) = lines.iter().position(|l| criteria_heading(l)) { + // "Acceptance criteria: the button links to /x" on one line. + if let Some((_, rest)) = lines[at].split_once(':') { + let rest = rest.trim(); + if rest.len() > 8 { + out.push(rest.to_string()); + } + } + let rest = &lines[at + 1..]; + for (k, l) in rest.iter().enumerate() { + if let Some(i) = item(l) { + if !i.is_empty() { + out.push(i.to_string()); + } + } else if l.trim().is_empty() { + // A blank line ends the list unless more items follow it. + let next = rest[k + 1..].iter().find(|n| !n.trim().is_empty()); + if !out.is_empty() && next.is_none_or(|n| item(n).is_none()) { + break; + } + } else if is_heading(l) || !out.is_empty() { + break; + } + } + return out; + } + lines + .iter() + .filter_map(|l| item(l)) + .filter(|i| { + let i = i.to_ascii_lowercase(); + [ + " should ", + " must ", + "links to", + "points to", + "goes to", + "opens ", + ] + .iter() + .any(|w| i.contains(w)) + }) + .map(str::to_string) + .collect() +} + +/// Every related ticket's criteria; a ticket with none brings its summary +/// as the one thing it asks for. +pub fn fold(related: &[Related]) -> Vec { + let mut out = Vec::new(); + for r in related { + let mut c = criteria(&r.body); + if c.is_empty() && !r.summary.trim().is_empty() { + c.push(r.summary.trim().to_string()); + } + for text in c { + out.push(Criterion { + from: r.key.clone(), + text, + }); + } + } + out +} + +/// What the planner reads about the related tickets: their criteria are +/// part of this change unless the plan says why one isn't. +pub fn plan_note(related: &[Related]) -> String { + if related.is_empty() { + return String::new(); + } + let mut s = String::from( + "\n\n## Related tickets\nThese tickets are linked to this one. Their acceptance criteria are \ + part of this change: plan a task for each, or say in the plan why one is not this \ + change's.\n", + ); + for r in related { + s.push_str(&format!( + "- {} ({}): {}\n", + r.key, + if r.relation.is_empty() { + "related" + } else { + &r.relation + }, + r.summary.trim() + )); + let mut c = criteria(&r.body); + if c.is_empty() { + c = r + .body + .lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .take(6) + .map(str::to_string) + .collect(); + } + for line in c.iter().take(12) { + s.push_str(&format!(" - {}\n", crate::truncate_str(line, 300))); + } + } + s +} + +fn is_addr_char(c: char) -> bool { + c.is_ascii_alphanumeric() || "-._~:/?#[]@!$&'()*+,;=%".contains(c) +} + +/// The addresses in a line: `https://` links and site paths (`/a/b`). +pub fn addresses(line: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = line; + while let Some(i) = rest.find("https://").or_else(|| rest.find("http://")) { + let tail = &rest[i..]; + let end = tail.find(|c: char| !is_addr_char(c)).unwrap_or(tail.len()); + let a = tail[..end].trim_end_matches(['.', ',', ';', ')', '\'', '"']); + out.push(a.to_string()); + rest = &tail[end..]; + } + // Quoted site paths: "/venue/register", '/x', `/x`. + for q in ['"', '\'', '`'] { + let parts: Vec<&str> = line.split(q).collect(); + for (k, p) in parts.iter().enumerate() { + if k % 2 == 1 + && p.starts_with('/') + && !p.starts_with("//") + && p.len() > 1 + && p.chars().all(is_addr_char) + && !out.iter().any(|o| o == p) + { + out.push(p.to_string()); + } + } + } + out +} + +/// An address one change replaced with another in one file: the pull +/// request closed in favor of this one moved `from` to `to` in `path`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct MovedLink { + pub path: String, + pub from: String, + pub to: String, +} + +/// The addresses a patch replaced: a removed line's address whose line was +/// replaced by one with a different address, in the same hunk. +pub fn moved_links(path: &str, patch: &str) -> Vec { + let mut out = Vec::new(); + let mut removed: Vec = Vec::new(); + let mut added: Vec = Vec::new(); + let mut flush = |removed: &mut Vec, added: &mut Vec| { + for (r, a) in removed.iter().zip(added.iter()) { + if r != a { + let m = MovedLink { + path: path.to_string(), + from: r.clone(), + to: a.clone(), + }; + if !out.contains(&m) { + out.push(m); + } + } + } + removed.clear(); + added.clear(); + }; + for line in patch.lines() { + if line.starts_with("+++") || line.starts_with("---") { + continue; + } + if let Some(l) = line.strip_prefix('-') { + if !added.is_empty() { + flush(&mut removed, &mut added); + } + removed.extend(addresses(l)); + } else if let Some(l) = line.strip_prefix('+') { + added.extend(addresses(l)); + } else { + flush(&mut removed, &mut added); + } + } + flush(&mut removed, &mut added); + out +} + +/// Whether this pull request's head made the move: `content` is the file +/// at the head (`None` when it doesn't exist there). +pub fn check_source(m: &MovedLink, content: Option<&str>) -> Verdict { + match content { + None => Verdict::NotCovered(format!( + "`{}` is not on this branch; the closed pull request changed `{}` to `{}` there", + m.path, m.from, m.to + )), + Some(c) if c.contains(&m.from) && !c.contains(&m.to) => Verdict::NotCovered(format!( + "`{}` still uses `{}`; the closed pull request changed it to `{}`", + m.path, m.from, m.to + )), + Some(c) if c.contains(&m.from) => Verdict::NotCovered(format!( + "`{}` uses `{}` but still also `{}`", + m.path, m.to, m.from + )), + Some(c) if c.contains(&m.to) => Verdict::Covered(format!("`{}` uses `{}`", m.path, m.to)), + Some(_) => Verdict::NotCovered(format!( + "`{}` has neither `{}` nor `{}`: the link moved somewhere this check doesn't read", + m.path, m.from, m.to + )), + } +} + +/// A criterion that names a control and where it goes: "the Register +/// button links to /camps/register". +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LinkExpectation { + /// The control's visible text. + pub label: String, + pub target: String, +} + +/// The control and address a criterion names, when it names both. +pub fn link_expectation(text: &str) -> Option { + let target = addresses(text).into_iter().next().or_else(|| { + text.split_whitespace() + .map(|w| w.trim_matches(|c: char| ",.;:()".contains(c))) + .find(|w| w.starts_with('/') && w.len() > 1 && w.chars().all(is_addr_char)) + .map(str::to_string) + })?; + // A quoted label first ("Register"), else the word before "button" or + // "link". + let quoted = ['"', '“', '\''].iter().find_map(|q| { + let close = if *q == '“' { '”' } else { *q }; + let start = text.find(*q)? + q.len_utf8(); + let end = text[start..].find(close)? + start; + let l = text[start..end].trim(); + (!l.is_empty() && !l.starts_with('/') && !l.starts_with("http") && l.len() < 40) + .then(|| l.to_string()) + }); + let label = quoted.or_else(|| { + let words: Vec<&str> = text.split_whitespace().collect(); + words.iter().enumerate().find_map(|(i, w)| { + let w = w.to_ascii_lowercase(); + (i > 0 && (w.starts_with("button") || w.starts_with("link") || w.starts_with("cta"))) + .then(|| { + words[i - 1] + .trim_matches(|c: char| !c.is_alphanumeric()) + .to_string() + }) + .filter(|l| { + !l.is_empty() && !["the", "a", "an"].contains(&l.to_ascii_lowercase().as_str()) + }) + }) + })?; + Some(LinkExpectation { label, target }) +} + +fn strip_tags(s: &str) -> String { + let mut out = String::new(); + let mut in_tag = false; + for c in s.chars() { + match c { + '<' => in_tag = true, + '>' => in_tag = false, + _ if !in_tag => out.push(c), + _ => {} + } + } + out.split_whitespace().collect::>().join(" ") +} + +fn attr<'a>(tag: &'a str, name: &str) -> Option<&'a str> { + let at = tag.find(&format!("{name}="))? + name.len() + 1; + let rest = &tag[at..]; + let q = rest.chars().next()?; + if q == '"' || q == '\'' { + let end = rest[1..].find(q)? + 1; + Some(&rest[1..end]) + } else { + let end = rest + .find(|c: char| c.is_whitespace() || c == '>') + .unwrap_or(rest.len()); + Some(&rest[..end]) + } +} + +fn same_target(href: &str, target: &str) -> bool { + let norm = |s: &str| s.trim_end_matches('/').to_ascii_lowercase(); + let (h, t) = (norm(href), norm(target)); + h == t || h.ends_with(&t) || (t.ends_with(&h) && !h.is_empty() && h.starts_with('/')) +} + +/// What the preview page's HTML says about a link expectation: the links +/// whose text is the label, and where they go. `None` when no link with +/// that text is on the page (it is drawn later, or in a drawer the page +/// opens): the page alone can't say. +pub fn check_page(page: &str, html: &str, e: &LinkExpectation) -> Option { + let lower = html.to_ascii_lowercase(); + let label = e.label.to_ascii_lowercase(); + let mut seen: Vec = Vec::new(); + let mut from = 0; + while let Some(i) = lower[from..].find("').map(|j| start + j) else { + break; + }; + let Some(close) = lower[tag_end..].find("").map(|j| tag_end + j) else { + break; + }; + let text = strip_tags(&html[tag_end + 1..close]).to_ascii_lowercase(); + let tag = &html[start..=tag_end]; + if text.contains(&label) + || attr(tag, "aria-label").is_some_and(|a| a.to_ascii_lowercase().contains(&label)) + { + if let Some(href) = attr(tag, "href") { + if same_target(href, &e.target) { + return Some(Verdict::Covered(format!( + "on {page}, the \"{}\" link goes to `{href}`", + e.label + ))); + } + seen.push(href.to_string()); + } + } + from = close + 4; + } + seen.first().map(|h| { + Verdict::NotCovered(format!( + "on {page}, the \"{}\" link goes to `{h}`, not `{}`", + e.label, e.target + )) + }) +} + +/// The description's related-tickets section: each criterion with what +/// checking it found. +pub fn section(results: &[(Criterion, Verdict)]) -> String { + if results.is_empty() { + return String::new(); + } + let mut s = format!("{MARKER}\n### Related tickets\n"); + for (c, v) in results { + let text = crate::truncate_str(c.text.trim(), 160); + match v { + Verdict::Covered(how) => { + s.push_str(&format!("- {}: {text}: covered ({how})\n", c.from)) + } + Verdict::NotCovered(why) => { + s.push_str(&format!("- {}: {text}: **not covered**: {why}\n", c.from)) + } + } + } + s +} + +/// `body` with its related-tickets section replaced by `section` (added at +/// the end when it has none; taken out when `section` is empty). +pub fn with_section(body: &str, section: &str) -> String { + let mut out: Vec<&str> = Vec::new(); + let mut skipping = false; + for line in body.lines() { + if line.trim() == MARKER { + skipping = true; + continue; + } + if skipping { + if line.trim() == "### Related tickets" || line.starts_with("- ") { + continue; + } + skipping = false; + } + out.push(line); + } + let kept = out.join("\n"); + if section.is_empty() { + return kept; + } + format!("{}\n\n{}\n", kept.trim_end(), section.trim_end()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn related_tickets_come_from_the_app_event() { + let p = serde_json::json!({"related": [ + {"key": "ABC-2", "relation": "relates to", "summary": "Drawer button", "status": "Closed", + "description": "{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"Links to /new\"}]}]}"}, + {"relation": "no key"} + ]}); + let r = from_payload(&p); + assert_eq!(r.len(), 1); + assert_eq!(r[0].key, "ABC-2"); + assert!(r[0].body.contains("Links to /new"), "{}", r[0].body); + assert!(from_payload(&serde_json::json!({})).is_empty()); + } + + #[test] + fn keys_named_in_text() { + assert_eq!( + keys_in_text( + "See ABC-12 and XY-3; not ABC-12 again, not abc-1, not OWN-1.", + "OWN-1" + ), + vec!["ABC-12", "XY-3"] + ); + } + + #[test] + fn criteria_under_their_heading() { + let t = "What & why\nChange the button.\n\nAcceptance criteria\n- The Register button links to /camps/register\n- Opens in the same tab\n\nNotes\n- not this\n"; + assert_eq!( + criteria(t), + vec![ + "The Register button links to /camps/register", + "Opens in the same tab" + ] + ); + } + + #[test] + fn a_moved_link_is_read_from_the_patch_and_checked_on_the_head() { + let patch = "@@ -10,3 +10,3 @@\n \n- \n+ \n \n"; + let m = moved_links("src/drawer.tsx", patch); + assert_eq!(m.len(), 1); + assert_eq!(m[0].from, "/old/register"); + assert_eq!(m[0].to, "/camps/register"); + let old = ""; + assert!(matches!( + check_source(&m[0], Some(old)), + Verdict::NotCovered(_) + )); + let new = ""; + assert!(matches!( + check_source(&m[0], Some(new)), + Verdict::Covered(_) + )); + } + + #[test] + fn a_link_criterion_is_checked_on_the_page() { + let e = + link_expectation("The drawer's \"Register\" button links to /camps/register").unwrap(); + assert_eq!(e.label, "Register"); + assert_eq!(e.target, "/camps/register"); + let old = r#""#; + assert!(matches!( + check_page("the preview", old, &e), + Some(Verdict::NotCovered(_)) + )); + let new = r#"Register"#; + assert!(matches!( + check_page("the preview", new, &e), + Some(Verdict::Covered(_)) + )); + assert_eq!(check_page("the preview", "

nothing

", &e), None); + } + + #[test] + fn the_section_replaces_itself() { + let c = Criterion { + from: "ABC-2".into(), + text: "Register links to /x".into(), + }; + let s1 = section(&[(c.clone(), Verdict::NotCovered("not checked".into()))]); + let b1 = with_section("## Summary\nx\n", &s1); + let s2 = section(&[(c, Verdict::Covered("ok".into()))]); + let b2 = with_section(&b1, &s2); + assert_eq!(b2.matches(MARKER).count(), 1, "{b2}"); + assert!( + b2.contains("covered (ok)") && !b2.contains("not checked"), + "{b2}" + ); + assert!(b2.starts_with("## Summary")); + } +} diff --git a/services/common/src/ticket_decisions.rs b/services/common/src/ticket_decisions.rs new file mode 100644 index 000000000..2c88fe8a3 --- /dev/null +++ b/services/common/src/ticket_decisions.rs @@ -0,0 +1,560 @@ +//! What a person answered on the ticket is a decision, in every run and on +//! every pull request for it. +//! +//! The failure this was written for: a run asked on its ticket for the +//! page's heading and intro copy, with a proposed default. The product +//! owner answered on the ticket ("Skip the heading and intro copy. Just use +//! the title."). That run took the answer as a round on its own pull +//! request. Two days later a new run on the same ticket opened a new pull +//! request: the answer was already marked handled, so the new run never +//! read it, built the intro anyway and listed it under "Decisions pending +//! product input". +//! +//! Now: +//! +//! - [`from_comments`]: every answer and instruction a person wrote on the +//! ticket is a decision for every run on it, whichever run handled it. +//! The worker merges them into the run's answers before triage and +//! planning, and before each round. +//! - [`settle`]: a description never lists an answered item as pending. An +//! item under a pending heading ("pending", "open questions", "awaiting +//! product") that an answer settles ([`answers_item`]: it shares the +//! question's words) is taken out, and the answer is listed under +//! "Decided on the ticket". When an answer goes against an acceptance +//! criterion of the ticket, one line says so ([`conflict`]). +//! - [`remember`] keeps a ticket's decisions for the description writer +//! (`description::save`), which knows the ticket from the description's +//! own "Ticket:" line ([`ticket_of`]). + +use crate::run_questions::Answer; +use crate::ticket_comments::{Class, Comment}; +use std::collections::{HashMap, HashSet}; +use std::sync::Mutex; + +/// The heading the answered items are listed under. +pub const DECIDED_HEADING: &str = "### Decided on the ticket"; + +/// Every answer or instruction a person wrote on the ticket, whatever run +/// read it and whatever state it is in, as answers (oldest first). +pub fn from_comments(comments: &[Comment]) -> Vec { + let mut sorted: Vec<&Comment> = comments + .iter() + .filter(|c| matches!(c.class, Some(Class::Answer) | Some(Class::Instruction))) + .filter(|c| !c.text.trim().is_empty()) + .collect(); + sorted.sort_by(|a, b| a.at.cmp(&b.at)); + sorted + .into_iter() + .map(|c| Answer { + question_id: format!("ticket-comment-{}", c.comment_id), + question: c.question.trim().to_string(), + answer: c.text.trim().to_string(), + author: c.author.clone(), + answered_at: c.at.clone(), + decision: String::new(), + }) + .collect() +} + +const STOP: &[&str] = &[ + "the", + "and", + "for", + "per", + "with", + "this", + "that", + "what", + "which", + "are", + "is", + "be", + "to", + "of", + "in", + "on", + "or", + "a", + "an", + "it", + "its", + "as", + "by", + "at", + "we", + "i", + "you", + "do", + "does", + "should", + "would", + "could", + "will", + "can", + "one", + "plus", + "default", + "proposed", + "building", + "now", + "different", + "answer", + "changes", + "change", + "use", + "using", + "final", + "pending", + "product", + "input", + "decision", + "decide", + "until", + "awaiting", + "yes", + "no", + "not", + "just", + "only", + "skip", +]; + +/// The words that carry meaning: lowercase, letters and digits, two or +/// more characters, no filler. +fn words(text: &str) -> HashSet { + text.split(|c: char| !c.is_alphanumeric()) + .map(|w| w.to_ascii_lowercase()) + .filter(|w| w.len() >= 2 && !STOP.contains(&w.as_str())) + .collect() +} + +/// Whether `a` settles the pending `item`: its question shares at least +/// two meaningful words with the item and half of the shorter's. +pub fn answers_item(item: &str, a: &Answer) -> bool { + let asked = if a.question.trim().is_empty() { + &a.answer + } else { + &a.question + }; + // The question's first sentence is what was asked; the rest is the + // proposal around it. + let head = asked.split(['?', '\n']).next().unwrap_or(asked).to_string(); + let q = words(&head); + let i = words(item); + if q.is_empty() || i.is_empty() { + return false; + } + let shared = q.intersection(&i).count(); + shared >= 2 && shared * 2 >= q.len().min(i.len()) +} + +/// Whether a heading names items that wait on someone's decision. +pub fn pending_heading(line: &str) -> bool { + let h = line + .trim() + .trim_start_matches('#') + .trim() + .trim_matches('*') + .trim() + .to_ascii_lowercase(); + if h.is_empty() || h.len() > 80 { + return false; + } + [ + "pending", + "open question", + "awaiting", + "needs product", + "product input", + "to decide", + "undecided", + "decisions needed", + "needs a decision", + "unresolved", + ] + .iter() + .any(|k| h.contains(k)) +} + +fn is_heading(line: &str) -> bool { + let t = line.trim(); + t.starts_with('#') || (t.starts_with("**") && t.ends_with("**") && t.len() > 4) +} + +fn list_item(line: &str) -> Option<&str> { + let t = line.trim_start(); + for p in ["- [ ] ", "- [x] ", "- ", "* ", "+ "] { + if let Some(rest) = t.strip_prefix(p) { + return Some(rest); + } + } + let digits = t.chars().take_while(|c| c.is_ascii_digit()).count(); + if digits > 0 && t[digits..].starts_with(". ") { + return Some(&t[digits + 2..]); + } + None +} + +/// Words that say an answer takes something out or does without it. +const WITHOUT: &[&str] = &[ + "skip", + "drop", + "remove", + "without", + "don't", + "do not", + "no ", + "omit", + "leave out", + "just use", + "only use", + "instead", +]; + +/// The one line on an answer that goes against an acceptance criterion: +/// the answer does without something a criterion asks for (they share two +/// meaningful words). `None` when no criterion is at odds with it. +pub fn conflict(a: &Answer, criteria: &[String]) -> Option { + let said = a.answer.to_ascii_lowercase(); + if !WITHOUT.iter().any(|w| said.contains(w)) { + return None; + } + let aw = words(&a.answer); + criteria.iter().find_map(|c| { + let shared = words(c).intersection(&aw).count(); + (shared >= 2).then(|| { + format!( + "The answer on the ticket (\"{}\") goes against the acceptance criterion \"{}\"; \ + the change follows the answer.", + crate::truncate_str(first_line(&a.answer), 120), + crate::truncate_str(c.trim(), 120) + ) + }) + }) +} + +fn first_line(s: &str) -> &str { + s.lines().next().unwrap_or(s).trim() +} + +/// A description with every answered item taken out of its pending lists. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Settled { + pub body: String, + /// The pending items taken out. + pub removed: Vec, +} + +/// Takes every item an answer settles out of the description's pending +/// sections (and a pending heading left with no item), and lists the +/// answers that settled them under [`DECIDED_HEADING`] with, for an answer +/// against an acceptance criterion, the one line that says so. +pub fn settle(body: &str, answers: &[Answer], criteria: &[String]) -> Settled { + if answers.is_empty() { + return Settled { + body: body.to_string(), + removed: Vec::new(), + }; + } + let lines: Vec<&str> = body.lines().collect(); + let mut keep = vec![true; lines.len()]; + let mut removed = Vec::new(); + let mut used: Vec = Vec::new(); + let mut i = 0; + while i < lines.len() { + if !(is_heading(lines[i]) && pending_heading(lines[i])) { + i += 1; + continue; + } + let head = i; + let mut items_left = 0; + let mut taken = 0; + let mut j = i + 1; + while j < lines.len() && !is_heading(lines[j]) { + if let Some(item) = list_item(lines[j]) { + match answers.iter().position(|a| answers_item(item, a)) { + Some(k) => { + keep[j] = false; + taken += 1; + removed.push(item.trim().to_string()); + if !used.contains(&k) { + used.push(k); + } + // The item's continuation lines go with it. + let mut c = j + 1; + while c < lines.len() + && !lines[c].trim().is_empty() + && list_item(lines[c]).is_none() + && !is_heading(lines[c]) + && lines[c].starts_with(" ") + { + keep[c] = false; + c += 1; + } + j = c; + continue; + } + None => items_left += 1, + } + } + j += 1; + } + if items_left == 0 && taken > 0 { + keep[head] = false; + // The blank lines and prose of an emptied section go too. + for (k, line) in lines.iter().enumerate().take(j).skip(head + 1) { + if list_item(line).is_none() { + keep[k] = false; + } + } + } + i = j; + } + if used.is_empty() { + return Settled { + body: body.to_string(), + removed, + }; + } + let mut out: Vec = lines + .iter() + .zip(&keep) + .filter(|(_, k)| **k) + .map(|(l, _)| l.to_string()) + .collect(); + let mut decided: Vec = Vec::new(); + for k in used { + let a = &answers[k]; + let asked = if a.question.is_empty() { + String::new() + } else { + format!( + "{}: ", + crate::truncate_str(a.question.split('?').next().unwrap_or("").trim(), 100) + ) + }; + let by = if a.author.trim().is_empty() { + String::new() + } else { + format!(" ({})", a.author.trim()) + }; + decided.push(format!( + "- {asked}\"{}\"{by}", + crate::truncate_str(first_line(&a.answer), 160) + )); + if let Some(c) = conflict(a, criteria) { + decided.push(format!("- {c}")); + } + } + match out.iter().position(|l| l.trim() == DECIDED_HEADING) { + Some(at) => { + let mut at = at + 1; + for d in decided { + if !out.contains(&d) { + out.insert(at, d); + at += 1; + } + } + } + None => { + while out.last().is_some_and(|l| l.trim().is_empty()) { + out.pop(); + } + out.push(String::new()); + out.push(DECIDED_HEADING.to_string()); + out.extend(decided); + } + } + let mut body_out = out.join("\n"); + if body.ends_with('\n') { + body_out.push('\n'); + } + Settled { + body: body_out, + removed, + } +} + +/// The ticket key a description names on its "Ticket:" line. +pub fn ticket_of(body: &str) -> Option { + for line in body.lines() { + let Some(rest) = line.trim().strip_prefix("Ticket:") else { + continue; + }; + let rest = rest.trim().trim_start_matches('['); + let key: String = rest + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '#') + .collect(); + if !key.is_empty() { + return Some(key.to_ascii_uppercase()); + } + } + None +} + +/// A ticket's decisions and acceptance criteria, as the worker last read +/// them, for [`settle`] where a description is written. +#[derive(Debug, Clone, Default)] +pub struct Known { + pub answers: Vec, + pub criteria: Vec, +} + +static KNOWN: Mutex>> = Mutex::new(None); + +/// The most tickets kept in memory at once. +const MAX_KNOWN: usize = 64; + +/// The key of a ticket's decisions: the GitHub App installation the run +/// writes with, its repository and the ticket. One team's decisions are +/// read back only by writes made with that team's own installation. +fn known_key(installation: u64, repo: &str, ticket: &str) -> String { + format!( + "{installation}:{}@{}", + repo.to_ascii_lowercase(), + ticket.to_ascii_uppercase() + ) +} + +/// Keeps `ticket`'s decisions for the descriptions written in `repo` with +/// `installation`. +pub fn remember(installation: u64, repo: &str, ticket: &str, known: Known) { + if ticket.trim().is_empty() { + return; + } + if let Ok(mut m) = KNOWN.lock() { + let m = m.get_or_insert_with(HashMap::new); + if m.len() >= MAX_KNOWN { + m.clear(); + } + m.insert(known_key(installation, repo, ticket), known); + } +} + +/// What [`remember`] kept for `ticket` in `repo`. +pub fn recall(installation: u64, repo: &str, ticket: &str) -> Option { + KNOWN + .lock() + .ok()? + .as_ref()? + .get(&known_key(installation, repo, ticket)) + .cloned() +} + +/// [`settle`] with what is known for the ticket the description names. +pub fn settle_known(installation: u64, repo: &str, body: &str) -> Settled { + let none = || Settled { + body: body.to_string(), + removed: Vec::new(), + }; + let Some(ticket) = ticket_of(body) else { + return none(); + }; + let Some(k) = recall(installation, repo, &ticket) else { + return none(); + }; + settle(body, &k.answers, &k.criteria) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn answer(q: &str, a: &str) -> Answer { + Answer { + question: q.into(), + answer: a.into(), + author: "a-person".into(), + ..Default::default() + } + } + + #[test] + fn an_answered_item_leaves_the_pending_list() { + let body = "## Summary\nAdds the page.\n\n### Decisions pending product input\n- Final heading and intro copy per venue: built with the default for now.\n- Analytics event names\n\n## Testing\n- unit tests\n"; + let a = answer( + "Final heading and intro copy per venue? Proposed default: '{Venue} Camp Registration'.", + "Skip the heading and intro copy. Just use the title", + ); + let s = settle(body, &[a], &[]); + assert!( + !s.body.contains("intro copy per venue: built"), + "{}", + s.body + ); + assert!(s.body.contains("Analytics event names")); + assert!(s.body.contains("### Decisions pending product input")); + assert!(s.body.contains(DECIDED_HEADING)); + assert_eq!(s.removed.len(), 1); + } + + #[test] + fn an_emptied_pending_section_goes() { + let body = "## Summary\nx\n\n**Open questions**\n- Heading and intro copy for each venue\n\n## Testing\n- ok\n"; + let a = answer( + "Heading and intro copy per venue?", + "Skip both, use the title", + ); + let s = settle(body, &[a], &[]); + assert!(!s.body.contains("Open questions"), "{}", s.body); + assert!(s.body.contains("## Testing")); + } + + #[test] + fn an_unrelated_answer_changes_nothing() { + let body = "### Pending\n- Analytics event names\n"; + let s = settle(body, &[answer("Which venue goes first?", "Venue A")], &[]); + assert_eq!(s.body, body); + } + + #[test] + fn an_answer_against_a_criterion_is_said_in_one_line() { + let a = answer( + "Heading and intro copy?", + "Skip the heading and intro copy. Just use the title", + ); + let c = conflict( + &a, + &["Each page shows a heading and intro copy above the portal".into()], + ) + .unwrap(); + assert!(c.contains("goes against the acceptance criterion"), "{c}"); + assert_eq!(c.lines().count(), 1); + assert!(conflict(&a, &["The portal loads at phone width".into()]).is_none()); + } + + #[test] + fn the_ticket_comes_from_the_description() { + assert_eq!( + ticket_of("Ticket: [ABC-12](https://x.atlassian.net/browse/ABC-12)\n").as_deref(), + Some("ABC-12") + ); + assert_eq!(ticket_of("no ticket").as_deref(), None); + } + + #[test] + fn every_answer_and_instruction_counts_whatever_run_handled_it() { + use crate::ticket_comments::State; + let c = |id: &str, class: Class, at: &str| Comment { + ticket_id: "ABC-1".into(), + comment_id: id.into(), + author: "a-person".into(), + text: format!("text {id}"), + at: at.into(), + run_id: "an-earlier-run".into(), + state: State::Handled, + class: Some(class), + ..Default::default() + }; + let got = from_comments(&[ + c("2", Class::Instruction, "2026-01-02"), + c("1", Class::Answer, "2026-01-01"), + c("3", Class::NotForCoderhelm, "2026-01-03"), + ]); + assert_eq!( + got.iter().map(|a| a.answer.as_str()).collect::>(), + ["text 1", "text 2"] + ); + } +} diff --git a/services/gateway/src/routes/jira_webhook.rs b/services/gateway/src/routes/jira_webhook.rs index c358db57a..4d6efec7a 100644 --- a/services/gateway/src/routes/jira_webhook.rs +++ b/services/gateway/src/routes/jira_webhook.rs @@ -794,6 +794,9 @@ async fn process_jira_payload( requester, image_attachments, ticket_type: common::messages::ticket_type_of_jira(issue), + // The tickets linked to this one: their criteria are part of the + // change (`related_tickets`). + related: common::related_tickets::from_payload(payload), ..Default::default() }); diff --git a/services/worker/src/models.rs b/services/worker/src/models.rs index eee30381b..6ed9a1099 100644 --- a/services/worker/src/models.rs +++ b/services/worker/src/models.rs @@ -323,6 +323,7 @@ mod tests { coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: None, }); let json = serde_json::to_string(&msg).unwrap(); diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index 8ed0fe504..3ff00e23b 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -61,6 +61,21 @@ pub async fn save( number: u64, body: &str, ) -> Result<(), Error> { + // An item a person answered on the ticket is a decision, never pending + // (`ticket_decisions`). + let settled = common::ticket_decisions::settle_known( + github.installation_id(), + &format!("{owner}/{repo}"), + body, + ); + if !settled.removed.is_empty() { + warn!( + pr_number = number, + items = ?settled.removed, + "The description listed answered items as pending; moved to the decisions" + ); + } + let body = settled.body.as_str(); let body = clean(body); // The final review, as its reader would read it: no running check as a // result, nothing CoderHelm can do handed to a person, nothing said diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index b206cdf11..4d398a406 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -1791,6 +1791,7 @@ pub(super) fn internal_ticket( coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: Some(run_id.to_string()), } } @@ -2010,6 +2011,7 @@ pub async fn act(state: &WorkerState, a: TestAction) -> Result<(), Err> { coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: None, }; enqueue(state, crate::models::WorkerMessage::Ticket(ticket)).await?; diff --git a/services/worker/src/passes/e2e_attribution.rs b/services/worker/src/passes/e2e_attribution.rs index 33689f4d4..8c27c3428 100644 --- a/services/worker/src/passes/e2e_attribution.rs +++ b/services/worker/src/passes/e2e_attribution.rs @@ -498,6 +498,7 @@ async fn start_fix( coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: None, }; let Ok(body) = serde_json::to_string(&crate::models::WorkerMessage::Ticket(ticket)) else { diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index ba32a647a..33f0e2ca7 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -726,6 +726,22 @@ Rules: comments = formatted, ci_failures = ci_failure_block, ); + // What people answered on the ticket is settled for this round too, and + // the description it may rewrite never lists it as pending. + let ticket_answers = super::ticket_comments::know_decisions( + state, + msg.installation_id, + &msg.team_id, + &ticket.0, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + "", + &[], + ) + .await; + let prompt = format!( + "{prompt}{}", + common::run_questions::answers_note(&ticket_answers) + ); // The branch update was done before this round and its answer is added // to the reply for the agent. let prompt = match &update_reply { @@ -3454,6 +3470,7 @@ async fn handle_wrong_repo( coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: None, }); @@ -4060,6 +4077,7 @@ fn run_ticket_message( coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: None, } } diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index f71fe1e3a..b47225709 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -272,6 +272,9 @@ pub async fn run( // (the snapshot reflects the branch, so the partial code is already visible). // A ticket update on an open PR uses the same slot: the branch already // holds work, and the agent must change it to match the new ticket. + // What people answered on the ticket is settled for every round, the + // build and each fix: never built against, never asked again. + let answers_note = common::run_questions::answers_note(&msg.answers); let continuation_note = if let Some(note) = msg.ticket_update_note.as_deref() { note } else if msg.continuation > 0 || msg.retry_of_run { @@ -324,6 +327,7 @@ pub async fn run( let conventions = super::load_git_conventions(state, &msg.team_id, &msg.ticket_id).await; let tokens = super::ticket_tokens(msg); let commit_hint = conventions.commit_hint(&tokens); + let issue_with_answers = format!("{issue_source_block}{answers_note}"); let prompt = task_prompt(&TaskPrompt { simple: complexity == "simple", number: msg.issue_number, @@ -333,7 +337,7 @@ pub async fn run( openspec: &openspec_block, files_hint: &files_hint, feedback: &feedback_section, - issue: &issue_source_block, + issue: &issue_with_answers, commit: &commit_hint, }); diff --git a/services/worker/src/passes/incidents/bm_teams_never_cross.rs b/services/worker/src/passes/incidents/bm_teams_never_cross.rs index 0acdebea9..3199c88c5 100644 --- a/services/worker/src/passes/incidents/bm_teams_never_cross.rs +++ b/services/worker/src/passes/incidents/bm_teams_never_cross.rs @@ -335,6 +335,7 @@ const CACHES: &[(&str, &str)] = &[ ("common/src/hybrid/client.rs::FAILING", "installation id"), ("common/src/knowledge/search.rs::C", "S3 key under `{team}/knowledge/`, checked by owns_key before the lookup"), ("common/src/knowledge/sources/pace.rs::GATES", "provider rate gate; no data"), + ("common/src/ticket_decisions.rs::KNOWN", "installation id plus `owner/repo@ticket`: read back only by description writes made with that installation"), ("common/src/reply_compose.rs::CACHE", "thread key plus a hash of the whole prompt it was written from"), ("common/src/review_check.rs::REFUSED", "installation id"), ("common/src/usage.rs::P", "model prices; install-wide config"), diff --git a/services/worker/src/passes/incidents/bz_ticket_answer_decides.rs b/services/worker/src/passes/incidents/bz_ticket_answer_decides.rs new file mode 100644 index 000000000..e9a2fe7c2 --- /dev/null +++ b/services/worker/src/passes/incidents/bz_ticket_answer_decides.rs @@ -0,0 +1,123 @@ +//! bz. A run asked on its ticket for a page's heading and intro copy, with +//! a proposed default. The product owner answered on the ticket: "Skip the +//! heading and intro copy. Just use the title." That run took the answer +//! as a round on its own pull request. Two days later a new run on the +//! same ticket opened a new pull request: the comment was already marked +//! handled, so the new run never read it, built the intro anyway and +//! listed it under "Decisions pending product input". +//! +//! Guarantee: every answer and instruction people wrote on the ticket is +//! a decision for every run on it, whichever run handled it: merged into +//! the run's answers before triage and planning, read again at each +//! boundary, and given to every coder round (the build and each fix) and +//! every feedback and resume round. Wherever a description is written +//! (`description::save`), an item the answers settle is taken out of the +//! pending lists and listed under "Decided on the ticket"; an answer that +//! goes against an acceptance criterion gets one line saying so. + +use common::run_questions::Answer; +use common::ticket_comments::{Class, Comment, State}; +use common::ticket_decisions::{ + from_comments, remember, settle, settle_known, Known, DECIDED_HEADING, +}; + +const QUESTION: &str = "Final heading and intro copy per venue? Proposed default: '{Venue} \ + Camp Registration' plus one portal sentence. I am building the default now; a different \ + answer changes it in src/utils/camp-portal-copy.ts."; + +/// The answer as it was kept: handled by the earlier run. +fn handled_answer() -> Comment { + Comment { + ticket_id: "ABC-76".into(), + comment_id: "98054".into(), + author: "a-product-owner".into(), + text: "Skip the H1 and intro copy. Just use the title\n Register for Camps | Example Site" + .into(), + at: "2026-01-14T16:16:36Z".into(), + run_id: "an-earlier-run".into(), + state: State::Handled, + class: Some(Class::Answer), + question: QUESTION.into(), + outcome: "applied as a round on the earlier pull request".into(), + handled_by: "an-earlier-run".into(), + ..Default::default() + } +} + +const DESCRIPTION: &str = "Ticket: [ABC-76](https://example.atlassian.net/browse/ABC-76) + +## Summary +Embeds the camp portal on the four registration pages. + +### Decisions pending product input +- Final H1 and intro copy per venue: built with the default '{Venue} Camp Registration' and one portal sentence until product confirms. +- Whether the portal opens in a new tab on phones + +## Testing +- Unit tests for the route and the embed +"; + +#[test] +fn an_answer_an_earlier_run_handled_is_still_the_answer() { + let answers = from_comments(&[handled_answer()]); + assert_eq!(answers.len(), 1); + assert_eq!(answers[0].question, QUESTION); + assert!(answers[0].answer.starts_with("Skip the H1")); + // The planner reads it as a resolved decision. + let note = common::run_questions::answers_note(&answers); + assert!(note.contains("Skip the H1"), "{note}"); +} + +#[test] +fn the_description_never_lists_an_answered_item_as_pending() { + let answers: Vec = from_comments(&[handled_answer()]); + let criteria = vec!["Each page shows an H1 and intro copy above the portal".to_string()]; + let s = settle(DESCRIPTION, &answers, &criteria); + assert!(!s.body.contains("until product confirms"), "{}", s.body); + // The unanswered item stays pending. + assert!(s.body.contains("opens in a new tab on phones")); + assert!(s.body.contains(DECIDED_HEADING)); + assert!(s.body.contains("Skip the H1 and intro copy")); + // The answer against the criterion is said in one line. + let conflict = s + .body + .lines() + .find(|l| l.contains("goes against the acceptance criterion")) + .expect("one line on the conflict"); + assert!(conflict.contains("H1 and intro copy above the portal")); +} + +#[test] +fn every_description_write_settles_with_what_the_run_knows() { + remember( + 7, + "acme/site", + "ABC-76", + Known { + answers: from_comments(&[handled_answer()]), + criteria: Vec::new(), + }, + ); + let s = settle_known(7, "acme/site", DESCRIPTION); + assert_eq!(s.removed.len(), 1); + // Another repository's description is not this ticket's. + assert!(settle_known(7, "acme/other", DESCRIPTION) + .removed + .is_empty()); + // Nor is another installation's (another team's). + assert!(settle_known(8, "acme/site", DESCRIPTION).removed.is_empty()); + + let save = include_str!("../description.rs"); + let at = save.find("pub async fn save(").unwrap(); + assert!(save[at..at + 900].contains("ticket_decisions::settle_known(")); + // Before triage and planning, at each boundary, and in the rounds that + // run outside the first step. + let passes = include_str!("../mod.rs"); + assert!( + passes.contains("ticket_comments::earlier_answers(state, &msg.team_id, &msg.ticket_id)") + ); + assert!(passes.contains("msg.answers = ticket_comments::know_decisions(")); + assert!(include_str!("../resume.rs").contains("super::ticket_comments::know_decisions(")); + assert!(include_str!("../feedback.rs").contains("super::ticket_comments::know_decisions(")); + assert!(include_str!("../implement.rs").contains("answers_note(&msg.answers)")); +} diff --git a/services/worker/src/passes/incidents/ca_related_ticket_covered.rs b/services/worker/src/passes/incidents/ca_related_ticket_covered.rs new file mode 100644 index 000000000..338c1d7ad --- /dev/null +++ b/services/worker/src/passes/incidents/ca_related_ticket_covered.rs @@ -0,0 +1,122 @@ +//! ca. A ticket's pull request was closed by a person who expected a +//! linked ticket's pull request to cover it. The pull request that was +//! kept never read the linked ticket: when it was called ready, the +//! drawer's Register button still pointed to the old address. +//! +//! Guarantee: the Jira app sends the ticket's issue links and the tickets +//! its text names, with their summaries and descriptions; the gateway +//! keeps them on the run's message, the planner reads their acceptance +//! criteria as part of the change, and the run keeps them. Before the pull +//! request is called ready, each address a pull request closed in favor of +//! this one moved is checked on the head's files, each link criterion is +//! checked on the preview page, and anything else is listed as not covered +//! with why, in the description's "Related tickets" section. + +use crate::passes::related::closed_in_favor; +use common::related_tickets::{ + check_page, check_source, criteria, fold, from_payload, link_expectation, moved_links, + plan_note, section, with_section, Verdict, MARKER, +}; +use serde_json::json; + +const DRAWER: &str = "src/components/nav/register-drawer.tsx"; + +/// The closed pull request's change: the drawer button to the new page. +const CLOSED_PATCH: &str = "@@ -18,7 +18,7 @@ export function RegisterDrawer() { + return ( + +- ++ + + ); +"; + +#[test] +fn the_linked_ticket_reaches_the_plan() { + let event = json!({"related": [{ + "key": "ABC-98", + "relation": "relates to", + "summary": "Drawer Register button goes to the new registration page", + "status": "Closed", + "description": "Acceptance criteria\n- The drawer's \"Register\" button links to /venue-a/summer-camps/register\n" + }]}); + let related = from_payload(&event); + assert_eq!(related.len(), 1); + let c = fold(&related); + assert_eq!(c.len(), 1); + assert_eq!(c[0].from, "ABC-98"); + let note = plan_note(&related); + assert!(note.contains("ABC-98 (relates to)"), "{note}"); + assert!(note.contains("links to /venue-a/summer-camps/register")); + assert_eq!( + criteria("Acceptance criteria\n- one\n- two\n\nNotes\n- not one"), + ["one", "two"] + ); +} + +#[test] +fn the_head_still_pointing_at_the_old_address_is_not_covered() { + let timeline = json!([{"event": "cross-referenced", "source": {"issue": { + "number": 1531, "title": "Drawer Register button to the new page", "state": "closed", + "pull_request": {"merged_at": null}, "repository": {"full_name": "acme/site"}}}}]); + assert_eq!(closed_in_favor(&timeline, "acme/site")[0].0, 1531); + let moves = moved_links(DRAWER, CLOSED_PATCH); + assert_eq!(moves.len(), 1); + let head = ""; + let v = check_source(&moves[0], Some(head)); + match &v { + Verdict::NotCovered(why) => assert!(why.contains("still uses"), "{why}"), + other => panic!("{other:?}"), + } + let fixed = ""; + assert!(matches!( + check_source(&moves[0], Some(fixed)), + Verdict::Covered(_) + )); +} + +#[test] +fn a_link_criterion_is_checked_on_the_preview_and_the_rest_is_listed() { + let e = link_expectation( + "The drawer's \"Register\" button links to /venue-a/summer-camps/register", + ) + .unwrap(); + let old = r#""#; + assert!(matches!( + check_page("the preview", old, &e), + Some(Verdict::NotCovered(_)) + )); + let c = fold(&from_payload( + &json!({"related": [{"key": "ABC-98", "description": + "Acceptance criteria\n- The drawer's \"Register\" button links to /venue-a/summer-camps/register"}]}), + )); + let s = section(&[( + c[0].clone(), + Verdict::NotCovered("not checked: no preview".into()), + )]); + assert!(s.starts_with(MARKER)); + assert!( + s.contains("**not covered**: not checked: no preview"), + "{s}" + ); + let body = with_section("## Summary\nx\n", &s); + assert_eq!(with_section(&body, &s).matches(MARKER).count(), 1); +} + +#[test] +fn ready_checks_them_and_the_jira_app_sends_them() { + let ready = include_str!("../ready.rs"); + assert!(ready.contains("related_section(ctx, &pr, f.preview.as_ref())")); + let passes = include_str!("../mod.rs"); + assert!(passes.contains("related::keep(state, &msg.team_id, run_id, &msg.related)")); + let plan = include_str!("../plan.rs"); + assert_eq!( + plan.matches("related_tickets::plan_note(&msg.related)") + .count(), + 2 + ); + let gateway = include_str!("../../../../gateway/src/routes/jira_webhook.rs"); + assert!(gateway.contains("related: common::related_tickets::from_payload(payload)")); + let app = include_str!("../../../../../coderhelm-jira/src/index.js"); + assert!(app.contains("issuelinks") && app.contains("relatedTickets(issue.key, fields")); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 5148e3b6f..a1fa13aa1 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -60,7 +60,9 @@ mod br_description_writer_upgrade; mod bs_cut_plan_revision; mod bt_proof_answer_closes; mod bu_web_change_unchecked; +mod bz_ticket_answer_decides; mod c_codegen_egress; +mod ca_related_ticket_covered; mod d_echoed_markers; mod e_large_generated_output; mod f_steps; diff --git a/services/worker/src/passes/log_autofix.rs b/services/worker/src/passes/log_autofix.rs index 13e2f3398..fe1d6c0af 100644 --- a/services/worker/src/passes/log_autofix.rs +++ b/services/worker/src/passes/log_autofix.rs @@ -135,6 +135,7 @@ impl StartEnv for WorkerEnv<'_> { coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: None, }); let body = serde_json::to_string(&msg).map_err(|e| e.to_string())?; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 456a62a82..6323018f0 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1349,6 +1349,7 @@ pub mod quarantine_work; /// Whether a finished run's pull request leaves draft, decided in one place. pub mod ready; pub mod recheck; +pub mod related; pub mod relay_retry; pub mod release_notes; pub mod release_plan; @@ -1899,6 +1900,18 @@ async fn read_ticket_comments( ) -> Result<(), Box> { let read = ticket_comments::at_boundary(state, msg, run_id, usage).await; common::run_questions::merge(&mut msg.answers, &read.folded); + // Before the next build or round and before any description: the + // ticket's answers are decisions, never pending items. + msg.answers = ticket_comments::know_decisions( + state, + msg.installation_id, + &msg.team_id, + &msg.ticket_id, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + &msg.body, + &msg.answers, + ) + .await; if read.stopped { // The text `orchestrate_ticket` reads as a person's cancel. return Err("Run cancelled by user".into()); @@ -2087,6 +2100,15 @@ async fn run_passes( .map(common::ticket_state::decision_answer) .collect(); common::run_questions::merge(&mut msg.answers, &decided); + // And every answer people wrote on the ticket itself, whichever earlier + // run handled it: an answer handled by the run before this one is + // still the answer (a new run once built what an answer had ruled out + // and listed it as pending). + let earlier = ticket_comments::earlier_answers(state, &msg.team_id, &msg.ticket_id).await; + common::run_questions::merge(&mut msg.answers, &earlier); + // The linked tickets' acceptance criteria are this run's too: kept so + // the pull request is checked against them before it is called ready. + related::keep(state, &msg.team_id, run_id, &msg.related).await; // What people wrote on the ticket itself: before this run started // (context for the plan) and since its last step. Read here, before // the run spends more work, and again at each boundary below. diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 40e1dedf3..8b4f74812 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -474,9 +474,12 @@ Then the ```fix_location.json block described above."#, Some(h) if !h.trim().is_empty() => format!("{prompt}{h}"), _ => prompt, }; + // The tickets linked to this one: their acceptance criteria are part + // of the change (`related_tickets`). let prompt = format!( - "{prompt}{}", - common::run_questions::answers_note(&msg.answers) + "{prompt}{}{}", + common::run_questions::answers_note(&msg.answers), + common::related_tickets::plan_note(&msg.related) ); // One part of a numbered series: the other parts' pull requests, so // the plan builds on them (see `series`). @@ -901,9 +904,10 @@ Then the ```fix_location.json block described above."#, super::plan_judge::prompt( &msg.title, &format!( - "{}{}", + "{}{}{}", msg.body, - common::run_questions::answers_note(&msg.answers) + common::run_questions::answers_note(&msg.answers), + common::related_tickets::plan_note(&msg.related) ), history_note, &live.as_ref().map(|l| l.connected()).unwrap_or_default(), diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index 809c4ceda..c8efc2173 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -1082,6 +1082,15 @@ async fn gather(ctx: &Ctx<'_>) -> Result { f.draft = pr["draft"].as_bool().unwrap_or(f.draft); f.body = pr["body"].as_str().unwrap_or("").to_string(); f.title = pr["title"].as_str().unwrap_or("").to_string(); + // Before it is called ready: each criterion of the linked tickets, and + // each address a pull request closed in favor of this one moved, is + // checked where it can be or listed as not covered with why. + if f.draft && !f.closed { + let section = related_section(ctx, &pr, f.preview.as_ref()).await; + if !section.is_empty() || f.body.contains(common::related_tickets::MARKER) { + f.body = common::related_tickets::with_section(&f.body, §ion); + } + } f.security = f.body.contains(common::security_fixes::MARKER); if reads_ci(&f) { let sha = pr["head"]["sha"].as_str().unwrap_or(""); @@ -1115,6 +1124,40 @@ async fn gather(ctx: &Ctx<'_>) -> Result { Ok(f) } +/// The description's related-tickets section for the head +/// (`passes::related`): empty when the run took on no criterion and no +/// pull request was closed in favor of this one. +async fn related_section( + ctx: &Ctx<'_>, + pr: &serde_json::Value, + preview: Option<&common::preview::State>, +) -> String { + 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 + .unwrap_or_default() + } else { + ctx.run_id.clone() + }; + let criteria = if run_id.is_empty() { + Vec::new() + } else { + super::related::kept(ctx.state, ctx.team_id, &run_id).await + }; + let results = super::related::check( + ctx.state, + ctx.github, + ctx.owner, + ctx.repo, + ctx.pr, + pr["head"]["sha"].as_str().unwrap_or(""), + preview.map(|p| p.url.as_str()).unwrap_or(""), + &criteria, + ) + .await; + common::related_tickets::section(&results) +} + /// 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 { diff --git a/services/worker/src/passes/related.rs b/services/worker/src/passes/related.rs new file mode 100644 index 000000000..e388918dd --- /dev/null +++ b/services/worker/src/passes/related.rs @@ -0,0 +1,215 @@ +//! The worker's side of related tickets (`common::related_tickets`): the +//! run keeps the criteria it took on from linked tickets, and before its +//! pull request is called ready each one, and each address change of a +//! pull request closed in favor of it, is checked where it can be, or +//! listed as not covered with why. + +use crate::clients::github::GitHubClient; +use crate::passes::attr_s; +use crate::WorkerState; +use common::related_tickets::{self as rt, Criterion, Verdict}; +use tracing::warn; + +/// The run record's field holding the criteria taken on from related +/// tickets (JSON). +pub const FIELD: &str = "related_criteria"; + +/// Keeps the criteria of `related` on the run (nothing when none). +pub async fn keep(state: &WorkerState, team_id: &str, run_id: &str, related: &[rt::Related]) { + let criteria = rt::fold(related); + if criteria.is_empty() { + return; + } + let Ok(json) = serde_json::to_string(&criteria) else { + return; + }; + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET #f = :v") + .expression_attribute_names("#f", FIELD) + .expression_attribute_values(":v", attr_s(&json)) + .send() + .await + { + warn!(run_id, error = %e, "Could not keep the related tickets' criteria"); + } +} + +/// The criteria the run took on from related tickets. +pub async fn kept(state: &WorkerState, team_id: &str, run_id: &str) -> Vec { + 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", FIELD) + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| i.get(FIELD).and_then(|v| v.as_s().ok()).cloned()) + .and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_default() +} + +/// The pull requests in a timeline that were closed in favor of this one: +/// in this repository, they link this pull request and were closed without +/// merging. (number, title). +pub fn closed_in_favor(timeline: &serde_json::Value, repo_full: &str) -> Vec<(u64, String)> { + let mut out: Vec<(u64, String)> = Vec::new(); + for e in timeline.as_array().into_iter().flatten() { + if e["event"].as_str() != Some("cross-referenced") { + continue; + } + let i = &e["source"]["issue"]; + let same_repo = i["repository"]["full_name"] + .as_str() + .is_none_or(|r| r.eq_ignore_ascii_case(repo_full)); + let closed_unmerged = i["state"].as_str() == Some("closed") + && i["pull_request"].is_object() + && i["pull_request"]["merged_at"].is_null(); + if let (true, true, Some(n)) = (same_repo, closed_unmerged, i["number"].as_u64()) { + if !out.iter().any(|(m, _)| *m == n) { + out.push((n, i["title"].as_str().unwrap_or("").to_string())); + } + } + } + out +} + +/// The most closed pull requests and address moves read for one check. +const MAX_CLOSED: usize = 3; +const MAX_MOVES: usize = 8; + +/// Every criterion with what checking it found: the address moves of the +/// pull requests closed in favor of this one, on the head's files; the +/// related tickets' link criteria, on the preview page; anything else +/// listed as not covered with why. +#[allow(clippy::too_many_arguments)] +pub async fn check( + state: &WorkerState, + gh: &GitHubClient, + owner: &str, + repo: &str, + pr: u64, + head: &str, + preview_url: &str, + criteria: &[Criterion], +) -> Vec<(Criterion, Verdict)> { + let mut out = Vec::new(); + let timeline = gh + .list_issue_timeline(owner, repo, pr) + .await + .unwrap_or_default(); + for (n, title) in closed_in_favor(&timeline, &format!("{owner}/{repo}")) + .into_iter() + .take(MAX_CLOSED) + { + let files = gh.list_pull_files(owner, repo, n).await.unwrap_or_default(); + let moves: Vec = files + .iter() + .flat_map(|(path, patch)| rt::moved_links(path, patch)) + .take(MAX_MOVES) + .collect(); + if moves.is_empty() { + out.push(( + Criterion { + from: format!("#{n}"), + text: title.clone(), + }, + Verdict::NotCovered( + "closed in favor of this pull request; not checked: its change moves no \ + address this check can compare" + .into(), + ), + )); + continue; + } + for m in moves { + let content = gh + .read_file_if_exists(owner, repo, &m.path, head) + .await + .ok() + .flatten(); + let v = rt::check_source(&m, content.as_deref()); + out.push(( + Criterion { + from: format!("#{n}"), + text: format!("`{}` goes to `{}` ({})", m.path, m.to, title.trim()), + }, + v, + )); + } + } + let wants_page = criteria + .iter() + .any(|c| rt::link_expectation(&c.text).is_some()); + let page = if wants_page && preview_url.starts_with("https://") { + fetch(state, preview_url).await + } else { + None + }; + for c in criteria { + let v = match (rt::link_expectation(&c.text), &page) { + (Some(e), Some(html)) => rt::check_page("the preview", html, &e).unwrap_or_else(|| { + Verdict::NotCovered(format!( + "not checked: the preview page shows no \"{}\" link (it may open in a drawer or \ + load later)", + e.label + )) + }), + (Some(_), None) => { + Verdict::NotCovered("not checked: no preview of this pull request to load".into()) + } + (None, _) => Verdict::NotCovered( + "not checked: it names no link or address a check can load".into(), + ), + }; + out.push((c.clone(), v)); + } + out +} + +/// The preview page's HTML (a page of at most 2 MB), `None` when it can't +/// be loaded. +async fn fetch(state: &WorkerState, url: &str) -> Option { + let resp = state + .http + .get(url) + .timeout(std::time::Duration::from_secs(20)) + .send() + .await + .ok()?; + if !resp.status().is_success() { + return None; + } + let text = resp.text().await.ok()?; + Some(text.chars().take(2_000_000).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn a_pull_request_closed_unmerged_that_links_this_one_is_in_favor_of_it() { + let t = json!([ + {"event": "cross-referenced", "source": {"issue": {"number": 12, "title": "Point the drawer button to the new page", "state": "closed", "pull_request": {"merged_at": null}, "repository": {"full_name": "acme/site"}}}}, + {"event": "cross-referenced", "source": {"issue": {"number": 13, "state": "closed", "pull_request": {"merged_at": "2026-01-01"}, "repository": {"full_name": "acme/site"}}}}, + {"event": "cross-referenced", "source": {"issue": {"number": 14, "state": "open", "pull_request": {"merged_at": null}, "repository": {"full_name": "acme/site"}}}}, + {"event": "cross-referenced", "source": {"issue": {"number": 15, "state": "closed", "repository": {"full_name": "acme/site"}}}}, + {"event": "labeled"} + ]); + assert_eq!( + closed_in_favor(&t, "acme/site"), + vec![(12, "Point the drawer button to the new page".to_string())] + ); + } +} diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 387a12031..767d716bb 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -3955,7 +3955,19 @@ async fn fix_context( .await, coder_learning: String::new(), person_direction: None, - answers: Vec::new(), + // What people answered on the ticket: every fix and review round + // builds with it, and the description never lists it as pending. + answers: super::ticket_comments::know_decisions( + state, + msg.installation_id, + &msg.team_id, + t.ticket_id, + &format!("{}/{}", t.owner, t.repo), + "", + &[], + ) + .await, + related: Vec::new(), new_run_id: None, }; diff --git a/services/worker/src/passes/ticket_comments.rs b/services/worker/src/passes/ticket_comments.rs index fc3dfd2db..d70ff8f84 100644 --- a/services/worker/src/passes/ticket_comments.rs +++ b/services/worker/src/passes/ticket_comments.rs @@ -33,6 +33,54 @@ use common::ticket_comments::{self as tc, Action, Comment, Settled, Source, Stag use common::ticket_state::{Intent, Note}; use tracing::{info, warn}; +/// Every answer and instruction people wrote on the ticket, whatever run +/// handled it (`common::ticket_decisions::from_comments`): a new run on the +/// ticket starts from them, never from the question again. +pub async fn earlier_answers(state: &WorkerState, team_id: &str, ticket_id: &str) -> Vec { + match store(state).of_ticket(team_id, ticket_id).await { + Ok(c) => common::ticket_decisions::from_comments(&c), + Err(e) => { + warn!(ticket_id, error = %e, "Could not read the ticket's earlier answers"); + Vec::new() + } + } +} + +/// Keeps the ticket's decisions and acceptance criteria where the +/// description is written (`description::save`), so no description lists +/// an answered item as pending. `answers`: those already in hand; the +/// ticket's own are read and added. +pub async fn know_decisions( + state: &WorkerState, + installation_id: u64, + team_id: &str, + ticket_id: &str, + repo: &str, + ticket_body: &str, + answers: &[Answer], +) -> Vec { + let mut all = answers.to_vec(); + common::run_questions::merge(&mut all, &earlier_answers(state, team_id, ticket_id).await); + // A caller without the ticket's text keeps the criteria read before. + let criteria = if ticket_body.trim().is_empty() { + common::ticket_decisions::recall(installation_id, repo, ticket_id) + .map(|k| k.criteria) + .unwrap_or_default() + } else { + common::related_tickets::criteria(ticket_body) + }; + common::ticket_decisions::remember( + installation_id, + repo, + ticket_id, + common::ticket_decisions::Known { + answers: all.clone(), + criteria, + }, + ); + all +} + /// What a boundary read gives the run. #[derive(Debug, Default)] pub struct Read {