From 320d640cd4f45e003f6fa138c55b92370540b6b0 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 17 Nov 2026 11:39:19 -0500 Subject: [PATCH 1/2] End-to-end selectors come from a live probe; untaken test branches are labelled; writes carry only the fix's lines A vendor-portal spec's registration-open branch was written from test-id strings found in the vendor's script bundle after the shell refused a Playwright probe. Only the closed branch ever ran, and a later run kept it and re-wrapped lines no formatter checks. The review's probe gate read only added, single-line getByTestId calls and ran only in the reviewer. - common::e2e::probe reads wrapped and pattern ids, holds kept ids too, treats framed pages as outside, and records states and clicks. - common::e2e::branches finds test branches on page state and which arm a report or a probe would take. - common::diff_shape tells and puts back formatting-only hunks. - worker::live_guard refuses coder writes with unprobed outside ids or only formatting, commits probe records, and feeds the habits check. --- .../cv_portal_branch_from_a_guess.md | 5 + services/common/src/diff_shape.rs | 428 +++++++++++ services/common/src/e2e/branches.rs | 557 ++++++++++++++ services/common/src/e2e/mod.rs | 5 + services/common/src/e2e/probe.rs | 503 +++++++++++-- services/common/src/lib.rs | 3 + services/worker/src/passes/feedback.rs | 17 + services/worker/src/passes/habits_check.rs | 15 + services/worker/src/passes/implement.rs | 116 ++- .../cv_portal_branch_from_a_guess.rs | 292 ++++++++ services/worker/src/passes/live_guard.rs | 708 ++++++++++++++++++ services/worker/src/passes/mod.rs | 12 +- services/worker/src/passes/web_check.rs | 155 ++-- 13 files changed, 2679 insertions(+), 137 deletions(-) create mode 100644 docs/incidents/cv_portal_branch_from_a_guess.md create mode 100644 services/common/src/diff_shape.rs create mode 100644 services/common/src/e2e/branches.rs create mode 100644 services/worker/src/passes/incidents/cv_portal_branch_from_a_guess.rs create mode 100644 services/worker/src/passes/live_guard.rs diff --git a/docs/incidents/cv_portal_branch_from_a_guess.md b/docs/incidents/cv_portal_branch_from_a_guess.md new file mode 100644 index 000000000..440477f35 --- /dev/null +++ b/docs/incidents/cv_portal_branch_from_a_guess.md @@ -0,0 +1,5 @@ +# cv. `cv_portal_branch_from_a_guess` + +**What happened:** A camp registration page embeds a vendor's portal in a frame. The run that added it wrote an end-to-end page object with two branches on the portal's state: registration closed (the camp's button disabled, it must say so) and registration open (choosing the camp must fill the cart). Its coder tried to load the portal with Playwright, the shell refused the command, and it wrote the open branch from test-id strings found in the vendor's script bundle. Only the closed branch ever ran. The next ticket's run edited the same file, kept the branch untouched, and re-wrapped a test's lines no formatter checks. The day the vendor opened registration the open branch failed on every branch: a signed-out visitor who picks a camp gets the vendor's sign-in drawer and the cart stays at $0. The review's probe gate saw none of it: it read only added lines, and only `getByTestId('…')` written on one line, so the page object's wrapped and pattern ids were invisible to it. + +**The guarantee:** An end-to-end file that drives another company's page (named by its host, or in a frame) carries only test ids a probe of that page saw, the ones a write adds and the ones it keeps, wrapped or written as patterns (`common::e2e::probe`). In every coder round the write is refused until the `probe_page` tool has run, and the round commits the record (`live_guard`). The probe clicks through the states a branch reads and lists each test id's state and what each click brings up, and the pull request quotes it. Each arm of a test branch on the page's state is labelled unverified in the pull request until a run takes it (`common::e2e::branches`); when a fresh probe shows the page in the state an arm needs, the coder is sent to run it against the live page. A write that only reformats a file is not made, a write's formatting hunks are put back where CI doesn't check formatting (`common::diff_shape`), and a file only reformatted on the branch goes back after the build. diff --git a/services/common/src/diff_shape.rs b/services/common/src/diff_shape.rs new file mode 100644 index 000000000..5d4a07a22 --- /dev/null +++ b/services/common/src/diff_shape.rs @@ -0,0 +1,428 @@ +//! A diff holds the lines the change needs, not a formatter's opinion. +//! +//! A pull request whose fix was a few lines also re-wrapped calls and +//! re-quoted strings in end-to-end files the repository keeps unformatted +//! and its CI never checks, so a reviewer read formatting churn to find the +//! fix. The rules: +//! +//! - [`format_only`] tells a change that is only formatting: the two texts +//! read the same once whitespace outside strings, quote style and +//! trailing commas are set aside (indentation stays meaningful in Python, +//! YAML and Makefiles, where only trailing spaces and blank lines are). +//! - [`drop_format_hunks`] puts back each hunk of a change that is only +//! formatting, keeping the hunks that change something. +//! - [`ci_formats`] says whether the repository's CI checks the formatting +//! of a path (`prettier --check`, `cargo fmt --check`, ...): only there +//! may the formatter's lines ride along, and only in files the change +//! touches anyway. + +/// How a file's text is compared for formatting. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Lang { + /// Braces and semicolons carry the structure: whitespace outside + /// strings is formatting. + Braces, + /// Indentation is structure: only trailing spaces and blank lines are + /// formatting. + Indent, + /// Prose and anything else: trailing spaces, blank lines at the end. + Text, +} + +fn ext(path: &str) -> String { + let name = path.rsplit('/').next().unwrap_or(path); + if name == "Makefile" || name == "Dockerfile" { + return name.to_ascii_lowercase(); + } + name.rsplit_once('.') + .map(|(_, e)| e.to_ascii_lowercase()) + .unwrap_or_default() +} + +fn lang(path: &str) -> Lang { + match ext(path).as_str() { + "js" | "jsx" | "ts" | "tsx" | "mjs" | "cjs" | "mts" | "cts" | "json" | "css" | "scss" + | "less" | "rs" | "go" | "java" | "kt" | "c" | "h" | "cc" | "cpp" | "hpp" | "cs" + | "swift" | "php" | "tf" | "hcl" | "graphql" | "gql" | "vue" | "svelte" => Lang::Braces, + "py" | "yaml" | "yml" | "makefile" | "toml" | "ini" | "cfg" => Lang::Indent, + _ => Lang::Text, + } +} + +/// Whether a semicolon is optional punctuation in the language (so a +/// formatter adds or drops it). +fn optional_semicolons(path: &str) -> bool { + matches!( + ext(path).as_str(), + "js" | "jsx" | "ts" | "tsx" | "mjs" | "cjs" | "mts" | "cts" | "vue" | "svelte" + ) +} + +/// Whether `'` and `"` delimit the same strings in the language. +fn same_quotes(path: &str) -> bool { + matches!( + ext(path).as_str(), + "js" | "jsx" + | "ts" + | "tsx" + | "mjs" + | "cjs" + | "mts" + | "cts" + | "vue" + | "svelte" + | "py" + | "css" + | "scss" + | "less" + | "yaml" + | "yml" + ) +} + +/// The text with formatting set aside: what two versions that differ only +/// in formatting share. +fn canonical(path: &str, text: &str) -> String { + match lang(path) { + Lang::Braces => braces(path, text), + Lang::Indent => text + .lines() + .map(|l| { + let l = l.trim_end(); + if same_quotes(path) { + l.replace('\'', "\"") + } else { + l.to_string() + } + }) + .filter(|l| !l.is_empty()) + .collect::>() + .join("\n"), + Lang::Text => text + .lines() + .map(str::trim_end) + .collect::>() + .join("\n") + .trim_end() + .to_string(), + } +} + +fn braces(path: &str, text: &str) -> String { + let quotes = same_quotes(path); + let semis = optional_semicolons(path); + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars().peekable(); + let mut in_str: Option = None; + while let Some(c) = chars.next() { + if let Some(q) = in_str { + if c == '\\' { + out.push(c); + if let Some(n) = chars.next() { + out.push(n); + } + continue; + } + if c == q { + in_str = None; + out.push(if quotes && q == '\'' { '"' } else { c }); + continue; + } + out.push(c); + continue; + } + match c { + '\'' | '"' | '`' => { + in_str = Some(c); + out.push(if quotes && c == '\'' { '"' } else { c }); + } + c if c.is_whitespace() => { + // Space between two words is still a separator (`return x` + // is not `returnx`); anywhere else it is formatting. + while chars.peek().is_some_and(|n| n.is_whitespace()) { + chars.next(); + } + let word = |ch: Option| { + ch.is_some_and(|ch| ch.is_alphanumeric() || ch == '_' || ch == '$') + }; + if word(out.chars().next_back()) && word(chars.peek().copied()) { + out.push(' '); + } + } + ';' if semis => {} + ',' => { + // A trailing comma before a closing bracket is formatting. + let mut ahead = chars.clone(); + let next = loop { + match ahead.next() { + Some(n) if n.is_whitespace() => continue, + other => break other, + } + }; + if !matches!(next, Some(')' | ']' | '}')) { + out.push(','); + } + } + // A line comment's end is its newline: keep one, or two + // comments joined would read the same as one. + '/' if chars.peek() == Some(&'/') => { + for n in chars.by_ref() { + if n == '\n' { + break; + } + out.push(n); + } + out.push('/'); + out.push('\n'); + } + _ => out.push(c), + } + } + out +} + +/// Whether `new` differs from `old` only in formatting. +pub fn format_only(path: &str, old: &str, new: &str) -> bool { + old != new && canonical(path, old) == canonical(path, new) +} + +/// Lines with their newlines, so joining them gives the text back. +fn lines(text: &str) -> Vec<&str> { + text.split_inclusive('\n').collect() +} + +/// The longest common subsequence's pairs of line indexes, or `None` when +/// the middle that differs is too large to compare line by line. +fn matching(a: &[&str], b: &[&str]) -> Option> { + const MAX_CELLS: usize = 4_000_000; + let mut pre = 0; + while pre < a.len() && pre < b.len() && a[pre] == b[pre] { + pre += 1; + } + let mut suf = 0; + while suf < a.len() - pre && suf < b.len() - pre && a[a.len() - 1 - suf] == b[b.len() - 1 - suf] + { + suf += 1; + } + let (am, bm) = (&a[pre..a.len() - suf], &b[pre..b.len() - suf]); + if am.len().saturating_mul(bm.len()) > MAX_CELLS { + return None; + } + let (n, m) = (am.len(), bm.len()); + let mut dp = vec![0u32; (n + 1) * (m + 1)]; + for i in (0..n).rev() { + for j in (0..m).rev() { + dp[i * (m + 1) + j] = if am[i] == bm[j] { + dp[(i + 1) * (m + 1) + j + 1] + 1 + } else { + dp[(i + 1) * (m + 1) + j].max(dp[i * (m + 1) + j + 1]) + }; + } + } + let mut pairs: Vec<(usize, usize)> = (0..pre).map(|k| (k, k)).collect(); + let (mut i, mut j) = (0, 0); + while i < n && j < m { + if am[i] == bm[j] { + pairs.push((pre + i, pre + j)); + i += 1; + j += 1; + } else if dp[(i + 1) * (m + 1) + j] >= dp[i * (m + 1) + j + 1] { + i += 1; + } else { + j += 1; + } + } + for k in 0..suf { + pairs.push((a.len() - suf + k, b.len() - suf + k)); + } + Some(pairs) +} + +/// `new` with each hunk that only reformats put back as it was in `old`, +/// and how many were put back. `new` unchanged when the texts are too far +/// apart to compare line by line. +pub fn drop_format_hunks(path: &str, old: &str, new: &str) -> (String, usize) { + if format_only(path, old, new) { + return (old.to_string(), 1); + } + let (a, b) = (lines(old), lines(new)); + let Some(pairs) = matching(&a, &b) else { + return (new.to_string(), 0); + }; + let mut out = String::with_capacity(new.len()); + let mut dropped = 0; + let (mut i, mut j) = (0, 0); + let mut hunk = |ai: std::ops::Range, bj: std::ops::Range, out: &mut String| { + let (text, n) = shape_hunk(path, &a[ai], &b[bj]); + dropped += n; + out.push_str(&text); + }; + for (pi, pj) in pairs { + hunk(i..pi, j..pj, &mut out); + out.push_str(b[pj]); + i = pi + 1; + j = pj + 1; + } + hunk(i..a.len(), j..b.len(), &mut out); + (out, dropped) +} + +/// One changed hunk, `a` (old lines) against `b` (new lines): the text it +/// keeps and how many parts of it were only formatting and went back. A +/// hunk that reformats lines and changes others is split where the +/// reformatted lines end or begin. +fn shape_hunk(path: &str, a: &[&str], b: &[&str]) -> (String, usize) { + const MAX_PAIRS: usize = 1600; + if a.is_empty() && b.is_empty() { + return (String::new(), 0); + } + let blank = |l: &[&str]| l.iter().all(|x| x.trim().is_empty()); + if blank(a) && blank(b) { + // Blank lines added or taken away: formatting. + return (a.concat(), 1); + } + if a.is_empty() || b.is_empty() { + return (b.concat(), 0); + } + let same = |x: &[&str], y: &[&str]| { + let cx = canonical(path, &x.concat()); + !cx.is_empty() && cx == canonical(path, &y.concat()) + }; + if same(a, b) { + return (a.concat(), 1); + } + if a.len() * b.len() > MAX_PAIRS { + return (b.concat(), 0); + } + for x in 1..=a.len() { + for y in 1..=b.len() { + if (x, y) == (a.len(), b.len()) || !same(&a[..x], &b[..y]) { + continue; + } + let (rest, n) = shape_hunk(path, &a[x..], &b[y..]); + return (format!("{}{rest}", a[..x].concat()), n + 1); + } + } + for x in 1..a.len() { + for y in 1..b.len() { + if !same(&a[a.len() - x..], &b[b.len() - y..]) { + continue; + } + let (rest, n) = shape_hunk(path, &a[..a.len() - x], &b[..b.len() - y]); + return (format!("{rest}{}", a[a.len() - x..].concat()), n + 1); + } + } + (b.concat(), 0) +} + +/// The formatter checks of a CI command, by the languages they cover. +fn covers(cmd: &str, path: &str) -> bool { + let c = cmd.to_ascii_lowercase(); + let e = ext(path); + let any = |exts: &[&str]| exts.contains(&e.as_str()); + let js = [ + "js", "jsx", "ts", "tsx", "mjs", "cjs", "mts", "cts", "json", "css", "scss", "less", "md", + "yaml", "yml", "vue", "svelte", "graphql", + ]; + if c.contains("prettier") + || c.contains("biome") + || c.contains("format:check") + || c.contains("format-check") + { + // A prettier run scoped to folders covers only those folders. + let scoped: Vec<&str> = c + .split_whitespace() + .filter(|w| !w.starts_with('-') && (w.contains('/') || *w == ".")) + .collect(); + let in_scope = scoped.is_empty() + || scoped.iter().any(|s| { + let s = s.trim_matches(|ch| ch == '"' || ch == '\''); + s == "." + || path.starts_with( + s.trim_start_matches("./") + .trim_end_matches("**") + .trim_end_matches('/'), + ) + }); + return any(&js) && in_scope; + } + if c.contains("cargo fmt") || c.contains("rustfmt") { + return e == "rs"; + } + if c.contains("black") || c.contains("ruff format") || c.contains("isort") { + return e == "py"; + } + if c.contains("gofmt") || c.contains("goimports") { + return e == "go"; + } + if c.contains("terraform fmt") || c.contains("tofu fmt") || c.contains("hclfmt") { + return any(&["tf", "hcl", "tfvars"]); + } + false +} + +/// Whether one of CI's formatter checks (`cmds`) covers `path`. +pub fn ci_formats(cmds: &[String], path: &str) -> bool { + cmds.iter().any(|c| covers(c, path)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rewrapping_and_requoting_is_formatting() { + let old = " expect(\n screen.queryByText('Open registration')\n ).toBeNull()\n"; + let new = " expect(screen.queryByText(\"Open registration\")).toBeNull();\n"; + assert!(format_only("e2e/a.spec.ts", old, new)); + // A changed string is not. + let other = " expect(screen.queryByText(\"Open the registration\")).toBeNull();\n"; + assert!(!format_only("e2e/a.spec.ts", old, other)); + // Indentation is structure in Python. + assert!(!format_only( + "a.py", + "if x:\n y()\nz()\n", + "if x:\n y()\n z()\n" + )); + assert!(format_only("a.py", "x = 'a' \n\n", "x = \"a\"\n")); + // A dropped final newline is formatting. + assert!(format_only( + "Dockerfile", + "CMD [\"node\"]\n", + "CMD [\"node\"]" + )); + // Rust's semicolon is not optional. + assert!(!format_only( + "a.rs", + "fn f() -> u8 { 1 }", + "fn f() -> u8 { 1; }" + )); + } + + #[test] + fn only_the_hunks_that_change_something_stay() { + let old = "const a = f(\n 1,\n 2,\n);\nconst b = 'x';\nconst c = 3;\n"; + let new = "const a = f(1, 2);\nconst b = 'x';\nconst c = 4;\n"; + let (kept, dropped) = drop_format_hunks("e2e/a.ts", old, new); + assert_eq!(dropped, 1); + assert_eq!( + kept, + "const a = f(\n 1,\n 2,\n);\nconst b = 'x';\nconst c = 4;\n" + ); + // Nothing to drop: the text is the new one. + let (same, n) = drop_format_hunks("e2e/a.ts", old, &old.replace("'x'", "'y'")); + assert_eq!((same.as_str(), n), (old.replace("'x'", "'y'").as_str(), 0)); + } + + #[test] + fn ci_says_where_formatting_is_checked() { + let ci = vec!["pnpm --filter web exec prettier --check apps/web".to_string()]; + assert!(ci_formats(&ci, "apps/web/src/a.tsx")); + assert!(!ci_formats(&ci, "e2e/pages/a.ts")); + assert!(ci_formats( + &["cargo fmt --all -- --check".into()], + "services/a.rs" + )); + assert!(!ci_formats(&[], "a.ts")); + } +} diff --git a/services/common/src/e2e/branches.rs b/services/common/src/e2e/branches.rs new file mode 100644 index 000000000..ce2a1b494 --- /dev/null +++ b/services/common/src/e2e/branches.rs @@ -0,0 +1,557 @@ +//! A test branch that has never run is unverified code. +//! +//! A portal spec had two branches on the page's state: registration closed +//! (the camp's button disabled, it must say so) and registration open (the +//! button enabled, choosing it must fill the cart). Only the closed one +//! ever ran; the open one was written from a guess, and the day the vendor +//! opened registration it failed on every branch, because a signed-out +//! visitor gets a sign-in drawer and the cart stays empty. +//! +//! - [`state_branches`] finds the branches of end-to-end code on a page's +//! state: `if` on an awaited `isEnabled()`, `isVisible()`, `isChecked()`, +//! `count()` and the like, directly or through a variable assigned from +//! one, and `test.skip`/`test.fixme` on a condition. Each has two arms +//! (an `if` with no `else` skips its block on the other), the expect +//! messages each arm asserts with, and the test id its condition reads +//! when the file names it ([`Branch::subject`]). +//! - [`executed`] reads which arms a recorded run went through, from the +//! step titles of a Playwright report (an expect with a message is a step +//! titled with it). +//! - [`runnable_now`] reads which arms the page's present state would run, +//! from a probe of it: an arm no recorded run executed is labelled +//! unverified in the pull request, and once the page shows the state it +//! needs, the coder runs it against the live page and settles it. + +use serde::{Deserialize, Serialize}; + +use super::probe::ProbeRecord; + +/// The page-state reads a branch can turn on. +const STATE_READS: &[&str] = &[ + "isEnabled", + "isDisabled", + "isVisible", + "isHidden", + "isChecked", + "isEditable", + "count", +]; + +/// One arm of a branch. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Arm { + /// Whether the condition holds on this arm. + pub when: bool, + /// Its first line (1-based); for an `if` with no `else`, the `if`'s. + pub line: usize, + /// The messages its expects carry (`expect(x, "…")`), which a report's + /// steps are titled with. + pub markers: Vec, +} + +/// A branch of end-to-end code on a page's state. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Branch { + pub path: String, + pub line: usize, + /// The condition as written. + pub condition: String, + /// The state read (`isEnabled`, `count`, …) and whether the condition + /// negates it. + pub read: String, + pub negated: bool, + /// The test id (or `/pattern/`) the condition reads, when the file + /// names it. + pub subject: Option, + pub arms: Vec, +} + +impl Branch { + /// How a person reads an arm: "when `isEnabled()` is true". + pub fn arm_words(&self, arm: &Arm) -> String { + let on = match &self.subject { + Some(s) => format!(" on `{s}`"), + None => String::new(), + }; + let holds = arm.when != self.negated; + match self.read.as_str() { + "count" => format!( + "when `{}` finds {}{on}", + self.condition.trim(), + if arm.when { + "what it asks" + } else { + "otherwise" + } + ), + r => format!("when `{r}()`{on} is {holds}"), + } + } +} + +fn line_of(code: &str, at: usize) -> usize { + code[..at].matches('\n').count() + 1 +} + +/// The byte index just past the bracket that closes the one at `open`. +fn close_of(code: &str, open: usize) -> Option { + let b = code.as_bytes(); + let (o, c) = match b[open] { + b'(' => (b'(', b')'), + b'{' => (b'{', b'}'), + _ => return None, + }; + let mut depth = 0i32; + let mut i = open; + let mut quote: Option = None; + while i < b.len() { + let ch = b[i]; + if let Some(q) = quote { + if ch == b'\\' { + i += 2; + continue; + } + if ch == q { + quote = None; + } + } else if matches!(ch, b'\'' | b'"' | b'`') { + quote = Some(ch); + } else if ch == o { + depth += 1; + } else if ch == c { + depth -= 1; + if depth == 0 { + return Some(i + 1); + } + } + i += 1; + } + None +} + +/// The statement or block that starts at `from` (after whitespace): its +/// span. +fn body_at(code: &str, from: usize) -> (usize, usize) { + let rest = &code[from..]; + let skip = rest.len() - rest.trim_start().len(); + let start = from + skip; + if code[start..].starts_with('{') { + let end = close_of(code, start).unwrap_or(code.len()); + return (start, end); + } + let end = code[start..] + .find(['\n', ';']) + .map(|i| start + i + 1) + .unwrap_or(code.len()); + (start, end) +} + +/// The messages of the expects in `text` (`expect(x, "…")`, with the +/// message on the same line or the next). +pub fn markers(text: &str) -> Vec { + let mut out = Vec::new(); + for (i, _) in text.match_indices("expect(") { + let open = i + "expect".len(); + let Some(end) = close_of(text, open) else { + continue; + }; + let args = &text[open + 1..end - 1]; + // The second top-level argument, when it is a plain string. + let b = args.as_bytes(); + let mut depth = 0i32; + let mut quote: Option = None; + let mut j = 0; + let mut comma = None; + while j < b.len() { + let ch = b[j]; + if let Some(q) = quote { + if ch == b'\\' { + j += 2; + continue; + } + if ch == q { + quote = None; + } + } else if matches!(ch, b'\'' | b'"' | b'`') { + quote = Some(ch); + } else if matches!(ch, b'(' | b'[' | b'{') { + depth += 1; + } else if matches!(ch, b')' | b']' | b'}') { + depth -= 1; + } else if ch == b',' && depth == 0 { + comma = Some(j); + break; + } + j += 1; + } + let Some(c) = comma else { continue }; + let msg = args[c + 1..].trim().trim_end_matches(',').trim(); + let Some(q) = msg.chars().next().filter(|q| matches!(q, '"' | '\'' | '`')) else { + continue; + }; + if let Some(stop) = msg[1..].find(q) { + let m = &msg[1..1 + stop]; + // A template's placeholders: keep its longest fixed words. + let m = m + .split("${") + .enumerate() + .map(|(k, part)| { + if k == 0 { + part + } else { + part.split_once('}').map_or("", |(_, rest)| rest) + } + }) + .map(|p| p.trim_matches(|c: char| c == ' ' || c == '"' || c == '\'')) + .max_by_key(|p| p.len()) + .unwrap_or(""); + if m.len() >= 6 && !out.iter().any(|o| o == m) { + out.push(m.to_string()); + } + } + } + out +} + +/// The state read a condition makes, if any: (read, negated). +fn read_in(cond: &str) -> Option<(String, String)> { + for r in STATE_READS { + let call = format!(".{r}("); + if let Some(i) = cond.find(&call) { + // The receiver: the expression the read is called on. + let before = &cond[..i]; + let start = before + .rfind(|c: char| !(c.is_alphanumeric() || matches!(c, '_' | '.' | '(' | ')'))) + .map(|k| k + 1) + .unwrap_or(0); + return Some((r.to_string(), before[start..].trim().to_string())); + } + } + None +} + +/// Variables assigned from a state read: name, (read, receiver). +fn state_vars(code: &str) -> Vec<(String, String, String)> { + let mut out = Vec::new(); + for line in code.lines() { + let l = line.trim(); + let Some(rest) = ["const ", "let ", "var "] + .iter() + .find_map(|k| l.strip_prefix(k)) + else { + continue; + }; + let Some((name, value)) = rest.split_once('=') else { + continue; + }; + let name = name.trim().trim_end_matches(':').trim(); + if !name.chars().all(|c| c.is_alphanumeric() || c == '_') || name.is_empty() { + continue; + } + if !value.contains("await") { + continue; + } + if let Some((read, recv)) = read_in(value) { + out.push((name.to_string(), read, recv)); + } + } + out +} + +/// The test id a receiver reads: through a local variable assigned from +/// it, and a method of the file that returns a `getByTestId(…)`. +fn subject_of(code: &str, receiver: &str) -> Option { + let mut expr = receiver.to_string(); + for _ in 0..3 { + if let Some(id) = super::probe::selectors_in(&expr).into_iter().next() { + return Some(id); + } + let head: String = expr + .trim_start_matches("this.") + .chars() + .take_while(|c| c.is_alphanumeric() || *c == '_') + .collect(); + if head.is_empty() { + return None; + } + // A local variable: `const head = ;`. + let var = ["const ", "let "].iter().find_map(|k| { + let pat = format!("{k}{head} ="); + code.find(&pat).map(|i| { + let v = &code[i + pat.len()..]; + v[..v.find(';').unwrap_or(v.len())].trim().to_string() + }) + }); + if let Some(v) = var { + expr = v; + continue; + } + // A method of the file: `head(): Locator {` … `}`. + let def = code.match_indices(&format!("{head}(")).find_map(|(i, _)| { + let line_start = code[..i].rfind('\n').map(|k| k + 1).unwrap_or(0); + let prefix = code[line_start..i].trim(); + if !(prefix.is_empty() || prefix == "async" || prefix == "get") { + return None; + } + let open = i + code[i..].find('{')?; + let end = close_of(code, open)?; + Some(code[open..end].to_string()) + }); + return def.and_then(|body| super::probe::selectors_in(&body).into_iter().next()); + } + None +} + +/// The branches of end-to-end code on a page's state. +pub fn state_branches(path: &str, code: &str) -> Vec { + let vars = state_vars(code); + let mut out = Vec::new(); + for (i, _) in code.match_indices("if (") { + // A word ending in "if" (e.g. "elif") isn't one. + if i > 0 { + let prev = code[..i].chars().next_back().unwrap_or(' '); + if prev.is_alphanumeric() || prev == '_' { + continue; + } + } + let open = i + 3; + let Some(close) = close_of(code, open) else { + continue; + }; + let cond = code[open + 1..close - 1].trim().to_string(); + let negated = cond.starts_with('!'); + let (read, receiver) = match read_in(&cond) { + Some(r) => r, + None => match vars.iter().find(|(v, _, _)| { + cond.split(|c: char| !(c.is_alphanumeric() || c == '_')) + .any(|w| w == v) + }) { + Some((_, r, recv)) => (r.clone(), recv.clone()), + None => continue, + }, + }; + let (ts, te) = body_at(code, close); + let mut arms = vec![Arm { + when: true, + line: line_of(code, ts), + markers: markers(&code[ts..te]), + }]; + let after = code[te..].trim_start(); + let else_at = te + (code[te..].len() - after.len()); + if let Some(rest) = after.strip_prefix("else") { + let from = else_at + 4 + (rest.len() - rest.trim_start().len()); + let (es, ee) = body_at(code, from); + arms.push(Arm { + when: false, + line: line_of(code, es), + markers: markers(&code[es..ee]), + }); + } else { + arms.push(Arm { + when: false, + line: line_of(code, i), + markers: Vec::new(), + }); + } + out.push(Branch { + path: path.to_string(), + line: line_of(code, i), + condition: cond, + read, + negated, + subject: subject_of(code, &receiver), + arms, + }); + } + for (i, _) in code + .match_indices("test.skip(") + .chain(code.match_indices("test.fixme(")) + { + let open = i + code[i..].find('(').unwrap_or(0); + let Some(close) = close_of(code, open) else { + continue; + }; + let args = code[open + 1..close - 1].trim(); + // `test.skip('title', fn)` declares a skipped test; a condition + // starts with something other than a string or a function. + if args.is_empty() + || args.starts_with(['\'', '"', '`']) + || args.starts_with("()") + || args.starts_with("async") + { + continue; + } + let cond = args.split(',').next().unwrap_or(args).trim().to_string(); + out.push(Branch { + path: path.to_string(), + line: line_of(code, i), + read: "skip".into(), + negated: false, + subject: None, + arms: vec![ + Arm { + when: true, + line: line_of(code, i), + markers: Vec::new(), + }, + Arm { + when: false, + line: line_of(code, i), + markers: Vec::new(), + }, + ], + condition: cond, + }); + } + out.sort_by_key(|b| b.line); + out +} + +/// The step titles of a Playwright JSON report, at every depth. +pub fn step_titles(report: &serde_json::Value) -> Vec { + fn walk(v: &serde_json::Value, out: &mut Vec) { + match v { + serde_json::Value::Object(m) => { + if let Some(steps) = m.get("steps").and_then(|s| s.as_array()) { + for s in steps { + if let Some(t) = s.get("title").and_then(|t| t.as_str()) { + out.push(t.to_string()); + } + } + } + for x in m.values() { + walk(x, out); + } + } + serde_json::Value::Array(a) => a.iter().for_each(|x| walk(x, out)), + _ => {} + } + } + let mut out = Vec::new(); + walk(report, &mut out); + out +} + +/// Whether a recorded run went through an arm: one of its expect messages +/// is a step title of the run. +pub fn executed(arm: &Arm, steps: &[String]) -> bool { + arm.markers + .iter() + .any(|m| steps.iter().any(|s| s.contains(m.as_str()))) +} + +/// Which arm the page's present state would run, read from a probe: the +/// condition's test id's state there. `None` when the probe didn't see it +/// or the read isn't one a probe records. +pub fn runnable_now(b: &Branch, probe: &ProbeRecord) -> Option { + let subject = b.subject.as_deref()?; + let states: Vec<_> = probe.states_of(subject).collect(); + let first = states.iter().find(|s| s.visible).or(states.first())?; + let holds = match b.read.as_str() { + "isEnabled" => first.enabled, + "isDisabled" => !first.enabled, + "isVisible" => first.visible, + "isHidden" => !first.visible, + "count" => states.iter().any(|s| s.visible), + _ => return None, + }; + Some(holds != b.negated) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::e2e::probe::ProbeState; + + const PAGE: &str = r#" +export class Portal { + sessions(): Locator { + return this.frame.getByTestId( + /^portal-option-guest-\d+$/, + ); + } + + async pickFirst() { + const session = this.sessions().first(); + const open = await session.isEnabled(); + + if (open) { + await session.click(); + await expect( + this.cartSubtotal(), + `Choosing "${camp}" did not add it to the order summary`, + ).not.toHaveText(/\$0$/); + } else { + await expect( + session, + `"${camp}" is disabled but doesn't say registration is closed`, + ).toContainText(/not open/i); + } + if ((await more.count()) > 0) await more.first().click(); + } +} +"#; + + #[test] + fn a_branch_on_the_pages_state_has_two_arms_and_a_subject() { + let b = state_branches("e2e/pages/portal.ts", PAGE); + assert_eq!(b.len(), 2); + let open = &b[0]; + assert_eq!(open.read, "isEnabled"); + assert_eq!( + open.subject.as_deref(), + Some("/^portal-option-guest-\\d+$/") + ); + assert_eq!( + open.arms[0].markers, + vec!["did not add it to the order summary"] + ); + assert_eq!( + open.arms[1].markers, + vec!["is disabled but doesn't say registration is closed"] + ); + assert!(open + .arm_words(&open.arms[0]) + .contains("`isEnabled()` on `/^portal-option-guest-\\d+$/` is true")); + // An `if` with no `else` skips its block on the other arm. + assert_eq!(b[1].read, "count"); + assert!(b[1].arms[1].markers.is_empty()); + } + + #[test] + fn a_report_says_which_arm_ran_and_a_probe_which_can_run_now() { + let b = &state_branches("e2e/pages/portal.ts", PAGE)[0]; + let report = serde_json::json!({"suites": [{"specs": [{"tests": [{"results": [{"steps": [ + {"title": "\"Mini camp\" is disabled but doesn't say registration is closed", "steps": []} + ]}]}]}]}]}); + let steps = step_titles(&report); + assert!(!executed(&b.arms[0], &steps)); + assert!(executed(&b.arms[1], &steps)); + let probe = |enabled| ProbeRecord { + steps: vec![crate::e2e::probe::ProbeStep { + click: "week-0".into(), + clicked: true, + states: vec![ProbeState { + testid: "portal-option-guest-0".into(), + visible: true, + enabled, + ..Default::default() + }], + }], + ..Default::default() + }; + assert_eq!(runnable_now(b, &probe(true)), Some(true)); + assert_eq!(runnable_now(b, &probe(false)), Some(false)); + assert_eq!(runnable_now(b, &ProbeRecord::default()), None); + } + + #[test] + fn a_conditional_skip_is_a_branch_and_a_skipped_test_is_not() { + let code = "test.skip(isMobile, 'desktop only');\ntest.skip('later', async () => {});"; + let b = state_branches("e2e/a.spec.ts", code); + assert_eq!(b.len(), 1); + assert_eq!(b[0].condition, "isMobile"); + // Plain conditions on data are no page state. + assert!(state_branches("e2e/a.spec.ts", "if (rows.length === 0) {\n}\n").is_empty()); + } +} diff --git a/services/common/src/e2e/mod.rs b/services/common/src/e2e/mod.rs index 860bc20da..76a699773 100644 --- a/services/common/src/e2e/mod.rs +++ b/services/common/src/e2e/mod.rs @@ -29,8 +29,13 @@ //! request comes from the change, from the page and the code it runs. //! - [`bug_rules`] tells a bug from a flake and holds a bug fix to the app, //! with a unit test, keeping only the changes that matter. +//! - [`probe`] records what a page another company serves really has, and +//! holds end-to-end selectors to it. +//! - [`branches`] finds test branches on a page's state and which of them a +//! recorded run, or the page as it is now, would run. pub mod attribution; +pub mod branches; pub mod bug_rules; pub mod check_gate; pub mod ci_setup; diff --git a/services/common/src/e2e/probe.rs b/services/common/src/e2e/probe.rs index 8c3ec4aa2..e213db250 100644 --- a/services/common/src/e2e/probe.rs +++ b/services/common/src/e2e/probe.rs @@ -3,20 +3,51 @@ //! //! 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: +//! test "covered" the checkout. Later a portal spec checked "a camp goes in +//! the cart while registration is open" from strings found in the vendor's +//! script bundle: the ids were real, the behaviour wasn't (a signed-out +//! visitor gets the vendor's sign-in drawer and the cart stays at $0), and +//! the branch only ran the day the vendor opened registration. 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. +//! frames) with each one's state (visible, enabled, its text), and the +//! field names of the JSON it fetches. Given clicks (test ids or +//! `/patterns/`), it clicks each in turn and lists what is there after +//! it: the states a spec's branches depend on are seen, not guessed. The +//! coder's `probe_page` tool runs it; the record is committed in the +//! repository ([`record_path`]) and quoted in the pull request +//! ([`quote`]). +//! - [`unprobed`] is the gate: an end-to-end file that reaches an outside +//! origin (a host other than the team's own, or a page in a frame) may +//! use only test ids and JSON fields a probe of that origin observed: +//! the ones it adds and the ones it keeps. Test ids written over several +//! lines or as patterns count like any other. use serde::{Deserialize, Serialize}; +/// What one test id looked like when the probe listed it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ProbeState { + pub testid: String, + pub visible: bool, + pub enabled: bool, + /// Its first line of text, short. + pub text: String, +} + +/// What the page showed after one click. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ProbeStep { + /// The test id (or `/pattern/`) clicked. + pub click: String, + /// Whether something matched and was clicked. + pub clicked: bool, + pub states: Vec, +} + /// What a probe of one page saw. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] @@ -26,10 +57,55 @@ pub struct ProbeRecord { pub url: String, /// When it was probed (RFC 3339). pub at: String, - /// Test ids on the page and in its frames. + /// Test ids on the page and in its frames, on load and after each click. pub testids: Vec, /// Field names of the JSON responses it fetched (dotted paths). pub json_fields: Vec, + /// Each test id's state on load. + pub states: Vec, + /// What each click showed. + pub steps: Vec, +} + +/// The origin of end-to-end code that drives a page in a frame and names +/// no outside host: any probe's ids may cover it. +pub const FRAMED: &str = "a page in a frame"; + +/// Whether `selector` (a test id, or a `/pattern/` as a spec writes it) +/// names `testid`. +pub fn names(selector: &str, testid: &str) -> bool { + match pattern(selector) { + Some(re) => re.is_match(testid), + None => selector == testid, + } +} + +fn pattern(selector: &str) -> Option { + let s = selector.strip_prefix('/')?; + let end = s.rfind('/')?; + regex::Regex::new(&s[..end]).ok() +} + +impl ProbeRecord { + /// Every state the probe saw, on load and after each click, in order. + pub fn all_states(&self) -> impl Iterator { + self.states + .iter() + .chain(self.steps.iter().flat_map(|s| s.states.iter())) + } + + /// Whether the probe saw a test id `selector` names. + pub fn observes(&self, selector: &str) -> bool { + self.testids.iter().any(|t| names(selector, t)) + || self.all_states().any(|s| names(selector, &s.testid)) + || self.json_fields.iter().any(|f| f == selector) + } + + /// The states the probe saw of what `selector` names. + pub fn states_of<'a>(&'a self, selector: &'a str) -> impl Iterator { + self.all_states() + .filter(move |s| names(selector, &s.testid)) + } } /// Where a probe of `host` is kept in the repository. @@ -52,76 +128,155 @@ 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'; +/// The line the probe tool's answer starts its record after. +pub const RECORD_MARK: &str = "Probe record:"; + +/// The record in a probe tool's answer, if it has one. +pub fn record_in(answer: &str) -> Option { + let at = answer.find(RECORD_MARK)?; + let json = answer[at + RECORD_MARK.len()..].trim(); + serde_json::from_str(json).ok() +} + +const SCRIPT: &str = r#"import { chromium } from 'playwright'; +import { writeFileSync } from 'node:fs'; const out = process.env.CODERHELM_OUT || '.'; -const url = {url}; +const url = __URL__; +const clicks = __CLICKS__; const fields = new Set(); -const walk = (v, p, d) => {{ +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); + 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 SEL = '[data-testid],[data-test],[data-cy],[data-test-id]'; +const idOf = (e) => e.getAttribute('data-testid') || e.getAttribute('data-test') || e.getAttribute('data-cy') || e.getAttribute('data-test-id'); const browser = await chromium.launch(); const page = await browser.newPage(); -page.on('response', async (r) => {{ - try {{ +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) {{}} -}} + } catch (e) {} +}); +await page.goto(url, { waitUntil: 'networkidle', timeout: 45000 }); +const settle = async () => { + try { await page.waitForLoadState('networkidle', { timeout: 15000 }); } catch (e) {} + await page.waitForTimeout(1500); +}; +const snapshot = async () => { + const seen = new Map(); + for (const f of page.frames()) { + try { + const got = await f.$$eval(SEL, (els) => els.map((e) => { + const id = e.getAttribute('data-testid') || e.getAttribute('data-test') || e.getAttribute('data-cy') || e.getAttribute('data-test-id'); + const r = e.getBoundingClientRect(); + const st = getComputedStyle(e); + const visible = r.width > 0 && r.height > 0 && st.visibility !== 'hidden' && st.display !== 'none'; + const enabled = !(e.disabled || e.getAttribute('aria-disabled') === 'true' || e.closest('[disabled],[aria-disabled="true"]')); + const text = (e.innerText || '').split('\n')[0].trim().slice(0, 80); + return { testid: id, visible, enabled, text }; + })); + for (const s of got) if (s.testid && !seen.has(s.testid)) seen.set(s.testid, s); + } catch (e) {} + } + return [...seen.values()]; +}; +const matches = (sel, id) => { + if (sel.startsWith('/') && sel.lastIndexOf('/') > 0) { + try { return new RegExp(sel.slice(1, sel.lastIndexOf('/'))).test(id); } catch (e) { return false; } + } + return sel === id; +}; +await settle(); +const states = await snapshot(); +const steps = []; +for (const c of clicks) { + let clicked = false; + for (const f of page.frames()) { + if (clicked) break; + try { + const handles = await f.$$(SEL); + for (const h of handles) { + const id = await h.evaluate(idOf); + if (!id || !matches(c, id)) continue; + if (!(await h.isVisible()) || !(await h.isEnabled())) continue; + await h.click({ timeout: 10000 }); + clicked = true; + break; + } + } catch (e) {} + } + await settle(); + steps.push({ click: c, clicked, states: await snapshot() }); +} await browser.close(); -writeFileSync(`${{out}}/probe.json`, JSON.stringify({{ +const ids = new Set(); +for (const s of states) ids.add(s.testid); +for (const st of steps) for (const s of st.states) ids.add(s.testid); +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)); -"# - ) + testids: [...ids].sort(), json_fields: [...fields].sort(), states, steps, +}, null, 2)); +"#; + +/// The sandbox script that probes `url`, clicking each of `clicks` (test +/// ids or `/patterns/`) in turn: it writes `probe.json` (a [`ProbeRecord`]) +/// to `$CODERHELM_OUT`. +pub fn probe_script(url: &str, clicks: &[String]) -> String { + let url = serde_json::to_string(url).unwrap_or_else(|_| "\"\"".into()); + let clicks = serde_json::to_string(clicks).unwrap_or_else(|_| "[]".into()); + SCRIPT + .replace("__URL__", &url) + .replace("__CLICKS__", &clicks) } -/// 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()); +/// The first quoted string or `/pattern/` at the start of `s` (after +/// whitespace), as the code writes it: a pattern keeps its slashes. +fn first_arg(s: &str) -> Option { + let t = s.trim_start(); + let q = t.chars().next()?; + match q { + '\'' | '"' | '`' => { + let end = t[1..].find(q)?; + let v = &t[1..1 + end]; + (!v.contains("${")).then(|| v.to_string()) + } + '/' => { + // A regex literal: up to the closing unescaped slash, flags dropped. + let b = t.as_bytes(); + let mut i = 1; + while i < b.len() { + match b[i] { + b'\\' => i += 2, + b'/' => return Some(t[..=i].to_string()), + b'\n' => return None, + _ => i += 1, + } + } + None } + _ => None, } - out } -/// The test ids a piece of end-to-end code uses. +/// The first argument of every `name(…)` call in `code`. +fn calls(code: &str, name: &str) -> Vec { + code.match_indices(name) + .filter_map(|(i, _)| first_arg(&code[i + name.len()..])) + .collect() +} + +/// The test ids a piece of end-to-end code uses: `getByTestId(…)` with a +/// string or a pattern, on one line or several, and `[data-testid=…]`. 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.retain(|s| !s.is_empty()); out.sort(); out.dedup(); out @@ -131,13 +286,20 @@ pub fn selectors_in(code: &str) -> Vec { /// (`toHaveProperty('a.b')`). pub fn fields_in(code: &str) -> Vec { let mut out = calls(code, "toHaveProperty("); + out.retain(|s| !s.starts_with('/')); out.sort(); out.dedup(); out } +/// Whether code drives a page inside a frame. +pub fn drives_frame(code: &str) -> bool { + code.contains("frameLocator(") || code.contains(".contentFrame()") +} + /// The https hosts a piece of code reaches that aren't the team's own -/// (`own` hosts and their subdomains, previews included). +/// (`own` hosts and their subdomains, previews included), and [`FRAMED`] +/// when it drives a frame and names no outside host. pub fn outside_origins(code: &str, own: &[String]) -> Vec { let mut out: Vec = Vec::new(); for (i, _) in code.match_indices("https://") { @@ -159,10 +321,13 @@ pub fn outside_origins(code: &str, own: &[String]) -> Vec { out.push(host); } } + if out.is_empty() && drives_frame(code) { + out.push(FRAMED.to_string()); + } out } -/// A new or changed e2e file's selectors or fields no probe observed. +/// An e2e file's selectors or fields no probe observed. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Unprobed { pub path: String, @@ -173,8 +338,13 @@ pub struct Unprobed { impl Unprobed { /// The review finding's text. pub fn body(&self) -> String { + let record = if self.origin == FRAMED { + record_path("") + } else { + record_path(&self.origin) + }; 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.", + "`{}` 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, with `clicks` to reach the state each branch needs), commit the record at `{record}`, 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 @@ -182,28 +352,29 @@ impl Unprobed { .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. +/// the file (the ones the change writes and the ones it keeps) that no +/// probe of that origin observed. A page in a frame with no host named is +/// covered by any probe. pub fn unprobed( files: &[(String, String, String)], probes: &[ProbeRecord], own: &[String], ) -> Vec { let mut out = Vec::new(); - for (path, full, added) in files { + for (path, full, _added) in files { let origins = outside_origins(full, own); if origins.is_empty() { continue; } - let used: Vec = selectors_in(added) + let used: Vec = selectors_in(full) .into_iter() - .chain(fields_in(added)) + .chain(fields_in(full)) .collect(); if used.is_empty() { continue; @@ -211,15 +382,11 @@ pub fn unprobed( for origin in origins { let seen: Vec<&ProbeRecord> = probes .iter() - .filter(|p| p.origin.eq_ignore_ascii_case(&origin)) + .filter(|p| origin == FRAMED || 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) - }) - }) + .filter(|u| !seen.iter().any(|p| p.observes(u))) .cloned() .collect(); if !missing.is_empty() { @@ -234,6 +401,84 @@ pub fn unprobed( out } +fn state_word(s: &ProbeState) -> String { + let mut w = vec![if s.visible { "visible" } else { "hidden" }]; + if !s.enabled { + w.push("disabled"); + } + let text = if s.text.is_empty() { + String::new() + } else { + format!(", \"{}\"", s.text.replace('`', "'")) + }; + format!("`{}` ({}{text})", s.testid, w.join(", ")) +} + +const QUOTE_MAX: usize = 25; + +fn listed(states: &[&ProbeState]) -> String { + let mut parts: Vec = states + .iter() + .take(QUOTE_MAX) + .map(|s| state_word(s)) + .collect(); + if states.len() > QUOTE_MAX { + parts.push(format!("and {} more", states.len() - QUOTE_MAX)); + } + if parts.is_empty() { + "nothing".to_string() + } else { + parts.join(", ") + } +} + +/// The pull request's lines quoting a probe: where and when, the visible +/// test ids and their states on load, and what each click brought up. +pub fn quote(r: &ProbeRecord) -> String { + let mut out = format!( + "- Probe of `{}` ({}) at {}: {} test ids.\n", + r.origin, + r.url, + r.at, + r.testids.len() + ); + let on_load: Vec<&ProbeState> = r.states.iter().filter(|s| s.visible).collect(); + out.push_str(&format!(" - On load, visible: {}.\n", listed(&on_load))); + let mut before: Vec = r.states.iter().map(|s| s.testid.clone()).collect(); + for st in &r.steps { + if !st.clicked { + out.push_str(&format!( + " - Clicking `{}`: nothing visible and enabled matched.\n", + st.click + )); + continue; + } + let new: Vec<&ProbeState> = st + .states + .iter() + .filter(|s| s.visible && !before.contains(&s.testid)) + .collect(); + out.push_str(&format!( + " - After clicking `{}`, newly visible: {}.\n", + st.click, + listed(&new) + )); + before.extend(st.states.iter().map(|s| s.testid.clone())); + } + if !r.json_fields.is_empty() { + out.push_str(&format!( + " - JSON fields fetched: {}.\n", + r.json_fields + .iter() + .take(QUOTE_MAX) + .map(|f| format!("`{f}`")) + .collect::>() + .join(", ") + )); + } + out +} + #[cfg(test)] mod tests { use super::*; @@ -294,6 +539,118 @@ export class VendorCheckout { code.to_string(), )]; assert!(unprobed(&files, &[], &["example.org".to_string()]).is_empty()); - assert!(probe_script("https://a.test/x").contains("probe.json")); + assert!(probe_script("https://a.test/x", &[]).contains("probe.json")); + } + + /// Prettier breaks long calls over lines and specs match generated ids + /// with patterns: both are selectors the gate reads. + #[test] + fn wrapped_calls_and_patterns_are_selectors() { + let code = "this.frame.getByTestId(\n \"portal-cart-subtotal\",\n );\nthis.frame.getByTestId(\n /^portal-option-guest-\\d+$/,\n);\nthis.frame.locator('[data-testid=\"drawer\"]');"; + assert_eq!( + selectors_in(code), + vec![ + "/^portal-option-guest-\\d+$/", + "drawer", + "portal-cart-subtotal" + ] + ); + let r = ProbeRecord { + testids: vec!["portal-option-guest-0".into()], + ..Default::default() + }; + assert!(r.observes("/^portal-option-guest-\\d+$/")); + assert!(!r.observes("/^portal-tag-guest-\\d+$/")); + } + + /// Kept selectors count: the change touched the file, so what it + /// leaves standing is held to the same probe. + #[test] + fn kept_selectors_in_a_changed_file_are_held_too() { + let full = "const URL = 'https://portal.vendor.test/p/1';\nthis.f.getByTestId('kept-id');\nthis.f.getByTestId('new-id');"; + let files = vec![( + "e2e/pages/portal.ts".to_string(), + full.to_string(), + "this.f.getByTestId('new-id');".to_string(), + )]; + let u = unprobed(&files, &[], &[]); + assert_eq!(u[0].missing, vec!["kept-id", "new-id"]); + } + + /// A spec that drives a frame and names no host is still on a page + /// another company serves. + #[test] + fn a_framed_page_with_no_host_named_needs_a_probe() { + let code = "const f = page.frameLocator('iframe[id^=\"pay-link\"]');\nawait f.getByTestId('continue').click();"; + let files = vec![("e2e/pages/pay.ts".into(), code.into(), code.into())]; + let u = unprobed(&files, &[], &[]); + assert_eq!(u[0].origin, FRAMED); + let r = ProbeRecord { + origin: "cdn.pay.test".into(), + testids: vec!["continue".into()], + ..Default::default() + }; + assert!(unprobed(&files, &[r], &[]).is_empty()); + } + + #[test] + fn a_probe_after_clicks_is_quoted_with_its_states() { + let r = ProbeRecord { + origin: "portal.vendor.test".into(), + url: "https://portal.vendor.test/p/1".into(), + at: "2026-11-17T15:40:00Z".into(), + testids: vec!["week-0".into(), "option-0".into(), "sign-in-drawer".into()], + states: vec![ProbeState { + testid: "week-0".into(), + visible: true, + enabled: true, + text: "Week 1".into(), + }], + steps: vec![ + ProbeStep { + click: "week-0".into(), + clicked: true, + states: vec![ + ProbeState { + testid: "week-0".into(), + visible: true, + enabled: true, + ..Default::default() + }, + ProbeState { + testid: "option-0".into(), + visible: true, + enabled: true, + text: "Mini camp (AM)".into(), + }, + ], + }, + ProbeStep { + click: "/^option-\\d+$/".into(), + clicked: true, + states: vec![ProbeState { + testid: "sign-in-drawer".into(), + visible: true, + enabled: true, + ..Default::default() + }], + }, + ], + ..Default::default() + }; + let q = quote(&r); + assert!(q.contains("Probe of `portal.vendor.test`")); + assert!(q.contains( + "After clicking `week-0`, newly visible: `option-0` (visible, \"Mini camp (AM)\")" + )); + assert!(q.contains("newly visible: `sign-in-drawer` (visible)")); + let answer = format!( + "Probe of x.\n{RECORD_MARK}\n{}", + serde_json::to_string(&r).unwrap() + ); + assert_eq!(record_in(&answer), Some(r)); + let script = probe_script("https://a.test/x", &["week-0".to_string()]); + assert!(script.contains("const clicks = [\"week-0\"];")); + assert!(!script.contains("__URL__")); } } diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 31813a1bf..24bd4a60d 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -161,6 +161,9 @@ pub mod ci_cover; /// The last check on a pull request description: no section twice, no /// deploy maps, no empty "who this affects". pub mod description_lint; +// A diff holds the lines the change needs: formatting-only hunks are told +// apart and put back. +pub mod diff_shape; #[cfg(test)] mod model_call_sites; /// Which pull requests CoderHelm may push to, edit or close: its own. diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index b8ff844e4..c6bec89ff 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -2770,6 +2770,23 @@ impl<'a> ToolExecutor for FeedbackToolExecutor<'a> { } if let Some(web) = self.web { if let Some(out) = web.handle(self.state, self.github, name, input).await { + // A probe's record is committed on the branch by the round + // (`live_guard`), as the tool's answer says. + if name == super::web_check::PROBE_TOOL { + if let Some(record) = common::e2e::probe::record_in(&out) { + let message = format!("Record the probe of {}", record.origin); + if let Err(e) = super::live_guard::commit_record( + self.github, + (self.owner, self.repo, self.branch), + &record, + &message, + ) + .await + { + tracing::warn!(error = %e, "Could not commit the probe record"); + } + } + } return Ok(serde_json::json!(out)); } } diff --git a/services/worker/src/passes/habits_check.rs b/services/worker/src/passes/habits_check.rs index b3909ccdc..b1ed4014a 100644 --- a/services/worker/src/passes/habits_check.rs +++ b/services/worker/src/passes/habits_check.rs @@ -103,6 +103,12 @@ pub struct PrFacts { /// nobody observed. #[serde(default)] pub wider: Vec, + /// What the change's end-to-end files rest on and what its diff + /// carries (`live_guard`): the probes of outside pages, selectors no + /// probe saw, each test branch on a page's state and whether a run + /// took it, files only reformatted. + #[serde(default)] + pub live: super::live_guard::LiveFacts, } /// Why the check didn't give a result. @@ -550,6 +556,9 @@ pub fn blocking(f: &PrFacts, plan: &PlanResult) -> Vec { for w in &f.wider { out.push(w.instruction()); } + // Selectors from a probe, branches run when they can run, no reformat + // of a file the fix doesn't change. + out.extend(f.live.blocking()); 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()); } @@ -594,6 +603,8 @@ pub fn open_findings(f: &PrFacts, plan: &PlanResult) -> Vec { w.point(), "CoderHelm makes the change smaller in its next round on this pull request.", ) + } else if let Some(p) = f.live.point_of(&l) { + p } else if l.contains("no task of the plan") { ( "Changed outside the plan", @@ -750,6 +761,7 @@ pub fn section(plan: &PlanResult, f: &PrFacts) -> String { } out.push('\n'); } + out.push_str(&f.live.section()); if out.is_empty() { return out; } @@ -1158,6 +1170,9 @@ async fn check_and_fix( .await; facts.e2e_missing = e2e_missing(w, &paths).await; facts.wider = wider(w, &diff, &evidence.notes).await; + // A page whose state a test branch reads is probed again while + // there is time: an arm that couldn't run before is re-checked. + facts.live = super::live_guard::facts_for(w, &diff, &evidence.notes, !short).await; let blocking = blocking(&facts, w.plan); info!( run_id = w.run_id, diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 99c9d48fb..f4f70f865 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -545,6 +545,13 @@ pub async fn run( { super::explore_guard::offer_fields(&mut t.input_schema); } + // Selectors on another company's page come from a probe of it, and a + // write carries only the lines the change needs (`live_guard`). + let live_guard = super::live_guard::LiveGuard::new( + super::live_guard::format_cmds(&ci_steps), + super::web_check::team_domains(state, &msg.team_id).await, + super::live_guard::branch_records(github, &msg.repo_owner, &msg.repo_name, branch).await, + ); // A bounded round's write tools take the reason for an edit outside // its files. @@ -885,6 +892,7 @@ pub async fn run( codegen_env, scope_guard, explore, + live: live_guard, run_id: run_id.map(|s| s.to_string()), node_version, terraform_version, @@ -1344,6 +1352,12 @@ pub async fn run( lines if lines.is_empty() => notes, lines => format!("{notes}\n{}", lines.trim_end()), }; + // Selectors kept without a probe (none could run) and formatting put + // back: the habits check and the pull request read these lines. + let notes = match executor.write_executor.live.evidence_lines() { + lines if lines.is_empty() => notes, + lines => format!("{notes}\n{}", lines.trim_end()), + }; // A file this round (or the rounds before it) changed and then put // back leaves no commit of its own on the pull request. super::round::fold_churn(github, &msg.repo_owner, &msg.repo_name, branch).await; @@ -1508,7 +1522,7 @@ Go to the target files listed in the OpenSpec. /// (`explore_guard`, `minimal_change`). pub(crate) const SMALLEST_CHANGE_RULES: &str = "- The smallest change that does the ticket: before the first write, `search_code` for the structure you would add and pass `reuses` naming what you extend. Add entries to the existing map, a parameter to the existing helper, a key to the existing config; never a second one beside it. - Never widen behaviour past the ticket: an insert-only path stays insert-only (no `DELETE`, no `ON CONFLICT DO UPDATE`, no replacing sync), log levels and shared logging stay as they are, and no counters or reports the ticket doesn't ask for. -- Tests sized to the change: the new behaviour and that nothing else changed, through the real entry point. Never invent another system's payload, page or test ids: probe it (`probe_page`) or reuse an existing fixture. Run the tests and quote their output in your Evidence. +- Tests sized to the change: the new behaviour and that nothing else changed, through the real entry point. Never invent another system's payload, page or test ids: probe it (`probe_page`, with `clicks` that reach each state a branch of the test reads) or reuse an existing fixture. A test branch on a page's state that no run has taken is unverified: the pull request says so until a run takes it. Run the tests and quote their output in your Evidence. Change only the lines the fix needs: a write that only reformats is not made. - When an acceptance criterion and an outside system disagree, change the product so the criterion holds; never change the test to expect the outside behaviour without the measured reason."; /// What a change to a table's schema, constraints, ids or stored data must @@ -2136,6 +2150,9 @@ struct WriteToolExecutor<'a> { scope_guard: super::write_guard::ScopeGuard, /// Search before the first write; no twin beside an existing structure. explore: super::explore_guard::ExploreGuard, + /// Selectors on another company's page from a probe of it; no write + /// that only reformats (`live_guard`). + live: super::live_guard::LiveGuard, /// Node major version to switch the sandbox to (None -> buildspec default). node_version: Option, /// Exact Terraform version the sandbox installs (None when the repo has @@ -2509,6 +2526,19 @@ impl<'a> WriteToolExecutor<'a> { ))); } } + // Selectors on another company's page come from a probe of + // it, and only the lines the change needs are written + // (`live_guard`). + let shaped = match self.live_write(path, existing.as_deref(), content).await { + Ok(t) => t, + Err(refusal) => { + note(LogOutcome::soft_fail( + "not written: unprobed selectors or only formatting", + )); + return Ok(json!(refusal)); + } + }; + let content: &str = &shaped; // The blob sha is looked up here, never taken from the model: // it cannot know it, and a guessed/stale one made GitHub reject // the write as a false "changed concurrently" conflict. @@ -2651,6 +2681,19 @@ impl<'a> WriteToolExecutor<'a> { Read the file again and retry with a smaller, more precise edit." ))); } + // Selectors from a probe; only the lines the change needs. + let content = match self + .live_write(path, Some(&original_content), &content) + .await + { + Ok(t) => t, + Err(refusal) => { + note(LogOutcome::soft_fail( + "not edited: unprobed selectors or only formatting", + )); + return Ok(json!(refusal)); + } + }; // Write the modified file back // Get sha for update @@ -2783,9 +2826,23 @@ impl<'a> WriteToolExecutor<'a> { ))); } } + // Selectors from a probe; only the lines the change + // needs (`live_guard`). + let content = + match self.live_write(path, bw_existing.as_deref(), content).await { + Ok(t) => t, + Err(refusal) => { + note(LogOutcome::soft_fail( + "nothing committed: unprobed selectors or only formatting", + )); + return Ok(json!(format!( + "Batch write REJECTED: nothing was committed. {refusal}" + ))); + } + }; ops.push(FileOp::Write { path: path.to_string(), - content: content.to_string(), + content, }); } } @@ -2998,6 +3055,54 @@ impl<'a> WriteToolExecutor<'a> { impl<'a> WriteToolExecutor<'a> { /// A file this pass committed: part of the change, and not checked yet. + /// The live guard's say on a write of `path` from `old` (`None`: a new + /// file) to `new`: the text to write, or the refusal the coder reads. + async fn live_write(&self, path: &str, old: Option<&str>, new: &str) -> Result { + let text = match old { + Some(old) => { + // Whether the change already changes the file: a reformat + // of a file it doesn't is never written. + let touched = match self + .github + .read_file(&self.owner, &self.repo, path, &self.base_branch) + .await + { + Ok(base) => base != old, + Err(_) => true, + }; + match self.live.shape(path, old, new, touched) { + super::live_guard::Shaped::Write(t, _) => t, + super::live_guard::Shaped::Refused(why) => return Err(why), + } + } + None => new.to_string(), + }; + self.live.check_e2e(path, &text)?; + Ok(text) + } + + /// Commits a probe's record at its path on the branch. A failure is + /// logged: the record is still in the round's guard. + async fn commit_probe(&self, record: &common::e2e::probe::ProbeRecord) { + let message = self.commit_message(&format!("record the probe of {}", record.origin)); + match super::live_guard::commit_record( + self.github, + (&self.owner, &self.repo, &self.branch), + record, + &message, + ) + .await + { + Ok(path) => { + self.mark_written(path.clone()); + self.scope_guard.allow(&path); + } + Err(e) => { + warn!(error = %e, origin = %record.origin, "Could not commit the probe record") + } + } + } + fn mark_written(&self, path: String) -> bool { self.unchecked .store(true, std::sync::atomic::Ordering::SeqCst); @@ -4087,6 +4192,13 @@ impl<'a> ToolExecutor for CombinedWriteToolExecutor<'a> { .handle(self.state, self.write_executor.github, name, input) .await { + // A probe's record is committed on the branch by the round + // itself: the gate and the review read it from there. + if name == super::web_check::PROBE_TOOL { + if let Some(record) = self.write_executor.live.saw_probe(input, &out) { + self.write_executor.commit_probe(&record).await; + } + } return Ok(serde_json::json!(out)); } } diff --git a/services/worker/src/passes/incidents/cv_portal_branch_from_a_guess.rs b/services/worker/src/passes/incidents/cv_portal_branch_from_a_guess.rs new file mode 100644 index 000000000..6ef391dc8 --- /dev/null +++ b/services/worker/src/passes/incidents/cv_portal_branch_from_a_guess.rs @@ -0,0 +1,292 @@ +//! cv. A camp registration page embeds a vendor's portal in a frame. The +//! run that added it wrote an end-to-end page object with two branches on +//! the portal's state: registration closed (the camp's button disabled, it +//! must say so) and registration open (choosing the camp must fill the +//! cart). Its coder tried to load the portal with Playwright; the shell +//! refused the command, and it wrote the open branch from test-id strings +//! it found in the vendor's script bundle. Only the closed branch ever ran. +//! The next ticket's run edited the same file, kept the branch untouched, +//! and re-wrapped a test's lines nobody's formatter checks. The day the +//! vendor opened registration the open branch failed on every branch: a +//! signed-out visitor who picks a camp gets the vendor's sign-in drawer, +//! and the cart stays at $0. The review's probe gate saw none of it: it +//! read only added lines, and only `getByTestId('…')` written on one line, +//! so the page object's wrapped and pattern ids were invisible to it. +//! +//! Guarantee: an end-to-end file that drives another company's page (named +//! by its host, or in a frame) carries only test ids a probe of that page +//! saw, the ones a write adds and the ones it keeps, wrapped or written as +//! patterns; the write is refused until the `probe_page` tool has run, and +//! the round commits its record. The probe clicks through the states a +//! branch reads and lists what each click brings up. Each arm of a test +//! branch on the page's state is labelled unverified in the pull request +//! until a run takes it; when a fresh probe shows the page in the state an +//! arm needs, the coder is sent to run it against the live page. A write +//! that only reformats a file is not made, and a write's formatting hunks +//! are put back where CI doesn't check formatting. + +use common::e2e::branches::state_branches; +use common::e2e::probe::{self, ProbeRecord, ProbeState, ProbeStep}; + +use crate::passes::live_guard::{assess, LiveGuard, Shaped, RAN_LINE}; + +const PORTAL: &str = "portal.vendor.test"; + +/// The page object as the first run left it (names changed). +const PAGE_OBJECT: &str = r#"import { expect, type FrameLocator, type Locator, type Page } from "@playwright/test"; + +export const PORTAL_URL = + "https://portal.vendor.test/program-portals/organization/1/portal/2"; + +export class CampRegistration { + readonly portalFrame: FrameLocator; + + constructor(readonly page: Page) { + this.portalFrame = page.frameLocator(`iframe[title="Camp registration"]`); + } + + registrationSection(): Locator { + return this.portalFrame.getByTestId("portal-registration"); + } + + weeks(): Locator { + return this.portalFrame.getByTestId( + /^portal-segment-tag-guest-\d+$/, + ); + } + + sessions(): Locator { + return this.portalFrame.getByTestId( + /^portal-segment-option-guest-\d+$/, + ); + } + + cartSubtotal(): Locator { + return this.portalFrame.getByTestId( + "portal-cart-preview-subtotal", + ); + } + + async selectFirstCamp(): Promise<{ camp: string; registrationOpen: boolean }> { + const session = this.sessions().first(); + const camp = (await session.innerText()).split("\n")[0]?.trim() ?? ""; + const registrationOpen = await session.isEnabled(); + + if (registrationOpen) { + await session.click(); + await expect( + this.cartSubtotal(), + `Choosing "${camp}" did not add it to the portal's Order Summary`, + ).not.toHaveText(/\$0(\.00)?\s*$/, { timeout: 60_000 }); + } else { + await expect( + session, + `"${camp}" is disabled but doesn't say registration is closed`, + ).toContainText(/registration is not open/i); + } + return { camp, registrationOpen }; + } +} +"#; + +fn state(id: &str, enabled: bool) -> ProbeState { + ProbeState { + testid: id.into(), + visible: true, + enabled, + ..Default::default() + } +} + +/// A probe of the portal clicking the first week, then the first camp. +fn probe_of(open: bool) -> ProbeRecord { + let mut after_camp = vec![state("portal-cart-preview-subtotal", true)]; + if open { + after_camp.push(state("portal-authentication-drawer", true)); + } + ProbeRecord { + origin: PORTAL.into(), + url: "https://portal.vendor.test/program-portals/organization/1/portal/2".into(), + at: "2026-11-17T15:40:00Z".into(), + testids: vec![ + "portal-registration".into(), + "portal-segment-tag-guest-0".into(), + "portal-segment-option-guest-0".into(), + "portal-cart-preview-subtotal".into(), + ], + states: vec![ + state("portal-registration", true), + state("portal-segment-tag-guest-0", true), + state("portal-cart-preview-subtotal", true), + ], + steps: vec![ + ProbeStep { + click: "portal-segment-tag-guest-0".into(), + clicked: true, + states: vec![state("portal-segment-option-guest-0", open)], + }, + ProbeStep { + click: "/^portal-segment-option-guest-\\d+$/".into(), + clicked: open, + states: after_camp, + }, + ], + ..Default::default() + } +} + +fn own() -> Vec { + vec!["acme-camps.test".into()] +} + +#[test] +fn every_portal_id_is_held_to_a_probe_even_wrapped_or_kept() { + // The ids the gate reads: all four, wrapped and pattern ones too. + assert_eq!( + probe::selectors_in(PAGE_OBJECT), + vec![ + "/^portal-segment-option-guest-\\d+$/", + "/^portal-segment-tag-guest-\\d+$/", + "portal-cart-preview-subtotal", + "portal-registration", + ] + ); + // The second run's change added no selector line; the kept ones are + // still the gate's. + let files = vec![( + "e2e/pages/camp-registration.ts".to_string(), + PAGE_OBJECT.to_string(), + " // the page header now scrolls away".to_string(), + )]; + let gaps = probe::unprobed(&files, &[], &own()); + assert_eq!(gaps.len(), 1); + assert_eq!(gaps[0].origin, PORTAL); + assert_eq!(gaps[0].missing.len(), 4); + assert!(probe::unprobed(&files, &[probe_of(false)], &own()).is_empty()); +} + +#[test] +fn the_write_waits_for_a_probe_and_the_round_records_it() { + let g = LiveGuard::new(vec![], own(), vec![]); + let refusal = g + .check_e2e("e2e/pages/camp-registration.ts", PAGE_OBJECT) + .unwrap_err(); + assert!(refusal.starts_with("Not written:")); + assert!(refusal.contains("`portal-cart-preview-subtotal`")); + assert!(refusal.contains("`clicks`")); + // The probe tool's answer carries its record; the round keeps it (and + // commits it at its path) and the write goes through. + let answer = format!( + "Probe of the portal.\n{}\n{}", + probe::RECORD_MARK, + serde_json::to_string(&probe_of(false)).unwrap() + ); + let r = g + .saw_probe(&serde_json::json!({"url": probe_of(false).url}), &answer) + .expect("a record"); + assert_eq!( + probe::record_path(&r.origin), + ".coderhelm/probes/portal.vendor.test.json" + ); + assert!(g + .check_e2e("e2e/pages/camp-registration.ts", PAGE_OBJECT) + .is_ok()); +} + +#[test] +fn the_open_branch_is_unverified_until_a_run_takes_it() { + let b = state_branches("e2e/pages/camp-registration.ts", PAGE_OBJECT); + assert_eq!(b.len(), 1); + assert_eq!( + b[0].subject.as_deref(), + Some("/^portal-segment-option-guest-\\d+$/") + ); + let files = vec![( + "e2e/pages/camp-registration.ts".to_string(), + Some(PAGE_OBJECT.to_string()), + PAGE_OBJECT.to_string(), + )]; + // Registration closed, as on the day the branch was written: the open + // arm is unverified in the pull request and nothing asks the coder to + // run what can't run; the closed arm, which the page shows, is the one + // it runs and records. + let closed = assess(&files, &[probe_of(false)], &[], &own(), ""); + let open_arm = closed.arms.iter().find(|a| a.when).unwrap(); + assert_eq!(open_arm.state, "unverified"); + let section = closed.section(); + assert!(section.contains("**Outside pages, as a probe saw them**")); + assert!(section.contains("unverified: no recorded run took it; CoderHelm runs it once the page shows that state")); + let lines = closed.blocking(); + assert_eq!(lines.len(), 1); + assert!(lines[0].contains(" when false: {\n expect(\n screen.queryByText(\"Open registration in a new tab\")\n ).toBeNull();\n });\n"; + let new = " expect((iframe as HTMLIFrameElement).style.width).toBe(\"100%\");\n });\n it(\"has no link\", () => {\n expect(screen.queryByText(\"Open registration in a new tab\")).toBeNull();\n });\n"; + let Shaped::Write(kept, n) = g.shape("web/src/test/portal-embed.test.tsx", old, new, true) + else { + panic!("the fix's lines are written"); + }; + assert_eq!(n, 1); + assert!(!kept.contains("h-svh!")); + assert!(kept.contains(" expect(\n screen.queryByText(")); + // An end-to-end file the fix doesn't change is never re-wrapped. + let e2e_old = "await expect(\n page.getByRole(\"heading\")\n).toBeVisible();\n"; + let e2e_new = "await expect(page.getByRole('heading')).toBeVisible();\n"; + assert!(matches!( + g.shape("e2e/tests/browse/camps.spec.ts", e2e_old, e2e_new, false), + Shaped::Refused(m) if m.contains("only reformats") + )); + // A file only reformatted on the branch goes back after the build. + let facts = assess( + &[( + "e2e/tests/browse/camps.spec.ts".to_string(), + Some(e2e_old.to_string()), + e2e_new.to_string(), + )], + &[], + &[], + &own(), + "", + ); + assert_eq!(facts.reformatted, vec!["e2e/tests/browse/camps.spec.ts"]); + assert!(facts.blocking()[0].contains("restore_file")); +} + +#[test] +fn every_write_path_and_the_check_after_the_build_use_the_guard() { + let implement = include_str!("../implement.rs"); + assert_eq!(implement.matches(".live_write(").count(), 3); + assert!(implement.contains("live.saw_probe(input, &out)")); + assert!(implement.contains("commit_probe(&record)")); + let habits = include_str!("../habits_check.rs"); + assert!(habits.contains("live_guard::facts_for(")); + assert!(habits.contains("f.live.blocking()")); + assert!(habits.contains("f.live.section()")); + let review = include_str!("../review_pr.rs"); + assert!(review.contains("probe_gaps(")); +} diff --git a/services/worker/src/passes/live_guard.rs b/services/worker/src/passes/live_guard.rs new file mode 100644 index 000000000..3b22369c4 --- /dev/null +++ b/services/worker/src/passes/live_guard.rs @@ -0,0 +1,708 @@ +//! What a write may carry: selectors seen on the live page, and only the +//! lines the change needs. +//! +//! A portal spec was written twice from guesses. The first time the coder +//! tried to load the vendor's page with Playwright, its shell refused the +//! command, and it read test-id strings out of the vendor's script bundle +//! instead; the second time a fix round kept that code untouched while it +//! edited the file around it. Neither ever saw what a signed-out visitor +//! gets. The same rounds re-wrapped lines in files CI never formats. +//! +//! In every coder round now, before a write is made: +//! +//! - **An end-to-end file that drives another company's page carries only +//! test ids a probe saw** ([`LiveGuard::check_e2e`]): the ids the write +//! adds and the ones it keeps. The probe is the `probe_page` tool, its +//! record committed on the branch by the round itself +//! ([`LiveGuard::saw_probe`]). Until there is one, the write is refused +//! with what to probe. When the probe of that page can't run (a refused +//! host, a sandbox failure), the write goes ahead and the selectors are +//! kept as unprobed in the round's evidence, which the pull request +//! lists: never a dead end, never silent. +//! - **A write that only reformats is not made, and a write's formatting +//! hunks are put back** ([`LiveGuard::shape`]), unless the repository's +//! CI checks that file's formatting and the change touches it anyway. + +use std::sync::Mutex; + +use serde::{Deserialize, Serialize}; + +use common::diff_shape; +use common::e2e::probe::{self, ProbeRecord}; + +/// What a write's text becomes, or why it is not made. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Shaped { + /// Write this text (the write's own, or with formatting hunks put back: + /// how many). + Write(String, usize), + /// Not written: why, for the coder. + Refused(String), +} + +/// Selectors written without a probe: path, origin, ids, why none ran. +type Kept = (String, String, Vec, String); + +/// The guard of one coder round. +#[derive(Debug, Default)] +pub struct LiveGuard { + /// CI's formatter checks (`prettier --check`, `cargo fmt --check`, ...). + ci_formats: Vec, + /// The team's own hosts: their pages need no probe. + own: Vec, + /// Probe records: the branch's, and this round's. + records: Mutex>, + /// Hosts a probe was tried on and couldn't run, with why. + failed: Mutex>, + /// Selectors written without a probe because none could run: path, + /// origin, ids, why. + unprobed: Mutex>, + /// Formatting hunks put back: path, how many. + dropped: Mutex>, +} + +/// Whether a path is end-to-end test code. +pub fn is_e2e(path: &str) -> bool { + let p = path.to_ascii_lowercase(); + let code = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] + .iter() + .any(|e| p.ends_with(e)); + code && (p.starts_with("e2e/") + || p.contains("/e2e/") + || p.contains("playwright/") + || p.contains("cypress/") + || p.contains(".e2e.") + || p.contains(".cy.")) +} + +impl LiveGuard { + /// A round's guard: CI's formatter commands, the team's own hosts and + /// the probe records on the branch. + pub fn new(ci_formats: Vec, own: Vec, records: Vec) -> Self { + Self { + ci_formats, + own, + records: Mutex::new(records), + ..Default::default() + } + } + + /// The text a write of `path` makes, from `old` (the branch's) to + /// `new`. `touched` says whether the change already changes the file + /// against the base branch. + pub fn shape(&self, path: &str, old: &str, new: &str, touched: bool) -> Shaped { + if old == new { + return Shaped::Write(new.to_string(), 0); + } + let ci = diff_shape::ci_formats(&self.ci_formats, path); + if diff_shape::format_only(path, old, new) { + if touched && ci { + // CI checks this file's formatting and the change is in it: + // the formatter's lines are the change's to carry. + return Shaped::Write(new.to_string(), 0); + } + return Shaped::Refused(format!( + "Not written: this write only reformats `{path}` (whitespace, wrapping, quotes, trailing commas). {} Keep the file as it is and change only the lines the fix needs.", + if ci { + "The change doesn't otherwise touch it, so CI's format check already passes on it." + } else { + "The repository's CI doesn't check its formatting, so a reformat is churn a reviewer has to read past." + } + )); + } + if ci { + return Shaped::Write(new.to_string(), 0); + } + let (kept, n) = diff_shape::drop_format_hunks(path, old, new); + if n > 0 { + self.dropped.lock().unwrap().push((path.to_string(), n)); + } + Shaped::Write(kept, n) + } + + /// Records a probe tool's answer: its record (committed by the caller) + /// or the host it couldn't probe. + pub fn saw_probe(&self, input: &serde_json::Value, answer: &str) -> Option { + if let Some(r) = probe::record_in(answer) { + let mut records = self.records.lock().unwrap(); + records.retain(|x| !x.origin.eq_ignore_ascii_case(&r.origin)); + records.push(r.clone()); + return Some(r); + } + let url = input["url"].as_str().unwrap_or(""); + let host = url + .split("://") + .nth(1) + .unwrap_or(url) + .split(['/', '?', '#']) + .next() + .unwrap_or("") + .to_ascii_lowercase(); + if !host.is_empty() { + self.failed + .lock() + .unwrap() + .push((host, common::truncate_str(answer.trim(), 200).to_string())); + } + None + } + + /// Whether a write of `path` with the full text `new` may go ahead: + /// every test id it uses on a page another company serves was seen by + /// a probe of that page, or a probe of it was tried and couldn't run. + pub fn check_e2e(&self, path: &str, new: &str) -> Result<(), String> { + if !is_e2e(path) { + return Ok(()); + } + let records = self.records.lock().unwrap().clone(); + let gaps = probe::unprobed( + &[(path.to_string(), new.to_string(), String::new())], + &records, + &self.own, + ); + let mut refuse = Vec::new(); + for g in gaps { + let failed = self + .failed + .lock() + .unwrap() + .iter() + .find(|(h, _)| g.origin == probe::FRAMED || h.eq_ignore_ascii_case(&g.origin)) + .map(|(_, why)| why.clone()); + match failed { + Some(why) => { + let mut u = self.unprobed.lock().unwrap(); + u.retain(|(p, o, _, _)| !(p == path && *o == g.origin)); + u.push((path.to_string(), g.origin.clone(), g.missing.clone(), why)); + } + None => refuse.push(g), + } + } + if refuse.is_empty() { + return Ok(()); + } + Err(format!( + "Not written: {} Then write again: the probe's record is committed for you and this write goes through once every test id it uses (added or kept) is one the probe saw.", + refuse + .iter() + .map(|g| g.body()) + .collect::>() + .join(" ") + )) + } + + /// The round's evidence lines: selectors kept without a probe (and why + /// none could run), and formatting put back. The habits check and the + /// pull request read them. + pub fn evidence_lines(&self) -> String { + let mut out = String::new(); + for (path, origin, ids, why) in self.unprobed.lock().unwrap().iter() { + out.push_str(&format!( + "Unprobed: {path}: {origin}: {}: the probe couldn't run ({why})\n", + ids.join(", ") + )); + } + for (path, n) in self.dropped.lock().unwrap().iter() { + out.push_str(&format!( + "Formatting put back: {path}: {n} hunk(s) that only reformatted\n" + )); + } + out + } +} + +/// The probe records committed on `branch` (`.coderhelm/probes/`). +pub async fn branch_records( + github: &crate::clients::github::GitHubClient, + owner: &str, + repo: &str, + branch: &str, +) -> Vec { + let Ok(tree) = github.get_tree(owner, repo, branch).await else { + return Vec::new(); + }; + let mut out = Vec::new(); + for e in tree.iter().filter(|e| probe::is_record(&e.path)).take(20) { + if let Ok(text) = github.read_file(owner, repo, &e.path, branch).await { + if let Ok(r) = serde_json::from_str::(&text) { + out.push(r); + } + } + } + out +} + +/// Commits a probe's record at its path on `branch` (`message` is the +/// commit's). The path, or why it couldn't be written. +pub async fn commit_record( + github: &crate::clients::github::GitHubClient, + (owner, repo, branch): (&str, &str, &str), + record: &ProbeRecord, + message: &str, +) -> Result { + let path = probe::record_path(&record.origin); + let body = serde_json::to_string_pretty(record).unwrap_or_default() + "\n"; + let sha = github.get_file_sha(owner, repo, &path, branch).await.ok(); + github + .write_file(owner, repo, &path, &body, branch, message, sha.as_deref()) + .await + .map(|_| path) + .map_err(|e| e.to_string()) +} + +/// The CI formatter commands among a round's CI steps. +pub fn format_cmds(steps: &[super::checks::Step]) -> Vec { + steps + .iter() + .filter(|s| s.kinds.contains(&super::checks::CheckKind::Format)) + .map(|s| s.cmd.clone()) + .collect() +} + +// ── After the build: what the pull request says and what goes back ───────── + +/// A test branch's arm and what is known of it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ArmLine { + pub path: String, + /// The branch's line. + pub line: usize, + /// Whether its condition holds on this arm. + pub when: bool, + /// How a person reads it ("when `isEnabled()` on `…` is true"). + pub words: String, + /// `ran`: a recorded run took it (`why` says which); `now`: the page + /// shows its state now (`why` says which probe); `unverified`. + pub state: String, + #[serde(default)] + pub why: String, +} + +/// Selectors a probe of their page didn't see. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct UnprobedLine { + pub path: String, + pub origin: String, + pub missing: Vec, + /// Why no probe could run; empty when none was tried. + #[serde(default)] + pub why_none: String, +} + +/// What the check reads from the change's end-to-end files and diff. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct LiveFacts { + /// The probes of the pages the change's end-to-end files drive. + pub probes: Vec, + pub unprobed: Vec, + /// Arms of test branches on a page's state. + pub arms: Vec, + /// Changed files whose change is only formatting. + pub reformatted: Vec, + /// Formatting the rounds put back: path, hunks. + pub put_back: Vec<(String, usize)>, +} + +/// The evidence line a coder writes once it ran a branch's arm: +/// `Branch ran: : when : `. +pub const RAN_LINE: &str = "branch ran:"; + +fn evidence(notes: &str, mark: &str) -> Vec { + notes + .lines() + .filter_map(|l| { + let l = l.trim().trim_start_matches(['-', '*']).trim(); + let at = l.to_ascii_lowercase().find(mark)?; + Some(l[at + mark.len()..].trim().to_string()) + }) + .collect() +} + +/// Reads the change: `files` are (path, base text when it existed, head +/// text); `records` the probes on the branch; `fresh` probes taken now; +/// `notes` the rounds' evidence lines. +pub fn assess( + files: &[(String, Option, String)], + records: &[ProbeRecord], + fresh: &[ProbeRecord], + own: &[String], + notes: &str, +) -> LiveFacts { + let mut f = LiveFacts::default(); + let latest = |origin: &str| -> Option<&ProbeRecord> { + fresh + .iter() + .chain(records.iter()) + .find(|r| r.origin.eq_ignore_ascii_case(origin)) + }; + let couldnt: Vec<(String, String)> = evidence(notes, "unprobed:") + .into_iter() + .filter_map(|rest| { + let mut parts = rest.splitn(4, ": "); + let path = parts.next()?.trim().to_string(); + let origin = parts.next()?.trim().to_string(); + let _ids = parts.next(); + Some(( + format!("{path}\u{1}{origin}"), + parts.next().unwrap_or("").to_string(), + )) + }) + .collect(); + let ran = evidence(notes, RAN_LINE); + for (path, base, head) in files { + if let Some(base) = base { + if diff_shape::format_only(path, base, head) { + f.reformatted.push(path.clone()); + } + } + if !is_e2e(path) { + continue; + } + let origins = probe::outside_origins(head, own); + for o in &origins { + let rs: Vec<&ProbeRecord> = if o == probe::FRAMED { + fresh.iter().chain(records.iter()).collect() + } else { + latest(o).into_iter().collect() + }; + for r in rs { + if !f.probes.iter().any(|p| p.origin == r.origin) { + f.probes.push(r.clone()); + } + } + } + let all: Vec = fresh.iter().chain(records.iter()).cloned().collect(); + for g in probe::unprobed(&[(path.clone(), head.clone(), String::new())], &all, own) { + let why_none = couldnt + .iter() + .find(|(k, _)| *k == format!("{}\u{1}{}", g.path, g.origin)) + .map(|(_, w)| w.clone()) + .unwrap_or_default(); + f.unprobed.push(UnprobedLine { + path: g.path, + origin: g.origin, + missing: g.missing, + why_none, + }); + } + if origins.is_empty() { + continue; + } + for b in common::e2e::branches::state_branches(path, head) { + let probe_now = origins + .iter() + .filter_map(|o| latest(o)) + .find_map(|r| common::e2e::branches::runnable_now(&b, r).map(|w| (w, r))); + for arm in &b.arms { + let key = format!("{path}:{} when {}", b.line, arm.when); + let (state, why) = if let Some(r) = ran.iter().find(|r| r.starts_with(&key)) { + ("ran", r.split_once(": ").map_or("", |x| x.1).to_string()) + } else { + match probe_now { + Some((w, r)) if w == arm.when => ( + "now", + format!("the probe of `{}` at {} shows that state", r.origin, r.at), + ), + _ => ("unverified", String::new()), + } + }; + f.arms.push(ArmLine { + path: path.clone(), + line: b.line, + when: arm.when, + words: b.arm_words(arm), + state: state.to_string(), + why, + }); + } + } + } + for rest in evidence(notes, "formatting put back:") { + if let Some((path, n)) = rest.split_once(": ") { + let n = n + .split_whitespace() + .next() + .and_then(|x| x.parse().ok()) + .unwrap_or(1); + f.put_back.push((path.trim().to_string(), n)); + } + } + f +} + +impl LiveFacts { + /// What the coder must fix, one line each. + pub fn blocking(&self) -> Vec { + let mut out = Vec::new(); + for u in self.unprobed.iter().filter(|u| u.why_none.is_empty()) { + out.push( + probe::Unprobed { + path: u.path.clone(), + origin: u.origin.clone(), + missing: u.missing.clone(), + } + .body(), + ); + } + for p in &self.reformatted { + out.push(format!( + "`{p}` is only reformatted: the fix changes nothing in it. Put it back with `restore_file` (omit `from_ref`)." + )); + } + for a in self.arms.iter().filter(|a| a.state == "now") { + out.push(format!( + "`{}:{}`: the branch {} has never run in a recorded run, and {} now. Run that spec against the live page now (the repository's Playwright command with its base address set to staging or the vendor), fix the branch from what the page really does, and when it passes write `Branch ran: {}:{} when {}: ` in your Evidence.", + a.path, + a.line, + a.words, + a.why, + a.path, + a.line, + a.when + )); + } + out + } + + /// The pull request's lines: the probes quoted, selectors no probe saw + /// (with why), each test branch's arm and whether a run took it, and + /// formatting put back. Empty when there is nothing to say. + pub fn section(&self) -> String { + let mut out = String::new(); + if !self.probes.is_empty() { + out.push_str("**Outside pages, as a probe saw them**\n"); + for r in &self.probes { + out.push_str(&probe::quote(r)); + } + out.push('\n'); + } + let kept: Vec<&UnprobedLine> = self.unprobed.iter().collect(); + if !kept.is_empty() { + out.push_str("**Selectors no probe saw**\n"); + for u in kept { + let why = if u.why_none.is_empty() { + "no probe yet; CoderHelm probes the page in its next round".to_string() + } else { + format!("no probe could run: {}", u.why_none) + }; + out.push_str(&format!( + "- `{}` on `{}`: {} ({why}).\n", + u.path, + u.origin, + u.missing + .iter() + .map(|m| format!("`{m}`")) + .collect::>() + .join(", ") + )); + } + out.push('\n'); + } + if !self.arms.is_empty() { + out.push_str("**Test branches on the page's state**\n"); + for a in &self.arms { + let state = match a.state.as_str() { + "ran" => format!("ran: {}", a.why), + "now" => format!( + "unverified: no recorded run took it; {}, so CoderHelm runs it in its next round", + a.why + ), + _ => "unverified: no recorded run took it; CoderHelm runs it once the page shows that state".to_string(), + }; + out.push_str(&format!( + "- `{}:{}` {}: {state}.\n", + a.path, a.line, a.words + )); + } + out.push('\n'); + } + if !self.put_back.is_empty() { + out.push_str("**Formatting put back** (the fix's lines only)\n"); + for (p, n) in &self.put_back { + out.push_str(&format!("- `{p}`: {n} hunk(s) that only reformatted.\n")); + } + out.push('\n'); + } + out + } + + /// The Open items point and how it settles, for one of [`blocking`]'s + /// lines. + pub fn point_of(&self, line: &str) -> Option<(&'static str, &'static str)> { + if !self.blocking().iter().any(|b| b == line) { + return None; + } + Some(if line.contains("no probe of that page observed") { + ( + "Selectors no probe saw", + "CoderHelm probes the page and rebuilds the selectors from what it saw in its next round on this pull request.", + ) + } else if line.contains("is only reformatted") { + ( + "Reformatted a file the fix doesn't change", + "CoderHelm puts it back in its next round on this pull request.", + ) + } else { + ( + "Test branch never run", + "CoderHelm runs it against the live page and fixes it from what it does in its next round on this pull request.", + ) + }) + } +} + +/// Probes the pages the change's end-to-end branches read again, now (at +/// most two), from their committed records' address and clicks: a branch +/// that couldn't run before is re-checked once the page can take it. +pub async fn fresh_probes( + state: &crate::WorkerState, + team_id: &str, + records: &[ProbeRecord], + files: &[(String, Option, String)], + own: &[String], +) -> Vec { + let mut wanted: Vec<&ProbeRecord> = Vec::new(); + for (path, _, head) in files.iter().filter(|(p, _, _)| is_e2e(p)) { + if common::e2e::branches::state_branches(path, head) + .iter() + .all(|b| b.subject.is_none()) + { + continue; + } + for o in probe::outside_origins(head, own) { + if let Some(r) = records.iter().find(|r| r.origin.eq_ignore_ascii_case(&o)) { + if !wanted.iter().any(|w| w.origin == r.origin) { + wanted.push(r); + } + } + } + } + let mut out = Vec::new(); + for r in wanted.into_iter().take(2) { + let clicks: Vec = r.steps.iter().map(|s| s.click.clone()).collect(); + match super::web_check::run_probe(state, team_id, &r.url, &r.origin, &clicks).await { + Ok(n) => out.push(n), + Err(e) => { + tracing::warn!(origin = %r.origin, error = %e, "Could not probe the page again") + } + } + } + out +} + +/// The facts for the habits check: the changed files' base and head text, +/// the branch's probes, a fresh probe of the pages whose state the +/// branches read (when there is time), and the rounds' evidence lines. +pub async fn facts_for( + w: &super::proof::Work<'_>, + diff: &[(String, String, String)], + notes: &str, + probe_again: bool, +) -> LiveFacts { + let (owner, repo) = (&w.msg.repo_owner, &w.msg.repo_name); + let mut files = Vec::new(); + for (path, status, _) in diff + .iter() + .filter(|(p, s, _)| s != "removed" && !probe::is_record(p)) + .take(40) + { + let Ok(head) = w.github.read_file(owner, repo, path, w.branch).await else { + continue; + }; + let base = if status == "added" { + None + } else { + w.github + .read_file(owner, repo, path, &w.msg.base_branch) + .await + .ok() + }; + files.push((path.clone(), base, head)); + } + let records = branch_records(w.github, owner, repo, w.branch).await; + let own = super::web_check::team_domains(w.state, &w.msg.team_id).await; + let fresh = if probe_again { + fresh_probes(w.state, &w.msg.team_id, &records, &files, &own).await + } else { + Vec::new() + }; + assess(&files, &records, &fresh, &own, notes) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const PORTAL: &str = "const URL = 'https://portal.vendor.test/p/1';\nexport class P {\n cart() { return this.f.getByTestId('cart-subtotal'); }\n}\n"; + + #[test] + fn an_outside_selector_waits_for_a_probe_or_its_failure() { + let g = LiveGuard::new(vec![], vec!["acme.test".into()], vec![]); + let e = g.check_e2e("e2e/pages/portal.ts", PORTAL).unwrap_err(); + assert!(e.contains("`cart-subtotal`")); + assert!(e.contains("probe_page")); + // Not end-to-end code: no gate. + assert!(g.check_e2e("apps/web/src/a.tsx", PORTAL).is_ok()); + // A probe that saw it lets the write through. + let r = ProbeRecord { + origin: "portal.vendor.test".into(), + testids: vec!["cart-subtotal".into()], + ..Default::default() + }; + let answer = format!( + "Probe of x.\n{}\n{}", + probe::RECORD_MARK, + serde_json::to_string(&r).unwrap() + ); + assert_eq!( + g.saw_probe(&json!({"url": "https://portal.vendor.test/p/1"}), &answer), + Some(r) + ); + assert!(g.check_e2e("e2e/pages/portal.ts", PORTAL).is_ok()); + } + + #[test] + fn a_probe_that_cannot_run_is_no_dead_end_and_is_said() { + let g = LiveGuard::new(vec![], vec![], vec![]); + g.saw_probe( + &json!({"url": "https://portal.vendor.test/p/1"}), + "https://portal.vendor.test/p/1: the sandbox couldn't run the probe (timeout)", + ); + assert!(g.check_e2e("e2e/pages/portal.ts", PORTAL).is_ok()); + assert!(g.evidence_lines().contains( + "Unprobed: e2e/pages/portal.ts: portal.vendor.test: cart-subtotal: the probe couldn't run" + )); + } + + #[test] + fn reformatting_is_not_written_and_formatting_hunks_go_back() { + let g = LiveGuard::new(vec![], vec![], vec![]); + let old = "expect(\n a('x')\n).toBe(1)\nconst n = 1\n"; + let reformat = "expect(a(\"x\")).toBe(1);\nconst n = 1;\n"; + assert!(matches!( + g.shape("e2e/a.spec.ts", old, reformat, false), + Shaped::Refused(m) if m.contains("only reformats") + )); + let mixed = "expect(a(\"x\")).toBe(1);\nconst n = 2;\n"; + assert_eq!( + g.shape("e2e/a.spec.ts", old, mixed, true), + Shaped::Write("expect(\n a('x')\n).toBe(1)\nconst n = 2;\n".into(), 1) + ); + assert!(g + .evidence_lines() + .contains("Formatting put back: e2e/a.spec.ts: 1 hunk(s)")); + // Where CI checks formatting and the change is in the file, the + // formatter's lines stay. + let ci = LiveGuard::new(vec!["npx prettier --check .".into()], vec![], vec![]); + assert_eq!( + ci.shape("web/a.ts", old, reformat, true), + Shaped::Write(reformat.into(), 0) + ); + assert!(matches!( + ci.shape("web/a.ts", old, reformat, false), + Shaped::Refused(_) + )); + } +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 136c0d72d..a2e9589cd 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1310,6 +1310,9 @@ pub mod lesson_cleanup; pub mod lessons; pub mod line_count; mod link_checks; +/// Selectors on another company's page come from a probe of it; a write carries +/// only the lines the change needs. +pub mod live_guard; pub mod live_sources; pub mod log_autofix; pub mod log_evidence; @@ -10083,10 +10086,11 @@ an end-to-end spec in that suite for the new behaviour, in this same branch. Fol 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. \ -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"; +Assert what the person sees. Before writing or keeping selectors or reading JSON of a page another company \ +serves (a payment form, a sign-in widget, a portal in a frame), probe it with `probe_page` (on the preview or \ +the vendor's URL, with `clicks` that reach each state a branch of the spec reads); the record is committed for \ +you, the pull request quotes it, and a write using test ids no probe saw is not made. A branch on the page's \ +state (enabled or not, visible or not) that no run has taken is unverified, and the pull request says so.\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/web_check.rs b/services/worker/src/passes/web_check.rs index 5e5dd5147..1b476d387 100644 --- a/services/worker/src/passes/web_check.rs +++ b/services/worker/src/passes/web_check.rs @@ -83,24 +83,90 @@ pub fn probe_tool() -> 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.", + there: every test id (data-testid, data-test, data-cy, also inside frames) with its \ + state (visible, enabled, its text), and the field names of the JSON responses it \ + fetches. With `clicks` (test ids or /patterns/), it clicks each in turn and lists \ + what each click brings up, so the state every branch of a spec depends on is seen \ + (what a signed-out visitor gets after choosing an item, a drawer, a disabled \ + button). Use it BEFORE writing or keeping end-to-end selectors or JSON fields of a \ + page another company serves (or a page on the preview), and build the spec only \ + from what it found. The record is committed at `{}` for you; quote it 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" } + "url": { "type": "string", "description": "The https page to probe" }, + "clicks": { + "type": "array", + "items": { "type": "string" }, + "description": "Test ids (or /patterns/ matching them) to click in turn after the page loads, each listed with what it brings up: the path a spec takes, so each of its branches' states is observed" + } }, "required": ["url"] }), } } +/// Loads `url` (on `host`) in the sandbox with Playwright, clicks each of +/// `clicks` in turn, and gives what it saw (`common::e2e::probe`). The +/// probe tool runs it, and the habits check runs it again to re-check a +/// test branch on a page whose state can change. +pub async fn run_probe( + state: &WorkerState, + team_id: &str, + url: &str, + host: &str, + clicks: &[String], +) -> Result { + let source = super::skill_run::pack(&[( + "probe.mjs".to_string(), + common::e2e::probe::probe_script(url, clicks), + )]) + .map_err(|e| 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, team_id).await); + let mut hosts: Vec = common::preview::CAPTURE_HOSTS + .iter() + .map(|h| h.to_string()) + .collect(); + hosts.push(host.to_string()); + 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 + .map_err(|e| format!("the sandbox couldn't run the probe ({e})"))?; + let body = out + .files + .iter() + .find(|(n, _)| n.ends_with("probe.json")) + .map(|(_, b)| b.clone()) + .ok_or_else(|| { + format!( + "the probe gave no record ({})", + common::truncate_str(out.output.lines().last().unwrap_or(""), 200) + ) + })?; + serde_json::from_str(&body).map_err(|e| format!("the probe's record couldn't be read ({e})")) +} + pub fn tool() -> ToolDefinition { ToolDefinition { name: TOOL.to_string(), @@ -1303,6 +1369,17 @@ impl WebCheck { /// 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 clicks: Vec = input["clicks"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|c| c.as_str()) + .map(|c| c.trim().to_string()) + .filter(|c| !c.is_empty()) + .take(8) + .collect() + }) + .unwrap_or_default(); let (parsed, host) = match vet_url(&url) { Ok(v) => v, Err(CheckError::Refused(m)) | Err(CheckError::Failed(m)) => { @@ -1314,57 +1391,19 @@ impl WebCheck { "{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) - ) + match run_probe(state, &self.team_id, parsed.as_str(), &host, &clicks).await { + Ok(record) => format!( + "Probe of {url}. It is committed at `{}`; quote what it found in the pull request and write selectors, field reads and each branch's expectations only from it:\n{}\n{}\n{}", + common::e2e::probe::record_path(&host), + common::e2e::probe::quote(&record).trim_end(), + common::e2e::probe::RECORD_MARK, + common::truncate_str( + &serde_json::to_string(&record).unwrap_or_default(), + 12_000 + ) + ), + Err(why) => format!("{url}: {why}"), + } } async fn run_urls( From 536594dcf2a95ee3a300d8a5ec818d3c269a2ccb Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 17 Nov 2026 11:43:04 -0500 Subject: [PATCH 2/2] Format the incident files --- .../src/passes/incidents/cv_portal_branch_from_a_guess.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/services/worker/src/passes/incidents/cv_portal_branch_from_a_guess.rs b/services/worker/src/passes/incidents/cv_portal_branch_from_a_guess.rs index 6ef391dc8..f3f6ad4b2 100644 --- a/services/worker/src/passes/incidents/cv_portal_branch_from_a_guess.rs +++ b/services/worker/src/passes/incidents/cv_portal_branch_from_a_guess.rs @@ -215,7 +215,9 @@ fn the_open_branch_is_unverified_until_a_run_takes_it() { assert_eq!(open_arm.state, "unverified"); let section = closed.section(); assert!(section.contains("**Outside pages, as a probe saw them**")); - assert!(section.contains("unverified: no recorded run took it; CoderHelm runs it once the page shows that state")); + assert!(section.contains( + "unverified: no recorded run took it; CoderHelm runs it once the page shows that state" + )); let lines = closed.blocking(); assert_eq!(lines.len(), 1); assert!(lines[0].contains(" when false: