From 6ce278c237dd986ef99bd9ca9485d5fffe3d7f7a Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Wed, 28 Oct 2026 21:12:03 -0400 Subject: [PATCH] PR updates stay true: description, risk, review, generated types, e2e skips, content notes, questions and ticket comments A new-feature PR that CoderHelm updated over several runs kept describing its first state, called a change to a shared query Low risk, left its own review saying the same, shipped without regenerated types, had an e2e test that skipped when content was missing, told editors to add a CMS block that staging already had, repeated one question on every update and posted the same ticket comment twice. - Fix rounds on an open PR rewrite its description from the whole diff; older review-fix rounds keep only their headline, so a failed suite of an earlier commit is not left in it. - The Risk level follows from the diff (shared files, a network call per page render, the reviewer's hard rules) and is raised with its reasons when the writer states less. - A silent review of a new commit replaces the body of CoderHelm's standing review, and threads the commit settled are resolved either way. - The generators gate checks that new schema types are in the generated output and that no file declares a parallel copy; review fix rounds run the same check; Sanity typegen settings in sanity.cli are read. - The feature checklist fails an e2e spec that skips on missing content. - Content notes look up blocks already on staging and name the one to replace, or say they could not look. - Questions are judged against the ticket text and comments, asked once per ticket, and ticket notices are posted once (edited in place on GitHub). --- services/common/src/ticket_state.rs | 119 ++++ services/worker/src/clients/github.rs | 22 + .../worker/src/passes/feature/checklist.rs | 128 +++- services/worker/src/passes/feature/content.rs | 318 ++++++++- services/worker/src/passes/feature/mod.rs | 66 +- services/worker/src/passes/feedback.rs | 1 + services/worker/src/passes/fix_location.rs | 88 ++- services/worker/src/passes/generators.rs | 441 ++++++++++++- services/worker/src/passes/infra_repo.rs | 1 + services/worker/src/passes/mod.rs | 269 ++++++-- services/worker/src/passes/plan.rs | 39 +- services/worker/src/passes/pr.rs | 40 +- services/worker/src/passes/pr_risk.rs | 617 ++++++++++++++++++ services/worker/src/passes/resolved.rs | 102 ++- services/worker/src/passes/resume.rs | 18 + .../worker/src/passes/review_fix/evidence.rs | 27 +- services/worker/src/passes/review_fix/mod.rs | 183 +++++- services/worker/src/passes/review_pr.rs | 18 +- services/worker/src/passes/review_verdict.rs | 101 +++ 19 files changed, 2520 insertions(+), 78 deletions(-) create mode 100644 services/worker/src/passes/pr_risk.rs diff --git a/services/common/src/ticket_state.rs b/services/common/src/ticket_state.rs index 7a8775ded..85188472f 100644 --- a/services/common/src/ticket_state.rs +++ b/services/common/src/ticket_state.rs @@ -148,6 +148,10 @@ pub struct Notice { /// When it was posted (RFC 3339). #[serde(default)] pub at: String, + /// The GitHub issue comment's id, so a later update edits it instead of + /// posting another; 0 when unknown (a Jira comment, an older record). + #[serde(default)] + pub comment_id: u64, } /// The decisions on a record, oldest first; empty when unreadable. @@ -186,8 +190,68 @@ pub fn posted_before<'a>( .find(|n| n.text_hash == text_hash || (!decided && n.key == key && !key.is_empty())) } +/// A notice's text as compared with earlier ones: whitespace collapsed, +/// markdown emphasis dropped, and dates, times and run links taken out, so +/// the same note posted by two runs minutes apart reads the same. +pub fn notice_text(text: &str) -> String { + let mut out: Vec = Vec::new(); + for word in text.split_whitespace() { + let w = word.replace("**", "").replace('`', ""); + let bare = w.trim_matches(|c: char| !c.is_ascii_alphanumeric()); + let stamp = bare.chars().filter(|c| c.is_ascii_digit()).count() >= 2 + && bare.contains([':', '-', '/']) + && bare.chars().all(|c| { + c.is_ascii_digit() || matches!(c, '-' | ':' | '.' | 'T' | 'Z' | '+' | '/') + }); + let run_link = w.contains("/runs/") || w.contains("run_id=") || w.contains("?id="); + if stamp || run_link || w.is_empty() { + continue; + } + out.push(w.to_lowercase()); + } + out.join(" ") +} + +/// The hash a notice is recorded under: its key and its compared text. +pub fn notice_hash(key: &str, text: &str) -> String { + crate::sha256_hex(&[key, ¬ice_text(text)]) +} + +/// What to do with a notice about to be posted on the ticket. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum NoticeAction<'a> { + /// The same text is already on the ticket: post nothing. + Skip(&'a Notice), + /// An earlier notice about the same thing says something else and can + /// be edited (a GitHub comment): edit it in place. + Edit(&'a Notice), + /// Nothing like it was posted, or the earlier one can't be edited. + Post, +} + +/// One comment per thing on a ticket: a notice whose text was posted before +/// (in any run) is not posted again; one whose key was posted with other +/// text edits the earlier comment where the platform allows. +pub fn notice_action<'a>(notices: &'a [Notice], key: &str, text_hash: &str) -> NoticeAction<'a> { + if let Some(n) = notices.iter().rev().find(|n| n.text_hash == text_hash) { + return NoticeAction::Skip(n); + } + match notices + .iter() + .rev() + .find(|n| !key.is_empty() && n.key == key && n.comment_id > 0) + { + Some(n) => NoticeAction::Edit(n), + None => NoticeAction::Post, + } +} + /// `notices` with `new` added, the oldest dropped past [`MAX_NOTICES`]. pub fn with_notice(mut notices: Vec, new: Notice) -> Vec { + // An edited comment keeps one record: the newest text for its key. + if new.comment_id > 0 { + notices.retain(|n| !(n.key == new.key && n.comment_id == new.comment_id)); + } notices.push(new); if notices.len() > MAX_NOTICES { let drop = notices.len() - MAX_NOTICES; @@ -295,6 +359,7 @@ mod tests { text_hash: "h1".into(), url: "https://example.com/c/1".into(), at: "2026-10-27T10:00:00Z".into(), + comment_id: 0, }; let all = with_notice(Vec::new(), n); // Same text: never again. @@ -316,6 +381,60 @@ mod tests { assert_eq!(many[0].key, "k10"); } + #[test] + fn the_same_note_from_two_runs_minutes_apart_is_posted_once() { + let first = "**Also needed outside the code**\n\nAdd the block on staging.\n\nChecked 2026-10-27T10:00:00Z, see https://app.example.com/runs/detail?id=r1"; + let second = "**Also needed outside the code**\n\nAdd the block on staging.\n\n\nChecked 2026-10-27T10:07:12Z, see https://app.example.com/runs/detail?id=r2"; + assert_eq!(notice_text(first), notice_text(second)); + let h = notice_hash("also_outside", first); + assert_eq!(h, notice_hash("also_outside", second)); + // A number that is content (a PR, a count) still counts. + assert_ne!(notice_text("see PR #12"), notice_text("see PR #13")); + let posted = with_notice( + Vec::new(), + Notice { + key: "also_outside".into(), + text_hash: h.clone(), + comment_id: 42, + ..Default::default() + }, + ); + assert!(matches!( + notice_action(&posted, "also_outside", &h), + NoticeAction::Skip(_) + )); + // New text about the same thing: the earlier comment is edited. + let other = notice_hash("also_outside", "Replace the block instead."); + match notice_action(&posted, "also_outside", &other) { + NoticeAction::Edit(n) => assert_eq!(n.comment_id, 42), + a => panic!("expected an edit, got {a:?}"), + } + // A Jira comment (no id) with new text is posted. + let jira = with_notice( + Vec::new(), + Notice { + key: "also_outside".into(), + text_hash: h, + ..Default::default() + }, + ); + assert_eq!( + notice_action(&jira, "also_outside", &other), + NoticeAction::Post + ); + // The edit keeps one record for the comment. + let edited = with_notice( + posted, + Notice { + key: "also_outside".into(), + text_hash: other, + comment_id: 42, + ..Default::default() + }, + ); + assert_eq!(edited.len(), 1); + } + #[test] fn intents_read_loosely() { assert_eq!( diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 0781932ad..735615d02 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -2561,6 +2561,28 @@ impl GitHubClient { Ok(()) } + /// Replaces the body of a review already posted (no new notification). + pub async fn update_pr_review( + &self, + owner: &str, + repo: &str, + pr_number: u64, + review_id: u64, + body: &str, + ) -> Result<(), Box> { + let url = format!("{API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}/reviews/{review_id}"); + let headers = self.auth_headers().await?; + let mut req = self + .http + .put(&url) + .json(&serde_json::json!({ "body": body })); + for (k, v) in headers { + req = req.header(k, v); + } + ok_or_body(req.send().await?).await?; + Ok(()) + } + /// List tags on a repo (used to compute the next semver release tag). pub async fn list_tags( &self, diff --git a/services/worker/src/passes/feature/checklist.rs b/services/worker/src/passes/feature/checklist.rs index de2e520fb..8e0d5d0c5 100644 --- a/services/worker/src/passes/feature/checklist.rs +++ b/services/worker/src/passes/feature/checklist.rs @@ -15,7 +15,12 @@ //! - the checks of each test package outside the main workspace; //! - the new spec run repeatedly (`--repeat-each=5`) against the preview; //! - for UI work, a no-horizontal-scroll check at a narrow and a wide -//! viewport in the spec ([`responsive_checked`]). +//! viewport in the spec ([`responsive_checked`]); +//! - a new or changed end-to-end test never skips itself when the content +//! or data it needs is missing: it fails, naming what is missing +//! ([`data_skips`]). Only a skip for a stated browser or platform +//! condition is allowed; a test that skips on missing content can never +//! fail. //! //! The counts and results go in the pull request; an item that fails keeps it //! a draft. @@ -575,6 +580,72 @@ pub fn root_steps(package_json: &str, tree: &[String]) -> Vec { steps } +/// Words that make a skip a browser or platform condition (allowed). +const PLATFORM_WORDS: &[&str] = &[ + "browsername", + "isMobile", + "ismobile", + "process.platform", + "platform", + "webkit", + "firefox", + "chromium", + "safari", + "devicename", + "project.name", + "testinfo.project", + "viewport", +]; + +/// Skip calls in end-to-end test code. +const SKIP_CALLS: &[&str] = &[ + "test.skip(", + "it.skip(", + "describe.skip(", + "test.describe.skip(", + "test.fixme(", + "testinfo.skip(", + "this.skip(", + "cy.skip(", + "pending(", +]; + +/// The skips a spec's diff adds that aren't for a browser or platform +/// condition, as "spec: line". Read from the added lines of the patch with +/// the lines just before each (an `if (!block) test.skip()` reads its +/// condition there). +pub fn data_skips(path: &str, patch: &str) -> Vec { + let lines: Vec<&str> = patch.lines().filter(|l| !l.starts_with("@@")).collect(); + let mut out = Vec::new(); + for (i, l) in lines.iter().enumerate() { + if !(l.starts_with('+') && !l.starts_with("+++")) { + continue; + } + let code = l[1..].trim(); + if code.starts_with("//") || code.starts_with('*') { + continue; + } + let low = code.to_ascii_lowercase().replace(' ', ""); + if !SKIP_CALLS.iter().any(|c| low.contains(c)) { + continue; + } + let from = i.saturating_sub(3); + let context = lines[from..=i] + .iter() + .map(|x| x.get(1..).unwrap_or("").to_ascii_lowercase()) + .collect::>() + .join(" "); + if PLATFORM_WORDS + .iter() + .any(|w| context.contains(&w.to_ascii_lowercase())) + { + continue; + } + out.push(format!("{path}: `{}`", common::truncate_str(code, 120))); + } + out +} + /// What the static part of the checklist reads. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Facts { @@ -595,6 +666,10 @@ pub struct Facts { /// Their values no test names, as "name: value". #[serde(default)] pub options_untested: Vec, + /// Skips the new or changed specs add for missing content or data, as + /// "spec: line" (see [`data_skips`]). + #[serde(default)] + pub data_skips: Vec, } /// The items that read the diff alone. @@ -667,6 +742,24 @@ pub fn static_items(f: &Facts) -> Vec { )); } } + if !f.specs.is_empty() { + if f.data_skips.is_empty() { + out.push(Item::new( + "end-to-end tests fail when their content is missing", + Status::Pass, + "no new or changed spec skips itself on missing content", + )); + } else { + out.push(Item::new( + "end-to-end tests fail when their content is missing", + Status::Fail, + format!( + "skips on missing content, so the test can never fail: {}", + f.data_skips.join("; ") + ), + )); + } + } if f.ui && !f.specs.is_empty() { if f.responsive_specs.is_empty() { out.push(Item::new( @@ -705,7 +798,11 @@ pub fn feedback(items: &[Item]) -> String { shown and the hidden case of an on/off field). A new \ end-to-end spec goes in every test map the repository keeps. For UI, the spec checks \ `document.documentElement.scrollWidth <= window.innerWidth` at a viewport {NARROW_MAX}px \ - wide or less and one {WIDE_MIN}px wide or more.\n" + wide or less and one {WIDE_MIN}px wide or more. An end-to-end test never calls \ + `test.skip` (or `fixme`, `it.skip`) when the content or data it needs is missing: rewrite \ + it to fail with a message naming the missing content (for example \ + `expect(block, 'staging page /x has no gallery block').toBeVisible()`); a skip is only \ + for a stated browser or platform condition.\n" )); s } @@ -714,6 +811,32 @@ pub fn feedback(items: &[Item]) -> String { mod tests { use super::*; + #[test] + fn a_spec_that_skips_on_missing_content_fails_the_checklist() { + let patch = "@@ -0,0 +1,12 @@\n+test('gallery renders', async ({ page }) => {\n+ await page.goto('/events')\n+ const block = page.locator('[data-block=gallery]')\n+ if ((await block.count()) === 0) {\n+ test.skip(true, 'no gallery block on staging')\n+ }\n+ // test.skip() in a comment is fine\n+ test.skip(browserName === 'webkit', 'webkit has no clipboard')\n+})\n"; + let skips = data_skips("e2e/gallery.spec.ts", patch); + assert_eq!(skips.len(), 1, "{skips:?}"); + assert!(skips[0].contains("no gallery block on staging")); + let f = Facts { + specs: vec!["e2e/gallery.spec.ts".into()], + data_skips: skips, + ..Default::default() + }; + let items = static_items(&f); + let item = items + .iter() + .find(|i| i.name.contains("content is missing")) + .unwrap(); + assert_eq!(item.status, Status::Fail); + assert!(feedback(&items).contains("never calls `test.skip`")); + // A platform skip alone passes. + let ok = data_skips( + "e2e/a.spec.ts", + "@@\n+test.skip(process.platform === 'win32', 'paths')\n", + ); + assert!(ok.is_empty()); + } + #[test] fn counts_the_cases_the_acceptance_criteria_list() { let body = "Build the filter.\n\nAcceptance criteria:\n- Shows all events by default\n- Filters by venue\n1. Filters by date\n\n## Notes\n- not a case\n"; @@ -801,6 +924,7 @@ mod tests { has_e2e: true, options_found: 0, options_untested: vec![], + data_skips: vec![], }; let items = static_items(&f); assert_eq!(failing(&items).len(), 3); diff --git a/services/worker/src/passes/feature/content.rs b/services/worker/src/passes/feature/content.rs index 3488f4a59..a5f852b11 100644 --- a/services/worker/src/passes/feature/content.rs +++ b/services/worker/src/passes/feature/content.rs @@ -17,7 +17,13 @@ //! changed; //! - anything else (no connection, a required field with no default, a page //! that must show the new block) stops the run before the pull request, -//! naming exactly which content must change. +//! naming exactly which content must change; +//! - before a note tells editors to add a block, staging is looked up for +//! blocks of that type already there ([`instance_queries`]): one in an +//! older shape is to be replaced or updated, by its document and key, with +//! the fields to set and to remove and the query that confirms it +//! ([`block_line`]). Without a connection to look with, the note says it +//! couldn't look instead of guessing. use std::collections::BTreeSet; @@ -81,7 +87,7 @@ pub fn is_schema_file(path: &str, text: &str) -> bool { /// The `name: 'x'` a line declares, if any (anywhere on the line, not /// `displayName:` or the like). -fn declared_name(line: &str) -> Option { +pub fn declared_name(line: &str) -> Option { let mut from = 0; while let Some(i) = line[from..].find("name:") { let at = from + i; @@ -219,7 +225,11 @@ impl Need { ), }, Need::BlockOnPage { block, spec } => format!( - "add a `{block}` block to the staging page `{spec}` opens, so the new test finds it" + "add a `{block}` block to the staging page `{spec}` opens, so the new test finds \ + it. I couldn't look up existing staging content (no staging CMS connection for \ + this repository), so check first: if that page already has a `{block}` block, \ + update that one (set the new fields, remove the old ones) instead of adding a \ + second" ), } } @@ -274,6 +284,195 @@ pub fn needs(changes: &[SchemaChange], specs: &[(String, String)]) -> Vec out } +/// What a new block's schema declares: its fields, the required ones, and +/// where documents hold it (`(document type, array field)`). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct BlockShape { + pub fields: Vec, + pub required: Vec, + pub held_in: Vec<(String, String)>, +} + +/// The fields a schema file declares after its type's own name, and which +/// of them are required. +pub fn fields_of(text: &str) -> (Vec, Vec) { + let ty = type_name(text); + let mut fields: Vec = Vec::new(); + let mut required: Vec = Vec::new(); + let mut last = String::new(); + for l in text.lines() { + if let Some(n) = declared_name(l) { + if n != ty && !fields.contains(&n) { + fields.push(n.clone()); + } + last = n; + } + if l.contains("required()") && !last.is_empty() && last != ty && !required.contains(&last) { + required.push(last.clone()); + } + } + (fields, required) +} + +/// Where documents hold blocks of `block`: for each schema file whose array +/// field lists `{ type: 'block' }`, that file's type and the field. +pub fn held_in(block: &str, schemas: &[(String, String)]) -> Vec<(String, String)> { + let mut out = Vec::new(); + for (_, text) in schemas { + let lines: Vec<&str> = text.lines().collect(); + for (i, l) in lines.iter().enumerate() { + let member = [format!("type: '{block}'"), format!("type: \"{block}\"")] + .iter() + .any(|m| l.contains(m.as_str())); + if !member || declared_name(l).as_deref() == Some(block) { + continue; + } + let Some(field) = lines[..i].iter().rev().find_map(|x| declared_name(x)) else { + continue; + }; + let doc = type_name(text); + if !doc.is_empty() && field != doc && !out.contains(&(doc.clone(), field.clone())) { + out.push((doc, field)); + } + } + } + out +} + +/// The read-only queries that find blocks of `block` already on staging: +/// inside each document field that holds it, and as documents of its own +/// type. +pub fn instance_queries(block: &str, shape: &BlockShape) -> Vec { + let Some(b) = groq_field(block) else { + return Vec::new(); + }; + let mut out: Vec = shape + .held_in + .iter() + .filter_map(|(doc, field)| { + let f = groq_field(field)?; + Some(format!( + "*[_type == {} && count({f}[_type == {}]) > 0][0...5]{{_id, \"field\": {}, \"items\": {f}[_type == {}]}}", + groq_str(doc), + groq_str(b), + groq_str(f), + groq_str(b) + )) + }) + .collect(); + out.push(format!( + "*[_type == {}][0...5]{{_id, \"items\": [@]}}", + groq_str(b) + )); + out +} + +/// A block already on staging: its document, the array field and key that +/// hold it (empty for a document of its own), and the fields it has. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Existing { + pub doc_id: String, + pub field: String, + pub key: String, + pub fields: Vec, +} + +/// The blocks an [`instance_queries`] result lists. +pub fn parse_instances(result: &Value) -> Vec { + let mut out = Vec::new(); + for d in result.as_array().into_iter().flatten() { + let doc_id = d["_id"].as_str().unwrap_or("").to_string(); + let field = d["field"].as_str().unwrap_or("").to_string(); + for item in d["items"].as_array().into_iter().flatten() { + let mut fields: Vec = item + .as_object() + .into_iter() + .flatten() + .map(|(k, _)| k.clone()) + .filter(|k| !k.starts_with('_')) + .collect(); + fields.sort(); + out.push(Existing { + doc_id: doc_id.clone(), + field: field.clone(), + key: item["_key"].as_str().unwrap_or("").to_string(), + fields, + }); + } + } + out +} + +/// The note for a block a spec needs, after staging was looked up: replace +/// or update the block that is there (fields to set and to remove, and the +/// query that confirms it), or add one when none is. +pub fn block_line(block: &str, spec: &str, shape: &BlockShape, found: &[Existing]) -> String { + let Some(e) = found.first() else { + return format!( + "add a `{block}` block to the staging page `{spec}` opens, so the new test finds it \ + (looked up on staging: no `{block}` block exists yet)" + ); + }; + let set: Vec = shape + .required + .iter() + .chain(shape.fields.iter()) + .filter(|f| !e.fields.contains(f)) + .fold(Vec::new(), |mut acc, f| { + if !acc.contains(f) { + acc.push(f.clone()); + } + acc + }); + let remove: Vec = e + .fields + .iter() + .filter(|f| !shape.fields.is_empty() && !shape.fields.contains(f)) + .cloned() + .collect(); + let (target, verify) = if e.key.is_empty() || e.field.is_empty() { + ( + format!("the `{block}` document `{}`", e.doc_id), + format!("*[_id == {}][0]", groq_str(&e.doc_id)), + ) + } else { + ( + format!( + "the `{block}` block in document `{}` (field `{}`, key `{}`)", + e.doc_id, e.field, e.key + ), + format!( + "*[_id == {}][0].{}[_key == {}][0]", + groq_str(&e.doc_id), + e.field, + groq_str(&e.key) + ), + ) + }; + let list = |v: &[String]| { + if v.is_empty() { + "nothing".to_string() + } else { + v.iter() + .map(|f| format!("`{f}`")) + .collect::>() + .join(", ") + } + }; + let more = if found.len() > 1 { + format!(" ({} more like it on staging)", found.len() - 1) + } else { + String::new() + }; + format!( + "staging already has {target}{more} in an older shape: replace or update that one, do \ + not add a second. Set {}; remove {}. Confirm with the query `{verify}`: it returns the \ + block with the new fields", + list(&set), + list(&remove) + ) +} + fn groq_str(s: &str) -> String { format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) } @@ -327,6 +526,27 @@ pub struct Outcome { pub blocking: Vec, } +/// Runs a read-only query on staging and returns its result. +async fn query( + http: &reqwest::Client, + c: &StagingCms, + token: &str, + q: &str, +) -> Result { + let r = http + .get(c.query_url()) + .query(&[("query", q)]) + .bearer_auth(token) + .send() + .await + .map_err(|e| format!("staging query failed: {e}"))?; + if !r.status().is_success() { + return Err(format!("staging query returned {}", r.status())); + } + let v: Value = r.json().await.map_err(|e| format!("staging query: {e}"))?; + Ok(v["result"].clone()) +} + /// Reads the ids an automatic need applies to on staging. async fn affected( http: &reqwest::Client, @@ -362,6 +582,7 @@ pub async fn settle( conn: Option<(&StagingCms, &str)>, production_in_code: &[String], needs: &[Need], + shapes: &[(String, BlockShape)], ) -> Outcome { let mut out = Outcome::default(); let Some((c, token)) = conn else { @@ -377,6 +598,34 @@ pub async fn settle( return out; } for n in needs { + // A block a spec needs: look for one already on staging first, so + // the note says which to replace instead of asking for a second. + if let Need::BlockOnPage { block, spec } = n { + let shape = shapes + .iter() + .find(|(b, _)| b == block) + .map(|(_, s)| s.clone()) + .unwrap_or_default(); + let mut found = Vec::new(); + let mut failed = None; + for q in instance_queries(block, &shape) { + match query(http, c, token, &q).await { + Ok(v) => found.extend(parse_instances(&v)), + Err(e) => failed = Some(e), + } + } + out.blocking.push(match failed { + Some(e) if found.is_empty() => format!( + "{} (the staging lookup failed: {e})", + n.line().replace( + "no staging CMS connection for this repository", + "the lookup failed" + ) + ), + _ => block_line(block, spec, &shape, &found), + }); + continue; + } let Some(q) = n.automatic().then(|| affected_query(n)).flatten() else { out.blocking.push(n.line()); continue; @@ -511,13 +760,71 @@ mod tests { assert_eq!(m[0], json!({"patch": {"id": "a", "unset": ["subtitle"]}})); } + /// The observed case: staging already had a block of the new type in an + /// older shape; the note asked editors to add one. + #[test] + fn a_block_already_on_staging_is_replaced_not_added() { + let block = "export default defineType({\n name: 'promoBanner',\n type: 'object',\n fields: [\n defineField({ name: 'heading', type: 'string', validation: (r) => r.required() }),\n defineField({ name: 'cta', type: 'link' }),\n ],\n})\n"; + let page = "export default defineType({\n name: 'page',\n type: 'document',\n fields: [\n defineField({\n name: 'sections',\n type: 'array',\n of: [{ type: 'hero' }, { type: 'promoBanner' }],\n }),\n ],\n})\n"; + let (fields, required) = fields_of(block); + assert_eq!(fields, vec!["heading", "cta"]); + assert_eq!(required, vec!["heading"]); + let shape = BlockShape { + fields, + required, + held_in: held_in( + "promoBanner", + &[ + ("schemas/promoBanner.ts".into(), block.into()), + ("schemas/page.ts".into(), page.into()), + ], + ), + }; + assert_eq!( + shape.held_in, + vec![("page".to_string(), "sections".to_string())] + ); + let qs = instance_queries("promoBanner", &shape); + assert_eq!( + qs[0], + "*[_type == \"page\" && count(sections[_type == \"promoBanner\"]) > 0][0...5]{_id, \"field\": \"sections\", \"items\": sections[_type == \"promoBanner\"]}" + ); + let found = parse_instances(&json!([ + {"_id": "page-events", "field": "sections", "items": [ + {"_key": "k1", "_type": "promoBanner", "title": "Old", "image": {}} + ]} + ])); + let line = block_line("promoBanner", "e2e/promo.spec.ts", &shape, &found); + assert!( + line.contains("document `page-events` (field `sections`, key `k1`)"), + "{line}" + ); + assert!(line.contains("do not add a second")); + assert!( + line.contains("Set `heading`, `cta`; remove `image`, `title`"), + "{line}" + ); + assert!(line.contains("*[_id == \"page-events\"][0].sections[_key == \"k1\"][0]")); + // Nothing there: add, saying it was looked up. + assert!(block_line("promoBanner", "e2e/promo.spec.ts", &shape, &[]) + .contains("looked up on staging: no `promoBanner` block exists yet")); + // No connection: it says it couldn't look. + let n = Need::BlockOnPage { + block: "promoBanner".into(), + spec: "e2e/promo.spec.ts".into(), + }; + assert!(n + .line() + .contains("couldn't look up existing staging content")); + } + #[tokio::test] async fn without_a_connection_everything_blocks_with_the_list() { let n = vec![Need::Unset { doc_type: "hero".into(), field: "subtitle".into(), }]; - let out = settle(&reqwest::Client::new(), None, &[], &n).await; + let out = settle(&reqwest::Client::new(), None, &[], &n, &[]).await; assert!(out.changed.is_empty()); assert_eq!( out.blocking, @@ -538,7 +845,7 @@ mod tests { doc_type: "hero".into(), field: "subtitle".into(), }]; - let out = settle(&reqwest::Client::new(), Some((&c, "t")), &[], &n).await; + let out = settle(&reqwest::Client::new(), Some((&c, "t")), &[], &n, &[]).await; assert!(out.changed.is_empty()); assert!(out.blocking.iter().any(|b| b.contains("only to staging"))); let c2 = StagingCms { @@ -550,6 +857,7 @@ mod tests { Some((&c2, "t")), &["copy".into()], &n, + &[], ) .await; assert!(out diff --git a/services/worker/src/passes/feature/mod.rs b/services/worker/src/passes/feature/mod.rs index 0a097f855..ebccaed7a 100644 --- a/services/worker/src/passes/feature/mod.rs +++ b/services/worker/src/passes/feature/mod.rs @@ -373,6 +373,11 @@ async fn checklist_facts( .map(|(m, s)| format!("{m}: {s}")) .collect(), has_e2e: tree.iter().any(|p| content::is_e2e_spec(p)), + data_skips: files + .iter() + .filter(|(p, s, _)| s != "removed" && content::is_e2e_spec(p)) + .flat_map(|(p, _, patch)| checklist::data_skips(p, patch)) + .collect(), }; (facts, maps) } @@ -633,6 +638,7 @@ async fn content_outcome( let (owner, repo, base) = (&w.msg.repo_owner, &w.msg.repo_name, &w.msg.base_branch); let mut changes = Vec::new(); let mut specs = Vec::new(); + let mut schemas: Vec<(String, String)> = Vec::new(); for (p, s, patch) in files { if s == "removed" { continue; @@ -656,6 +662,7 @@ async fn content_outcome( patch, &content::type_name(&text), )); + schemas.push((p.clone(), text)); } } if changes.is_empty() || !tree.iter().any(|p| content::is_e2e_spec(p)) { @@ -693,11 +700,35 @@ async fn content_outcome( } } let prod = common::staging_cms::production_datasets_in_code(&prod_files); + // Each new block's fields and where documents hold it, so a block of + // that type already on staging is named for replacement. + let shapes: Vec<(String, content::BlockShape)> = needs + .iter() + .filter_map(|n| match n { + content::Need::BlockOnPage { block, .. } => { + let (fields, required) = schemas + .iter() + .find(|(_, t)| content::type_name(t) == *block) + .map(|(_, t)| content::fields_of(t)) + .unwrap_or_default(); + Some(( + block.clone(), + content::BlockShape { + fields, + required, + held_in: content::held_in(block, &schemas), + }, + )) + } + _ => None, + }) + .collect(); let out = content::settle( &w.state.http, conn.as_ref().map(|(c, t)| (c, t.as_str())), &prod, &needs, + &shapes, ) .await; info!( @@ -902,7 +933,12 @@ pub async fn gate( facts.checklist = static_items.into_iter().chain(sandbox).collect(); facts.facts = cf; facts.maps = maps; - facts.questions = questions::collect(&w.plan.design, &evidence.notes); + facts.questions = open_questions( + w, + usage, + questions::collect(&w.plan.design, &evidence.notes), + ) + .await; facts.sandbox_failed = sandbox_failed; facts.head = head; super::add_progress_note( @@ -977,6 +1013,34 @@ pub async fn gate( } } +/// The product questions nothing on the ticket settles yet: the ticket's own +/// text, people's comments on it and the answers given in CoderHelm are read +/// first (see `resolved::settled_on_ticket`), so an answered question leaves +/// the description instead of being asked on every update. +async fn open_questions( + w: &super::proof::Work<'_>, + usage: &mut TokenUsage, + qs: Vec, +) -> Vec { + if qs.is_empty() { + return qs; + } + let notes = super::open_pr_choice::load_record(w.state, &w.msg.team_id, &w.msg.ticket_id) + .await + .notes; + let settled = super::resolved::settled_on_ticket( + &w.msg.answers, + &super::plan::ticket_text(&w.msg.title, &w.msg.body), + ¬es, + ); + let asked = common::run_questions::from_lines(&qs); + let verdicts = super::resolved::judge(w.state, w.provider, &asked, &settled, usage).await; + super::resolved::open_only(asked, &verdicts) + .into_iter() + .map(|q| q.question) + .collect() +} + // ── the ready check ───────────────────────────────────────────────────── #[derive(Debug, Clone, Default, Serialize, Deserialize)] diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 637cbfe0a..15af4a409 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -1183,6 +1183,7 @@ Rules: let changed = super::pr::refresh_description( state, &github, + (&msg.team_id, msg.installation_id), &msg.repo_owner, &msg.repo_name, msg.pr_number, diff --git a/services/worker/src/passes/fix_location.rs b/services/worker/src/passes/fix_location.rs index c1828a440..0af9cfd02 100644 --- a/services/worker/src/passes/fix_location.rs +++ b/services/worker/src/passes/fix_location.rs @@ -192,12 +192,52 @@ pub struct OutsideChange { /// How to confirm it worked afterwards. #[serde(default)] pub verify: String, + /// For a change that adds content (a block, an entry, a record): what + /// was looked up about content of that kind already in the environment + /// the tests use, and what came back (by id); or why it couldn't be + /// looked up. Empty when nothing was looked up. + #[serde(default)] + pub existing: String, } +/// Words that make a change add content. +const ADD_WORDS: &[&str] = &["add", "adds", "create", "creates", "insert", "new"]; +/// Words that name content a person adds in another system. +const CONTENT_WORDS: &[&str] = &[ + "block", + "blocks", + "document", + "documents", + "entry", + "entries", + "record", + "records", + "page", + "pages", + "item", + "items", + "content", + "row", + "rows", + "post", + "posts", +]; + impl OutsideChange { fn is_usable(&self) -> bool { !self.change.trim().is_empty() && !self.system.trim().is_empty() } + + /// Whether the change asks a person to add content in another system. + pub fn adds_content(&self) -> bool { + let low = self.change.to_ascii_lowercase(); + let words: Vec<&str> = low + .split(|c: char| !c.is_ascii_alphanumeric()) + .filter(|w| !w.is_empty()) + .collect(); + words.iter().any(|w| ADD_WORDS.contains(w)) + && words.iter().any(|w| CONTENT_WORDS.contains(w)) + } } /// The planner's structured decision. @@ -673,7 +713,8 @@ After the four openspec files, output this block (JSON, all fields required; `ou "system": "the system the change is made in", "change": "exactly what to change, naming the record(s)", "where": "who can make it, or where in that system", - "verify": "how to confirm afterwards (for example: after the next sync, the item shows on the site)" + "verify": "how to confirm afterwards (for example: after the next sync, the item shows on the site); for content, the API query that shows it and what it returns", + "existing": "when the change adds content (a block, an entry, a record): look up content of that kind in the environment the tests use first (the team's connected data sources or CMS API), and write what came back by id and key. If one exists, `change` says to REPLACE or update that exact one (fields to set, fields to remove), never to add a second. If you could not look, say why here. Empty only when the change adds no content" }, "history_check": "only when the prompt has a ticket history: each earlier pull request by number, what you reuse from it, what changes this time and why (and for one closed without a reason in its comments: who closed it and when); otherwise empty", "questions": ["each question only a person can answer, one decision each; [] when there are none"], @@ -807,6 +848,12 @@ pub fn ask_title(d: &FixDecision) -> &'static str { } } +/// What a note that adds content says when nothing was looked up. +pub const NOT_LOOKED_UP: &str = "I didn't look up whether content of this kind already exists \ + in the environment the tests use. Check there first: if one exists (even in an older \ + shape), update or replace that one, setting the new fields and removing the old ones, \ + instead of adding a second."; + fn push_change(out: &mut String, c: &OutsideChange) { out.push_str(&format!("- **Where:** {}", c.system.trim())); if !c.where_.trim().is_empty() { @@ -814,6 +861,13 @@ fn push_change(out: &mut String, c: &OutsideChange) { } out.push('\n'); out.push_str(&format!("- **What to change:** {}\n", c.change.trim())); + // A note that adds content says what is already there, or that nobody + // looked: it never guesses that nothing is. + if !c.existing.trim().is_empty() { + out.push_str(&format!("- **Already there:** {}\n", one_line(&c.existing))); + } else if c.adds_content() { + out.push_str(&format!("- **Not checked:** {NOT_LOOKED_UP}\n")); + } if !c.verify.trim().is_empty() { out.push_str(&format!("- **How to confirm:** {}\n", c.verify.trim())); } @@ -1177,6 +1231,38 @@ mod tests { assert!(d.outside_change.is_none()); } + #[test] + fn a_note_that_adds_content_says_what_is_already_there_or_that_nobody_looked() { + let add = OutsideChange { + system: "the CMS (staging)".into(), + change: "Add a promo banner block to the staging events page".into(), + ..Default::default() + }; + assert!(add.adds_content()); + let mut out = String::new(); + push_change(&mut out, &add); + assert!(out.contains("**Not checked:** I didn't look up"), "{out}"); + let looked = OutsideChange { + change: "Replace the promo banner block (document page-events, key k1): set heading, remove title".into(), + existing: "page-events has a promoBanner block, key k1, with old fields title and image".into(), + ..add.clone() + }; + let mut out = String::new(); + push_change(&mut out, &looked); + assert!(out.contains("**Already there:** page-events has a promoBanner block")); + assert!(!out.contains("Not checked")); + // A setting change adds no content: no note. + let setting = OutsideChange { + system: "the booking system".into(), + change: "Set the venue's opening time to 6am".into(), + ..Default::default() + }; + assert!(!setting.adds_content()); + let mut out = String::new(); + push_change(&mut out, &setting); + assert!(!out.contains("Not checked")); + } + #[test] fn both_puts_the_outside_change_in_the_pr_body() { let mut d = parse(fixture::PLANNER_REPLY).unwrap(); diff --git a/services/worker/src/passes/generators.rs b/services/worker/src/passes/generators.rs index 63e86c458..f8a64d79f 100644 --- a/services/worker/src/passes/generators.rs +++ b/services/worker/src/passes/generators.rs @@ -329,6 +329,21 @@ fn sanity_globs(dir: &str, files: &HashMap) -> (Vec, Vec .map(|g| under(dir, g)) .collect(); let mut outputs = vec![under(dir, "**/sanity.types.ts")]; + // Newer setups keep the typegen settings in the CLI config + // (`typegen: { generates: './src/sanity.types.ts' }`). + let cli = files + .iter() + .filter(|(p, _)| dir_of(p) == dir && base_name(p).starts_with("sanity.cli.")) + .map(|(_, t)| t); + for text in cli { + let gen = values(text, "generates"); + if !gen.is_empty() { + outputs = gen.iter().map(|g| under(dir, g)).collect(); + } + for p in values(text, "path") { + inputs.push(under(dir, &p)); + } + } if let Some(v) = cfg.and_then(|c| serde_json::from_str::(c).ok()) { if let Some(p) = v["path"].as_str() { inputs.push(under(dir, p)); @@ -696,9 +711,10 @@ pub fn fix_feedback(problems: &[(Generator, Vec, String)]) -> String { .iter() .map(|(g, inputs, why)| { format!( - "- `{}` reads {} and {why} Regenerate its output{}: call run_codegen when it is \ - offered, otherwise update the generated files ({}) exactly as the generator \ - would.", + "- `{}` reads {} and {why} Regenerate its output{}: call run_codegen. Only when \ + run_codegen is not offered, update the generated files ({}) exactly as the \ + generator would. Never declare a type by hand for something the generator \ + types: import the generated type.", g.name, list(inputs, 3), if g.outputs.is_empty() { @@ -721,6 +737,276 @@ pub fn fix_feedback(problems: &[(Generator, Vec, String)]) -> String { ) } +// ── Generated types are used, never written in parallel ─────────────────── + +/// A type the change adds to a generator's inputs: the generator owns its +/// type, so code that uses it imports the generated one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OwnedType { + /// The name the input declares (`gallery`). + pub name: String, + /// The name the generated type has (`Gallery`). + pub type_name: String, + /// The input file that declares it. + pub input: String, +} + +/// The type name a generator gives a declared name: each word capitalised, +/// separators dropped (`gallery-block` and `galleryBlock` both read +/// `GalleryBlock`). +pub fn type_name_of(name: &str) -> String { + name.split(|c: char| !c.is_ascii_alphanumeric()) + .filter(|w| !w.is_empty()) + .map(|w| { + let mut c = w.chars(); + match c.next() { + Some(f) => f.to_ascii_uppercase().to_string() + c.as_str(), + None => String::new(), + } + }) + .collect() +} + +fn added_lines(patch: &str) -> impl Iterator { + patch + .lines() + .filter(|l| l.starts_with('+') && !l.starts_with("+++")) + .map(|l| &l[1..]) +} + +/// The word after `kw` at the start of a trimmed line (`type Foo {`). +fn keyword_name(line: &str, kws: &[&str]) -> Option { + let t = line.trim_start(); + let t = t.strip_prefix("export ").unwrap_or(t).trim_start(); + for kw in kws { + if let Some(rest) = t.strip_prefix(kw).and_then(|r| r.strip_prefix(' ')) { + let n: String = rest + .trim_start() + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect(); + if !n.is_empty() { + return Some(n); + } + } + } + None +} + +/// The types an input file's diff adds, by the generator's kind. +pub fn added_types(kind: GenKind, status: &str, patch: &str) -> Vec { + let mut out: Vec = Vec::new(); + match kind { + GenKind::Sanity => { + let lines: Vec<&str> = patch.lines().collect(); + for (i, l) in lines.iter().enumerate() { + if !(l.starts_with('+') && l.contains("defineType(")) { + continue; + } + let name = lines[i..] + .iter() + .take(6) + .filter(|x| x.starts_with('+')) + .find_map(|x| super::feature::content::declared_name(x)); + if let Some(n) = name { + out.push(n); + } + } + if out.is_empty() && status == "added" { + if let Some(n) = added_lines(patch).find_map(super::feature::content::declared_name) + { + out.push(n); + } + } + } + GenKind::GraphqlCodegen => out.extend( + added_lines(patch) + .filter_map(|l| keyword_name(l, &["type", "input", "enum", "interface", "union"])), + ), + GenKind::Prisma => { + out.extend(added_lines(patch).filter_map(|l| keyword_name(l, &["model", "enum"]))) + } + GenKind::Protobuf => { + out.extend(added_lines(patch).filter_map(|l| keyword_name(l, &["message", "enum"]))) + } + GenKind::OpenApi | GenKind::Documented => {} + } + out.dedup(); + out +} + +/// The types the change adds to the inputs of `g`, from the diff as +/// (path, status, patch). +pub fn owned_types(g: &Generator, files: &[(String, String, String)]) -> Vec { + let mut out: Vec = Vec::new(); + for (path, status, patch) in files { + if status == "removed" || !any_match(&g.inputs, path) || any_match(&g.outputs, path) { + continue; + } + for name in added_types(g.kind, status, patch) { + let type_name = type_name_of(&name); + if type_name.is_empty() || out.iter().any(|o| o.type_name == type_name) { + continue; + } + out.push(OwnedType { + name, + type_name, + input: path.clone(), + }); + } + } + out +} + +/// Whether the generated output has the type: its type name as a word, or +/// the declared name as a quoted literal (`_type: "gallery"`). +pub fn output_has(t: &OwnedType, output: &str) -> bool { + let word = output + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .any(|w| w == t.type_name); + word || output.contains(&format!("\"{}\"", t.name)) || output.contains(&format!("'{}'", t.name)) +} + +/// Suffixes a hand-written type for a thing carries (`GalleryProps`). +const TYPE_SUFFIXES: &[&str] = &[ + "Props", "Block", "Data", "Fields", "Type", "Schema", "Content", "Item", "Section", "Doc", + "Document", "Value", +]; + +fn base_of(ident: &str) -> String { + let mut s = ident.to_string(); + loop { + let before = s.clone(); + for suf in TYPE_SUFFIXES { + if s.len() > suf.len() && s.ends_with(suf) { + s.truncate(s.len() - suf.len()); + } + } + if s == before { + break; + } + } + s.to_ascii_lowercase() +} + +/// Whether a source file may declare types (not a test, not generated). +fn is_source(path: &str) -> bool { + let l = path.to_ascii_lowercase(); + let code = [".ts", ".tsx", ".js", ".jsx", ".vue", ".svelte", ".astro"] + .iter() + .any(|e| l.ends_with(e)); + code && !l.ends_with(".d.ts") + && !l.contains(".test.") + && !l.contains(".spec.") + && !l.contains("generated") +} + +/// Types the change declares by hand for something a generator types: +/// `(file, declared name, owned type)`. A declaration built from the +/// generated type (`type GalleryProps = Gallery & {…}`) is not parallel. +pub fn hand_typed<'a>( + owned: &'a [OwnedType], + g: &Generator, + files: &[(String, String, String)], +) -> Vec<(String, String, &'a OwnedType)> { + let mut out = Vec::new(); + for (path, status, patch) in files { + if status == "removed" + || !is_source(path) + || any_match(&g.outputs, path) + || any_match(&g.inputs, path) + { + continue; + } + let added: Vec<&str> = added_lines(patch).collect(); + for (i, l) in added.iter().enumerate() { + let Some(ident) = keyword_name(l, &["type", "interface"]) else { + continue; + }; + let Some(t) = owned + .iter() + .find(|t| base_of(&ident) == base_of(&t.type_name)) + else { + continue; + }; + // Built from the generated type: the declaration's own lines + // (up to its closing brace) name it as a type. + let mut decl: Vec<&str> = Vec::new(); + for (j, x) in added[i..].iter().take(8).enumerate() { + decl.push(x); + let t = x.trim(); + if (j > 0 && t.starts_with('}')) || (j == 0 && t.ends_with(';')) { + break; + } + } + let body = decl.join(" "); + let derived = names_type(&body.replacen(&ident, "", 1), &t.type_name); + if !derived { + out.push((path.clone(), ident, t)); + } + } + } + out +} + +/// Whether `text` uses `name` as a type: the whole word, not called +/// (`Gallery(` is a function). +fn names_type(text: &str, name: &str) -> bool { + let b = text.as_bytes(); + let word = |c: u8| c.is_ascii_alphanumeric() || c == b'_'; + text.match_indices(name).any(|(at, _)| { + let before = at.checked_sub(1).map(|i| b[i]); + let after = b.get(at + name.len()).copied(); + !before.is_some_and(word) && !after.is_some_and(|c| word(c) || c == b'(') + }) +} + +/// What the generated output and the code that uses it must show for the +/// types the change adds: the output has each (else the generator didn't +/// pick it up), and no file declares its own copy. `outputs`: the text of +/// the generator's output files on the branch (empty when none could be +/// read, then only the hand-typed check runs). +pub fn ownership_problems( + g: &Generator, + files: &[(String, String, String)], + outputs: &[(String, String)], +) -> Vec { + let owned = owned_types(g, files); + if owned.is_empty() { + return Vec::new(); + } + let mut out = Vec::new(); + if !outputs.is_empty() { + for t in &owned { + if !outputs.iter().any(|(_, text)| output_has(t, text)) { + out.push(format!( + "its generated output ({}) has no `{}` for the `{}` that `{}` adds: the \ + generator didn't pick it up.", + list( + &outputs.iter().map(|(p, _)| p.clone()).collect::>(), + 2 + ), + t.type_name, + t.name, + t.input + )); + } + } + } + let from = outputs + .first() + .map(|(p, _)| format!(" from `{p}`")) + .unwrap_or_default(); + for (path, ident, t) in hand_typed(&owned, g, files) { + out.push(format!( + "`{path}` declares `{ident}` by hand for the `{}` the generator types: import the \ + generated `{}`{from} instead of a parallel type.", + t.name, t.type_name + )); + } + out +} + // ── Async: read the repo, run, check ──────────────────────────────────────── /// Reads what detection needs from the repository at `git_ref`. @@ -980,6 +1266,39 @@ async fn regenerate(w: &Work<'_>, attempt: usize, notes: &mut Vec) -> Op } } } + // The new types are in the generated output and used from there: + // a run that "passed" without picking up the schema, a hand-edited + // output, or a parallel hand-written type are caught here. + if let Ok(diff) = w + .github + .compare_files_with_patches(owner, name, &w.msg.base_branch, w.branch) + .await + { + for g in &gens { + if problems.iter().any(|(p, _, _)| p == g) { + continue; + } + let mut outputs: Vec<(String, String)> = Vec::new(); + for p in repo + .tree + .iter() + .filter(|p| any_match(&g.outputs, p)) + .take(3) + { + if let Ok(t) = w.github.read_file(owner, name, p, w.branch).await { + outputs.push((p.clone(), t)); + } + } + let found = ownership_problems(g, &diff, &outputs); + if !found.is_empty() { + let inputs = owned_types(g, &diff) + .into_iter() + .map(|t| t.input) + .collect::>(); + problems.push((g.clone(), inputs, found.join(" "))); + } + } + } Some(Pass::Problems(problems)) } @@ -1336,6 +1655,122 @@ mod tests { assert!(all_command(&RepoFiles::default()).is_none()); } + fn sanity_gen() -> Generator { + Generator { + kind: GenKind::Sanity, + name: "npm run typegen".into(), + command: "npm run typegen".into(), + inputs: vec!["**/schemaTypes/**".into()], + outputs: vec!["src/sanity.types.ts".into()], + } + } + + /// The observed case: a new block in the CMS schema, the generated + /// union without it, and its props typed by hand in the component. + #[test] + fn a_new_schema_type_must_be_generated_and_imported() { + let g = sanity_gen(); + let files = vec![ + ( + "studio/schemaTypes/blocks/gallery.ts".to_string(), + "added".to_string(), + "@@\n+import { defineType } from 'sanity'\n+export default defineType({\n+ name: 'gallery',\n+ type: 'object',\n+ fields: [{ name: 'title', type: 'string' }],\n+})\n".to_string(), + ), + ( + "src/components/blocks/Gallery.tsx".to_string(), + "added".to_string(), + "@@\n+export interface GalleryProps {\n+ title?: string\n+}\n+export function Gallery(p: GalleryProps) {}\n".to_string(), + ), + ]; + let owned = owned_types(&g, &files); + assert_eq!(owned.len(), 1); + assert_eq!(owned[0].type_name, "Gallery"); + let stale = vec![( + "src/sanity.types.ts".to_string(), + "export type Hero = { _type: \"hero\" }\nexport type Block = Hero\n".to_string(), + )]; + let p = ownership_problems(&g, &files, &stale); + assert_eq!(p.len(), 2, "{p:?}"); + assert!(p[0].contains("has no `Gallery`")); + assert!(p[1].contains("declares `GalleryProps` by hand")); + assert!(p[1].contains("from `src/sanity.types.ts`")); + + // Regenerated, and the component builds on the generated type. + let fresh = vec![( + "src/sanity.types.ts".to_string(), + "export type Gallery = { _type: \"gallery\"; title?: string }\n".to_string(), + )]; + let mut good = files.clone(); + good[1].2 = "@@\n+import type { Gallery } from '@/sanity.types'\n+export type GalleryProps = Gallery & { className?: string }\n".into(); + assert!(ownership_problems(&g, &good, &fresh).is_empty()); + // An unrelated type is never flagged. + let other = vec![( + "src/components/Nav.tsx".to_string(), + "modified".to_string(), + "@@\n+type NavProps = { open: boolean }\n".to_string(), + )]; + assert!(hand_typed(&owned, &g, &other).is_empty()); + } + + #[test] + fn schema_languages_name_their_new_types() { + assert_eq!( + added_types( + GenKind::GraphqlCodegen, + "modified", + "@@\n+type Gallery {\n+ id: ID!\n+}\n+extend type Query { x: Int }\n" + ), + vec!["Gallery".to_string()] + ); + assert_eq!( + added_types(GenKind::Prisma, "modified", "@@\n+model Booking {\n"), + vec!["Booking".to_string()] + ); + assert_eq!( + added_types( + GenKind::Sanity, + "modified", + "@@\n fields: [\n+ defineField({ name: 'caption', type: 'string' }),\n" + ), + Vec::::new() + ); + assert_eq!(type_name_of("gallery-block"), "GalleryBlock"); + assert_eq!(type_name_of("galleryBlock"), "GalleryBlock"); + } + + #[test] + fn typegen_settings_in_the_sanity_cli_config_are_read() { + let r = repo( + &[ + ( + "package.json", + r#"{"scripts":{"typegen":"sanity schema extract && sanity typegen generate"}}"#, + ), + ( + "sanity.cli.ts", + "export default defineCliConfig({\n typegen: {\n path: './app/**/*.{ts,tsx}',\n generates: './app/types/cms.generated.ts',\n },\n})\n", + ), + ], + &["studio/schemaTypes/gallery.ts"], + ); + let gens = detect(&r); + assert_eq!( + gens[0].outputs, + vec!["app/types/cms.generated.ts".to_string()] + ); + assert!(outputs_missing( + &gens[0], + &changed(&["studio/schemaTypes/gallery.ts"]) + )); + assert!(!outputs_missing( + &gens[0], + &changed(&[ + "studio/schemaTypes/gallery.ts", + "app/types/cms.generated.ts" + ]) + )); + } + #[test] fn the_fix_round_names_the_generator_and_its_outputs() { let g = Generator { diff --git a/services/worker/src/passes/infra_repo.rs b/services/worker/src/passes/infra_repo.rs index e9e1acddb..1371f236e 100644 --- a/services/worker/src/passes/infra_repo.rs +++ b/services/worker/src/passes/infra_repo.rs @@ -552,6 +552,7 @@ mod tests { change: "Raise the task's ephemeral storage and alarm on its use".into(), where_: "the task definition".into(), verify: "the alarm shows in CloudWatch".into(), + ..Default::default() }), ..Default::default() }), diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 17745dab5..768a02dfb 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -735,6 +735,7 @@ pub mod plugins; mod pr; mod pr_holder; pub mod pr_outcomes; +mod pr_risk; mod proof; pub mod quarantine; /// Hosted side of hybrid: forward a held event to a self-hosted install again. @@ -6174,29 +6175,17 @@ async fn report_also_outside( ); let title = "Also needed outside the code"; add_progress_note(state, &msg.team_id, run_id, title).await; - if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { - let _ = github - .create_issue_comment( - &msg.repo_owner, - &msg.repo_name, - msg.issue_number, - &format!("**{title}**\n\n{report}"), - ) - .await; - } else if matches!(msg.source, TicketSource::Jira) && !msg.ticket_id.is_empty() { - if let Err(e) = post_jira_comment( - state, - &msg.team_id, - &msg.ticket_id, - &fix_location::jira_text(&report), - "clarification", - title, - ) - .await - { - warn!(run_id, error = %e, "Could not post the outside part of the fix on the ticket"); - } - } + post_ticket_notice( + state, + msg, + run_id, + github, + NOTICE_ALSO_OUTSIDE, + &format!("**{title}**\n\n{report}"), + &fix_location::jira_text(&report), + title, + ) + .await; let _ = state .dynamo .update_item() @@ -6216,8 +6205,142 @@ async fn report_also_outside( .await; } +/// Notice key: the part of the fix outside the code, one comment per ticket. +const NOTICE_ALSO_OUTSIDE: &str = "also_outside"; +/// Notice key prefix: one question the plan asks, by its compared text. +const NOTICE_QUESTION: &str = "question:"; + +/// The notice key of one question. +fn question_key(question: &str) -> String { + format!( + "{NOTICE_QUESTION}{}", + &common::sha256_hex(&[&common::ticket_state::notice_text(question)])[..16] + ) +} + +/// The questions not asked on the ticket before (by any run), in order. +fn new_questions<'a>( + questions: &'a [String], + notices: &[common::ticket_state::Notice], +) -> Vec<&'a String> { + questions + .iter() + .filter(|q| !q.trim().is_empty()) + .filter(|q| { + let key = question_key(q); + !notices.iter().any(|n| n.key == key) + }) + .collect() +} + +/// Posts a notice on the ticket once: the same text (in any run, whatever +/// its dates or run links) is never posted again, and new text about the +/// same thing edits the earlier GitHub comment instead of adding another. +/// A Jira comment can't be edited here, so only changed text is posted. +/// Returns the comment's address when one was posted or edited. +#[allow(clippy::too_many_arguments)] +async fn post_ticket_notice( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + github: &GitHubClient, + key: &str, + github_body: &str, + jira_body: &str, + jira_title: &str, +) -> Option { + use common::ticket_state::{notice_action, notice_hash, Notice, NoticeAction}; + let github_ticket = matches!(msg.source, TicketSource::Github) && msg.issue_number > 0; + let jira_ticket = matches!(msg.source, TicketSource::Jira) && !msg.ticket_id.is_empty(); + if !github_ticket && !jira_ticket { + return None; + } + let text_hash = notice_hash(key, github_body); + let rec = open_pr_choice::load_record(state, &msg.team_id, &msg.ticket_id).await; + let action = notice_action(&rec.notices, key, &text_hash); + let (url, comment_id) = match (action, github_ticket) { + (NoticeAction::Skip(earlier), _) => { + info!( + run_id, + key, "Same notice already on the ticket — not posted again" + ); + return (!earlier.url.is_empty()).then(|| earlier.url.clone()); + } + (NoticeAction::Edit(earlier), true) => { + match github + .edit_issue_comment( + &msg.repo_owner, + &msg.repo_name, + earlier.comment_id, + github_body, + ) + .await + { + Ok(_) => { + info!(run_id, key, "Edited the earlier notice on the issue"); + (earlier.url.clone(), earlier.comment_id) + } + Err(e) => { + warn!(run_id, key, error = %e, "Could not edit the earlier notice on the issue"); + return None; + } + } + } + (_, true) => match github + .create_issue_comment( + &msg.repo_owner, + &msg.repo_name, + msg.issue_number, + github_body, + ) + .await + { + Ok(c) => ( + c["html_url"].as_str().unwrap_or("").to_string(), + c["id"].as_u64().unwrap_or(0), + ), + Err(e) => { + warn!(run_id, key, error = %e, "Could not post the notice on the issue"); + return None; + } + }, + (_, false) => match post_jira_comment_link( + state, + &msg.team_id, + &msg.ticket_id, + jira_body, + "clarification", + jira_title, + ) + .await + { + Ok(link) => (link.unwrap_or_default(), 0), + Err(e) => { + warn!(run_id, key, error = %e, "Could not post the notice on the ticket"); + return None; + } + }, + }; + open_pr_choice::record_notice( + state, + &msg.team_id, + &msg.ticket_id, + Notice { + key: key.to_string(), + text_hash, + url: url.clone(), + at: chrono::Utc::now().to_rfc3339(), + comment_id, + }, + ) + .await; + (!url.is_empty()).then_some(url) +} + /// Tells the ticket the plan's questions only a person can answer when the -/// run goes on to write code. Nothing when the plan has none. +/// run goes on to write code: each question once per ticket, whatever run +/// asks it again; the run never waits on them. Nothing when the plan has +/// none, or every one was asked before. async fn report_questions( state: &WorkerState, msg: &TicketMessage, @@ -6225,7 +6348,33 @@ async fn report_questions( github: &GitHubClient, decision: &fix_location::FixDecision, ) { - let questions = fix_location::questions_markdown(decision); + let rec = open_pr_choice::load_record(state, &msg.team_id, &msg.ticket_id).await; + let fresh = new_questions(&decision.questions, &rec.notices); + let earlier = decision + .questions + .iter() + .filter(|q| !q.trim().is_empty()) + .count() + - fresh.len(); + if earlier > 0 { + add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "{earlier} question(s) already asked on the ticket — not asked again; the run goes on without the answers" + ), + ) + .await; + } + if fresh.is_empty() { + return; + } + let shown = fix_location::FixDecision { + questions: fresh.iter().map(|q| q.to_string()).collect(), + ..Default::default() + }; + let questions = fix_location::questions_markdown(&shown); let Some((_, list)) = questions.split_once('\n') else { return; }; @@ -6235,28 +6384,37 @@ async fn report_questions( list.trim() ); add_progress_note(state, &msg.team_id, run_id, title).await; - if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { - let _ = github - .create_issue_comment( - &msg.repo_owner, - &msg.repo_name, - msg.issue_number, - &format!("**{title}**\n\n{report}"), - ) - .await; - } else if matches!(msg.source, TicketSource::Jira) && !msg.ticket_id.is_empty() { - if let Err(e) = post_jira_comment( + let key = fresh + .iter() + .map(|q| question_key(q)) + .collect::>() + .join(","); + let url = post_ticket_notice( + state, + msg, + run_id, + github, + &key, + &format!("**{title}**\n\n{report}"), + &fix_location::jira_text(&report), + title, + ) + .await; + // Each question is kept as asked, so no later run asks it again. + for q in &fresh { + open_pr_choice::record_notice( state, &msg.team_id, &msg.ticket_id, - &fix_location::jira_text(&report), - "clarification", - title, + common::ticket_state::Notice { + key: question_key(q), + text_hash: common::ticket_state::notice_hash(&question_key(q), q), + url: url.clone().unwrap_or_default(), + at: chrono::Utc::now().to_rfc3339(), + comment_id: 0, + }, ) - .await - { - warn!(run_id, error = %e, "Could not post the plan's questions on the ticket"); - } + .await; } } @@ -7422,6 +7580,7 @@ async fn ask_on_ticket_keyed( text_hash, url: comment_url.clone().unwrap_or_default(), at: chrono::Utc::now().to_rfc3339(), + comment_id: 0, }, ) .await; @@ -10349,6 +10508,30 @@ mod open_pr_tests { } } +#[cfg(test)] +mod ticket_notice_tests { + use super::{new_questions, question_key}; + use common::ticket_state::Notice; + + /// A question asked by one run is not asked again by the next, however + /// its spacing or emphasis changes; a new question still is. + #[test] + fn a_question_is_asked_on_the_ticket_once() { + let asked = vec![Notice { + key: question_key("Does this replace the earlier pull request #12?"), + ..Default::default() + }]; + let next_run = vec![ + "Does this replace the earlier pull request **#12**?".to_string(), + "Who sees the block?".to_string(), + ]; + let fresh = new_questions(&next_run, &asked); + assert_eq!(fresh, vec![&next_run[1]]); + assert!(new_questions(&next_run[..1], &asked).is_empty()); + assert_ne!(question_key("Who sees it?"), question_key("Who edits it?")); + } +} + #[cfg(test)] mod asking_tests { use super::{clarification_questions, jira_comment_link, unknown_fix_questions}; diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 41d4ea532..f101825a6 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -1076,17 +1076,34 @@ Then the ```fix_location.json block described above."#, files.tasks = super::resolved::keep_open(&asked, &v); } } - if let Some(d) = files.fix.as_mut() { - let qs = common::run_questions::from_lines(&d.questions); - let v = super::resolved::judge(state, provider, &qs, &msg.answers, usage).await; - if v.iter().any(|v| !v.may_ask()) { - d.questions = qs - .into_iter() - .zip(v) - .filter(|(_, v)| v.may_ask()) - .map(|(q, _)| q.question) - .collect(); - } + } + // The decision's questions don't stop the run; each is checked against + // everything that settles it on the ticket: the answers, the ticket's + // own text (a ticket that says it replaces earlier work answers a + // question about that work) and what people wrote on it. A settled one + // is dropped here, so it is neither asked on the ticket nor listed in + // the pull request again. + if let Some(d) = files.fix.as_mut().filter(|d| !d.questions.is_empty()) { + let notes = super::open_pr_choice::load_record(state, &msg.team_id, &msg.ticket_id) + .await + .notes; + let settled = super::resolved::settled_on_ticket( + &msg.answers, + &ticket_text(&msg.title, &msg.body), + ¬es, + ); + let qs = common::run_questions::from_lines(&d.questions); + let v = super::resolved::judge(state, provider, &qs, &settled, usage).await; + if v.iter().any(|v| !v.may_ask()) { + info!( + ticket_id = %msg.ticket_id, + dropped = v.iter().filter(|v| !v.may_ask()).count(), + "The ticket already settles some of the plan's questions — not asking them" + ); + d.questions = super::resolved::open_only(qs, &v) + .into_iter() + .map(|q| q.question) + .collect(); } } diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index fe95f9277..1153ebf32 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -209,6 +209,20 @@ pub async fn run( .get_diff(&msg.repo_owner, &msg.repo_name, &msg.base_branch, branch) .await?; let diff_summary = format_diff_summary(&diff); + // The lowest Risk the diff allows (shared files, a network call per page + // render), told to the writer and enforced on what it writes. + let risk_files = super::pr_risk::diff_files(&diff); + let risk_floor = super::pr_risk::floor( + &risk_files, + &super::pr_risk::importers( + state, + &msg.team_id, + msg.installation_id, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + &risk_files, + ) + .await, + ); // Check for PR template in the repo let pr_template = @@ -281,11 +295,12 @@ pub async fn run( "Write a PR description following this structure, and nothing else:\n\n\ 1. **Summary** — One sentence: the problem and what this change does about it.\n\ 2. **Changes** — Bolded per-area headers with bullet details. Keep it tight.\n\ - 3. **Risk** — State risk level in bold (**Low**, **Medium**), then why it's safe.\n\ + 3. **Risk** — State the risk level in bold (**Low**, **Medium** or **High**) and why, from the diff: a change to a file every page or request goes through, or a new network call per page render, is never Low.\n\ 4. **Verification** — Numbered steps to verify the change." }; let evidence_block = format!( - "{}{}{}{}", + "{}{}{}{}{}", + super::pr_risk::writer_note(&risk_floor), evidence_instructions(proof.evidence), manual_instructions(proof.manual), ci_instructions(proof.ci), @@ -496,6 +511,8 @@ Return ONLY the markdown body text."#, Some(f) => super::feature::shape_body(body_text, f), None => body_text, }; + // The Risk it states is at least what the diff makes it, with why. + let body_text = super::pr_risk::enforce(&body_text, &risk_floor); // Add issue link for GitHub tickets. // Strip any "Closes #N" the model may have included to avoid duplication. @@ -1463,6 +1480,7 @@ fn request_block(requests: &[String]) -> String { pub async fn refresh_description( state: &WorkerState, github: &GitHubClient, + team: (&str, u64), owner: &str, repo: &str, pr_number: u64, @@ -1491,6 +1509,18 @@ pub async fn refresh_description( } let diff = github.get_diff(owner, repo, &base, &head).await.ok()?; let patches = format_diff_patches(&diff); + let risk_files = super::pr_risk::diff_files(&diff); + let risk_floor = super::pr_risk::floor( + &risk_files, + &super::pr_risk::importers( + state, + team.0, + team.1, + &format!("{owner}/{repo}"), + &risk_files, + ) + .await, + ); let lead = if requests.is_empty() { "This pull request got more commits after its description was written. Rewrite the description so every statement in it is true of the diff below, which is the whole change as it stands now." } else { @@ -1513,12 +1543,16 @@ pub async fn refresh_description( - Keep any line that starts with "Source ticket:", "Closes #", "Fixes #" or "Resolves #" exactly as it is, and keep any HTML comments and `` lines at the end exactly as they are. - Remove or correct anything the diff no longer bears out (a field name, a guess, a step, a file), and describe what the later commits changed. - Keep the Evidence list (what was looked up and what came back), unless the diff no longer relies on what it describes. +- Rewrite Changes from this diff, one entry per changed file or area: a statement about an earlier version ("schema only", "not registered or rendered yet", "follow-up PR") that the diff no longer bears out goes, it is never kept beside the new one. +- Risk follows from this diff: a change to a file every page or request goes through (a shared query or fragment, a layout, middleware, global config) or a new network call per page render is never Low; say the level in bold and why. +- Verification names only commands whose results this description's own sections show for the current commit, with their counts; a result of an earlier commit (a suite that failed then, an old count) goes.{risk_note} {shape_rules} - Don't add filler. If the description is already true and nothing was asked, return it unchanged. Return ONLY the markdown body text, then a line `{CHANGES_MARK}` and one bullet per change you made to the description, in a few words each."#, requests = request_block(requests), files = format_diff_summary(&diff), + risk_note = super::pr_risk::writer_note(&risk_floor), shape_rules = SHAPE_RULES, ); let mut messages = vec![( @@ -1572,6 +1606,8 @@ Return ONLY the markdown body text, then a line `{CHANGES_MARK}` and one bullet ) .await; let written = split_changes(&written).0; + // The Risk it states is at least what the diff now makes it. + let written = super::pr_risk::enforce(&written, &risk_floor); if !keeps_ticket_line(&old, &written) { warn!( pr_number, diff --git a/services/worker/src/passes/pr_risk.rs b/services/worker/src/passes/pr_risk.rs new file mode 100644 index 000000000..27d06e231 --- /dev/null +++ b/services/worker/src/passes/pr_risk.rs @@ -0,0 +1,617 @@ +//! The Risk a pull request description states follows from its diff. +//! +//! A description called a change "Low" risk while it edited a query fragment +//! every page imports and added a network call to each page render. The +//! writer judged it from the plan, and nothing checked the level against +//! the change. +//! +//! The rules here: +//! +//! - [`floor`] reads the diff: a file every page or route goes through (a +//! shared query or fragment, a layout, middleware, global config, or a +//! file the code graph says many files import) and a network call added +//! where pages render each raise the lowest level the description may +//! state. Both together, or a change the reviewer's rubric forces HIGH +//! (a migration, auth, payments), make it High. Each reason names the +//! file. +//! - [`enforce`] reads the level the description states and, when it is +//! lower than the floor (or no Risk section says one), rewrites the Risk +//! section's level and puts the reasons first. It never lowers a level +//! the writer chose. + +use std::collections::HashMap; + +/// A risk level, lowest first. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Level { + Low, + Medium, + High, +} + +impl Level { + pub fn word(self) -> &'static str { + match self { + Level::Low => "Low", + Level::Medium => "Medium", + Level::High => "High", + } + } + + fn parse(word: &str) -> Option { + match word.to_ascii_lowercase().as_str() { + "low" => Some(Level::Low), + "medium" | "moderate" => Some(Level::Medium), + "high" | "critical" => Some(Level::High), + _ => None, + } + } +} + +/// The lowest level the diff allows, and why. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Floor { + pub level: Level, + pub reasons: Vec, +} + +/// Importers from the code graph at which a file counts as shared. +pub const SHARED_IMPORTERS: usize = 8; + +/// File names (without extension) every page or request goes through. +const SHARED_STEMS: &[&str] = &[ + "layout", + "_app", + "_document", + "root", + "middleware", + "global", + "globals", + "app.config", + "next.config", + "nuxt.config", + "vite.config", + "astro.config", + "svelte.config", + "remix.config", +]; + +/// Folder names whose files many pages import. +const SHARED_DIRS: &[&str] = &["shared", "common", "fragments", "fragment"]; + +fn stem(path: &str) -> String { + let base = path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase(); + match base.rsplit_once('.') { + Some((s, ext)) if !s.is_empty() && ext.len() <= 5 => s.to_string(), + _ => base, + } +} + +fn is_test(path: &str) -> bool { + let l = path.to_ascii_lowercase(); + l.contains(".test.") + || l.contains(".spec.") + || l.contains("__tests__") + || l.contains("/test/") + || l.contains("/tests/") + || l.contains("/e2e/") + || l.starts_with("e2e/") + || l.starts_with("test/") + || l.starts_with("tests/") +} + +fn is_code(path: &str) -> bool { + let l = path.to_ascii_lowercase(); + [ + ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".vue", ".svelte", ".astro", ".py", ".rb", + ".go", ".rs", ".php", ".groq", ".graphql", ".gql", + ] + .iter() + .any(|e| l.ends_with(e)) +} + +/// Why a file is one every page or request goes through, if it is. +pub fn shared_reason(path: &str, importers: usize) -> Option { + if is_test(path) { + return None; + } + if importers >= SHARED_IMPORTERS { + return Some(format!("`{path}` is imported by {importers} files")); + } + let s = stem(path); + if SHARED_STEMS.contains(&s.as_str()) { + return Some(format!("`{path}` wraps every page or request")); + } + if !is_code(path) { + return None; + } + let lower = path.to_ascii_lowercase(); + let dirs: Vec<&str> = lower.split('/').collect(); + let in_shared_dir = dirs[..dirs.len().saturating_sub(1)] + .iter() + .any(|d| SHARED_DIRS.contains(d)); + let shared_query = (s.contains("fragment") || s.contains("query") || s.contains("queries")) + && (s.contains("shared") + || s.contains("common") + || s.contains("base") + || s.contains("global") + || s.contains("page") + || s.contains("fragment")); + if in_shared_dir || shared_query { + return Some(format!("`{path}` is a shared module pages import")); + } + None +} + +/// Whether a file renders pages or handles requests (where a call added runs +/// once per page view or request). +fn renders(path: &str) -> bool { + let l = path.to_ascii_lowercase(); + let s = stem(path); + l.ends_with(".tsx") + || l.ends_with(".jsx") + || l.ends_with(".vue") + || l.ends_with(".svelte") + || l.ends_with(".astro") + || l.contains("/pages/") + || l.starts_with("pages/") + || l.contains("/app/") + || l.starts_with("app/") + || l.contains("/routes/") + || l.starts_with("routes/") + || matches!( + s.as_str(), + "page" | "layout" | "route" | "loader" | "server" + ) +} + +/// Calls that go over the network. +const NETWORK_CALLS: &[&str] = &[ + "fetch(", + "axios(", + "axios.", + "got(", + "ky(", + "ky.", + "superagent", + "http.get(", + "https.get(", + "http.request(", + "requests.get(", + "requests.post(", + "httpx.", + "urlopen(", + "graphqlrequest(", + "apollo", + "usequery(", +]; + +/// The network call a patch's added lines make, if any. +pub fn added_network_call(patch: &str) -> Option { + patch + .lines() + .filter(|l| l.starts_with('+') && !l.starts_with("+++")) + .map(|l| l[1..].trim()) + .filter(|l| !l.starts_with("//") && !l.starts_with('*') && !l.starts_with('#')) + .find(|l| { + let low = l.to_ascii_lowercase(); + NETWORK_CALLS.iter().any(|c| low.contains(c)) + }) + .map(|l| common::truncate_str(l, 80).to_string()) +} + +/// The lowest level the diff (path, status, patch) allows. `importers`: how +/// many files import each changed file, from the code graph (missing when +/// the graph can't say). +pub fn floor(files: &[(String, String, String)], importers: &HashMap) -> Floor { + let mut shared: Vec = Vec::new(); + let mut calls: Vec = Vec::new(); + for (path, status, patch) in files { + if status == "removed" || is_test(path) { + continue; + } + let shared_why = shared_reason(path, importers.get(path).copied().unwrap_or(0)); + if let Some(why) = &shared_why { + shared.push(why.clone()); + } + if shared_why.is_some() || renders(path) { + if let Some(call) = added_network_call(patch) { + calls.push(format!( + "`{path}` adds a network call where pages render (`{call}`), once per page \ + view or request" + )); + } + } + } + let (_, _, hard) = super::review_risk::classify_sensitive(files); + let mut reasons: Vec = Vec::new(); + if let Some(h) = &hard { + reasons.push(h.clone()); + } + reasons.extend(shared.iter().take(3).cloned()); + reasons.extend(calls.iter().take(3).cloned()); + let level = if hard.is_some() || (!shared.is_empty() && !calls.is_empty()) { + Level::High + } else if !shared.is_empty() || !calls.is_empty() { + Level::Medium + } else { + Level::Low + }; + Floor { level, reasons } +} + +/// A compare response's files as (path, status, patch). +pub fn diff_files(diff: &serde_json::Value) -> Vec<(String, String, String)> { + diff["files"] + .as_array() + .into_iter() + .flatten() + .map(|f| { + ( + f["filename"].as_str().unwrap_or("").to_string(), + f["status"].as_str().unwrap_or("").to_string(), + f["patch"].as_str().unwrap_or("").to_string(), + ) + }) + .filter(|(p, _, _)| !p.is_empty()) + .collect() +} + +/// How many files import each changed file, from the repository's code +/// graph when it is built (empty otherwise). At most 20 files are looked up. +pub async fn importers( + state: &crate::WorkerState, + team_id: &str, + installation_id: u64, + repo: &str, + files: &[(String, String, String)], +) -> HashMap { + let mut out = HashMap::new(); + let super::code_graph::Avail::Ready(graph) = + super::code_graph::availability(state, team_id, repo, installation_id).await + else { + return out; + }; + for (path, status, _) in files.iter().filter(|(_, s, _)| s != "added").take(20) { + if status == "removed" { + continue; + } + let n = graph.importers(state, path).await.len(); + if n > 0 { + out.insert(path.clone(), n); + } + } + out +} + +/// What the writer is told about the floor. Empty when the diff allows Low. +pub fn writer_note(f: &Floor) -> String { + if f.level == Level::Low { + return String::new(); + } + format!( + "\n\n## Risk (computed from the diff)\nThe Risk level is at least **{}**, because: {}. \ + State that level (or higher) and these reasons; never call this change Low.", + f.level.word(), + f.reasons.join("; ") + ) +} + +fn is_risk_heading(line: &str) -> bool { + let t = line.trim(); + let marked = + t.starts_with('#') || t.starts_with("**") || t.starts_with(|c: char| c.is_ascii_digit()); + if !marked { + return false; + } + let t = t.trim_start_matches('#').trim_start(); + let t = t.trim_start_matches(|c: char| c.is_ascii_digit() || c == '.' || c == ')'); + let t = t.trim_start().trim_start_matches("**").trim_start(); + let low = t.to_ascii_lowercase(); + low.starts_with("risk") && !low[4..].chars().next().is_some_and(|c| c.is_alphanumeric()) +} + +fn is_heading(line: &str) -> bool { + let t = line.trim(); + if t.starts_with('#') || t.starts_with(""; pub const END: &str = ""; @@ -60,10 +63,15 @@ fn rounds_in(section: &str) -> Vec { out } -/// The section with `round` added first and older rounds after it. +/// The section with `round` added first and older rounds after it, each +/// older one cut to its headline line. pub fn section(existing: &str, round: &Round) -> String { let mut rounds = vec![round.render()]; - rounds.extend(rounds_in(existing)); + rounds.extend( + rounds_in(existing) + .into_iter() + .map(|r| format!("{}\n", r.lines().next().unwrap_or("").trim_end())), + ); rounds.truncate(MAX_ROUNDS); format!("{START}\n{HEADING}\n{}{END}", rounds.concat()) } @@ -103,6 +111,21 @@ mod tests { assert!(!s.contains("abc2")); } + #[test] + fn an_older_rounds_results_go_when_a_newer_round_lands() { + let failed = Round { + date: "2026-10-26".into(), + commit: "aaa1111".into(), + headline: "Register the block".into(), + lines: vec!["Full test suite FAILED (exit 127): `npm test` (0 passed)".into()], + }; + let s = section("", &failed); + let s = section(&s, &round(2)); + assert!(s.contains("* 2026-10-26, commit `aaa1111`: Register the block\n")); + assert!(!s.contains("FAILED"), "{s}"); + assert!(s.contains("Full test suite passed")); + } + #[test] fn a_held_round_says_it_was_not_pushed() { let r = Round { diff --git a/services/worker/src/passes/review_fix/mod.rs b/services/worker/src/passes/review_fix/mod.rs index e55f573fd..955a7cdc9 100644 --- a/services/worker/src/passes/review_fix/mod.rs +++ b/services/worker/src/passes/review_fix/mod.rs @@ -12,7 +12,13 @@ //! code matches (metric filters, alarms, alert rules, scripts, runbooks, //! tests) keeps its wording; a changed log level or message needs a test //! that asserts it. -//! 3. The full test suite ([`suite`]), found the way the repository runs it +//! 3. Generated files ([`generated_step`]): a round that edits what a code +//! generator reads (a CMS schema, a GraphQL schema) carries the +//! regenerated output, the new types are in it, and no file declares its +//! own copy of a generated type: the same check the pull request had +//! before it opened (`super::generators`), so a later round can't skip +//! it. +//! 4. The full test suite ([`suite`]), found the way the repository runs it //! and run in the sandbox against the staged files. //! //! What a check finds goes back to the agent for one fix-up turn, then the @@ -311,6 +317,9 @@ pub async fn check( // 2. Logs. logs_step(round, staged, usage, last, &mut out).await; + // 3. Generated files. + generated_step(round, staged, last, &mut out).await; + // 3. The full suite: on the first check only when nothing else goes back // to the agent (the fix-up turn changes the files anyway), always on // the last. @@ -340,6 +349,124 @@ pub async fn check( out } +/// A staged change as (path, status, patch), the patch holding the lines +/// the file gains (enough for the generator checks, which read added lines). +pub fn staged_patch(path: &str, c: &staged::Change) -> (String, String, String) { + let status = match (&c.original, &c.current) { + (None, _) => "added", + (_, None) => "removed", + _ => "modified", + }; + let before: std::collections::HashSet<&str> = c + .original + .as_deref() + .map(|t| t.lines().collect()) + .unwrap_or_default(); + let patch: String = c + .current + .as_deref() + .unwrap_or("") + .lines() + .filter(|l| !before.contains(l)) + .map(|l| format!("+{l}\n")) + .collect(); + (path.to_string(), status.to_string(), format!("@@\n{patch}")) +} + +/// What the generator checks find in a round's staged files: for each +/// generator whose inputs the round edits, its outputs not regenerated, a +/// new type missing from them, or a hand-written copy of a generated type. +pub fn generated_problems( + gens: &[super::generators::Generator], + files: &[(String, String, String)], + outputs_of: impl Fn(&super::generators::Generator) -> Vec<(String, String)>, +) -> Vec { + let paths: Vec = files.iter().map(|(p, _, _)| p.clone()).collect(); + let mut out = Vec::new(); + for (g, inputs) in super::generators::affected(gens, &paths) { + let mut why: Vec = Vec::new(); + let outputs = outputs_of(g); + let owned = super::generators::ownership_problems(g, files, &outputs); + if super::generators::outputs_missing(g, &paths) + && !super::generators::owned_types(g, files).is_empty() + { + why.push(format!( + "its generated files ({}) are not in this round.", + g.outputs + .iter() + .take(3) + .map(|o| format!("`{o}`")) + .collect::>() + .join(", ") + )); + } + why.extend(owned); + if !why.is_empty() { + out.push(super::generators::block_reason(g, &inputs, &why.join(" "))); + } + } + out +} + +async fn generated_step(round: &Round<'_>, staged: &Staged, last: bool, out: &mut Check) { + let files: Vec<(String, String, String)> = staged + .changes() + .iter() + .map(|(p, c)| staged_patch(p, c)) + .collect(); + if files.is_empty() { + return; + } + let repo = super::generators::load(round.github, round.owner, round.repo, round.branch).await; + let gens = super::generators::detect(&repo); + if gens.is_empty() { + return; + } + // Each generator's output as the round leaves it: staged, else the + // branch. + let mut texts: Vec<(String, String)> = Vec::new(); + for g in &gens { + for p in repo + .tree + .iter() + .filter(|p| { + g.outputs + .iter() + .any(|o| super::generators::glob_match(o, p)) + }) + .take(3) + { + if !texts.iter().any(|(q, _)| q == p) { + texts.push((p.clone(), round.text(staged, p).await)); + } + } + } + let problems = generated_problems(&gens, &files, |g| { + texts + .iter() + .filter(|(p, _)| { + g.outputs + .iter() + .any(|o| super::generators::glob_match(o, p)) + }) + .cloned() + .collect() + }); + if problems.is_empty() { + return; + } + if last { + out.hold.extend(problems); + } else { + out.findings.push(format!( + "{} Regenerate the generated output (with run_codegen when it is offered, else \ + exactly what the generator writes) in this round, and type new things from the \ + generated types, never with a hand-written copy.", + problems.join(" ") + )); + } +} + async fn scope_step( round: &Round<'_>, staged: &Staged, @@ -1192,6 +1319,60 @@ pub async fn mark_reapproval(state: &WorkerState, team_id: &str, run_id: &str, w mod tests { use super::*; + /// A later round on an open PR adds a CMS block and types it by hand: + /// the round is held until the output is regenerated and imported. + #[test] + fn a_later_round_that_edits_a_schema_needs_the_generated_types() { + use super::super::generators::{GenKind, Generator}; + let gens = vec![Generator { + kind: GenKind::Sanity, + name: "npm run typegen".into(), + command: "npm run typegen".into(), + inputs: vec!["**/schemaTypes/**".into()], + outputs: vec!["src/sanity.types.ts".into()], + }]; + let schema = staged::Change { + original: None, + current: Some( + "export default defineType({\n name: 'gallery',\n type: 'object',\n})\n".into(), + ), + }; + let component = staged::Change { + original: Some("export function Page() {}\n".into()), + current: Some( + "export function Page() {}\ntype GalleryBlock = { title: string }\n".into(), + ), + }; + let files = vec![ + staged_patch("studio/schemaTypes/gallery.ts", &schema), + staged_patch("src/components/Page.tsx", &component), + ]; + assert_eq!(files[0].1, "added"); + assert_eq!(files[1].2, "@@\n+type GalleryBlock = { title: string }\n"); + let p = generated_problems(&gens, &files, |_| { + vec![("src/sanity.types.ts".into(), "export type Hero = {}".into())] + }); + assert_eq!(p.len(), 1, "{p:?}"); + assert!(p[0].contains("are not in this round")); + assert!(p[0].contains("has no `Gallery`")); + assert!(p[0].contains("declares `GalleryBlock` by hand")); + // Regenerated in the round and used from there: nothing. + let mut ok = files.clone(); + ok[1].2 = "@@\n+import type { Gallery } from '../sanity.types'\n".into(); + ok.push(( + "src/sanity.types.ts".into(), + "modified".into(), + "@@\n+export type Gallery = {}\n".into(), + )); + let p = generated_problems(&gens, &ok, |_| { + vec![( + "src/sanity.types.ts".into(), + "export type Gallery = {}".into(), + )] + }); + assert!(p.is_empty(), "{p:?}"); + } + #[test] fn only_files_the_checks_changed_are_written_back_to_the_wip_branch() { let s = Staged::new(); diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 5dd717351..8c7ef20ec 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -2362,12 +2362,18 @@ async fn run_once( return Err(e); } posted_event = Some(event); - // Resolve the earlier threads this head fixed (after the review is up, so - // the "N fixed" note is visible when they collapse). - for t in &fixed_threads { - if let Err(e) = github.resolve_review_thread(&t.id).await { - warn!(pr = msg.pr_number, thread = %t.id, error = %e, "Failed to resolve fixed thread"); - } + } else if !already_answered && !head_sha.is_empty() { + // Nothing new to post for this commit (same verdict, CoderHelm's own + // push): the earlier review must not keep standing with what it + // said about the older commit. Its body becomes this review. + super::review_verdict::refresh_standing(&github, &msg, &head_sha, &full_body).await; + } + // Resolve the earlier threads this head fixed, posted or not (after the + // review is up when there is one, so the "N fixed" note is visible when + // they collapse): a thread the new commits settled never stays open. + for t in &fixed_threads { + if let Err(e) = github.resolve_review_thread(&t.id).await { + warn!(pr = msg.pr_number, thread = %t.id, error = %e, "Failed to resolve fixed thread"); } } diff --git a/services/worker/src/passes/review_verdict.rs b/services/worker/src/passes/review_verdict.rs index abaea069b..961b1cb39 100644 --- a/services/worker/src/passes/review_verdict.rs +++ b/services/worker/src/passes/review_verdict.rs @@ -249,6 +249,87 @@ async fn dismiss_stale_change_requests(github: &GitHubClient, msg: &ReviewMessag } } +/// Marks a review body that was brought up to date for a newer commit. +pub const UPDATED_MARK: &str = ""; + +/// CoderHelm's newest own review with a body: its id and the commit it was +/// of. +pub(crate) fn own_latest_review(reviews: &serde_json::Value) -> Option<(u64, String)> { + reviews + .as_array()? + .iter() + .filter(|r| { + r["user"]["type"].as_str() == Some("Bot") + && r["user"]["login"] + .as_str() + .is_some_and(|l| l.contains("coderhelm")) + && !r["body"].as_str().unwrap_or("").trim().is_empty() + }) + .filter_map(|r| { + Some(( + r["id"].as_u64()?, + r["commit_id"].as_str().unwrap_or("").to_string(), + )) + }) + .next_back() +} + +/// The standing review's body brought up to date: this review of `head`, +/// headed by a line saying it replaces what was written for `old_head`. +pub fn updated_body(body: &str, old_head: &str, head: &str) -> String { + let short = |s: &str| s[..s.len().min(7)].to_string(); + format!( + "{UPDATED_MARK}\n_Updated for `{}`: what this review said about `{}` was replaced by \ + the review of the current commit below._\n\n{}", + short(head), + short(old_head), + body.trim() + ) +} + +/// When a finished review of a newer commit posts nothing (same verdict, +/// nothing new to say), CoderHelm's own earlier review still stands on the +/// PR with what it said about the older commit. Its body is replaced with +/// this review, so no comment of CoderHelm's keeps claims the new commits +/// made wrong. Best effort. +pub async fn refresh_standing(github: &GitHubClient, msg: &ReviewMessage, head: &str, body: &str) { + let reviews = match github + .list_pr_reviews(&msg.repo_owner, &msg.repo_name, msg.pr_number) + .await + { + Ok(v) => v, + Err(e) => { + warn!(pr = msg.pr_number, error = %e, "Could not list reviews to bring the standing one up to date"); + return; + } + }; + let Some((id, old_head)) = own_latest_review(&reviews) else { + return; + }; + if old_head == head || body.trim().is_empty() { + return; + } + match github + .update_pr_review( + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + id, + &updated_body(body, &old_head, head), + ) + .await + { + Ok(()) => info!( + pr = msg.pr_number, + review_id = id, + "Brought CoderHelm's standing review up to date for the new commit" + ), + Err(e) => { + warn!(pr = msg.pr_number, review_id = id, error = %e, "Could not update the standing review") + } + } +} + /// Ids of CoderHelm's own reviews still in the "changes requested" state. pub(crate) fn own_change_requests(reviews: &serde_json::Value) -> Vec { reviews @@ -502,6 +583,25 @@ mod tests { /// Nothing but this module posts or dismisses a formal review: every /// other source file in the worker is scanned for the GitHub review /// calls. + #[test] + fn a_silent_review_of_a_new_commit_replaces_the_old_reviews_claims() { + let reviews = serde_json::json!([ + {"id": 1, "commit_id": "aaaaaaa1", "body": "Schema only, not registered.", "user": {"type": "Bot", "login": "coderhelm[bot]"}}, + {"id": 2, "commit_id": "aaaaaaa1", "body": "Looks good", "user": {"type": "User", "login": "sam"}}, + {"id": 3, "commit_id": "bbbbbbb2", "body": "", "user": {"type": "Bot", "login": "coderhelm[bot]"}} + ]); + assert_eq!( + own_latest_review(&reviews), + Some((1, "aaaaaaa1".to_string())) + ); + let b = updated_body("Registers and renders the block.", "aaaaaaa1", "ccccccc3"); + assert!(b.starts_with(UPDATED_MARK)); + assert!(b.contains("Updated for `ccccccc`")); + assert!(b.contains("about `aaaaaaa`")); + assert!(b.ends_with("Registers and renders the block.")); + assert!(!b.contains("Schema only")); + } + #[test] fn no_other_module_posts_a_formal_review() { let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); @@ -531,6 +631,7 @@ mod tests { ".create_pr_review(", ".create_pr_review_inline(", ".dismiss_review(", + ".update_pr_review(", ] { if text.contains(call) { offenders.push(format!("{rel}: {call}"));