From ab77580a79ab81539e1e2e2b9d2492e82a430b61 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 17 Nov 2026 14:15:27 -0500 Subject: [PATCH] Each ticket criterion is proven end to end both ways; twin helpers in one change are caught The plan maps each criterion that names a page or what a person sees to an end-to-end test of that page (Criteria map), and is sent back without it. Before the pull request is done, each test runs on staging (must fail) and on the preview (must pass) through the red-check runner; both results go on the run and into the pull request. A test passing on both, failing on the preview or missing goes back to the coder; a side that couldn't run is labelled unverified with its reason. New helpers in one diff are compared with each other, and the coder's guard asks a second similar helper to name what it shares. --- docs/coder-loop.md | 38 + .../incidents/cp_criteria_proven_both_ways.md | 5 + services/common/src/ci_repro.rs | 3 +- services/common/src/e2e_proof.rs | 880 ++++++++++++++++++ services/common/src/lib.rs | 3 + services/worker/src/passes/ci_repro.rs | 109 ++- services/worker/src/passes/description.rs | 5 + .../worker/src/passes/description_facts.rs | 28 + services/worker/src/passes/e2e_proof.rs | 349 +++++++ services/worker/src/passes/explore_guard.rs | 134 ++- .../incidents/cp_criteria_proven_both_ways.rs | 290 ++++++ services/worker/src/passes/minimal_change.rs | 270 +++++- services/worker/src/passes/mod.rs | 3 + services/worker/src/passes/plan.rs | 21 +- services/worker/src/passes/plan_shape.rs | 21 + services/worker/src/passes/pr_watch.rs | 33 +- services/worker/src/passes/ready.rs | 42 +- 17 files changed, 2184 insertions(+), 50 deletions(-) create mode 100644 docs/incidents/cp_criteria_proven_both_ways.md create mode 100644 services/common/src/e2e_proof.rs create mode 100644 services/worker/src/passes/e2e_proof.rs create mode 100644 services/worker/src/passes/incidents/cp_criteria_proven_both_ways.rs diff --git a/docs/coder-loop.md b/docs/coder-loop.md index 36978cff1..dada743f2 100644 --- a/docs/coder-loop.md +++ b/docs/coder-loop.md @@ -68,6 +68,16 @@ The causes were in the loop, not only in prompt wording: ticket asks to replace. The camps run's plan named the right map, then reused the link helper that deletes every link it isn't given. + The plan also writes `## Criteria map`: one line for each acceptance + criterion (or Expected line, when the ticket has no acceptance list) that + names a page or what a person sees, with the page, an end-to-end test in + the repository's suite that loads it, and what it asserts + (`common::e2e_proof`). A plan without that line, or with a unit test in + place of the end-to-end test, is sent back (`plan_shape::criteria_gaps`). + Unit tests may go with it; they never replace it. A ticket once asked + for one chip on one page and got about 530 lines of unit tests and no + test of the page (`incidents::cp_criteria_proven_both_ways`). + Whatever is still open after the one send-back stays on the decision. 4. **Implement.** In the coder's tool loop (`explore_guard`): @@ -75,6 +85,10 @@ The causes were in the loop, not only in prompt wording: names what it reuses (`reuses`). - An edit that adds a top-level map, helper or config beside a similar existing one is refused unless it says why (`why_new`). + - An edit that adds a helper whose name or body nearly matches one this + build already added (in that edit or an earlier one) is refused unless + it names what they share (`shares`). The check above compares new code + with old, so three near-identical helpers added together once passed it. Both are kept as evidence lines. The coder's prompt carries the same rules (`SMALLEST_CHANGE_RULES`). The data rules ask for reporting on a skip only when @@ -83,6 +97,9 @@ The causes were in the loop, not only in prompt wording: 5. **Review against the ticket.** After the build, the habits check reads the diff against the base and the ticket (`minimal_change::check`). It flags: - parallel structures; + - twin helpers: two new helpers in the same diff whose names parallel each + other, or whose signatures and bodies nearly match + (`minimal_change::twin_helpers`); - deleting or overwriting semantics where the base only added; - log level changes; - new counters and log calls nobody asked for; @@ -120,6 +137,27 @@ The causes were in the loop, not only in prompt wording: run) is judged again with what it found, even when it wrote no code (`proof::round_answered`, `incidents::cn_proof_answer_judged`). + **Two ways, end to end.** Before the pull request is called done, once + its preview is up and its own end-to-end checks passed, the pull request + watch runs each criterion's test (the one the criteria map names, else a + changed spec that loads the criterion's page) on the base branch's + deployment (staging) and on the preview, in the sandbox, with the runner + that reproduces a red check (`ci_repro::two_way`, from #754). Both results + are kept on the run (`e2e_proof`), said on the run page, and written into + the pull request: a proven criterion as a check with both results, + anything else as unverified with what each side did + (`description_facts::with_two_way`). + - Fails on staging, passes on the preview: proven. + - Passes on both: it doesn't test the ticket; back to the coder. + - Fails on the preview, or no test of the page on the head: back to the + coder. + - A side that couldn't run (no browser, no network, no address): + unverified, with the reason, on the pull request. Never a silent pass. + + Work it sends back is a fix round (`resume::queue_own_review_round`), and + the ready decision waits while the proof runs or the round fixes it + (`ready::decide`, `e2e_proof::standing`). + 7. **Rounds agree.** Planned work that a review commit on the pull request took out is not built again by a planned-work round, and the run says which commit took it diff --git a/docs/incidents/cp_criteria_proven_both_ways.md b/docs/incidents/cp_criteria_proven_both_ways.md new file mode 100644 index 000000000..59fbe0376 --- /dev/null +++ b/docs/incidents/cp_criteria_proven_both_ways.md @@ -0,0 +1,5 @@ +# cp. `cp_criteria_proven_both_ways` + +**What happened:** A ticket asked for one thing: on a venue's summer camps page, the sports filter showed two Multi-Sport chips and should show one. The run wrote about 530 lines of unit tests in five files and never loaded the page the ticket names. Nothing ran on staging or the preview, so nothing showed the chip was doubled before or single after. It also added three helpers to one file in the same change, two of them copies of the same first-per-key filter, with no shared logic. A person later replaced them with one helper, cut the unit tests and added the one end-to-end test of the page. Across the 53 runs audited with it, twelve pull requests whose ticket named a page had no end-to-end spec, and eleven of the thirteen that changed one never ran it on staging. + +**The guarantee:** The plan maps each criterion that names a page or what a person sees to an end-to-end test of that page, with its assertion (`## Criteria map`). A plan without one, or with a unit test in its place, is sent back (`plan_shape::criteria_gaps`). Before the pull request is called done, each criterion's test runs on staging and on the preview through the red-check runner (`ci_repro::two_way`). Both results are kept on the run and written into the pull request (`common::e2e_proof`, `e2e_proof`). Failing on staging and passing on the preview is proven. Passing on both, failing on the preview, or having no test goes back to the coder, and the ready decision waits for it. A side that couldn't run is labelled unverified with its reason. Near-identical helpers added in one change are compared with each other (`minimal_change::twin_helpers`), and the coder's guard refuses the second until the edit names what they share (`explore_guard`, `shares`). diff --git a/services/common/src/ci_repro.rs b/services/common/src/ci_repro.rs index 0157027eb..77d2e1f90 100644 --- a/services/common/src/ci_repro.rs +++ b/services/common/src/ci_repro.rs @@ -205,7 +205,8 @@ pub fn on_head<'a>(records: &'a [Record], head: &str) -> Vec<&'a Record> { out } -fn same_sha(a: &str, b: &str) -> bool { +/// Whether two commit ids name the same commit (one may be short). +pub fn same_sha(a: &str, b: &str) -> bool { let (a, b) = (a.trim(), b.trim()); !a.is_empty() && !b.is_empty() && (a.starts_with(b) || b.starts_with(a)) } diff --git a/services/common/src/e2e_proof.rs b/services/common/src/e2e_proof.rs new file mode 100644 index 000000000..3c04311a6 --- /dev/null +++ b/services/common/src/e2e_proof.rs @@ -0,0 +1,880 @@ +//! Each thing the ticket asks for is proven end to end, both ways. +//! +//! A ticket asked for one thing: one sport chip, not two, on one venue's +//! summer camps page. The run wrote about 530 lines of unit tests over +//! three new helpers and never loaded the page the ticket names. Its unit +//! tests passed before and after; nothing showed the chip was ever doubled +//! or that it is single now. +//! +//! The rules, each enforced in code: +//! +//! - **The plan maps each criterion to a page and what a person sees +//! there** ([`criteria`], [`parse_map`], [`map_gaps`]). The criteria are +//! the ticket's acceptance list, else its Expected lines; each carries +//! the page it names, or the page the ticket's steps name. A criterion +//! that names a page or a visible behaviour needs a line under +//! [`MAP_HEADING`] with the page, an end-to-end spec in the repository's +//! suite and the assertion. Unit tests may go with it; they never stand +//! in for it. The plan goes back without it. +//! - **Each criterion's test runs both ways before the pull request is +//! called done** ([`Proof`], [`outcome`]): on the base branch's +//! deployment (staging) it must fail, which shows the bug; on the pull +//! request's preview it must pass, which shows the fix. Both results are +//! kept on the run ([`FIELD`]) and go into the pull request. +//! - Passing on both: the test doesn't test the ticket, so it goes back +//! to the coder ([`Outcome::NotTheTicket`]). +//! - Failing on the preview: the change doesn't do it yet, coder work +//! ([`Outcome::CoderWork`]). +//! - No test for the criterion's page on the head: coder work +//! ([`Outcome::Missing`]). +//! - A side that couldn't run (no browser, no network, no address): +//! labelled unverified with the reason ([`Outcome::Unverified`]), never +//! a silent pass. + +use serde::{Deserialize, Serialize}; + +use crate::ci_repro::{Leg, Record}; + +/// The run record attribute that keeps the proofs, as JSON. +pub const FIELD: &str = "e2e_proof"; + +/// The plan's section that maps each criterion to its end-to-end proof. +pub const MAP_HEADING: &str = "## Criteria map"; + +/// What the planner is told. +pub const PLANNER: &str = "\n\n## The criteria map (CoderHelm checks it)\n\ +Start from the ticket's acceptance criteria (or its Expected lines) and plan how each one is \ +proven end to end. Write a `## Criteria map` section in design.md with one line per criterion:\n\ +`- | page: | e2e: › | asserts: `\n\ +- A criterion that names a page or something a person sees gets an end-to-end test that loads \ +that page and asserts it. Unit tests may go with it but never replace it.\n\ +- The test must fail on the base branch's deployment (staging) today, which shows the bug, and \ +pass on this pull request's preview, which shows the fix. CoderHelm runs it both ways before \ +the pull request is done; a test that passes on both doesn't test the ticket.\n\ +- A criterion with nothing a person sees (a job, an API's data) says `e2e: none: ` and \ +names the check that proves it instead.\n"; + +// ── The criteria ─────────────────────────────────────────────────────────── + +/// One thing the ticket asks for. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Criterion { + pub text: String, + /// The site path it is about (`/venue/summer-camps`), its own or the + /// page the ticket's steps name. + pub page: Option, + /// It describes something a person sees on a page. + pub visible: bool, +} + +impl Criterion { + /// Whether it needs an end-to-end test. + pub fn needs_e2e(&self) -> bool { + self.visible || self.page.is_some() + } +} + +/// Section names plain ticket text uses without any mark. +const HEADINGS: &[&str] = &[ + "steps to reproduce", + "steps", + "repro steps", + "observed", + "observed behavior", + "observed behaviour", + "actual", + "actual result", + "actual results", + "actual behavior", + "actual behaviour", + "current behavior", + "current behaviour", + "expected", + "expected result", + "expected results", + "expected behavior", + "expected behaviour", + "notes", + "environment", + "screenshots", + "description", + "acceptance criteria", + "context", + "background", + "summary", +]; + +fn heading(line: &str) -> Option { + let t = line + .trim() + .trim_start_matches('#') + .trim_matches(|c: char| c == '*' || c == '_' || c == ':' || c.is_whitespace()) + .to_ascii_lowercase(); + HEADINGS.contains(&t.as_str()).then_some(t) +} + +/// The lines under the ticket's Expected heading, up to the next heading. +pub fn expected(body: &str) -> Vec { + let mut out = Vec::new(); + let mut under = false; + for line in body.lines() { + if let Some(h) = heading(line) { + under = h.starts_with("expected"); + continue; + } + if !under { + continue; + } + let t = line + .trim() + .trim_start_matches(['-', '*']) + .trim_start_matches("[ ]") + .trim(); + if !t.is_empty() { + out.push(t.to_string()); + } + } + out +} + +const CODE_EXT: &[&str] = &[ + ".ts", ".tsx", ".js", ".jsx", ".mjs", ".py", ".rs", ".go", ".rb", ".json", ".md", ".css", + ".scss", ".yml", ".yaml", ".sql", ".png", ".jpg", ".svg", ".html", +]; + +fn path_ok(p: &str) -> bool { + let low = p.to_ascii_lowercase(); + p.len() > 1 + && p.starts_with('/') + && !p.starts_with("//") + && p.chars().any(|c| c.is_ascii_alphabetic()) + && p.chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '-' | '_' | '.')) + && !CODE_EXT.iter().any(|e| low.ends_with(e)) +} + +/// The site paths `text` names: `/venue/summer-camps`, or the path of a +/// full address, without its query. +pub fn pages(text: &str) -> Vec { + let mut out: Vec = Vec::new(); + for tok in text.split(|c: char| { + c.is_whitespace() + || matches!( + c, + '(' | ')' | '[' | ']' | '<' | '>' | ',' | '"' | '\'' | '`' + ) + }) { + let tok = tok.trim_end_matches(['.', ',', ';', ':', '!', '?']); + let path = if let Some(rest) = tok + .strip_prefix("https://") + .or_else(|| tok.strip_prefix("http://")) + { + match rest.find('/') { + Some(i) => rest[i..].to_string(), + None => continue, + } + } else if tok.starts_with('/') { + tok.to_string() + } else { + continue; + }; + let path = path + .split(['?', '#']) + .next() + .unwrap_or("") + .trim_end_matches('/') + .to_string(); + if path_ok(&path) && !out.contains(&path) { + out.push(path); + } + } + out +} + +const VISIBLE: &[&str] = &[ + "show", + "shows", + "shown", + "showing", + "display", + "displays", + "displayed", + "visible", + "appear", + "appears", + "see", + "sees", + "button", + "buttons", + "filter", + "filters", + "chip", + "chips", + "link", + "links", + "menu", + "page", + "drawer", + "banner", + "label", + "heading", + "title", + "scroll", + "scrolls", + "click", + "clicks", + "render", + "renders", + "modal", + "popup", + "tab", + "icon", + "image", + "card", + "cards", + "carousel", + "dropdown", + "form", + "pill", + "pills", +]; + +/// Whether `text` describes something a person sees. +pub fn is_visible(text: &str) -> bool { + text.split(|c: char| !c.is_ascii_alphanumeric()) + .any(|w| VISIBLE.contains(&w.to_ascii_lowercase().as_str())) +} + +/// The ticket's criteria: its acceptance list (`acceptance`, as the stop +/// judge reads it) when it has one, else its Expected lines, else the +/// title when the ticket names a page. Each carries the page it names, or +/// the ticket's own page when it describes something a person sees. +pub fn criteria(title: &str, body: &str, acceptance: &[String]) -> Vec { + let ticket_page = pages(&format!("{title}\n{body}")).into_iter().next(); + let mut items: Vec = acceptance.to_vec(); + if items.is_empty() { + items = expected(body); + } + if items.is_empty() && ticket_page.is_some() && !title.trim().is_empty() { + items.push(title.trim().to_string()); + } + items + .into_iter() + .map(|text| { + let visible = is_visible(&text); + let page = pages(&text) + .into_iter() + .next() + .or_else(|| ticket_page.clone().filter(|_| visible)); + Criterion { + text, + page, + visible, + } + }) + .collect() +} + +// ── The plan's map ───────────────────────────────────────────────────────── + +/// One line of the plan's criteria map. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct MapLine { + pub criterion: String, + pub page: String, + /// The spec path and the test title (`file › title`); empty when none. + pub test: String, + /// The reason it has no end-to-end test (`e2e: none: `). + pub none: Option, + pub asserts: String, +} + +impl MapLine { + /// The spec path of its test. + pub fn spec(&self) -> String { + crate::ci_repro::spec_and_title(&self.test).0 + } +} + +/// The section `heading` of a markdown text, up to the next `## `. +fn section<'a>(text: &'a str, heading: &str) -> Option<&'a str> { + let at = text.find(heading)?; + let rest = &text[at + heading.len()..]; + let end = rest.find("\n## ").unwrap_or(rest.len()); + Some(&rest[..end]) +} + +/// The lines of the plan's [`MAP_HEADING`] section. +pub fn parse_map(design: &str) -> Vec { + let Some(s) = section(design, MAP_HEADING) else { + return Vec::new(); + }; + let mut out = Vec::new(); + for line in s.lines() { + let t = line.trim(); + let Some(t) = t.strip_prefix("- ").or_else(|| t.strip_prefix("* ")) else { + continue; + }; + let mut parts = t.split(" | "); + let mut m = MapLine { + criterion: parts + .next() + .unwrap_or("") + .trim() + .trim_matches('`') + .to_string(), + ..Default::default() + }; + for p in parts { + let Some((k, v)) = p.split_once(':') else { + continue; + }; + let v = v.trim().trim_matches('`').trim().to_string(); + match k.trim().to_ascii_lowercase().as_str() { + "page" | "url" => m.page = v, + "e2e" | "test" => { + let low = v.to_ascii_lowercase(); + if low == "none" || low.starts_with("none:") || low.starts_with("none ") { + m.none = Some(v[4..].trim_start_matches(':').trim().to_string()); + } else { + // `>` is accepted for `›`. + m.test = v.replacen(" > ", " › ", 1); + } + } + "asserts" | "assert" | "expect" => m.asserts = v, + _ => {} + } + } + out.push(m); + } + out +} + +/// Whether a path is an end-to-end spec, not a unit test: it sits in an +/// end-to-end folder (`e2e`, `playwright`, `cypress`) or is named as one. +pub fn is_e2e_path(path: &str) -> bool { + let low = path.to_ascii_lowercase(); + let name = low.rsplit('/').next().unwrap_or(&low); + low.split('/').any(|s| { + matches!( + s, + "e2e" | "playwright" | "cypress" | "e2e-tests" | "tests-e2e" + ) + }) || name.contains(".e2e.") + || name.contains(".cy.") +} + +/// Five-letter stems of the words worth matching. +fn stems(text: &str) -> Vec { + const SKIP: &[&str] = &[ + "should", "there", "which", "where", "these", "those", "after", + ]; + text.split(|c: char| !c.is_ascii_alphanumeric()) + .map(str::to_ascii_lowercase) + .filter(|w| w.len() >= 4 && !SKIP.contains(&w.as_str())) + .map(|w| w.chars().take(5).collect()) + .collect() +} + +fn overlap(a: &str, b: &str) -> usize { + let sb = stems(b); + let mut sa = stems(a); + sa.dedup(); + sa.iter().filter(|w| sb.contains(w)).count() +} + +/// The map line for a criterion: the one sharing the most words with it. +pub fn line_for<'a>(c: &Criterion, map: &'a [MapLine]) -> Option<&'a MapLine> { + map.iter() + .map(|m| (overlap(&c.text, &m.criterion), m)) + .filter(|(n, _)| *n > 0) + .max_by_key(|(n, _)| *n) + .map(|(_, m)| m) +} + +/// What the plan's criteria map misses, one line each for its send-back. +/// `suite`: the repository has an end-to-end suite, so a criterion a person +/// sees can't go without a test in it. +pub fn map_gaps(criteria: &[Criterion], map: &[MapLine], suite: bool) -> Vec { + let needed: Vec<&Criterion> = criteria.iter().filter(|c| c.needs_e2e()).collect(); + if needed.is_empty() { + return Vec::new(); + } + let quote = |c: &Criterion| match &c.page { + Some(p) => format!("\"{}\" (page `{p}`)", c.text), + None => format!("\"{}\"", c.text), + }; + if map.is_empty() { + return vec![format!( + "design.md has no `{MAP_HEADING}`, and the ticket's criteria name a page or what a person sees: {}. Write one line per criterion: `- | page: | e2e: › | asserts: `. The end-to-end test loads that page and asserts it; unit tests can go with it but never replace it.", + needed.iter().map(|c| quote(c)).collect::>().join("; ") + )]; + } + let mut out = Vec::new(); + for c in needed { + let Some(m) = line_for(c, map) else { + out.push(format!( + "`{MAP_HEADING}` has no line for {}. Add one with the page, the end-to-end test that loads it and what it asserts.", + quote(c) + )); + continue; + }; + if m.test.trim().is_empty() { + if suite { + out.push(format!( + "{} plans no end-to-end test{}. Plan a test in the repository's end-to-end suite that loads the page and asserts what the criterion says; unit tests don't replace it.", + quote(c), + m.none + .as_ref() + .filter(|w| !w.is_empty()) + .map(|w| format!(" (\"{w}\")")) + .unwrap_or_default() + )); + } + continue; + } + if !is_e2e_path(&m.spec()) { + out.push(format!( + "{} is planned with `{}`, which isn't an end-to-end spec. Plan a test in the end-to-end suite that loads the page; a unit test can go with it but never replaces it.", + quote(c), + m.spec() + )); + } + if c.page.is_some() && m.page.trim().is_empty() { + out.push(format!( + "The map line for {} names no page. Say which page its test loads.", + quote(c) + )); + } + if m.asserts.trim().is_empty() { + out.push(format!( + "The map line for {} says no assertion. Say what a person sees there when it works (`asserts: ...`).", + quote(c) + )); + } + } + out +} + +// ── Running each test both ways ──────────────────────────────────────────── + +/// One criterion's end-to-end test, run on staging and on the preview. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Proof { + pub criterion: String, + #[serde(default)] + pub page: String, + /// `file › title`, empty when no test of it is on the head. + #[serde(default)] + pub test: String, + /// The two runs: `base` on staging, `change` on the preview. + pub record: Record, +} + +/// What a proof shows. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + /// It fails on staging and passes on the preview. + Proven(String), + /// It passes on both: it doesn't test what the ticket says is wrong. + NotTheTicket(String), + /// It fails on the preview: the change doesn't do it yet. + CoderWork(String), + /// The head has no end-to-end test of the criterion. + Missing(String), + /// A side couldn't run: unverified, with why. + Unverified(String), +} + +impl Outcome { + /// The coder has work to do for it. + pub fn is_coder_work(&self) -> bool { + matches!( + self, + Outcome::NotTheTicket(_) | Outcome::CoderWork(_) | Outcome::Missing(_) + ) + } +} + +fn leg_why(l: &Leg) -> String { + let n = l.note.trim(); + if n.is_empty() { + "no result".to_string() + } else { + crate::truncate_str(n, 200).to_string() + } +} + +fn at(l: &Leg) -> String { + if l.target.is_empty() { + String::new() + } else { + format!(" ({})", l.target) + } +} + +/// What the two runs show (see the module's rules). +pub fn outcome(p: &Proof) -> Outcome { + let (base, change) = (&p.record.base, &p.record.change); + let what = if p.test.is_empty() { + format!("\"{}\"", p.criterion) + } else { + format!("`{}`", p.test) + }; + if p.test.is_empty() { + return Outcome::Missing(format!( + "\"{}\" has no end-to-end test{} on this head", + p.criterion, + if p.page.is_empty() { + String::new() + } else { + format!(" that loads `{}`", p.page) + } + )); + } + if !change.ran { + return Outcome::Unverified(format!( + "{what} didn't run on the preview{}: {}", + at(change), + leg_why(change) + )); + } + if change.red() { + return Outcome::CoderWork(format!( + "{what} fails on the preview{}: {}", + at(change), + leg_why(change) + )); + } + if !base.ran { + return Outcome::Unverified(format!( + "{what} passes on the preview{} but didn't run on staging{}: {}", + at(change), + at(base), + leg_why(base) + )); + } + if base.red() { + return Outcome::Proven(format!( + "{what} fails on staging{} ({} failed) and passes on the preview{} ({} passed)", + at(base), + base.failed, + at(change), + change.passed + )); + } + if base.green() { + return Outcome::NotTheTicket(format!( + "{what} passes on staging{} too, so it doesn't show what the ticket says is wrong", + at(base) + )); + } + Outcome::Unverified(format!("{what}: staging gave no count")) +} + +impl Proof { + /// One line for the run page and the pull request. + pub fn line(&self) -> String { + match outcome(self) { + Outcome::Proven(w) => format!("Proven both ways: \"{}\": {w}.", self.criterion), + Outcome::NotTheTicket(w) => { + format!("Doesn't test the ticket: \"{}\": {w}.", self.criterion) + } + Outcome::CoderWork(w) => format!("Not done yet: \"{}\": {w}.", self.criterion), + Outcome::Missing(w) => format!("No end-to-end test: {w}."), + Outcome::Unverified(w) => format!("Unverified: \"{}\": {w}.", self.criterion), + } + } + + /// What the coder is told to do about it, when anything. + pub fn instruction(&self) -> Option { + let page = if self.page.is_empty() { + "the page".to_string() + } else { + format!("`{}`", self.page) + }; + match outcome(self) { + Outcome::NotTheTicket(w) => Some(format!( + "Two-way proof: {w}. Make the test assert what the ticket says is wrong on {page} (\"{}\"), so it fails on staging and passes on this preview.", + self.criterion + )), + Outcome::CoderWork(w) => Some(format!( + "Two-way proof: {w}. The change doesn't do \"{}\" on the preview yet; fix the code (not the test) until it passes there.", + self.criterion + )), + Outcome::Missing(w) => Some(format!( + "Two-way proof: {w}. Add a test to the end-to-end suite that loads {page} and asserts \"{}\"; it must fail on staging and pass on this preview.", + self.criterion + )), + _ => None, + } + } +} + +/// The proofs made on `head`. +pub fn on_head<'a>(proofs: &'a [Proof], head: &str) -> Vec<&'a Proof> { + proofs + .iter() + .filter(|p| crate::ci_repro::same_sha(&p.record.head, head)) + .collect() +} + +/// What goes back to the coder for `head`. +pub fn coder_items(proofs: &[Proof], head: &str) -> Vec { + on_head(proofs, head) + .into_iter() + .filter_map(Proof::instruction) + .collect() +} + +/// The proofs of `head` a side of which couldn't run: (what, why). +pub fn unverified(proofs: &[Proof], head: &str) -> Vec<(String, String)> { + on_head(proofs, head) + .into_iter() + .filter_map(|p| match outcome(p) { + Outcome::Unverified(w) => { + Some((format!("\"{}\" end to end, both ways", p.criterion), w)) + } + _ => None, + }) + .collect() +} + +/// The proofs of `head` that held: (what, result). +pub fn proven(proofs: &[Proof], head: &str) -> Vec<(String, String)> { + on_head(proofs, head) + .into_iter() + .filter_map(|p| match outcome(p) { + Outcome::Proven(w) => Some((format!("\"{}\"", p.criterion), w)), + _ => None, + }) + .collect() +} + +pub fn to_json(proofs: &[Proof]) -> String { + serde_json::to_string(proofs).unwrap_or_default() +} + +pub fn from_json(s: &str) -> Vec { + serde_json::from_str(s).unwrap_or_default() +} + +/// `proofs` with `p` in place of an older one for its head and criterion; +/// the newest thirty kept. +pub fn upsert(proofs: &[Proof], p: Proof) -> Vec { + let mut out: Vec = proofs + .iter() + .filter(|o| { + !(crate::ci_repro::same_sha(&o.record.head, &p.record.head) + && o.criterion == p.criterion) + }) + .cloned() + .collect(); + out.push(p); + let n = out.len(); + if n > 30 { + out.drain(..n - 30); + } + out +} + +// ── Reading specs ────────────────────────────────────────────────────────── + +/// The test titles a Playwright or Cypress spec declares +/// (`test("...")`, `it('...')`). +pub fn test_titles(spec: &str) -> Vec { + let mut out = Vec::new(); + for call in ["test(", "it(", "test.only("] { + for (i, _) in spec.match_indices(call) { + let before = spec[..i].chars().last(); + if before.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.') { + continue; + } + let rest = spec[i + call.len()..].trim_start(); + let Some(q) = rest + .chars() + .next() + .filter(|c| matches!(c, '"' | '\'' | '`')) + else { + continue; + }; + if let Some(end) = rest[1..].find(q) { + let t = rest[1..1 + end].trim(); + if !t.is_empty() && !out.iter().any(|o| o == t) { + out.push(t.to_string()); + } + } + } + } + out +} + +/// Whether a spec's text loads `page` (a `goto` with its path, or its last +/// segment in a page object call). +pub fn loads_page(spec: &str, page: &str) -> bool { + let page = page.trim_end_matches('/'); + if page.is_empty() { + return false; + } + spec.contains("goto(") && spec.contains(page) +} + +/// The test of `c` on the head, when the plan named none that is there: +/// a changed spec (`(path, text)`) that loads its page, and its test whose +/// title shares the most words with the criterion (the whole spec when +/// none does). +pub fn find_test(c: &Criterion, specs: &[(String, String)]) -> Option { + let page = c.page.as_deref()?; + let (path, text) = specs.iter().find(|(_, t)| loads_page(t, page))?; + let best = test_titles(text) + .into_iter() + .map(|t| (overlap(&c.text, &t), t)) + .filter(|(n, _)| *n > 0) + .max_by_key(|(n, _)| *n) + .map(|(_, t)| t); + Some(match best { + Some(t) => format!("{path} › {t}"), + None => path.clone(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const TICKET: &str = "Steps to reproduce\nGo to /acme-club/summer-camps\nScroll to the sports filter\nObserved\nTwo Multi-Sport filters show\nExpected\nOnly one multi-sport filter to show\n"; + + fn leg(ran: bool, passed: u32, failed: u32, note: &str) -> Leg { + Leg { + target: "https://x.example.com".into(), + ran, + passed, + failed, + note: note.into(), + } + } + + fn proof(test: &str, base: Leg, change: Leg) -> Proof { + Proof { + criterion: "Only one multi-sport filter to show".into(), + page: "/acme-club/summer-camps".into(), + test: test.into(), + record: Record { + head: "abc1234".into(), + check: "two-way proof".into(), + tests: vec![test.into()], + base, + change, + source: "sandbox".into(), + at: String::new(), + }, + } + } + + #[test] + fn criteria_come_from_expected_lines_with_the_tickets_page() { + let c = criteria("Duplicate filter on the camps page", TICKET, &[]); + assert_eq!(c.len(), 1); + assert_eq!(c[0].text, "Only one multi-sport filter to show"); + assert_eq!(c[0].page.as_deref(), Some("/acme-club/summer-camps")); + assert!(c[0].needs_e2e()); + // An acceptance list wins; a criterion's own page wins. + let c = criteria( + "x", + TICKET, + &[ + "The pricing table shows on https://acme.example.com/pricing?x=1".into(), + "The nightly job logs its count".into(), + ], + ); + assert_eq!(c[0].page.as_deref(), Some("/pricing")); + assert!(!c[1].needs_e2e()); + // A file path is no page. + assert!(pages("see apps/web/src/a.tsx and /src/utils/filterMaps.ts").is_empty()); + } + + #[test] + fn the_map_needs_an_end_to_end_test_of_the_page() { + let c = criteria("Duplicate filter", TICKET, &[]); + let unit_only = "## Proof\nunit tests\n"; + let g = map_gaps(&c, &parse_map(unit_only), true); + assert_eq!(g.len(), 1); + assert!(g[0].contains("no `## Criteria map`"), "{g:?}"); + let unit = "## Criteria map\n- Only one multi-sport filter shows | page: /acme-club/summer-camps | e2e: apps/web/src/test/filter.test.tsx › one chip | asserts: one chip\n"; + let g = map_gaps(&c, &parse_map(unit), true); + assert!(g[0].contains("isn't an end-to-end spec"), "{g:?}"); + let none = "## Criteria map\n- Only one multi-sport filter shows | page: /acme-club/summer-camps | e2e: none: unit tests cover it | asserts: one chip\n"; + assert!(map_gaps(&c, &parse_map(none), true)[0].contains("plans no end-to-end test")); + // Without a suite in the repository it goes to the two-way proof, + // which labels it unverified. + assert!(map_gaps(&c, &parse_map(none), false).is_empty()); + let good = "## Criteria map\n- Only one multi-sport filter shows | page: /acme-club/summer-camps | e2e: e2e/tests/camps.spec.ts › one multi-sport chip | asserts: exactly one Multi-Sport chip\n\n## Proof\nx"; + let m = parse_map(good); + assert_eq!(m[0].test, "e2e/tests/camps.spec.ts › one multi-sport chip"); + assert!(map_gaps(&c, &m, true).is_empty()); + // Nothing a person sees needs nothing here. + assert!(map_gaps( + &criteria("x", "Expected\nThe job logs 3 rows\n", &[]), + &[], + true + ) + .is_empty()); + } + + #[test] + fn the_two_runs_decide() { + let t = "e2e/tests/camps.spec.ts › one multi-sport chip"; + let p = proof( + t, + leg(true, 0, 1, "Expected: 1 Received: 2"), + leg(true, 1, 0, ""), + ); + assert!(matches!(outcome(&p), Outcome::Proven(_))); + assert!(p.line().starts_with("Proven both ways")); + let both = proof(t, leg(true, 1, 0, ""), leg(true, 1, 0, "")); + assert!(matches!(outcome(&both), Outcome::NotTheTicket(_))); + assert!(both + .instruction() + .unwrap() + .contains("fails on staging and passes")); + let red = proof(t, leg(true, 0, 1, ""), leg(true, 0, 1, "Received: 2")); + assert!(matches!(outcome(&red), Outcome::CoderWork(_))); + let no_browser = proof( + t, + leg(false, 0, 0, "browserType.launch: Executable doesn't exist"), + leg(true, 1, 0, ""), + ); + match outcome(&no_browser) { + Outcome::Unverified(w) => assert!(w.contains("Executable doesn't exist"), "{w}"), + o => panic!("{o:?}"), + } + assert!(no_browser.instruction().is_none()); + let missing = proof("", Leg::default(), Leg::default()); + assert!(matches!(outcome(&missing), Outcome::Missing(_))); + let all = vec![p.clone(), both, no_browser]; + assert_eq!(coder_items(&all, "abc1234").len(), 1); + assert_eq!(unverified(&all, "abc").len(), 1); + assert_eq!(proven(&all, "abc1234").len(), 1); + assert!(coder_items(&all, "def5678").is_empty()); + // One proof per head and criterion: the newest. + let kept = upsert(&all, p.clone()); + assert_eq!(kept, vec![p.clone()]); + assert_eq!(from_json(&to_json(&kept)), kept); + } + + #[test] + fn a_changed_spec_that_loads_the_page_is_its_test() { + let spec = "test.describe('camps', () => {\n test('shows one multi-sport chip', async ({ page }) => {\n await page.goto('/acme-club/summer-camps');\n });\n it(\"other\", () => {});\n});\n"; + assert_eq!( + test_titles(spec), + vec!["shows one multi-sport chip", "other"] + ); + let c = &criteria("x", TICKET, &[])[0]; + assert_eq!( + find_test(c, &[("e2e/tests/camps.spec.ts".into(), spec.into())]).as_deref(), + Some("e2e/tests/camps.spec.ts › shows one multi-sport chip") + ); + assert!(find_test(c, &[("e2e/a.spec.ts".into(), "goto('/other')".into())]).is_none()); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 8c35553cb..975b56fc7 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -171,6 +171,9 @@ 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; +/// Each ticket criterion mapped to an end-to-end test and proven both +/// ways: failing on staging, passing on the preview. +pub mod e2e_proof; #[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/ci_repro.rs b/services/worker/src/passes/ci_repro.rs index 7ed0b0a19..549b40b1b 100644 --- a/services/worker/src/passes/ci_repro.rs +++ b/services/worker/src/passes/ci_repro.rs @@ -199,11 +199,58 @@ pub(crate) async fn compare( { return Some(r); } - let (owner, repo) = (&msg.repo_owner, &msg.repo_name); + let r = two_way( + state, + github, + provider.scope.ctx(common::agent_policy::Agent::Coder), + Target { + team_id: &msg.team_id, + run_id, + owner: &msg.repo_owner, + repo: &msg.repo_name, + pr, + branch, + head, + }, + &ev.check, + &test, + ) + .await; + info!(run_id, verdict = ?r.verdict(), "Failing test compared with the base branch"); + record(state, &msg.team_id, run_id, r.clone(), true).await; + Some(r) +} + +/// The pull request a test is run for. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Target<'a> { + pub team_id: &'a str, + pub run_id: &'a str, + pub owner: &'a str, + pub repo: &'a str, + pub pr: u64, + pub branch: &'a str, + pub head: &'a str, +} + +/// One Playwright test (`file › title`) with the head's test code, run in +/// the sandbox against the base branch's deployment (`base`, staging) and +/// against the pull request's preview (`change`). A side that couldn't run +/// says why in its note. Nothing is recorded here: the red-check +/// comparison ([`compare`]) and the two-way proof (`e2e_proof`) keep it. +pub(crate) async fn two_way( + state: &WorkerState, + github: &GitHubClient, + ctx: common::agent_policy::GateCtx, + t: Target<'_>, + check: &str, + test: &str, +) -> Record { + let (owner, repo, head) = (t.owner, t.repo, t.head); let mut r = Record { head: head.to_string(), - check: ev.check.clone(), - tests: vec![test.clone()], + check: check.to_string(), + tests: vec![test.to_string()], source: "sandbox".into(), at: chrono::Utc::now().to_rfc3339(), ..Default::default() @@ -212,13 +259,12 @@ pub(crate) async fn compare( r.base.note = why.to_string(); r.change.note = why.to_string(); }; - let (spec, title) = ci_repro::spec_and_title(&test); + let (spec, title) = ci_repro::spec_and_title(test); let tree: Vec = match github.get_tree(owner, repo, head).await { Ok(t) => t.into_iter().map(|e| e.path).collect(), Err(e) => { not_run(&mut r, &format!("the head's files couldn't be read ({e})")); - record(state, &msg.team_id, run_id, r.clone(), true).await; - return Some(r); + return r; } }; let Some(path) = tree @@ -227,8 +273,7 @@ pub(crate) async fn compare( .cloned() else { not_run(&mut r, &format!("`{spec}` isn't a file on the head")); - record(state, &msg.team_id, run_id, r.clone(), true).await; - return Some(r); + return r; }; // The package the spec lives in, and its runner. let mut texts: HashMap = HashMap::new(); @@ -245,8 +290,7 @@ pub(crate) async fn compare( &mut r, "the spec's runner isn't Playwright, the one CoderHelm runs against an address", ); - record(state, &msg.team_id, run_id, r.clone(), true).await; - return Some(r); + return r; }; let rel = path .strip_prefix(&format!("{}/", pkg.dir)) @@ -254,7 +298,7 @@ pub(crate) async fn compare( .to_string(); // Where each side runs: the configured test address and the preview, // else the staging address the repository's end-to-end setup names. - let configured = test_address(state, &msg.team_id, &format!("{owner}/{repo}")).await; + let configured = test_address(state, t.team_id, &format!("{owner}/{repo}")).await; let mut setup: Vec<(String, String)> = Vec::new(); for p in tree .iter() @@ -266,12 +310,12 @@ pub(crate) async fn compare( }) .take(6) { - if let Ok(t) = github.read_file(owner, repo, p, head).await { - setup.push((p.clone(), t)); + if let Ok(text) = github.read_file(owner, repo, p, head).await { + setup.push((p.clone(), text)); } } let base_url = ci_repro::base_target(configured.as_deref(), &setup); - let preview = super::preview::load(state, &msg.team_id, run_id) + let preview = super::preview::load(state, t.team_id, t.run_id) .await .filter(|p| p.head == head && !p.url.trim().is_empty()) .map(|p| p.url); @@ -279,7 +323,7 @@ pub(crate) async fn compare( configured .as_deref() .filter(|c| c.contains("{pr}")) - .map(|c| c.replace("{pr}", &pr.to_string())) + .map(|c| c.replace("{pr}", &t.pr.to_string())) }); r.base.target = base_url.clone().unwrap_or_default(); r.change.target = change_url.clone().unwrap_or_default(); @@ -288,8 +332,7 @@ pub(crate) async fn compare( &mut r, "no address for the base branch's deployment: the Tests settings have none without `{pr}`, and the end-to-end setup names no staging address", ); - record(state, &msg.team_id, run_id, r.clone(), true).await; - return Some(r); + return r; }; let mut legs: Vec<(&str, String)> = Vec::new(); match ci_repro::leg_cmd(&pkg.dir, &rel, &title, &base_url) { @@ -304,20 +347,14 @@ pub(crate) async fn compare( None => r.change.note = "no preview address for this pull request's head".into(), } if legs.is_empty() { - record(state, &msg.team_id, run_id, r.clone(), true).await; - return Some(r); + return r; } if state.config.sandbox_bucket_name.is_empty() || state.config.sandbox_project_name.is_empty() { not_run(&mut r, "no sandbox here to run the test"); - record(state, &msg.team_id, run_id, r.clone(), true).await; - return Some(r); + return r; } // The team's agent permissions decide whether the commands may run. - let gate = crate::agent::policy::gate( - state, - provider.scope.ctx(common::agent_policy::Agent::Coder), - None, - ); + let gate = crate::agent::policy::gate(state, ctx, None); let install = test_package::install_cmd(&pkg); let mut steps: Vec<(&str, String)> = vec![("install", install)]; steps.extend(legs); @@ -325,7 +362,7 @@ pub(crate) async fn compare( if !matches!( gate.check_command( cmd, - "Run the failing test against the base branch and the preview" + "Run the test against the base branch's deployment and the preview" ) .await, common::agent_policy::Outcome::Run { .. } @@ -334,8 +371,7 @@ pub(crate) async fn compare( &mut r, &format!("the team's agent permissions don't allow the {side} command"), ); - record(state, &msg.team_id, run_id, r.clone(), true).await; - return Some(r); + return r; } } let sandbox = crate::clients::sandbox::SandboxClient::new( @@ -345,9 +381,11 @@ pub(crate) async fn compare( &state.config.sandbox_bucket_name, &state.config.sandbox_project_name, ) - .with_egress(crate::agent::policy::sandbox_egress(state, &msg.team_id).await); + .with_egress(crate::agent::policy::sandbox_egress(state, t.team_id).await); let source = match sandbox - .ensure_source(run_id, head, || github.download_tarball(owner, repo, head)) + .ensure_source(t.run_id, head, || { + github.download_tarball(owner, repo, head) + }) .await { Ok(k) => k, @@ -356,12 +394,11 @@ pub(crate) async fn compare( &mut r, &format!("the branch couldn't be prepared in the sandbox ({e})"), ); - record(state, &msg.team_id, run_id, r.clone(), true).await; - return Some(r); + return r; } }; let script = ci_repro::script(&steps); - let node = super::detect_node_version(github, owner, repo, branch).await; + let node = super::detect_node_version(github, owner, repo, t.branch).await; match sandbox .run_checks(&source, &script, node.as_deref(), None, None) .await @@ -386,9 +423,7 @@ pub(crate) async fn compare( ), Err(e) => not_run(&mut r, &format!("the sandbox couldn't run ({e})")), } - info!(run_id, verdict = ?r.verdict(), "Failing test compared with the base branch"); - record(state, &msg.team_id, run_id, r.clone(), true).await; - Some(r) + r } /// The team's test address for the repository (Tests settings), as set. diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index 8d82ce8d0..7e8872a98 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -578,6 +578,9 @@ struct RunBits { preview: Option, /// What the pull request waits on, one line (`waiting_line`). waiting: String, + /// Each criterion's end-to-end test on staging and the preview + /// (`e2e_proof`). + two_way: Vec, } impl Gathered { @@ -637,6 +640,7 @@ impl Gathered { }); let preview = self.run.preview.as_ref().filter(|p| p.head == self.head()); super::description_facts::with_preview(&mut f, preview); + super::description_facts::with_two_way(&mut f, &self.run.two_way); f.waiting = self.run.waiting.clone(); f } @@ -698,6 +702,7 @@ async fn run_bits( ticket_url, preview: common::preview::State::from_json(&get(common::preview::FIELD)), waiting: waiting_of(&item, number), + two_way: common::e2e_proof::from_json(&get(common::e2e_proof::FIELD)), }, run_id, ) diff --git a/services/worker/src/passes/description_facts.rs b/services/worker/src/passes/description_facts.rs index bf7d5d1a4..734f40edb 100644 --- a/services/worker/src/passes/description_facts.rs +++ b/services/worker/src/passes/description_facts.rs @@ -489,6 +489,34 @@ pub fn with_preview(f: &mut Facts, preview: Option<&common::preview::State>) { scope_to_change(f); } +/// The two-way proof of each criterion on this head (`common::e2e_proof`): +/// a test that failed on staging and passed on the preview is a check made +/// with both results; anything else is unverified with what each side did. +pub fn with_two_way(f: &mut Facts, proofs: &[common::e2e_proof::Proof]) { + use common::e2e_proof::{on_head, outcome, Outcome}; + let short: String = f.head.chars().take(7).collect(); + for p in on_head(proofs, &f.head) { + let what = format!( + "\"{}\" end to end on staging and on the preview", + p.criterion + ); + match outcome(p) { + Outcome::Proven(w) => f.checked.push(common::pr_steps::Checked { + what, + result: w, + when: format!("on {short}"), + }), + Outcome::Unverified(w) => f.unverified.push(Unverified { what, why: w }), + Outcome::NotTheTicket(w) | Outcome::CoderWork(w) | Outcome::Missing(w) => { + f.unverified.push(Unverified { + what, + why: format!("{w}; CoderHelm is fixing it"), + }) + } + } + } +} + /// The backticked check commands a line names. fn commands_in(text: &str) -> Vec { text.split('`') diff --git a/services/worker/src/passes/e2e_proof.rs b/services/worker/src/passes/e2e_proof.rs new file mode 100644 index 000000000..360908e0f --- /dev/null +++ b/services/worker/src/passes/e2e_proof.rs @@ -0,0 +1,349 @@ +//! The two-way proof of a pull request: each ticket criterion that names a +//! page or what a person sees, run end to end on the base branch's +//! deployment (staging, where it must fail) and on the pull request's +//! preview (where it must pass), before the pull request is called done. +//! The rules are `common::e2e_proof`'s. +//! +//! - [`prove`] runs once per head, from the pull request watch, once the +//! head's preview is up and its own end-to-end checks passed. Each +//! criterion's test is the one the plan's `## Criteria map` names, else a +//! changed spec that loads the criterion's page. It runs in the sandbox +//! through `ci_repro::two_way`, the same runner a red check is +//! reproduced with, and both results are kept on the run +//! (`e2e_proof`) and said on the run page. +//! - What the coder must do (a test that passes on both, a criterion that +//! fails on the preview, a page with no test) goes back to it as a fix +//! round (`resume::queue_own_review_round`), and the ready decision waits +//! for it ([`standing`]). +//! - A side that couldn't run is labelled unverified in the pull request +//! with its reason; it never passes silently. + +use common::e2e_proof::{self as ep, Proof}; +use common::preview::{Stage, State}; +use tracing::{info, warn}; + +use super::attr_s; +use crate::clients::github::GitHubClient; +use crate::WorkerState; + +/// Criteria proven per head at most: each is a sandbox run. +pub const MAX_CRITERIA: usize = 4; +/// Spec files read from the head at most. +const MAX_SPECS: usize = 8; +/// The check name a proof's record carries. +pub const CHECK: &str = "two-way proof"; + +/// The proofs kept on the run. +pub(crate) async fn load(state: &WorkerState, team_id: &str, run_id: &str) -> Vec { + run_strings(state, team_id, run_id, &[ep::FIELD]) + .await + .remove(0) + .map(|s| ep::from_json(&s)) + .unwrap_or_default() +} + +async fn save(state: &WorkerState, team_id: &str, run_id: &str, proofs: &[Proof]) { + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET #f = :v") + .expression_attribute_names("#f", ep::FIELD) + .expression_attribute_values(":v", attr_s(&ep::to_json(proofs))) + .send() + .await + { + warn!(run_id, error = %e, "Could not keep the two-way proof on the run"); + } +} + +/// String attributes of the run, in the order asked. +async fn run_strings( + state: &WorkerState, + team_id: &str, + run_id: &str, + keys: &[&str], +) -> Vec> { + let item = if run_id.is_empty() { + None + } else { + state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .send() + .await + .ok() + .and_then(|o| o.item) + }; + keys.iter() + .map(|k| { + item.as_ref() + .and_then(|i| i.get(*k)) + .and_then(|v| v.as_s().ok()) + .cloned() + }) + .collect() +} + +/// The run's ticket criteria that need an end-to-end proof. +async fn criteria_of(state: &WorkerState, team_id: &str, run_id: &str) -> Vec { + let v = run_strings(state, team_id, run_id, &["title", "ticket_body"]).await; + let (title, body) = ( + v[0].clone().unwrap_or_default(), + v[1].clone().unwrap_or_default(), + ); + ep::criteria(&title, &body, &super::stop_judge::acceptance(&body)) + .into_iter() + .filter(ep::Criterion::needs_e2e) + .collect() +} + +/// The plan's design.md for the run's ticket and repository, empty when +/// it can't be read. +async fn design_of( + state: &WorkerState, + team_id: &str, + run_id: &str, + owner: &str, + repo: &str, +) -> String { + let v = run_strings(state, team_id, run_id, &["ticket_id"]).await; + let Some(ticket) = v[0].clone() else { + return String::new(); + }; + let key = format!( + "{}/design.md", + super::openspec_prefix(team_id, &ticket, owner, repo) + ); + match state + .s3 + .get_object() + .bucket(&state.config.bucket_name) + .key(&key) + .send() + .await + { + Ok(o) => o + .body + .collect() + .await + .map(|b| String::from_utf8_lossy(&b.into_bytes()).to_string()) + .unwrap_or_default(), + Err(_) => String::new(), + } +} + +/// Runs each criterion's test both ways on the head, once per head, once +/// the preview is up. Returns the run's proofs and whether new ones were +/// made now. +pub(crate) async fn prove( + state: &WorkerState, + github: &GitHubClient, + p: super::preview::Pr<'_>, + st: &State, + branch: &str, +) -> (Vec, bool) { + let all = load(state, p.team_id, p.run_id).await; + if !matches!(st.stage, Stage::Ready | Stage::Checked) + || st.url.trim().is_empty() + || st.head.is_empty() + || !ep::on_head(&all, &st.head).is_empty() + { + return (all, false); + } + let criteria = criteria_of(state, p.team_id, p.run_id).await; + if criteria.is_empty() { + return (all, false); + } + let map = ep::parse_map(&design_of(state, p.team_id, p.run_id, p.owner, p.repo).await); + // The end-to-end specs the pull request changes, as they are on the head. + let base = github + .get_pull_request(p.owner, p.repo, p.number) + .await + .ok() + .and_then(|pr| pr["base"]["ref"].as_str().map(str::to_string)) + .unwrap_or_else(|| "main".to_string()); + let changed: Vec = github + .compare_files_with_patches(p.owner, p.repo, &base, &st.head) + .await + .map(|v| { + v.into_iter() + .filter(|(path, status, _)| status != "removed" && ep::is_e2e_path(path)) + .map(|(path, _, _)| path) + .collect() + }) + .unwrap_or_default(); + let mut specs: Vec<(String, String)> = Vec::new(); + for path in changed.iter().take(MAX_SPECS) { + if let Ok(t) = github.read_file(p.owner, p.repo, path, &st.head).await { + specs.push((path.clone(), t)); + } + } + let ctx = common::agent_policy::GateCtx::new(p.team_id, common::agent_policy::Agent::Coder) + .repo(&format!("{}/{}", p.owner, p.repo)) + .run(p.run_id); + let mut proofs = all; + for c in criteria.iter().take(MAX_CRITERIA) { + // The plan's test when it is on the head, else a changed spec that + // loads the page. + let planned = ep::line_for(c, &map) + .filter(|m| !m.test.trim().is_empty()) + .map(|m| m.test.clone()) + .filter(|t| { + let spec = common::ci_repro::spec_and_title(t).0; + specs.iter().any(|(p, _)| p.ends_with(&spec)) + }); + let test = planned.or_else(|| ep::find_test(c, &specs)); + let record = match test.as_deref() { + Some(t) => { + super::ci_repro::two_way( + state, + github, + ctx.clone(), + super::ci_repro::Target { + team_id: p.team_id, + run_id: p.run_id, + owner: p.owner, + repo: p.repo, + pr: p.number, + branch, + head: &st.head, + }, + CHECK, + t, + ) + .await + } + None => common::ci_repro::Record { + head: st.head.clone(), + check: CHECK.into(), + source: "sandbox".into(), + at: chrono::Utc::now().to_rfc3339(), + ..Default::default() + }, + }; + let proof = Proof { + criterion: c.text.clone(), + page: c.page.clone().unwrap_or_default(), + test: test.unwrap_or_default(), + record, + }; + info!(run_id = p.run_id, outcome = ?ep::outcome(&proof), "Two-way proof of a criterion"); + super::add_progress_note( + state, + p.team_id, + p.run_id, + &format!( + "Two-way proof (staging, then the preview): {}", + proof.line() + ), + ) + .await; + proofs = ep::upsert(&proofs, proof); + } + save(state, p.team_id, p.run_id, &proofs).await; + (proofs, true) +} + +/// Where the two-way proof stands for the ready decision. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub enum Standing { + /// No criterion needs it, or the preview isn't up yet. + #[default] + None, + /// The preview is up and the criteria aren't proven on this head yet. + Pending, + /// The coder is fixing what it sent back (that many items). + Fixing(usize), + /// Done; the criteria a side of which couldn't run, each a note. + Done(Vec), +} + +/// The two-way proof's standing on `head` (`preview`: the head's preview). +pub(crate) async fn standing( + state: &WorkerState, + team_id: &str, + run_id: &str, + head: &str, + preview: Option<&State>, +) -> Standing { + if run_id.is_empty() || head.is_empty() { + return Standing::None; + } + let proofs = load(state, team_id, run_id).await; + if !ep::on_head(&proofs, head).is_empty() { + return standing_of(&proofs, head); + } + let up = + preview.is_some_and(|p| p.head == head && matches!(p.stage, Stage::Ready | Stage::Checked)); + if up && !criteria_of(state, team_id, run_id).await.is_empty() { + Standing::Pending + } else { + Standing::None + } +} + +/// [`standing`] from the proofs made on `head`. +pub fn standing_of(proofs: &[Proof], head: &str) -> Standing { + let work = ep::coder_items(proofs, head); + if !work.is_empty() { + return Standing::Fixing(work.len()); + } + Standing::Done( + ep::unverified(proofs, head) + .into_iter() + .map(|(what, why)| format!("unverified: {what}: {why}")) + .collect(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use common::ci_repro::{Leg, Record}; + + fn proof(base: Leg, change: Leg) -> Proof { + Proof { + criterion: "Only one chip shows".into(), + page: "/acme/camps".into(), + test: "e2e/camps.spec.ts › one chip".into(), + record: Record { + head: "abc1234".into(), + base, + change, + ..Default::default() + }, + } + } + + fn leg(ran: bool, passed: u32, failed: u32) -> Leg { + Leg { + ran, + passed, + failed, + note: if ran { "" } else { "no browser" }.into(), + ..Default::default() + } + } + + #[test] + fn what_the_ready_decision_reads() { + let both_green = proof(leg(true, 1, 0), leg(true, 1, 0)); + assert_eq!(standing_of(&[both_green], "abc1234"), Standing::Fixing(1)); + let proven = proof(leg(true, 0, 1), leg(true, 1, 0)); + assert_eq!(standing_of(&[proven], "abc1234"), Standing::Done(vec![])); + let half = proof(leg(false, 0, 0), leg(true, 1, 0)); + match standing_of(&[half], "abc1234") { + Standing::Done(notes) => { + assert_eq!(notes.len(), 1); + assert!(notes[0].contains("no browser"), "{notes:?}"); + } + s => panic!("{s:?}"), + } + } +} diff --git a/services/worker/src/passes/explore_guard.rs b/services/worker/src/passes/explore_guard.rs index 3a2bf262b..c936e86ed 100644 --- a/services/worker/src/passes/explore_guard.rs +++ b/services/worker/src/passes/explore_guard.rs @@ -16,6 +16,14 @@ //! definition parallels one already in the file (`minimal_change`) needs //! [`WHY_NEW_INPUT`], saying why the existing one can't hold the change. //! The reason is kept as the habits check's line `Wider than the ticket:`. +//! - **A second near-identical helper in the same build names what it +//! shares** ([`ExploreGuard::check_edit`]): the guard keeps the helpers +//! the build added, and an edit adding one whose name or body nearly +//! matches one of them (`minimal_change::twins`), in this edit or an +//! earlier one, needs [`SHARES_INPUT`]: the helper both now call, or why +//! they can't share one. One build once added three near-identical +//! helpers to one file in turn; each compared only with the code that +//! was there before the build, so none was stopped. //! //! The refusals are the same every time; no count of tries opens them. @@ -28,6 +36,8 @@ use super::minimal_change; pub const REUSES_INPUT: &str = "reuses"; /// The write tools' field saying why a parallel structure is needed. pub const WHY_NEW_INPUT: &str = "why_new"; +/// The write tools' field naming what a second similar helper shares. +pub const SHARES_INPUT: &str = "shares"; /// The tools that count as a search of the code. pub fn is_search(tool: &str, input: &serde_json::Value) -> bool { @@ -72,6 +82,13 @@ pub fn offer_fields(schema: &mut serde_json::Value) { "description": "Only when this edit adds a map, helper or config next to an existing similar one: why the existing one can't hold the change." }), ); + props.insert( + SHARES_INPUT.to_string(), + serde_json::json!({ + "type": "string", + "description": "Only when this edit adds a helper like one this build already added: the shared helper both call (by name and path), or why they can't share one." + }), + ); } } @@ -83,6 +100,8 @@ pub struct ExploreGuard { searched: AtomicBool, reuses: Mutex>, kept: Mutex>, + /// The helpers this build added: (path, definition, body). + added: Mutex>, } impl ExploreGuard { @@ -127,7 +146,8 @@ impl ExploreGuard { } /// Whether an edit of an existing file may add the definitions it adds: - /// one parallel to an existing definition in the file needs a reason. + /// one parallel to an existing definition in the file needs a reason, + /// and one twin to a helper this build added names what they share. pub fn check_edit( &self, path: &str, @@ -135,6 +155,7 @@ impl ExploreGuard { new: &str, input: &serde_json::Value, ) -> Result<(), String> { + self.check_twins(path, old, new, input)?; let pairs = minimal_change::parallel_in_edit(path, old, new); if pairs.is_empty() { return Ok(()); @@ -156,6 +177,76 @@ impl ExploreGuard { )) } + /// A helper the edit adds that is a twin of one this build added (in + /// this edit or before it) needs [`SHARES_INPUT`]. The helpers it adds + /// are kept for the next edit. + fn check_twins( + &self, + path: &str, + old: &str, + new: &str, + input: &serde_json::Value, + ) -> Result<(), String> { + let before: Vec = minimal_change::defs(old, path) + .into_iter() + .map(|d| d.name) + .collect(); + let fresh: Vec<(String, minimal_change::Def, String)> = minimal_change::defs(new, path) + .into_iter() + .filter(|d| d.kind == minimal_change::DefKind::Function && !before.contains(&d.name)) + .map(|d| { + let body = minimal_change::body_of(new, path, &d.name).unwrap_or_default(); + (path.to_string(), d, body) + }) + .collect(); + if fresh.is_empty() { + return Ok(()); + } + let mut added = self.added.lock().unwrap(); + let mut pairs: Vec = Vec::new(); + for (i, (_, d, body)) in fresh.iter().enumerate() { + let earlier = added + .iter() + .filter(|(_, a, _)| a.name != d.name) + .chain(fresh[..i].iter()); + if let Some((p, a, _)) = earlier + .into_iter() + .find(|(_, a, b)| minimal_change::twins(a, b, d, body)) + { + let at = if p == path { + String::new() + } else { + format!(" in `{p}`") + }; + pairs.push(format!("`{}` like `{}`{at}", d.name, a.name)); + } + } + if !pairs.is_empty() { + match text_input(input, SHARES_INPUT) { + Some(shares) => self + .kept + .lock() + .unwrap() + .push((path.to_string(), format!("shares {shares}"))), + None => { + return Err(format!( + "Not written: this edit adds {}, which this build already added. Put the shared logic in one helper (a parameter for what differs) and call it from both places. If they truly can't share one, call again with `{SHARES_INPUT}` naming what they share and why they stay apart.", + pairs.join(", ") + )) + } + } + } + for f in fresh { + if !added + .iter() + .any(|(p, d, _)| *p == f.0 && d.name == f.1.name) + { + added.push(f); + } + } + Ok(()) + } + /// The coder's evidence lines: what it reuses, and each kept parallel /// with its reason (read by the habits check). pub fn evidence_lines(&self) -> String { @@ -227,5 +318,46 @@ mod tests { let mut schema = json!({"type": "object", "properties": {}}); offer_fields(&mut schema); assert!(schema["properties"]["reuses"].is_object()); + assert!(schema["properties"]["shares"].is_object()); + } + + #[test] + fn a_second_similar_helper_in_one_build_names_what_it_shares() { + let g = ExploreGuard::for_fix(); + let base = "export const keyOf = (s: Item) => s.label.toLowerCase();\n"; + let first = format!("{base}export const dedupeItemsByKey = (items: Item[]): Item[] => {{\n const seen = new Set();\n return items.filter((i) => {{\n if (seen.has(keyOf(i))) return false;\n seen.add(keyOf(i));\n return true;\n }});\n}};\n"); + assert!(g + .check_edit("src/maps.ts", base, &first, &json!({})) + .is_ok()); + let second = format!("{first}export const dedupeOptionsByValue = (options: T[]): T[] => {{\n const seen = new Set();\n return options.filter((o) => {{\n if (seen.has(o.value)) return false;\n seen.add(o.value);\n return true;\n }});\n}};\n"); + let e = g + .check_edit("src/maps.ts", &first, &second, &json!({})) + .unwrap_err(); + assert!( + e.contains("`dedupeOptionsByValue` like `dedupeItemsByKey`"), + "{e}" + ); + // Both in one edit are caught too. + let g2 = ExploreGuard::for_fix(); + assert!(g2 + .check_edit("src/maps.ts", base, &second, &json!({})) + .is_err()); + // Naming what they share lets it through, kept as the reason. + assert!(g + .check_edit( + "src/maps.ts", + &first, + &second, + &json!({"shares": "`firstBy` in src/maps.ts; options carry no label"}) + ) + .is_ok()); + assert!(g + .evidence_lines() + .contains("Wider than the ticket: src/maps.ts: shares `firstBy`")); + // An unrelated helper goes ahead. + let other = format!("{first}export const priceLabel = (cents: number): string => {{\n const d = Math.floor(cents / 100);\n return `${{d}}`;\n}};\n"); + assert!(ExploreGuard::for_fix() + .check_edit("src/maps.ts", &first, &other, &json!({})) + .is_ok()); } } diff --git a/services/worker/src/passes/incidents/cp_criteria_proven_both_ways.rs b/services/worker/src/passes/incidents/cp_criteria_proven_both_ways.rs new file mode 100644 index 000000000..fec586525 --- /dev/null +++ b/services/worker/src/passes/incidents/cp_criteria_proven_both_ways.rs @@ -0,0 +1,290 @@ +//! cp. A ticket said one thing: on a venue's summer camps page, the sports +//! filter showed two Multi-Sport chips; it should show one. The run planned +//! and wrote about 530 lines of unit tests over five test files and never +//! loaded the page the ticket names: no end-to-end test, nothing run on +//! staging or the preview. It added three helpers to one file in the same +//! change (`slugToIds` beside the existing `slugToId`, then +//! `dedupeSportsBySlug` and `dedupeSportOptionsBySlug`, two copies of the +//! same first-per-key filter) with no shared logic. A person later replaced +//! the two dedupe helpers with one, cut the unit tests and added the one +//! end-to-end test of the page. Across the 53 runs audited with it, twelve +//! pull requests whose ticket named a page had no end-to-end spec, and +//! eleven of thirteen that changed one never ran it on staging. +//! +//! Guarantee: the plan maps each criterion (the acceptance list, else the +//! Expected lines) that names a page or what a person sees to an +//! end-to-end test of that page, with the assertion, under `## Criteria +//! map`; a plan without it, or with a unit test in its place, is sent back +//! (`plan_shape::criteria_gaps`, `common::e2e_proof::map_gaps`). Before the +//! pull request is called done, each criterion's test runs on staging and on +//! the preview through the red-check runner (`ci_repro::two_way`), and both +//! results are kept on the run and written into the pull request: failing +//! on staging and passing on the preview is proven; passing on both doesn't +//! test the ticket and goes back to the coder, as does failing on the +//! preview or having no test; a side that couldn't run is labelled +//! unverified with its reason (`e2e_proof`, `ready::decide`). Near-identical +//! helpers added in one change are found against each other, not only +//! against the code that was there (`minimal_change::twin_helpers`), and the +//! coder's guard refuses the second one until the edit names what they share +//! (`explore_guard`, `shares`). + +use super::fixture::fn_src; +use crate::passes::e2e_proof::{standing_of, Standing}; +use crate::passes::explore_guard::ExploreGuard; +use crate::passes::minimal_change::{self, Kind}; +use crate::passes::plan::PlanResult; +use crate::passes::plan_shape; +use common::ci_repro::{self as repro, Record}; +use common::e2e_proof::{self as ep, Outcome, Proof}; + +const TITLE: &str = "Duplicate Multi-Sport filter showing on the Acme Club Summer Camps page"; +/// The ticket as it was written (plain text, no acceptance heading). +const BODY: &str = "Steps to reproduce\nGo to /acme-club/summer-camps\nScroll to the sports filter\nObserved\nTwo Multi-Sport filters show\nExpected\nOnly one multi-sport filter to show"; +const HEAD: &str = "395769a5f00d"; + +fn plan(design: &str) -> PlanResult { + PlanResult { + design: design.into(), + tasks: "- [ ] apps/web/src/utils/filterMaps.ts: one sport per slug".into(), + ..Default::default() + } +} + +/// The plan's proof as the run wrote it: unit tests only. +const PLAN_BEFORE: &str = "## Reuse\n- `slugToId` in apps/web/src/utils/filterMaps.ts\n\n## Proof\nUnit tests: filterMaps.test.ts for the slug helpers; sports-filter-dedupe.test.tsx renders one chip per slug; filter-nav-sport-grid.test.tsx renders one button per slug.\n"; + +/// The same plan with the criteria map the person's fix needed. +fn plan_after() -> String { + format!( + "{PLAN_BEFORE}\n## Criteria map\n- Only one multi-sport filter shows | page: /acme-club/summer-camps | e2e: e2e/tests/browse/venues.spec.ts › the camps page shows one Multi-Sport chip | asserts: exactly one chip named Multi-Sport in the sports filter\n" + ) +} + +/// The helpers the change added to `filterMaps.ts`, as its patch had them. +fn helpers_patch() -> String { + [ + "@@ -562,21 +562,77 @@", + " export const slugToId = (allSports: SportItem[], slug: string) => {", + " const found = allSports.find((s) => normalizeSportName(s.label) === slug);", + " return found?.id || slug;", + " };", + " ", + "+export const slugToIds = (allSports: SportItem[], slug: string): string[] =>", + "+ Array.from(", + "+ new Set(", + "+ allSports", + "+ .filter((s) => Boolean(s?.id) && normalizeSportName(s.label) === slug)", + "+ .map((s) => s.id)", + "+ )", + "+ );", + "+", + "+export const dedupeSportsBySlug = (allSports: SportItem[]): SportItem[] => {", + "+ const seen = new Set();", + "+ return allSports.filter((sport): sport is SportItem => {", + "+ if (!sport?.id) return false;", + "+ const slug = normalizeSportName(sport.label);", + "+ if (seen.has(slug)) return false;", + "+ seen.add(slug);", + "+ return true;", + "+ });", + "+};", + "+", + "+export const dedupeSportOptionsBySlug = (", + "+ options: T[]", + "+): T[] => {", + "+ const seen = new Set();", + "+ return options.filter((option) => {", + "+ if (seen.has(option.value)) return false;", + "+ seen.add(option.value);", + "+ return true;", + "+ });", + "+};", + "", + ] + .join("\n") +} + +fn leg(target: &str, out: &str) -> repro::Leg { + repro::leg_of(target, out) +} + +fn proof(test: &str, base_out: &str, change_out: &str) -> Proof { + Proof { + criterion: "Only one multi-sport filter to show".into(), + page: "/acme-club/summer-camps".into(), + test: test.into(), + record: Record { + head: HEAD.into(), + check: "two-way proof".into(), + tests: vec![test.into()], + base: leg("https://staging.example.com", base_out), + change: leg("https://pr-12.preview.example.com", change_out), + source: "sandbox".into(), + at: String::new(), + }, + } +} + +#[test] +fn the_plan_maps_the_criterion_to_a_test_of_its_page() { + let c = ep::criteria(TITLE, BODY, &[]); + assert_eq!(c.len(), 1); + assert_eq!(c[0].text, "Only one multi-sport filter to show"); + assert_eq!(c[0].page.as_deref(), Some("/acme-club/summer-camps")); + // The run's plan: unit tests only, sent back. + let g = plan_shape::criteria_gaps(&plan(PLAN_BEFORE), TITLE, BODY, true); + assert_eq!(g.len(), 1, "{g:?}"); + assert!(g[0].contains("## Criteria map") && g[0].contains("/acme-club/summer-camps")); + assert!(g[0].contains("never replace it")); + // A unit test named in the map is no end-to-end test. + let unit = plan_after().replace( + "e2e/tests/browse/venues.spec.ts", + "apps/web/src/test/components/sports-filter-dedupe.test.tsx", + ); + assert!( + plan_shape::criteria_gaps(&plan(&unit), TITLE, BODY, true)[0] + .contains("isn't an end-to-end spec") + ); + // The plan with the map passes; the planner is told to write it. + assert!(plan_shape::criteria_gaps(&plan(&plan_after()), TITLE, BODY, true).is_empty()); + assert!(ep::PLANNER.contains("## Criteria map")); + let plan_src = include_str!("../plan.rs"); + assert!(plan_src.contains("common::e2e_proof::PLANNER")); + assert_eq!( + plan_src + .matches("super::plan_shape::criteria_gaps(") + .count(), + 2, + "the draft and the revised plan are both checked" + ); +} + +#[test] +fn each_criterion_runs_both_ways_before_it_is_done() { + let t = "e2e/tests/browse/venues.spec.ts › the camps page shows one Multi-Sport chip"; + let red = " 1) [chromium] › venues.spec.ts › the camps page shows one Multi-Sport chip\n Error: expect(locator).toHaveCount(expected) failed\n Expected: 1\n Received: 2\n 1 failed\n"; + let green = " 1 passed (4.2s)\n"; + // The run's change had no end-to-end test of the page. + let none = Proof { + test: String::new(), + record: Record { + head: HEAD.into(), + ..Default::default() + }, + ..proof(t, "", "") + }; + assert!(matches!(ep::outcome(&none), Outcome::Missing(_))); + assert!(none + .instruction() + .unwrap() + .contains("loads `/acme-club/summer-camps`")); + // A test that passes on staging too doesn't test the ticket. + let both = proof(t, green, green); + assert!(matches!(ep::outcome(&both), Outcome::NotTheTicket(_))); + assert_eq!(standing_of(&[both], HEAD), Standing::Fixing(1)); + // Red on the preview is the coder's. + assert!(matches!( + ep::outcome(&proof(t, red, red)), + Outcome::CoderWork(_) + )); + // No browser on one side: unverified, with why, never a pass. + let no_browser = proof( + t, + "Error: browserType.launch: Executable doesn't exist at /ms-playwright/chromium", + green, + ); + match standing_of(std::slice::from_ref(&no_browser), HEAD) { + Standing::Done(notes) => assert!(notes[0].contains("Executable doesn't exist")), + s => panic!("{s:?}"), + } + // Red on staging, green on the preview: proven, with both results. + let good = proof(t, red, green); + match ep::outcome(&good) { + Outcome::Proven(w) => { + assert!(w.contains("staging") && w.contains("preview"), "{w}"); + assert!(w.contains("1 failed") && w.contains("1 passed"), "{w}"); + } + o => panic!("{o:?}"), + } + assert_eq!(standing_of(&[good], HEAD), Standing::Done(vec![])); +} + +#[test] +fn the_proof_is_wired_into_the_watch_the_ready_decision_and_the_pull_request() { + let watch = fn_src(include_str!("../pr_watch.rs"), "async fn preview("); + assert!(watch.contains("super::e2e_proof::prove(")); + assert!(watch.contains("queue_own_review_round(")); + let ready = include_str!("../ready.rs"); + assert!(fn_src(ready, "fn decide_raw(").contains("Standing::Fixing")); + assert!(ready.contains("super::e2e_proof::standing(")); + assert!(include_str!("../description.rs").contains("with_two_way(")); + // The proof runs through the same runner as a red check's comparison. + let proof_src = include_str!("../e2e_proof.rs"); + assert!(proof_src.contains("super::ci_repro::two_way(")); + assert!(fn_src( + include_str!("../ci_repro.rs"), + "pub(crate) async fn compare(" + ) + .contains("two_way(")); +} + +#[test] +fn twin_helpers_in_one_change_are_found_and_stopped() { + let diff = [( + "apps/web/src/utils/filterMaps.ts".to_string(), + "modified".to_string(), + helpers_patch(), + )]; + // Before: compared only with the code that was there, the two dedupe + // helpers passed. + let parallel = minimal_change::parallel_structures(&diff, &[]); + assert!(parallel + .iter() + .all(|w| !w.what.contains("dedupeSportOptionsBySlug"))); + assert!(parallel.iter().any(|w| w + .what + .contains("`slugToIds` next to the existing `slugToId`"))); + // Now: compared with each other. + let found = minimal_change::check(&diff, &[], &format!("{TITLE}\n{BODY}"), false); + let twins: Vec<_> = found.iter().filter(|w| w.kind == Kind::Twin).collect(); + assert_eq!(twins.len(), 1, "{found:?}"); + assert!(twins[0] + .what + .contains("`dedupeSportOptionsBySlug` next to `dedupeSportsBySlug`")); + + // The coder's guard: the second helper in the build names what it shares. + let g = ExploreGuard::for_build(); + let base = + "export const slugToId = (allSports: SportItem[], slug: string) => {\n return slug;\n};\n"; + let new_side: String = helpers_patch() + .lines() + .skip(1) + .filter(|l| !l.starts_with('-')) + .map(|l| l.get(1..).unwrap_or("")) + .collect::>() + .join("\n"); + let (first, _) = new_side + .split_once("export const dedupeSportOptionsBySlug") + .unwrap(); + let first = format!("{first}\n"); + assert!(g + .check_edit( + "apps/web/src/utils/filterMaps.ts", + base, + &first, + &serde_json::json!({"why_new": "every id behind a slug"}) + ) + .is_ok()); + let e = g + .check_edit( + "apps/web/src/utils/filterMaps.ts", + &first, + &new_side, + &serde_json::json!({}), + ) + .unwrap_err(); + assert!( + e.contains("`dedupeSportOptionsBySlug` like `dedupeSportsBySlug`"), + "{e}" + ); +} diff --git a/services/worker/src/passes/minimal_change.rs b/services/worker/src/passes/minimal_change.rs index 1b682c336..ea0224472 100644 --- a/services/worker/src/passes/minimal_change.rs +++ b/services/worker/src/passes/minimal_change.rs @@ -15,6 +15,13 @@ //! list, constant table or helper whose name shares its words with an //! existing one in the same file (or another changed file). Extend the //! existing one. +//! - **Twin helpers in one change** ([`Kind::Twin`]): two new top-level +//! helpers in the same diff whose names parallel each other, or whose +//! signatures and bodies nearly match ([`twin_helpers`]). The parallel +//! check above compares a new definition with the code that was already +//! there, so three near-identical helpers added together passed it: one +//! change once added `slugToIds`, `dedupeSportsBySlug` and +//! `dedupeSportOptionsBySlug` side by side. Share the logic in one. //! - **Replacing where the base was additive** ([`Kind::Replacing`]): the //! diff adds deleting or overwriting semantics (`DELETE`, `ON CONFLICT DO //! UPDATE`, `TRUNCATE TABLE`, `REPLACE INTO`, an ORM delete) the base @@ -50,6 +57,7 @@ pub type Diff = [(String, String, String)]; #[serde(rename_all = "snake_case")] pub enum Kind { Parallel, + Twin, Replacing, LogLevel, Reporting, @@ -71,6 +79,7 @@ impl Widening { pub fn point(&self) -> &'static str { match self.kind { Kind::Parallel => "A parallel structure next to an existing one", + Kind::Twin => "Near-identical helpers added together", Kind::Replacing => "Deletes or overwrites where the code only added", Kind::LogLevel => "A log level changed", Kind::Reporting => "Reporting the ticket doesn't ask for", @@ -99,6 +108,10 @@ impl Widening { "`{}` adds {}. Extend the existing one (add the entries or the parameter there) and remove the new one.", self.path, self.what ), + Kind::Twin => format!( + "`{}` adds {}. Keep one helper with the shared logic (a parameter for what differs) and call it from both places.", + self.path, self.what + ), Kind::Replacing => format!( "`{}` now deletes or overwrites stored data ({}) where the base only added, and the ticket doesn't ask for that. Keep the write additive (insert, `ON CONFLICT DO NOTHING`) and remove the delete or overwrite.", self.path, self.what @@ -323,9 +336,16 @@ pub fn top_level_def(line: &str, path: &str) -> Option { let name = ident(decl)?; let rhs = decl.split_once('=')?.1.trim_start(); let rhs_l = rhs.to_lowercase(); + // A generic arrow function: `(items: T[]) =>`, its + // parameters often on the next lines. + let generic_arrow = rhs_l.starts_with('<') + && (rhs_l.contains("=>") + || rhs_l.contains(">(") + || rhs_l.trim_end().ends_with('(')); if rhs_l.starts_with("(") && (rhs_l.contains("=>") || rhs_l.starts_with("(async")) || rhs_l.starts_with("async") || rhs_l.starts_with("function") + || generic_arrow { return Some(Def { name, @@ -481,6 +501,219 @@ pub fn parallel_structures(diff: &Diff, base: &[(String, String)]) -> Vec String { + patch + .lines() + .filter(|l| (l.starts_with('+') && !l.starts_with("+++")) || l.starts_with(' ')) + .map(|l| &l[1..]) + .collect::>() + .join("\n") +} + +const KEYWORDS: &[&str] = &[ + "export", + "const", + "let", + "var", + "return", + "if", + "else", + "function", + "async", + "await", + "new", + "true", + "false", + "null", + "undefined", + "is", + "fn", + "pub", + "def", + "self", + "this", + "in", + "of", + "for", + "extends", + "None", + "True", + "False", + "not", + "and", + "or", + "mut", + "impl", +]; + +/// A body's shape: keywords, punctuation and member names (`.filter`, +/// `.has`) kept; every other name made `_`, so two helpers that differ only +/// in their names and types read the same. +pub fn shape(body: &str) -> Vec { + let mut out = Vec::new(); + let chars: Vec = body.chars().collect(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + if c.is_whitespace() { + i += 1; + continue; + } + if c.is_ascii_alphanumeric() || c == '_' || c == '$' { + let start = i; + while i < chars.len() + && (chars[i].is_ascii_alphanumeric() || chars[i] == '_' || chars[i] == '$') + { + i += 1; + } + let word: String = chars[start..i].iter().collect(); + let member = start > 0 && chars[start - 1] == '.'; + if KEYWORDS.contains(&word.as_str()) || member { + out.push(word); + } else { + out.push("_".to_string()); + } + continue; + } + out.push(c.to_string()); + i += 1; + } + out +} + +/// How alike two bodies' shapes are, 0 to 1: shared runs of four tokens. +pub fn shape_similarity(a: &str, b: &str) -> f64 { + let grams = |s: &str| -> std::collections::BTreeSet { + let t = shape(s); + t.windows(4).map(|w| w.join(" ")).collect() + }; + let (a, b) = (grams(a), grams(b)); + if a.is_empty() || b.is_empty() { + return 0.0; + } + a.intersection(&b).count() as f64 / a.union(&b).count() as f64 +} + +/// A definition's signature shape: its first line up to the body, with +/// generic parameters dropped (``). +fn signature(body: &str) -> String { + let first = body.lines().next().unwrap_or(""); + let mut out = String::new(); + let mut depth = 0; + for c in first.chars() { + match c { + '<' => depth += 1, + '>' if depth > 0 => depth -= 1, + _ if depth == 0 => out.push(c), + _ => {} + } + } + let s = shape(&out); + let start = s.iter().position(|t| t == "(").unwrap_or(s.len()); + s[start..].join(" ") +} + +/// Whether two new helpers are twins: names that parallel each other +/// ([`parallels`]); or the same signature shape and bodies at least half +/// alike; or bodies at least seven tenths alike. Bodies of fewer than +/// three lines are too short to compare. +pub fn twins(a: &Def, a_body: &str, b: &Def, b_body: &str) -> bool { + if a.kind != DefKind::Function || b.kind != DefKind::Function || a.name == b.name { + return false; + } + if parallels(a, b) { + return true; + } + let lines = |s: &str| s.lines().filter(|l| !l.trim().is_empty()).count(); + if lines(a_body) < 3 || lines(b_body) < 3 { + return false; + } + let sim = shape_similarity(a_body, b_body); + sim >= 0.7 || (sim >= 0.5 && signature(a_body) == signature(b_body)) +} + +/// A new helper of a diff with its body. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NewHelper { + pub path: String, + pub def: Def, + pub body: String, +} + +/// The top-level definitions a diff adds (not renames of removed ones), +/// with their bodies from the patch's new side. +pub fn new_helpers(diff: &Diff) -> Vec { + let mut out = Vec::new(); + for (path, status, patch) in diff { + if status == "removed" || !code_file(path) || is_test(path) { + continue; + } + let removed: Vec = lines_of(patch, '-') + .into_iter() + .filter_map(|l| top_level_def(l, path)) + .map(|d| d.name) + .collect(); + let context: Vec = context_of(patch) + .into_iter() + .filter_map(|l| top_level_def(l, path)) + .map(|d| d.name) + .collect(); + let text = new_side(patch); + for d in lines_of(patch, '+') + .into_iter() + .filter_map(|l| top_level_def(l, path)) + { + if removed.contains(&d.name) + || context.contains(&d.name) + || out + .iter() + .any(|h: &NewHelper| h.path == *path && h.def.name == d.name) + { + continue; + } + let body = body_of(&text, path, &d.name).unwrap_or_default(); + out.push(NewHelper { + path: path.clone(), + def: d, + body, + }); + } + } + out +} + +/// New helpers in one diff that are twins of one added before them in it +/// ([`twins`]): the parallel check compares new code with old, never new +/// with new. +pub fn twin_helpers(diff: &Diff) -> Vec { + let found = new_helpers(diff); + let mut out = Vec::new(); + for (i, b) in found.iter().enumerate() { + if let Some(a) = found[..i] + .iter() + .find(|a| twins(&a.def, &a.body, &b.def, &b.body)) + { + let where_a = if a.path == b.path { + String::new() + } else { + format!(" (in `{}`)", a.path) + }; + out.push(Widening { + kind: Kind::Twin, + path: b.path.clone(), + what: format!( + "`{}` next to `{}`{where_a}, added in the same change", + b.def.name, a.def.name + ), + }); + } + } + out +} + // ── Replacing semantics ──────────────────────────────────────────────────── /// Statements that delete or overwrite stored rows, with how a report @@ -881,6 +1114,7 @@ pub fn check( has_probe: bool, ) -> Vec { let mut out = parallel_structures(diff, base); + out.extend(twin_helpers(diff)); if !ticket_asks(ticket, REPLACE_ASKS) { out.extend(replacing(diff, base)); } @@ -1053,12 +1287,13 @@ mod tests { assert_eq!(got.len(), 2); assert_eq!(got[0].kind, DefKind::Table); assert_eq!(got[1].kind, DefKind::Function); - let ts = "export const SPORT_MAP: Record = {\nexport function sportFor(x) {\nconst handler = async (e) => {"; + let ts = "export const SPORT_MAP: Record = {\nexport function sportFor(x) {\nconst handler = async (e) => {\nexport const firstBy = ("; let got = defs(ts, "src/a.ts"); assert_eq!( got.iter().map(|d| d.name.as_str()).collect::>(), - vec!["SPORT_MAP", "sportFor", "handler"] + vec!["SPORT_MAP", "sportFor", "handler", "firstBy"] ); + assert_eq!(got[3].kind, DefKind::Function); let rs = "pub const RULES: &[&str] = &[\npub(crate) fn rules_for() {}"; assert_eq!(defs(rs, "a.rs").len(), 2); } @@ -1209,6 +1444,37 @@ mod tests { )); } + #[test] + fn twin_helpers_added_together_are_found() { + // Two new helpers whose names parallel each other. + let patch = "@@ -1,3 +1,20 @@\n export const keyOf = (s: Item) => s.label.toLowerCase();\n+export const dedupeItemsByKey = (items: Item[]): Item[] => {\n+ const seen = new Set();\n+ return items.filter((item) => {\n+ const key = keyOf(item);\n+ if (seen.has(key)) return false;\n+ seen.add(key);\n+ return true;\n+ });\n+};\n+export const dedupeItemOptionsByKey = (options: T[]): T[] => {\n+ const seen = new Set();\n+ return options.filter((option) => {\n+ if (seen.has(option.value)) return false;\n+ seen.add(option.value);\n+ return true;\n+ });\n+};\n"; + let w = twin_helpers(&[d("src/utils/maps.ts", "modified", patch)]); + assert_eq!(w.len(), 1, "{w:?}"); + assert_eq!(w[0].kind, Kind::Twin); + assert!(w[0] + .what + .contains("`dedupeItemOptionsByKey` next to `dedupeItemsByKey`")); + assert!(w[0].instruction().contains("Keep one helper")); + // Different names, the same body shape: still twins. + let a = "export const uniqueRows = (rows: Row[]): Row[] => {\n const seen = new Set();\n return rows.filter((r) => {\n if (seen.has(r.id)) return false;\n seen.add(r.id);\n return true;\n });\n};"; + let b = "export const firstPerCode = (codes: Code[]): Code[] => {\n const seen = new Set();\n return codes.filter((c) => {\n if (seen.has(c.code)) return false;\n seen.add(c.code);\n return true;\n });\n};"; + let def = |n: &str| Def { + name: n.into(), + kind: DefKind::Function, + }; + assert!(shape_similarity(a, b) >= 0.5, "{}", shape_similarity(a, b)); + assert!(twins(&def("uniqueRows"), a, &def("firstPerCode"), b)); + // Two unrelated helpers are not. + let c = "export const priceLabel = (cents: number): string => {\n const dollars = Math.floor(cents / 100);\n return `$${dollars}`;\n};"; + assert!(!twins(&def("uniqueRows"), a, &def("priceLabel"), c)); + // A helper added next to an existing one is the parallel check's, + // not reported twice. + let one = "@@ -1,2 +1,4 @@\n export const slugToId = (all: Item[], slug: string) => {\n+export const slugToIds = (all: Item[], slug: string): string[] =>\n+ all.filter((s) => s.slug === slug).map((s) => s.id);\n"; + let diff = [d("src/utils/maps.ts", "modified", one)]; + assert!(twin_helpers(&diff).is_empty()); + assert_eq!(parallel_structures(&diff, &[]).len(), 1); + } + #[test] fn an_edit_that_adds_a_parallel_helper() { let old = "SPORT_OVERRIDES = {\n}\ndef sport_overrides_for(n):\n pass\n"; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index a8b22d42f..f220ce113 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1275,6 +1275,9 @@ pub mod description_facts; pub mod dlq_cleanup; pub mod e2e; pub mod e2e_attribution; +/// Each ticket criterion's end-to-end test run on staging and on the +/// preview before the pull request is called done. +pub(crate) mod e2e_proof; pub mod e2e_reads; pub mod e2e_setup; pub mod email_events; diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 33605f4ec..4dca17855 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -305,12 +305,13 @@ pub async fn run( that CoderHelm carries out to the end, verification included.\n\n\ You have access to these repos:\n{repos_list}\n\n\ All tools default to {owner}/{repo} when the `repo` parameter is omitted. \ - To explore another repo, pass `repo` as `owner/name` (e.g. `\"{default_repo}\"`).{cross_repo}{instructions_block}{team_block}{tests_block}{feature_block}{smallest}", + To explore another repo, pass `repo` as `owner/name` (e.g. `\"{default_repo}\"`).{cross_repo}{instructions_block}{team_block}{tests_block}{feature_block}{smallest}{criteria_map}", owner = msg.repo_owner, repo = msg.repo_name, stance = super::ownership::planner_stance(), feature_block = super::feature::planner_block(intent), smallest = super::plan_shape::PLANNER, + criteria_map = common::e2e_proof::PLANNER, cross_repo = if team_repos.len() > 1 { super::cross_repo::PLANNER_LINE } else { @@ -848,6 +849,16 @@ Then the ```fix_location.json block described above."#, ) .await; let existing_names = super::plan_shape::existing_names(&found); + // Whether the repository has an end-to-end suite: a criterion a person + // sees is then planned with a test in it (`plan_shape::criteria_gaps`). + let e2e_suite = github + .get_tree(&msg.repo_owner, &msg.repo_name, &msg.base_branch) + .await + .map(|t| { + let paths: Vec = t.into_iter().map(|e| e.path).collect(); + common::preview::e2e_suite(&paths).is_some() + }) + .unwrap_or(false); let prompt = format!("{prompt}{}", super::plan_shape::existing_block(&found)); let mut content_blocks = vec![serde_json::json!({"type": "text", "text": prompt})]; for img in &msg.image_attachments { @@ -963,6 +974,11 @@ Then the ```fix_location.json block described above."#, let is_feature = intent == super::triage::TicketIntent::Feature; let mut shape_gaps = super::plan_shape::plan_gaps(&draft, &ticket_words, is_feature, &existing_names); + // Each criterion a person sees is mapped to an end-to-end test of its + // page (`common::e2e_proof`). + shape_gaps.extend(super::plan_shape::criteria_gaps( + &draft, &msg.title, &msg.body, e2e_suite, + )); // What the reused helpers do to stored rows, read from their bodies: a // replacing helper on a path that only inserts deleted rows nobody asked // about. @@ -1467,6 +1483,9 @@ Then the ```fix_location.json block described above."#, if !shape_gaps.is_empty() { let mut left = super::plan_shape::plan_gaps(&files, &ticket_words, is_feature, &existing_names); + left.extend(super::plan_shape::criteria_gaps( + &files, &msg.title, &msg.body, e2e_suite, + )); let facts = super::plan_shape::read_write_facts( &executor.read_only, github, diff --git a/services/worker/src/passes/plan_shape.rs b/services/worker/src/passes/plan_shape.rs index af70c4462..4f1e7cdcd 100644 --- a/services/worker/src/passes/plan_shape.rs +++ b/services/worker/src/passes/plan_shape.rs @@ -21,6 +21,11 @@ //! smaller does it; //! - [`PROOF`]: the one test (or the check) that shows it, in proportion. //! +//! - `## Criteria map` ([`criteria_gaps`], `common::e2e_proof`): each +//! acceptance criterion (or Expected line) that names a page or what a +//! person sees, with the page, an end-to-end test in the suite that loads +//! it, and what it asserts. Unit tests go with it, never in its place. +//! //! [`plan_gaps`] holds the draft to them and rejects a plan that proposes a //! structure parallel to one it names under Reuse, replacing or deleting //! semantics or log changes the ticket doesn't ask for, assertions about an @@ -331,6 +336,22 @@ pub fn plan_gaps( out } +/// What the plan's criteria map misses (`common::e2e_proof::map_gaps`): +/// the ticket's criteria read from its acceptance list or Expected lines, +/// each that names a page or what a person sees mapped to an end-to-end +/// test of that page. `suite`: the repository has an end-to-end suite. +pub fn criteria_gaps(files: &PlanResult, title: &str, body: &str, suite: bool) -> Vec { + if stops(files) { + return Vec::new(); + } + let criteria = common::e2e_proof::criteria(title, body, &super::stop_judge::acceptance(body)); + common::e2e_proof::map_gaps( + &criteria, + &common::e2e_proof::parse_map(&files.design), + suite, + ) +} + // ── What reused helpers do to stored rows ────────────────────────────────── /// A helper the plan reuses, and what it does to stored rows. diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 42a056ff6..1a7767d66 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -824,16 +824,35 @@ async fn preview(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> P let Some(mut st) = super::preview::advance(state, github, p, &pr).await else { return Performed::NotStarted; }; - if st.stage == common::preview::Stage::Ready - && !CAPTURING.swap(true, std::sync::atomic::Ordering::SeqCst) + let mut proved = false; + if matches!( + st.stage, + common::preview::Stage::Ready | common::preview::Stage::Checked + ) && !CAPTURING.swap(true, std::sync::atomic::Ordering::SeqCst) { - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(9 * 60); - super::preview::capture(state, github, p, &mut st, Some(deadline)).await; + if st.stage == common::preview::Stage::Ready { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(9 * 60); + super::preview::capture(state, github, p, &mut st, Some(deadline)).await; + } + // Each criterion's end-to-end test, on staging and on the preview + // (`e2e_proof`), once per head; what it sends back is a fix round. + let branch = pr["head"]["ref"].as_str().unwrap_or("").to_string(); + let (proofs, fresh) = super::e2e_proof::prove(state, github, p, &st, &branch).await; CAPTURING.store(false, std::sync::atomic::Ordering::SeqCst); + proved = fresh; + let items = common::e2e_proof::coder_items(&proofs, &st.head); + if fresh && !items.is_empty() { + let queued = super::resume::queue_own_review_round( + state, github, &c.team_id, &c.run_id, &st.head, &items, + ) + .await; + info!(run_id = %c.run_id, pr = c.pr, items = items.len(), queued = ?matches!(queued, super::resume::OwnRound::Fixing), "PR watch: the two-way proof sent work back to the coder"); + } } - let moved = before.as_ref().is_none_or(|b| { - b.head != st.head || b.stage != st.stage || b.shots != st.shots || b.checks != st.checks - }); + let moved = proved + || before.as_ref().is_none_or(|b| { + b.head != st.head || b.stage != st.stage || b.shots != st.shots || b.checks != st.checks + }); if moved { info!(run_id = %c.run_id, pr = c.pr, stage = ?st.stage, "PR watch: the preview moved; the description follows"); super::description::rebuild_run( diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index 0bacee23e..3be996c63 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -184,8 +184,15 @@ pub struct Facts { /// once its preview deploy and end-to-end checks passed on it, and only /// with an end-to-end spec when the repository has a suite. pub preview: Option, + /// Each ticket criterion's end-to-end test run on staging and on the + /// preview (`e2e_proof`). + pub two_way: super::e2e_proof::Standing, } +/// What a draft waits for while its criteria are proven both ways. +pub const TWO_WAY_WAIT: &str = + "each ticket criterion's end-to-end test runs on staging (where it must fail) and on the preview (where it must pass)"; + /// What a change a person sees waits on while it has no end-to-end spec in /// a repository with a suite: CoderHelm writes it in its next round, so it /// is CoderHelm's own wait (bounded like every wait), never a person's hold. @@ -457,7 +464,7 @@ fn decide_raw(f: &Facts) -> Decision { if f.closed { return Decision::Closed; } - let open = match (&f.feature, f.ci.green && f.approved) { + let mut open = match (&f.feature, f.ci.green && f.approved) { (Some(h), true) => h.items(), _ => Vec::new(), }; @@ -564,6 +571,24 @@ fn decide_raw(f: &Facts) -> Decision { if p.e2e_required && !p.e2e_covered { proof_wait.get_or_insert_with(|| E2E_WAIT.to_string()); } + // Each criterion proven both ways before it is done: a test that + // passes on staging too, or fails on the preview, is the coder's. + match &f.two_way { + super::e2e_proof::Standing::Pending => { + proof_wait.get_or_insert_with(|| TWO_WAY_WAIT.to_string()); + } + super::e2e_proof::Standing::Fixing(n) => { + wait.get_or_insert_with(|| { + format!( + "CoderHelm is fixing {n} criterion test(s) the two-way proof sent back (a test that passes on staging too, fails on the preview, or is missing)" + ) + }); + } + super::e2e_proof::Standing::Done(notes) => { + open.extend(notes.iter().map(|n| note_line(n))); + } + super::e2e_proof::Standing::None => {} + } match p.stage { Stage::Failed => { let failed: Vec = p @@ -1225,6 +1250,21 @@ async fn gather(ctx: &Ctx<'_>) -> Result { super::feature::ready_hold(ctx.state, gh, ctx.team_id, ctx.owner, ctx.repo, ctx.pr) .await; f.preview = preview_of(ctx, &pr).await; + let run_id = if ctx.run_id.is_empty() { + super::review_pr::lookup_run_by_pr(ctx.state, ctx.team_id, ctx.owner, ctx.repo, ctx.pr) + .await + .unwrap_or_default() + } else { + ctx.run_id.clone() + }; + f.two_way = super::e2e_proof::standing( + ctx.state, + ctx.team_id, + &run_id, + &f.head, + f.preview.as_ref(), + ) + .await; } // The description as it is now (the link check may have rewritten it). let pr = read_pr().await?;