From ac193c5877b3b7c2388f5089c4a7a8a1531f4baf Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 27 Oct 2026 15:35:56 -0400 Subject: [PATCH] New-feature tickets: create/modify task tags, earlier attempts, reuse, registrations, staging content, checklist and open questions --- services/common/src/lib.rs | 3 + services/common/src/staging_cms.rs | 329 +++++ services/gateway/src/main.rs | 6 + services/gateway/src/permissions.rs | 4 + services/gateway/src/routes/mod.rs | 1 + services/gateway/src/routes/staging_cms.rs | 194 +++ services/worker/src/clients/github.rs | 44 + services/worker/src/main.rs | 14 + .../worker/src/passes/feature/checklist.rs | 522 ++++++++ services/worker/src/passes/feature/content.rs | 560 ++++++++ services/worker/src/passes/feature/mod.rs | 1173 +++++++++++++++++ .../worker/src/passes/feature/plan_files.rs | 346 +++++ services/worker/src/passes/feature/prior.rs | 790 +++++++++++ .../worker/src/passes/feature/questions.rs | 94 ++ .../worker/src/passes/feature/registration.rs | 510 +++++++ services/worker/src/passes/feature/reuse.rs | 488 +++++++ services/worker/src/passes/mod.rs | 180 ++- services/worker/src/passes/plan.rs | 23 +- services/worker/src/passes/pr.rs | 16 + services/worker/src/passes/resume.rs | 7 + services/worker/src/passes/review_eval.rs | 1 + services/worker/src/passes/ticket_history.rs | 8 +- 22 files changed, 5251 insertions(+), 62 deletions(-) create mode 100644 services/common/src/staging_cms.rs create mode 100644 services/gateway/src/routes/staging_cms.rs create mode 100644 services/worker/src/passes/feature/checklist.rs create mode 100644 services/worker/src/passes/feature/content.rs create mode 100644 services/worker/src/passes/feature/mod.rs create mode 100644 services/worker/src/passes/feature/plan_files.rs create mode 100644 services/worker/src/passes/feature/prior.rs create mode 100644 services/worker/src/passes/feature/questions.rs create mode 100644 services/worker/src/passes/feature/registration.rs create mode 100644 services/worker/src/passes/feature/reuse.rs diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 6478cf18b..4f93c9dd9 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -64,6 +64,9 @@ pub mod merge_gate; pub mod messages; /// Retrying model API calls on transient failures, classified by status. pub mod model_retry; +/// A repository's staging-only CMS write connection (for content the +/// end-to-end tests read). +pub mod staging_cms; // Anthropic SSE calls, metered per attempt (drops, retries, the deadline) pub mod model_stream; // Titan embeddings, metered as CoderHelm's own cost diff --git a/services/common/src/staging_cms.rs b/services/common/src/staging_cms.rs new file mode 100644 index 000000000..56e4215a5 --- /dev/null +++ b/services/common/src/staging_cms.rs @@ -0,0 +1,329 @@ +//! A repository's staging CMS write connection: optional, per repository, +//! staging only. +//! +//! When a feature changes a CMS schema and the repository's end-to-end tests +//! run against pages the CMS serves, the staging content the tests read can +//! go out of date. With this connection CoderHelm updates that content +//! itself, never production; without it the run stops before the pull +//! request and says exactly which content must change. +//! +//! The rules, enforced here and covered by the tests below: +//! - one provider today: Sanity (a project id and a dataset); +//! - the dataset must not look like production (`production`, `prod`, +//! `live`, `master`, `main`, `prd` as a word) and must differ from the +//! production dataset the team names; [`StagingCms::check_writable`] runs +//! again before every write, so a record edited by hand can't reach +//! production; +//! - the token is sealed by KMS bound to the team, the repository and this +//! purpose, and never returned by the API. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use serde::{Deserialize, Serialize}; + +/// The settings-table sort key for a repository's connection. +pub fn sk(repo: &str) -> String { + format!("STAGING_CMS#REPO#{repo}") +} + +/// Where the sealed token is kept on the record. +pub const TOKEN_ATTR: &str = "token_sealed"; +const PURPOSE: &str = "staging-cms-write"; +/// The Sanity HTTP API version CoderHelm calls. +pub const SANITY_API_VERSION: &str = "2021-06-07"; +/// Providers CoderHelm can write to. +pub const PROVIDERS: &[&str] = &["sanity"]; + +/// Words that mark a production dataset. +const PRODUCTION_WORDS: &[&str] = &["production", "prod", "prd", "live", "master", "main"]; + +/// Whether a dataset name looks like production. +pub fn is_production_name(name: &str) -> bool { + name.to_ascii_lowercase() + .split(|c: char| !c.is_ascii_alphanumeric()) + .any(|w| PRODUCTION_WORDS.contains(&w)) +} + +/// A repository's staging CMS connection, without its token. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct StagingCms { + /// `owner/name`. + pub repo: String, + /// `sanity`. + pub provider: String, + pub project_id: String, + /// The staging dataset CoderHelm writes to. + pub dataset: String, + /// The production dataset, named so it is refused. Optional. + #[serde(default)] + pub production_dataset: String, +} + +fn valid_id(s: &str, max: usize, extra: &[char]) -> bool { + !s.is_empty() + && s.len() <= max + && s.chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || extra.contains(&c)) +} + +impl StagingCms { + /// Checks a connection as a team entered it. The error is one sentence a + /// person can act on. + pub fn validate(&self) -> Result<(), String> { + if !self.repo.contains('/') || self.repo.len() > 200 { + return Err("Pick the repository this connection is for.".into()); + } + if !PROVIDERS.contains(&self.provider.as_str()) { + return Err("CoderHelm can write to Sanity staging datasets; pick Sanity.".into()); + } + if !valid_id(&self.project_id, 32, &[]) { + return Err("Enter the Sanity project id (lowercase letters and digits).".into()); + } + if !valid_id(&self.dataset, 64, &['-', '_']) { + return Err( + "Enter the staging dataset name (lowercase letters, digits, - and _).".into(), + ); + } + if !self.production_dataset.is_empty() + && !valid_id(&self.production_dataset, 64, &['-', '_']) + { + return Err("The production dataset name isn't valid.".into()); + } + self.check_writable() + } + + /// Whether CoderHelm may write here: never a dataset that looks like + /// production or is the one named as production. + pub fn check_writable(&self) -> Result<(), String> { + if is_production_name(&self.dataset) { + return Err(format!( + "`{}` looks like a production dataset. CoderHelm writes only to staging; enter the staging dataset.", + self.dataset + )); + } + if !self.production_dataset.is_empty() && self.production_dataset == self.dataset { + return Err( + "The staging dataset is the same as the production dataset. CoderHelm writes only to staging." + .into(), + ); + } + Ok(()) + } + + /// Refuses a dataset the repository's own production settings name + /// (for example `SANITY_DATASET=...` in `.env.production`). + pub fn check_against_code(&self, production_in_code: &[String]) -> Result<(), String> { + if production_in_code.iter().any(|d| d == &self.dataset) { + return Err(format!( + "The repository's production settings use the dataset `{}`. CoderHelm writes only to staging.", + self.dataset + )); + } + Ok(()) + } + + fn base(&self) -> String { + format!( + "https://{}.api.sanity.io/v{SANITY_API_VERSION}/data", + self.project_id + ) + } + + /// The query endpoint; the query goes in the `query` parameter. + pub fn query_url(&self) -> String { + format!("{}/query/{}", self.base(), self.dataset) + } + + /// The mutate endpoint. + pub fn mutate_url(&self) -> String { + format!("{}/mutate/{}", self.base(), self.dataset) + } + + /// The record, without the token. + pub fn item(&self, team_id: &str) -> HashMap { + let s = |v: &str| AttributeValue::S(v.to_string()); + HashMap::from([ + ("pk".to_string(), s(team_id)), + ("sk".to_string(), s(&sk(&self.repo))), + ("repo".to_string(), s(&self.repo)), + ("provider".to_string(), s(&self.provider)), + ("project_id".to_string(), s(&self.project_id)), + ("dataset".to_string(), s(&self.dataset)), + ( + "production_dataset".to_string(), + s(&self.production_dataset), + ), + ]) + } + + /// Reads a record. `None` when it isn't one. + pub fn from_item(item: &HashMap) -> Option { + let s = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let c = StagingCms { + repo: s("repo"), + provider: s("provider"), + project_id: s("project_id"), + dataset: s("dataset"), + production_dataset: s("production_dataset"), + }; + (!c.repo.is_empty() && !c.dataset.is_empty()).then_some(c) + } + + /// The API's view: never the token, only whether one is set. + pub fn view(&self, token_set: bool) -> serde_json::Value { + serde_json::json!({ + "configured": true, + "repo": self.repo, + "provider": self.provider, + "project_id": self.project_id, + "dataset": self.dataset, + "production_dataset": self.production_dataset, + "token_set": token_set, + }) + } +} + +/// Datasets a repository's production settings name: `*DATASET=value` lines +/// in production env files, given as (path, text). +pub fn production_datasets_in_code(files: &[(String, String)]) -> Vec { + let mut out = Vec::new(); + for (path, text) in files { + let name = path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase(); + if !(name.starts_with(".env") && name.contains("prod")) { + continue; + } + for line in text.lines() { + let Some((k, v)) = line.split_once('=') else { + continue; + }; + if k.trim().to_ascii_uppercase().ends_with("DATASET") { + let v = v.trim().trim_matches(|c| c == '"' || c == '\'').to_string(); + if !v.is_empty() && !out.contains(&v) { + out.push(v); + } + } + } + } + out +} + +/// The encryption context: the team, the repository and the purpose. +pub fn context(team_id: &str, repo: &str) -> HashMap { + HashMap::from([ + ("team".to_string(), team_id.to_string()), + ("repo".to_string(), repo.to_string()), + ("purpose".to_string(), PURPOSE.to_string()), + ]) +} + +/// Seals a token for one team's repository. Returns text safe to store. +pub async fn seal( + cipher: &dyn crate::mcp_credentials::Cipher, + team_id: &str, + repo: &str, + token: &str, +) -> Result { + use base64::Engine; + let blob = cipher + .encrypt(context(team_id, repo), token.as_bytes()) + .await?; + Ok(base64::engine::general_purpose::STANDARD.encode(blob)) +} + +/// Opens a token sealed for one team's repository. +pub async fn open( + cipher: &dyn crate::mcp_credentials::Cipher, + team_id: &str, + repo: &str, + sealed: &str, +) -> Result { + use base64::Engine; + let bytes = base64::engine::general_purpose::STANDARD + .decode(sealed) + .map_err(|_| "stored token is not valid".to_string())?; + let plain = cipher.decrypt(context(team_id, repo), &bytes).await?; + String::from_utf8(plain).map_err(|_| "stored token is not text".to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn conn(dataset: &str) -> StagingCms { + StagingCms { + repo: "acme/web".into(), + provider: "sanity".into(), + project_id: "abc123".into(), + dataset: dataset.into(), + production_dataset: "public".into(), + } + } + + #[test] + fn a_staging_dataset_is_accepted() { + assert!(conn("staging").validate().is_ok()); + assert!(conn("qa-2").validate().is_ok()); + assert_eq!( + conn("staging").mutate_url(), + "https://abc123.api.sanity.io/v2021-06-07/data/mutate/staging" + ); + } + + #[test] + fn production_is_never_writable() { + for d in ["production", "prod", "site-prod", "live", "main", "prd_eu"] { + let err = conn(d).validate().unwrap_err(); + assert!(err.contains("only to staging"), "{d}: {err}"); + } + // The dataset the team names as production, whatever its name. + assert!(conn("public").validate().is_err()); + // Words that only contain a production word are fine. + assert!(!is_production_name("products-staging")); + assert!(!is_production_name("maintenance")); + } + + #[test] + fn the_repositorys_production_settings_are_refused_too() { + let files = vec![ + ( + ".env.production".to_string(), + "NEXT_PUBLIC_SANITY_DATASET=\"stage-copy\"\nOTHER=1".to_string(), + ), + (".env.local".to_string(), "SANITY_DATASET=dev".to_string()), + ]; + let prod = production_datasets_in_code(&files); + assert_eq!(prod, vec!["stage-copy"]); + assert!(conn("stage-copy").check_against_code(&prod).is_err()); + assert!(conn("staging").check_against_code(&prod).is_ok()); + } + + #[test] + fn bad_input_reads_as_a_sentence() { + let mut c = conn("staging"); + c.provider = "other".into(); + assert!(c.validate().unwrap_err().contains("Sanity")); + let mut c = conn("staging"); + c.project_id = "Bad Id".into(); + assert!(c.validate().is_err()); + let mut c = conn("Staging Data"); + c.production_dataset.clear(); + assert!(c.validate().is_err()); + } + + #[test] + fn the_record_round_trips_without_a_token() { + let c = conn("staging"); + let item = c.item("team1"); + assert_eq!(StagingCms::from_item(&item), Some(c.clone())); + assert!(!item.contains_key(TOKEN_ATTR)); + let v = c.view(true); + assert_eq!(v["token_set"], true); + assert!(v.get("token").is_none()); + } +} diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index bc6e3888e..1c993e93f 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -368,6 +368,12 @@ async fn main() -> Result<(), Error> { .route("/runs/:run_id/reopen", post(routes::run_close::reopen_run)) .route("/runs/close", post(routes::run_close::close_runs)) .route("/repos", get(routes::api::list_repos)) + .route( + "/repos/:owner/:name/staging-cms", + get(routes::staging_cms::get) + .put(routes::staging_cms::put) + .delete(routes::staging_cms::delete), + ) .route("/repos/sync", post(routes::api::sync_repos)) .route( "/repos/:owner/:name", diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 0324c1301..3e0760979 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -390,6 +390,10 @@ pub const CAPABILITIES: &[Capability] = &[ "graph::rebuild", "infrastructure::refresh_infrastructure", "infrastructure::refresh_repo_infrastructure", + // The staging-only CMS write connection (see routes::staging_cms). + "staging_cms::get", + "staging_cms::put", + "staging_cms::delete", ], }, Capability { diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index abaf9ac90..7df04b635 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -58,6 +58,7 @@ pub mod setup_checks; pub mod sign_in; pub mod skills; pub mod sns; +pub mod staging_cms; pub mod support; pub mod support_access; pub mod system; diff --git a/services/gateway/src/routes/staging_cms.rs b/services/gateway/src/routes/staging_cms.rs new file mode 100644 index 000000000..7e7177b5c --- /dev/null +++ b/services/gateway/src/routes/staging_cms.rs @@ -0,0 +1,194 @@ +//! A repository's staging CMS write connection (Settings, Repositories): +//! optional, staging only. When a feature's schema change makes the content +//! its end-to-end tests read out of date, CoderHelm updates that content on +//! staging through this connection; without one the run says exactly which +//! content must change. See `common::staging_cms` for the rules (never +//! production, the token sealed and never returned). + +use std::sync::Arc; + +use aws_sdk_dynamodb::types::AttributeValue; +use axum::{ + extract::{Path, State}, + http::StatusCode, + Extension, Json, +}; +use common::staging_cms::{self, StagingCms}; +use serde_json::{json, Value}; +use tracing::error; + +use crate::models::Claims; +use crate::AppState; + +type Reply = Result, (StatusCode, Json)>; + +fn fail(status: StatusCode, message: &str) -> (StatusCode, Json) { + ( + status, + Json(json!({ "error": message, "code": crate::openapi::default_code(status) })), + ) +} + +fn internal(context: &str, e: String) -> (StatusCode, Json) { + error!(error = %e, "{context}"); + fail( + StatusCode::INTERNAL_SERVER_ERROR, + "Something went wrong on our side. Try again.", + ) +} + +fn repo_of(owner: &str, name: &str) -> Result)> { + let repo = format!("{owner}/{name}"); + let ok = repo.len() <= 200 + && !repo.contains("..") + && repo + .chars() + .all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '/'); + if ok { + Ok(repo) + } else { + Err(fail( + StatusCode::BAD_REQUEST, + "That isn't a repository name.", + )) + } +} + +fn forbidden() -> (StatusCode, Json) { + fail( + StatusCode::FORBIDDEN, + "Only admins can change a repository's staging CMS connection.", + ) +} + +/// GET /api/repos/:owner/:name/staging-cms +pub async fn get( + State(state): State>, + Extension(claims): Extension, + Path((owner, name)): Path<(String, String)>, +) -> Reply { + claims.require_role(3).map_err(|_| forbidden())?; + let repo = repo_of(&owner, &name)?; + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", AttributeValue::S(claims.team_id.clone())) + .key("sk", AttributeValue::S(staging_cms::sk(&repo))) + .send() + .await + .map_err(|e| internal("Failed to read the staging CMS connection", e.to_string()))? + .item; + Ok(Json(match item.as_ref().and_then(StagingCms::from_item) { + Some(c) => c.view( + item.as_ref() + .and_then(|i| i.get(staging_cms::TOKEN_ATTR)) + .and_then(|v| v.as_s().ok()) + .is_some_and(|s| !s.is_empty()), + ), + None => json!({ "configured": false, "repo": repo, "providers": staging_cms::PROVIDERS }), + })) +} + +/// PUT /api/repos/:owner/:name/staging-cms +/// Body: `{provider, project_id, dataset, production_dataset?, token?}`. The +/// token is required the first time and kept when left out later. +pub async fn put( + State(state): State>, + Extension(claims): Extension, + Path((owner, name)): Path<(String, String)>, + Json(body): Json, +) -> Reply { + claims.require_role(3).map_err(|_| forbidden())?; + let repo = repo_of(&owner, &name)?; + let s = |k: &str| body[k].as_str().unwrap_or("").trim().to_string(); + let c = StagingCms { + repo: repo.clone(), + provider: s("provider"), + project_id: s("project_id"), + dataset: s("dataset"), + production_dataset: s("production_dataset"), + }; + c.validate() + .map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; + let token = s("token"); + if token.len() > 500 { + return Err(fail(StatusCode::BAD_REQUEST, "The token is too long.")); + } + let prior_sealed = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", AttributeValue::S(claims.team_id.clone())) + .key("sk", AttributeValue::S(staging_cms::sk(&repo))) + .send() + .await + .map_err(|e| internal("Failed to read the staging CMS connection", e.to_string()))? + .item + .and_then(|i| { + i.get(staging_cms::TOKEN_ATTR) + .and_then(|v| v.as_s().ok().cloned()) + }) + .filter(|s| !s.is_empty()); + let sealed = if token.is_empty() { + prior_sealed.ok_or_else(|| { + fail( + StatusCode::BAD_REQUEST, + "Enter a token with write access to the staging dataset.", + ) + })? + } else { + let cipher = super::alerts::cipher(&state); + staging_cms::seal(&cipher, &claims.team_id, &repo, &token) + .await + .map_err(|e| internal("Failed to seal the staging CMS token", e))? + }; + let mut item = c.item(&claims.team_id); + item.insert(staging_cms::TOKEN_ATTR.into(), AttributeValue::S(sealed)); + item.insert("updated_by".into(), AttributeValue::S(claims.email.clone())); + item.insert( + "updated_at".into(), + AttributeValue::S(chrono::Utc::now().to_rfc3339()), + ); + state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .set_item(Some(item)) + .send() + .await + .map_err(|e| internal("Failed to save the staging CMS connection", e.to_string()))?; + Ok(Json(c.view(true))) +} + +/// DELETE /api/repos/:owner/:name/staging-cms +pub async fn delete( + State(state): State>, + Extension(claims): Extension, + Path((owner, name)): Path<(String, String)>, +) -> Reply { + claims.require_role(3).map_err(|_| forbidden())?; + let repo = repo_of(&owner, &name)?; + state + .dynamo + .delete_item() + .table_name(&state.config.settings_table_name) + .key("pk", AttributeValue::S(claims.team_id.clone())) + .key("sk", AttributeValue::S(staging_cms::sk(&repo))) + .send() + .await + .map_err(|e| internal("Failed to remove the staging CMS connection", e.to_string()))?; + Ok(Json(json!({ "configured": false, "repo": repo }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn repository_names_are_checked() { + assert_eq!(repo_of("acme", "web").unwrap(), "acme/web"); + assert!(repo_of("acme", "..").is_err()); + assert!(repo_of("acme", "we b").is_err()); + } +} diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 9d03c73f2..ade7424d0 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -3054,6 +3054,50 @@ impl GitHubClient { .collect()) } + /// The repository's branch names, at most `max` (100 per page). + pub async fn list_branches( + &self, + owner: &str, + repo: &str, + max: usize, + ) -> Result, Box> { + let mut out = Vec::new(); + for page in 1..=10u32 { + let url = format!("{API_BASE}/repos/{owner}/{repo}/branches?per_page=100&page={page}"); + let v = self.get(&url).await?; + let batch: Vec = v + .as_array() + .into_iter() + .flatten() + .filter_map(|b| b["name"].as_str().map(String::from)) + .collect(); + let done = batch.len() < 100; + out.extend(batch); + if done || out.len() >= max { + break; + } + } + out.truncate(max); + Ok(out) + } + + /// The files one commit changed. + pub async fn commit_files( + &self, + owner: &str, + repo: &str, + sha: &str, + ) -> Result, Box> { + let url = format!("{API_BASE}/repos/{owner}/{repo}/commits/{sha}"); + let v = self.get(&url).await?; + Ok(v["files"] + .as_array() + .into_iter() + .flatten() + .filter_map(|f| f["filename"].as_str().map(String::from)) + .collect()) + } + /// Starts a workflow by its file name on a branch, with inputs. pub async fn dispatch_workflow( &self, diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 55b958182..40bf75210 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -686,6 +686,20 @@ async fn mark_pr_ready( { return Ok(()); } + // A new feature stays a draft until its verification checklist passes. + if passes::feature::ready_hold( + state, + &github, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + ) + .await + .is_some() + { + return Ok(()); + } let node_id = pr .get("node_id") .and_then(|v| v.as_str()) diff --git a/services/worker/src/passes/feature/checklist.rs b/services/worker/src/passes/feature/checklist.rs new file mode 100644 index 000000000..af68e6aa5 --- /dev/null +++ b/services/worker/src/passes/feature/checklist.rs @@ -0,0 +1,522 @@ +//! Rule 7: the verification checklist a feature meets before it is ready. +//! +//! Derived from the repository and the ticket, never from the coder's own +//! account: +//! +//! - type-check, lint and unit tests, with the repository's own scripts; +//! - the unit tests the acceptance criteria imply: one per listed option or +//! case ([`acceptance_cases`]), counted in the diff ([`unit_cases_added`]); +//! - the end-to-end spec, and its entry in any test map the repository keeps +//! ([`missing_from_test_maps`]); +//! - 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`]). +//! +//! The counts and results go in the pull request; an item that fails keeps it +//! a draft. + +use common::e2e::test_package::Step; +use serde::{Deserialize, Serialize}; + +/// Repeats of the new spec. +pub const REPEATS: u32 = 5; +/// The narrowest and widest viewports the responsive check needs. +pub const NARROW_MAX: u32 = 480; +pub const WIDE_MIN: u32 = 1280; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Status { + Pass, + Fail, + /// Not run here; the detail says where it runs. + NotRun, +} + +impl Status { + fn word(self) -> &'static str { + match self { + Status::Pass => "PASS", + Status::Fail => "FAIL", + Status::NotRun => "not run here", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Item { + pub name: String, + pub status: Status, + pub detail: String, +} + +impl Item { + pub fn new(name: &str, status: Status, detail: impl Into) -> Self { + Item { + name: name.to_string(), + status, + detail: detail.into(), + } + } + + pub fn line(&self) -> String { + format!("- [{}] {}: {}", self.status.word(), self.name, self.detail) + } +} + +/// The checklist as the description shows it. +pub fn markdown(items: &[Item]) -> String { + if items.is_empty() { + return String::new(); + } + let mut s = String::from("## Verification checklist\n"); + for i in items { + s.push_str(&i.line()); + s.push('\n'); + } + s +} + +/// The failing items, one line each. +pub fn failing(items: &[Item]) -> Vec { + items + .iter() + .filter(|i| i.status == Status::Fail) + .map(|i| format!("{}: {}", i.name, i.detail)) + .collect() +} + +fn list_item(l: &str) -> bool { + let t = l.trim_start(); + t.starts_with("- ") + || t.starts_with("* ") + || t.split_once(". ") + .is_some_and(|(n, _)| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())) +} + +/// How many cases the acceptance criteria list: the list items under an +/// "acceptance criteria" heading in the ticket, else the scenarios in the +/// plan's spec.md. +pub fn acceptance_cases(ticket_body: &str, spec_md: &str) -> usize { + let mut in_ac = false; + let mut n = 0; + for l in ticket_body.lines() { + let low = l.trim().to_lowercase(); + if low.contains("acceptance criteria") { + in_ac = true; + continue; + } + if in_ac { + if l.trim_start().starts_with('#') || (low.ends_with(':') && !list_item(l)) { + break; + } + if list_item(l) { + n += 1; + } + } + } + if n > 0 { + return n; + } + spec_md + .lines() + .filter(|l| { + let t = l + .trim_start() + .trim_start_matches(['#', '*', '-', ' ']) + .to_lowercase(); + t.starts_with("scenario") + }) + .count() +} + +fn is_e2e(path: &str) -> bool { + super::content::is_e2e_spec(path) +} + +/// Test cases the diff adds outside end-to-end specs. +pub fn unit_cases_added(files: &[(String, String, String)]) -> usize { + files + .iter() + .filter(|(p, s, _)| s != "removed" && !is_e2e(p)) + .map(|(_, _, patch)| { + patch + .lines() + .filter(|l| l.starts_with('+') && !l.starts_with("+++")) + .map(|l| l[1..].trim_start()) + .filter(|l| { + l.starts_with("it(") + || l.starts_with("test(") + || l.starts_with("it.each") + || l.starts_with("test.each") + || l.starts_with("#[test]") + || l.starts_with("#[tokio::test]") + || l.starts_with("def test_") + || l.starts_with("func Test") + }) + .count() + }) + .sum() +} + +/// Widths a spec sets its viewport to. +fn widths(text: &str) -> Vec { + let mut out = Vec::new(); + let mut from = 0; + while let Some(i) = text[from..].find("width") { + let at = from + i + 5; + from = at; + let rest = text[at..].trim_start_matches([' ', ':', '=', '\'', '"']); + let n: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + if let Ok(w) = n.parse::() { + if (200..=4000).contains(&w) { + out.push(w); + } + } + } + out +} + +/// Whether a spec checks there is no horizontal scroll at a narrow and a +/// wide viewport. +pub fn responsive_checked(text: &str) -> bool { + let w = widths(text); + let measures = text.contains("scrollWidth") || text.contains("overflow"); + measures && w.iter().any(|&x| x <= NARROW_MAX) && w.iter().any(|&x| x >= WIDE_MIN) +} + +/// Whether the change is UI work. +pub fn is_ui(paths: &[String]) -> bool { + paths.iter().any(|p| { + let l = p.to_lowercase(); + [".tsx", ".jsx", ".vue", ".svelte", ".css", ".scss", ".astro"] + .iter() + .any(|e| l.ends_with(e)) + && !l.contains(".test.") + && !l.contains(".spec.") + }) +} + +/// Whether a path is a test map: a file that lists specs by name. +pub fn is_test_map(path: &str) -> bool { + let l = path.to_lowercase(); + let name = l.rsplit('/').next().unwrap_or(&l); + [ + "test-map", + "testmap", + "test_map", + "spec-map", + "specmap", + "test-registry", + ] + .iter() + .any(|m| name.contains(m)) +} + +/// The new specs a test map that lists specs doesn't name, as (map, spec). +pub fn missing_from_test_maps( + maps: &[(String, String)], + specs: &[String], +) -> Vec<(String, String)> { + let mut out = Vec::new(); + for (map, text) in maps { + for s in specs { + let base = s.rsplit('/').next().unwrap_or(s); + let stem = base.split('.').next().unwrap_or(base); + if !text.contains(base) && !text.contains(stem) { + out.push((map.clone(), s.clone())); + } + } + } + out +} + +/// Which package manager the root uses, by its lockfile. +fn runner(tree: &[String]) -> &'static str { + if tree.iter().any(|p| p == "pnpm-lock.yaml") { + "pnpm" + } else if tree.iter().any(|p| p == "yarn.lock") { + "yarn" + } else if tree.iter().any(|p| p == "bun.lockb" || p == "bun.lock") { + "bun" + } else { + "npm" + } +} + +fn install(tree: &[String]) -> String { + match runner(tree) { + "pnpm" => "pnpm install --frozen-lockfile".into(), + "yarn" => "yarn install --frozen-lockfile".into(), + "bun" => "bun install --frozen-lockfile".into(), + _ if tree.iter().any(|p| p == "package-lock.json") => "npm ci".into(), + _ => "npm install".into(), + } +} + +fn safe_script(name: &str) -> bool { + !name.is_empty() + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || ":-_".contains(c)) +} + +/// The root's type-check, lint and unit-test steps, from its package.json +/// scripts. Empty when the root has none of them. +pub fn root_steps(package_json: &str, tree: &[String]) -> Vec { + let Ok(v) = serde_json::from_str::(package_json) else { + return Vec::new(); + }; + let Some(scripts) = v["scripts"].as_object() else { + return Vec::new(); + }; + let r = runner(tree); + let find = |names: &[&str], skip: &[&str]| { + names.iter().find_map(|n| { + let cmd = scripts.get(*n)?.as_str()?; + (safe_script(n) && !skip.iter().any(|s| cmd.contains(s))).then(|| n.to_string()) + }) + }; + let mut steps = Vec::new(); + let mut add = |kind: &'static str, script: Option| { + if let Some(s) = script { + steps.push(Step { + kind, + cmd: format!("{r} run {s}"), + }); + } + }; + add( + "typecheck", + find(&["typecheck", "type-check", "check-types", "tsc"], &[]), + ); + add("lint", find(&["lint"], &[])); + add( + "unit", + find( + &["test:unit", "unit", "test"], + &["playwright", "cypress", "e2e"], + ), + ); + if steps.is_empty() { + return steps; + } + steps.insert( + 0, + Step { + kind: "install", + cmd: install(tree), + }, + ); + steps +} + +/// What the static part of the checklist reads. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Facts { + pub cases_required: usize, + pub cases_added: usize, + pub ui: bool, + /// The end-to-end specs the change adds or changes. + pub specs: Vec, + /// Specs with the responsive check. + pub responsive_specs: Vec, + /// Test maps that don't name a new spec, as "map: spec". + pub map_missing: Vec, + /// The repository has end-to-end tests. + pub has_e2e: bool, +} + +/// The items that read the diff alone. +pub fn static_items(f: &Facts) -> Vec { + let mut out = Vec::new(); + if f.cases_required > 0 { + let status = if f.cases_added >= f.cases_required { + Status::Pass + } else { + Status::Fail + }; + out.push(Item::new( + "unit tests for the acceptance criteria", + status, + format!( + "{} test case(s) added for {} listed case(s)", + f.cases_added, f.cases_required + ), + )); + } + if f.has_e2e && f.ui { + if f.specs.is_empty() { + out.push(Item::new( + "end-to-end spec", + Status::Fail, + "the change adds UI but no end-to-end spec", + )); + } else { + out.push(Item::new( + "end-to-end spec", + Status::Pass, + f.specs.join(", "), + )); + } + } + if !f.specs.is_empty() || !f.map_missing.is_empty() { + if f.map_missing.is_empty() { + out.push(Item::new( + "test map entry", + Status::Pass, + "every new spec is listed in the repository's test maps (or it keeps none)", + )); + } else { + out.push(Item::new( + "test map entry", + Status::Fail, + format!("not listed: {}", f.map_missing.join("; ")), + )); + } + } + if f.ui && !f.specs.is_empty() { + if f.responsive_specs.is_empty() { + out.push(Item::new( + "no horizontal scroll at narrow and wide viewports", + Status::Fail, + format!( + "no spec checks scrollWidth at a width of {NARROW_MAX}px or less and {WIDE_MIN}px or more" + ), + )); + } else { + out.push(Item::new( + "no horizontal scroll at narrow and wide viewports", + Status::Pass, + format!("checked in {}", f.responsive_specs.join(", ")), + )); + } + } + out +} + +/// What the coder is told about failing static items. +pub fn feedback(items: &[Item]) -> String { + let fails = failing(items); + if fails.is_empty() { + return String::new(); + } + let mut s = String::from( + "\nThe verification checklist for this feature isn't met yet. Fix each item:\n", + ); + for f in fails { + s.push_str(&format!("- {f}\n")); + } + s.push_str(&format!( + "Unit tests: one test per option or case the acceptance criteria list. 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" + )); + s +} + +#[cfg(test)] +mod tests { + use super::*; + + #[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"; + assert_eq!(acceptance_cases(body, ""), 3); + let spec = "### Scenario: default\nGiven...\n### Scenario: by venue\n"; + assert_eq!(acceptance_cases("No criteria here", spec), 2); + } + + #[test] + fn counts_unit_cases_outside_e2e_specs() { + let files = vec![ + ( + "src/filter.test.ts".to_string(), + "added".to_string(), + "+it('shows all', () => {})\n+ test('by venue', () => {})\n+const x = 1\n" + .to_string(), + ), + ( + "e2e/filter.spec.ts".to_string(), + "added".to_string(), + "+test('e2e', async () => {})\n".to_string(), + ), + ]; + assert_eq!(unit_cases_added(&files), 2); + } + + #[test] + fn a_responsive_check_needs_both_viewports_and_a_measure() { + let ok = "await page.setViewportSize({ width: 375, height: 800 });\nexpect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(375);\nawait page.setViewportSize({ width: 1440, height: 900 });"; + assert!(responsive_checked(ok)); + assert!(!responsive_checked( + "setViewportSize({ width: 375 }) scrollWidth" + )); + assert!(!responsive_checked("width: 375 width: 1440")); + } + + #[test] + fn finds_test_maps_missing_a_new_spec() { + assert!(is_test_map("e2e/test-map.json")); + assert!(!is_test_map("e2e/quote.spec.ts")); + let maps = vec![( + "e2e/test-map.json".to_string(), + "{\"hero\": \"hero.spec.ts\"}".to_string(), + )]; + let m = missing_from_test_maps(&maps, &["e2e/quote.spec.ts".to_string()]); + assert_eq!( + m, + vec![( + "e2e/test-map.json".to_string(), + "e2e/quote.spec.ts".to_string() + )] + ); + assert!(missing_from_test_maps(&maps, &["e2e/hero.spec.ts".to_string()]).is_empty()); + } + + #[test] + fn root_steps_come_from_the_repositorys_scripts() { + let pj = r#"{"scripts":{"typecheck":"tsc --noEmit","lint":"eslint .","test":"playwright test","test:unit":"vitest run"}}"#; + let tree = vec!["pnpm-lock.yaml".to_string()]; + let steps = root_steps(pj, &tree); + let cmds: Vec<&str> = steps.iter().map(|s| s.cmd.as_str()).collect(); + assert_eq!( + cmds, + vec![ + "pnpm install --frozen-lockfile", + "pnpm run typecheck", + "pnpm run lint", + "pnpm run test:unit" + ] + ); + // `test` that runs the browser suite isn't the unit tests. + let pj = r#"{"scripts":{"test":"playwright test"}}"#; + assert!(root_steps(pj, &tree).is_empty()); + } + + #[test] + fn the_static_items_hold_the_feature_to_its_tests() { + let f = Facts { + cases_required: 3, + cases_added: 2, + ui: true, + specs: vec!["e2e/quote.spec.ts".into()], + responsive_specs: vec![], + map_missing: vec!["e2e/test-map.json: e2e/quote.spec.ts".into()], + has_e2e: true, + }; + let items = static_items(&f); + assert_eq!(failing(&items).len(), 3); + assert!(markdown(&items) + .contains("[FAIL] unit tests for the acceptance criteria: 2 test case(s) added for 3")); + assert!(feedback(&items).contains("scrollWidth")); + let ok = Facts { + cases_added: 3, + responsive_specs: vec!["e2e/quote.spec.ts".into()], + map_missing: vec![], + ..f + }; + assert!(failing(&static_items(&ok)).is_empty()); + } +} diff --git a/services/worker/src/passes/feature/content.rs b/services/worker/src/passes/feature/content.rs new file mode 100644 index 000000000..3488f4a59 --- /dev/null +++ b/services/worker/src/passes/feature/content.rs @@ -0,0 +1,560 @@ +//! Rule 6: end-to-end tests that read CMS content, and a schema change that +//! makes the staging content out of date. +//! +//! A repository serves pages from its CMS through a catch-all route +//! ([`is_cms_catch_all`]); its end-to-end tests open those pages on staging. +//! When the change edits the CMS schema, the content they read can go out of +//! date: a field the schema drops is still on the documents, a field it now +//! requires is missing, a new block the new test looks for is on no page. +//! [`needs`] lists that content from the diff. Then, before the pull +//! request: +//! +//! - with the repository's staging CMS write connection (Settings, per +//! repository; staging only, see `common::staging_cms`), the changes that +//! can be made without inventing content are made on staging: a dropped +//! field is removed from the documents that hold it, a newly required field +//! with a default gets the default. The description says exactly what +//! 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. + +use std::collections::BTreeSet; + +use common::staging_cms::StagingCms; +use serde_json::{json, Value}; +use tracing::warn; + +/// Words in a route file that mark a CMS client. +const CMS_MARKS: &[&str] = &[ + "sanity", + "groq", + "contentful", + "storyblok", + "prismic", + "datocms", + "hygraph", + "payload", + "strapi", + "builder.io", + "graphcms", + "cms", +]; + +/// Whether a route path is a catch-all (`[...slug]`, `[[...slug]]`). +pub fn is_catch_all_path(path: &str) -> bool { + path.contains("[...") || path.contains("[[...") +} + +/// A catch-all route file whose code reads a CMS. +pub fn is_cms_catch_all(path: &str, text: &str) -> bool { + if !is_catch_all_path(path) { + return false; + } + let l = text.to_lowercase(); + CMS_MARKS.iter().any(|m| l.contains(m)) +} + +/// Whether a path is an end-to-end spec. +pub fn is_e2e_spec(path: &str) -> bool { + let l = path.to_lowercase(); + (l.contains(".spec.") || l.contains(".e2e.") || l.contains(".cy.")) + && (l.contains("e2e") + || l.contains("playwright") + || l.contains("cypress") + || l.contains("tests/")) +} + +/// Whether a file is a CMS schema definition. +pub fn is_schema_file(path: &str, text: &str) -> bool { + let l = path.to_lowercase(); + let pathy = l.contains("schema") + || l.contains("studio") + || l.contains("/cms/") + || l.starts_with("cms/"); + pathy + && (text.contains("defineType") + || text.contains("defineField") + || text.contains("createContentType") + || (text.contains("fields:") && text.contains("type:"))) +} + +/// The `name: 'x'` a line declares, if any (anywhere on the line, not +/// `displayName:` or the like). +fn declared_name(line: &str) -> Option { + let mut from = 0; + while let Some(i) = line[from..].find("name:") { + let at = from + i; + from = at + 5; + let before = line[..at].chars().next_back(); + if before.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') { + continue; + } + let rest = line[at + 5..].trim_start(); + let Some(q) = rest + .chars() + .next() + .filter(|c| matches!(c, '\'' | '"' | '`')) + else { + continue; + }; + let inner = &rest[1..]; + let end = inner.find(q)?; + let n = &inner[..end]; + if !n.is_empty() { + return Some(n.to_string()); + } + } + None +} + +/// The type a schema file defines: the first name it declares. +pub fn type_name(text: &str) -> String { + text.lines().find_map(declared_name).unwrap_or_default() +} + +/// What a schema diff changes. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SchemaChange { + /// A new type (a document or a block). + NewType(String), + /// A field taken off a type. + RemovedField { doc_type: String, field: String }, + /// A field a type now requires, with its default when the schema gives + /// one (`initialValue`). + RequiredField { + doc_type: String, + field: String, + default: Option, + }, +} + +/// The schema changes one file's diff makes. `type_name` is the file's type +/// (its first declared name on the branch). +pub fn schema_changes(status: &str, patch: &str, type_name: &str) -> Vec { + let mut out = Vec::new(); + if status == "added" { + if !type_name.is_empty() { + out.push(SchemaChange::NewType(type_name.to_string())); + } + return out; + } + let added: BTreeSet = patch + .lines() + .filter(|l| l.starts_with('+') && !l.starts_with("+++")) + .filter_map(declared_name) + .collect(); + let mut last_name = String::new(); + let mut last_default: Option = None; + for l in patch.lines() { + if l.starts_with("+++") || l.starts_with("---") { + continue; + } + if let Some(n) = declared_name(l) { + if l.starts_with('-') && !added.contains(&n) && n != type_name { + out.push(SchemaChange::RemovedField { + doc_type: type_name.to_string(), + field: n.clone(), + }); + } + if !l.starts_with('-') { + last_name = n; + last_default = None; + } + } + let body = l.get(1..).unwrap_or("").trim(); + if !l.starts_with('-') { + if let Some(v) = body.strip_prefix("initialValue:") { + let v = v.trim().trim_end_matches(','); + last_default = serde_json::from_str(&v.replace('\'', "\"")).ok(); + } + } + if l.starts_with('+') + && body.contains("required()") + && !last_name.is_empty() + && last_name != type_name + { + out.push(SchemaChange::RequiredField { + doc_type: type_name.to_string(), + field: last_name.clone(), + default: last_default.clone(), + }); + } + } + out.dedup(); + out +} + +/// Content staging must have for the tests to read it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Need { + /// Remove a dropped field from every document of a type that holds it. + Unset { doc_type: String, field: String }, + /// Every document of a type needs a field. `default`: set it to this. + Require { + doc_type: String, + field: String, + default: Option, + }, + /// A staging page must show a block of the new type, for a spec. + BlockOnPage { block: String, spec: String }, +} + +impl Need { + pub fn line(&self) -> String { + match self { + Need::Unset { doc_type, field } => { + format!("remove `{field}` from every `{doc_type}` document that still has it") + } + Need::Require { + doc_type, + field, + default, + } => match default { + Some(v) => { + format!("set `{field}` to `{v}` on every `{doc_type}` document without it") + } + None => format!( + "give every `{doc_type}` document a value for the now required `{field}`" + ), + }, + Need::BlockOnPage { block, spec } => format!( + "add a `{block}` block to the staging page `{spec}` opens, so the new test finds it" + ), + } + } + + /// Whether CoderHelm can make it without inventing content. + pub fn automatic(&self) -> bool { + match self { + Need::Unset { .. } => true, + Need::Require { default, .. } => default.is_some(), + Need::BlockOnPage { .. } => false, + } + } +} + +/// The staging content the change needs, given its schema changes and the +/// end-to-end specs it adds or changes as (path, text). A new type counts +/// only when a changed spec names it. +pub fn needs(changes: &[SchemaChange], specs: &[(String, String)]) -> Vec { + let mut out = Vec::new(); + for c in changes { + let n = match c { + SchemaChange::RemovedField { doc_type, field } => Need::Unset { + doc_type: doc_type.clone(), + field: field.clone(), + }, + SchemaChange::RequiredField { + doc_type, + field, + default, + } => Need::Require { + doc_type: doc_type.clone(), + field: field.clone(), + default: default.clone(), + }, + SchemaChange::NewType(t) => { + let Some((spec, _)) = specs + .iter() + .find(|(_, text)| super::registration::names_item(text, t)) + else { + continue; + }; + Need::BlockOnPage { + block: t.clone(), + spec: spec.clone(), + } + } + }; + if !out.contains(&n) { + out.push(n); + } + } + out +} + +fn groq_str(s: &str) -> String { + format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) +} + +fn groq_field(f: &str) -> Option<&str> { + (!f.is_empty() && f.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')).then_some(f) +} + +/// The query for the ids of the documents an automatic need applies to. +pub fn affected_query(n: &Need) -> Option { + match n { + Need::Unset { doc_type, field } => Some(format!( + "*[_type == {} && defined({})]._id", + groq_str(doc_type), + groq_field(field)? + )), + Need::Require { + doc_type, + field, + default: Some(_), + } => Some(format!( + "*[_type == {} && !defined({})]._id", + groq_str(doc_type), + groq_field(field)? + )), + _ => None, + } +} + +/// The mutations that make an automatic need on `ids`. +pub fn mutations(n: &Need, ids: &[String]) -> Vec { + ids.iter() + .filter_map(|id| match n { + Need::Unset { field, .. } => Some(json!({"patch": {"id": id, "unset": [field]}})), + Need::Require { + field, + default: Some(v), + .. + } => Some(json!({"patch": {"id": id, "setIfMissing": {field: v}}})), + _ => None, + }) + .collect() +} + +/// What happened to the staging content, for the description. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Outcome { + /// What was changed on staging, one line each. + pub changed: Vec, + /// What must still change, one line each: stops the pull request. + pub blocking: Vec, +} + +/// Reads the ids an automatic need applies to on staging. +async fn affected( + http: &reqwest::Client, + c: &StagingCms, + token: &str, + q: &str, +) -> Result, String> { + 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"] + .as_array() + .into_iter() + .flatten() + .filter_map(|x| x.as_str().map(String::from)) + .collect()) +} + +/// Makes what can be made on staging and lists what can't. `conn`: the +/// repository's connection and its opened token, `None` without one. +/// `production_in_code`: datasets the repository's production settings +/// name, refused like production. +pub async fn settle( + http: &reqwest::Client, + conn: Option<(&StagingCms, &str)>, + production_in_code: &[String], + needs: &[Need], +) -> Outcome { + let mut out = Outcome::default(); + let Some((c, token)) = conn else { + out.blocking = needs.iter().map(Need::line).collect(); + return out; + }; + if let Err(e) = c + .check_writable() + .and_then(|_| c.check_against_code(production_in_code)) + { + out.blocking = needs.iter().map(Need::line).collect(); + out.blocking.push(e); + return out; + } + for n in needs { + let Some(q) = n.automatic().then(|| affected_query(n)).flatten() else { + out.blocking.push(n.line()); + continue; + }; + let ids = match affected(http, c, token, &q).await { + Ok(ids) => ids, + Err(e) => { + warn!(error = %e, "Could not read staging content"); + out.blocking.push(format!("{} ({e})", n.line())); + continue; + } + }; + if ids.is_empty() { + continue; + } + let body = json!({ "mutations": mutations(n, &ids) }); + let sent = http + .post(c.mutate_url()) + .bearer_auth(token) + .json(&body) + .send() + .await; + match sent { + Ok(r) if r.status().is_success() => out.changed.push(format!( + "{} on {} document(s) in the `{}` dataset ({})", + n.line(), + ids.len(), + c.dataset, + ids.iter().take(5).cloned().collect::>().join(", ") + )), + Ok(r) => out + .blocking + .push(format!("{} (staging returned {})", n.line(), r.status())), + Err(e) => out.blocking.push(format!("{} ({e})", n.line())), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finds_a_catch_all_route_served_by_a_cms() { + assert!(is_cms_catch_all( + "app/[...slug]/page.tsx", + "import { client } from '@/sanity/client'" + )); + assert!(is_cms_catch_all( + "src/pages/[[...path]].tsx", + "fetchFromCMS()" + )); + assert!(!is_cms_catch_all( + "app/[...slug]/page.tsx", + "export default function P() {}" + )); + assert!(!is_cms_catch_all("app/about/page.tsx", "sanity")); + assert!(is_e2e_spec("e2e/blocks/quote.spec.ts")); + assert!(!is_e2e_spec("src/lib/date.test.ts")); + assert!(is_schema_file( + "studio/schemas/quote.ts", + "export default defineType({ name: 'quote' })" + )); + } + + #[test] + fn reads_dropped_and_newly_required_fields_from_the_diff() { + let patch = "@@\n defineType({\n name: 'hero',\n fields: [\n- defineField({ name: 'subtitle', type: 'string' }),\n defineField({\n name: 'theme',\n+ initialValue: 'light',\n+ validation: (Rule) => Rule.required(),\n }),\n+ defineField({ name: 'cta', type: 'string', validation: (r) => r.required() }),\n"; + let c = schema_changes("modified", patch, "hero"); + assert_eq!( + c, + vec![ + SchemaChange::RemovedField { + doc_type: "hero".into(), + field: "subtitle".into() + }, + SchemaChange::RequiredField { + doc_type: "hero".into(), + field: "theme".into(), + default: Some(json!("light")) + }, + SchemaChange::RequiredField { + doc_type: "hero".into(), + field: "cta".into(), + default: None + }, + ] + ); + assert_eq!( + schema_changes("added", "+defineType({ name: 'quote' })", "quote"), + vec![SchemaChange::NewType("quote".into())] + ); + } + + #[test] + fn lists_exactly_which_content_must_change() { + let changes = vec![ + SchemaChange::RemovedField { + doc_type: "hero".into(), + field: "subtitle".into(), + }, + SchemaChange::RequiredField { + doc_type: "hero".into(), + field: "cta".into(), + default: None, + }, + SchemaChange::NewType("quoteBlock".into()), + SchemaChange::NewType("unused".into()), + ]; + let specs = vec![( + "e2e/quote.spec.ts".to_string(), + "await expect(page.getByTestId('quote-block')).toBeVisible()".to_string(), + )]; + let n = needs(&changes, &specs); + assert_eq!(n.len(), 3); + assert!(n[0].automatic()); + assert!(!n[1].automatic()); + assert_eq!( + n[2], + Need::BlockOnPage { + block: "quoteBlock".into(), + spec: "e2e/quote.spec.ts".into() + } + ); + assert_eq!( + affected_query(&n[0]).unwrap(), + "*[_type == \"hero\" && defined(subtitle)]._id" + ); + assert!(affected_query(&n[1]).is_none()); + let m = mutations(&n[0], &["a".into(), "b".into()]); + assert_eq!(m[0], json!({"patch": {"id": "a", "unset": ["subtitle"]}})); + } + + #[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; + assert!(out.changed.is_empty()); + assert_eq!( + out.blocking, + vec!["remove `subtitle` from every `hero` document that still has it"] + ); + } + + #[tokio::test] + async fn a_production_dataset_is_refused_before_any_call() { + let c = StagingCms { + repo: "o/r".into(), + provider: "sanity".into(), + project_id: "p1".into(), + dataset: "production".into(), + production_dataset: String::new(), + }; + let n = vec![Need::Unset { + doc_type: "hero".into(), + field: "subtitle".into(), + }]; + 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 { + dataset: "copy".into(), + ..c + }; + let out = settle( + &reqwest::Client::new(), + Some((&c2, "t")), + &["copy".into()], + &n, + ) + .await; + assert!(out + .blocking + .iter() + .any(|b| b.contains("production settings"))); + } +} diff --git a/services/worker/src/passes/feature/mod.rs b/services/worker/src/passes/feature/mod.rs new file mode 100644 index 000000000..74b9456b4 --- /dev/null +++ b/services/worker/src/passes/feature/mod.rs @@ -0,0 +1,1173 @@ +//! New-feature tickets, handled the way a careful person would, for every +//! team. Each rule is enforced in code where it can be: +//! +//! 1. **New files are expected** ([`plan_files`]): every plan task says +//! whether it creates, modifies, deletes or replaces its path. Only +//! modify, delete and replace paths must exist; a create path must not. +//! 2. **Earlier attempts first** ([`prior`]): earlier pull requests and +//! branches for the feature (the ticket, the tickets it names, similar +//! titles) are read with what each did and why it ended; unrelated +//! commits are never carried over and the branch starts from the default +//! branch. The plan lists where an attempt and the ticket differ. +//! 3. **Reuse before writing** and 4. **mirror the closest sibling** +//! ([`reuse`]): the plan lists what it reuses and the closest existing +//! sibling; before the pull request, new exports that duplicate an +//! existing helper are flagged (code search for candidates, a model +//! judges). +//! 5. **Registration completeness** ([`registration`]): a new item appears +//! everywhere its siblings are registered, or the pull request is blocked +//! with the list. +//! 6. **Content-dependent tests** ([`content`]): a schema change that makes +//! the staging content the end-to-end tests read out of date is settled +//! through the repository's staging-only CMS write connection, or the run +//! stops naming exactly what must change. +//! 7. **Verification checklist** ([`checklist`]): type-check, lint, unit +//! tests per acceptance case, the spec and its test map entry, test +//! packages outside the workspace, repeat runs and responsive checks, +//! with counts in the pull request; a failing item keeps it a draft. +//! 8. **Open product questions** ([`questions`]): raised in the pull request, +//! never decided. +//! +//! The planner reads [`planner_block`]; the plan's own check adds +//! [`plan_gaps`]; [`gate`] runs before the pull request; [`shape_body`] +//! writes the description's sections; [`ready_hold`] keeps the draft. + +pub mod checklist; +pub mod content; +pub mod plan_files; +pub mod prior; +pub mod questions; +pub mod registration; +pub mod reuse; + +use common::e2e::test_package::{self, Repeat, Step}; +use serde::{Deserialize, Serialize}; +use tracing::{info, warn}; + +use crate::clients::github::GitHubClient; +use crate::models::{TicketMessage, TokenUsage}; +use crate::passes::plan::PlanResult; +use crate::passes::triage::TicketIntent; +use crate::WorkerState; + +/// Fix rounds the gate gives before it blocks or reports. +const MAX_FIX_ROUNDS: u32 = 1; + +/// What the planner is told, by the ticket's kind. +pub fn planner_block(intent: TicketIntent) -> String { + let mut s = String::new(); + if intent == TicketIntent::Feature { + s.push_str(&format!( + "\n\n## New-feature rules (CoderHelm checks these)\n\ + - Reuse before writing: search the code for existing utilities, components, \ + constants and data-fetch functions with similar names and behaviour. List the ones \ + you will reuse, each with its path, in design.md under `{}` (or what you searched \ + when none fits). New code that duplicates an existing exported helper is flagged.\n\ + - Mirror the closest sibling: when adding a component, block, route, handler or any \ + file of a kind that already exists, name the closest existing one by path in \ + design.md under `{}` and follow its structure and usage exactly (props, layout \ + wrappers, overflow and scroll handling, accessibility labels).\n\ + - Register it everywhere: find every place a comparable sibling is referenced \ + (registries, index files, query fragments, maps, test maps, docs) and add a task \ + for each. Regenerate generated files. A missing registration blocks the pull \ + request.\n\ + - Tests: one unit test per option or case the acceptance criteria list; for UI, an \ + end-to-end spec (added to any test map the repository keeps) that also checks there \ + is no horizontal scroll at a narrow ({}px or less) and a wide ({}px or more) \ + viewport.\n\ + - {}\n", + reuse::REUSE_HEADING, + reuse::SIBLING_HEADING, + checklist::NARROW_MAX, + checklist::WIDE_MIN, + questions::PLANNER, + )); + } else { + s.push_str(&format!("\n\n{}\n", questions::PLANNER)); + } + s +} + +/// What the plan leaves out, for the plan's own check to send back once. +pub fn plan_gaps(files: &PlanResult, intent: TicketIntent, found: &prior::Found) -> Vec { + let text = format!( + "{}\n{}\n{}\n{}", + files.proposal, files.design, files.tasks, files.spec + ); + let codes = !files.tasks.trim().is_empty() + && !files.tasks.starts_with("NO_CHANGES_NEEDED:") + && !files.tasks.starts_with("CLARIFICATION_NEEDED:"); + if !codes { + return Vec::new(); + } + let mut out = prior::plan_gaps(&files.design, &text, &found.attempts); + if intent == TicketIntent::Feature { + let creates = plan_files::planned_files(&files.tasks) + .iter() + .any(plan_files::PlannedFile::is_new); + out.extend(reuse::plan_gaps(&files.design, creates)); + } + out +} + +/// Finds the earlier attempts for the run's repository (see [`prior`]). +pub async fn find_attempts( + github: &GitHubClient, + msg: &TicketMessage, + own_branch: &str, + known: &[crate::passes::ticket_history::EarlierPr], +) -> prior::Found { + let default_branch = github + .get_default_branch(&msg.repo_owner, &msg.repo_name) + .await + .unwrap_or_else(|_| msg.base_branch.clone()); + let s = prior::Search { + owner: &msg.repo_owner, + name: &msg.repo_name, + default_branch: &default_branch, + ticket_id: &msg.ticket_id, + title: &msg.title, + body: &msg.body, + own_branch, + }; + prior::Found { + attempts: prior::gather(github, &s, known).await, + keys: s.keys(), + words: s.ticket_words(), + } +} + +/// What the gate found, for the description and the ready check. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct PrFacts { + pub attempts: Vec, + pub sibling: Option, + /// New code still flagged as duplicating an existing helper. + pub duplicates: Vec, + /// Registration places checked for the new items. + pub registrations_checked: usize, + /// Places a new item still isn't registered in (runs other than + /// features; a feature is blocked instead). + pub unregistered: Vec, + /// Set when the change touches a CMS schema the end-to-end tests read. + pub content: Option, + pub checklist: Vec, + pub facts: checklist::Facts, + pub maps: Vec, + pub questions: Vec, + /// The sandbox steps that failed, and the head they ran on. + pub sandbox_failed: Vec, + pub head: String, +} + +impl PrFacts { + fn is_empty(&self) -> bool { + self.attempts.is_empty() + && self.sibling.is_none() + && self.duplicates.is_empty() + && self.registrations_checked == 0 + && self.unregistered.is_empty() + && self.content.is_none() + && self.checklist.is_empty() + && self.questions.is_empty() + } +} + +/// The description's sections, after what the writer wrote. +pub fn sections(f: &PrFacts) -> String { + let mut s = String::new(); + if !f.attempts.is_empty() { + s.push_str("## Earlier attempts\nThis branch starts from the default branch; only what fits was reused.\n"); + for a in &f.attempts { + s.push_str(&format!("- {a}\n")); + } + s.push('\n'); + } + if f.sibling.is_some() + || !f.duplicates.is_empty() + || !f.unregistered.is_empty() + || f.registrations_checked > 0 + { + s.push_str("## Reuse and registration\n"); + if let Some(sib) = &f.sibling { + s.push_str(&format!("- Follows the closest sibling: `{sib}`\n")); + } + if f.registrations_checked > 0 && f.unregistered.is_empty() { + s.push_str(&format!( + "- Registered in every place its siblings are ({} checked)\n", + f.registrations_checked + )); + } + for d in f.duplicates.iter().chain(&f.unregistered) { + s.push_str(&format!("- Flagged for review: {d}\n")); + } + s.push('\n'); + } + if let Some(c) = &f.content { + s.push_str("## Staging content\n"); + if c.changed.is_empty() { + s.push_str("- No staging content was changed.\n"); + } + for l in &c.changed { + s.push_str(&format!("- Changed on staging: {l}\n")); + } + s.push('\n'); + } + let cl = checklist::markdown(&f.checklist); + if !cl.is_empty() { + s.push_str(&cl); + s.push('\n'); + } + let qs = questions::markdown(&f.questions); + if !qs.is_empty() { + s.push_str(&qs); + } + s.trim_end().to_string() +} + +/// The description with the sections added once. +pub fn shape_body(body: String, f: &PrFacts) -> String { + let add = sections(f); + if add.is_empty() || body.contains(add.as_str()) { + return body; + } + format!("{}\n\n{add}\n", body.trim_end()) +} + +/// The run's diff as (path, status, patch). +async fn diff(w: &super::proof::Work<'_>) -> Result, String> { + w.github + .compare_files_with_patches( + &w.msg.repo_owner, + &w.msg.repo_name, + &w.msg.base_branch, + w.branch, + ) + .await + .map_err(|e| format!("the diff couldn't be read ({e})")) +} + +/// The added lines of a patch from the line exporting `name`, for the judge. +fn new_body(patch: &str, name: &str) -> String { + let lines: Vec<&str> = patch + .lines() + .filter(|l| l.starts_with('+') && !l.starts_with("+++")) + .map(|l| &l[1..]) + .collect(); + let start = lines.iter().position(|l| l.contains(name)).unwrap_or(0); + lines[start..] + .iter() + .take(40) + .copied() + .collect::>() + .join("\n") +} + +/// Duplicate candidates for the new exports, judged. +async fn duplicates( + w: &super::proof::Work<'_>, + files: &[(String, String, String)], + usage: &mut TokenUsage, +) -> Vec { + let (owner, repo, base) = (&w.msg.repo_owner, &w.msg.repo_name, &w.msg.base_branch); + let changed: Vec = files.iter().map(|(p, _, _)| p.clone()).collect(); + let mut pairs = Vec::new(); + for (path, name) in reuse::new_exports(files).into_iter().take(6) { + let Some(term) = reuse::search_term(&name) else { + continue; + }; + let hits: Vec<(String, Vec)> = + match w.github.search_code(owner, repo, base, &term).await { + Ok(h) => h.into_iter().map(|r| (r.path, r.matches)).collect(), + Err(_) => continue, + }; + let patch = files + .iter() + .find(|(p, _, _)| p == &path) + .map(|(_, _, x)| x.as_str()) + .unwrap_or(""); + for c in reuse::similar_existing(&path, &name, &hits, &changed) + .into_iter() + .take(2) + { + let old = w + .github + .read_file_lines(owner, repo, &c.path, base, c.line, c.line + 40) + .await + .unwrap_or_default(); + pairs.push((c, new_body(patch, &name), old)); + } + } + reuse::judge(w.state, w.provider, usage, &pairs).await +} + +/// The static checklist facts, read from the diff and the branch. +async fn checklist_facts( + w: &super::proof::Work<'_>, + files: &[(String, String, String)], + tree: &[String], +) -> (checklist::Facts, Vec) { + let (owner, repo) = (&w.msg.repo_owner, &w.msg.repo_name); + let paths: Vec = files + .iter() + .filter(|(_, s, _)| s != "removed") + .map(|(p, _, _)| p.clone()) + .collect(); + let specs: Vec = paths + .iter() + .filter(|p| content::is_e2e_spec(p)) + .cloned() + .collect(); + let mut responsive = Vec::new(); + for s in &specs { + if let Ok(t) = w.github.read_file(owner, repo, s, w.branch).await { + if checklist::responsive_checked(&t) { + responsive.push(s.clone()); + } + } + } + let maps: Vec = tree + .iter() + .filter(|p| checklist::is_test_map(p)) + .take(5) + .cloned() + .collect(); + let mut map_texts = Vec::new(); + for m in &maps { + if let Ok(t) = w.github.read_file(owner, repo, m, w.branch).await { + map_texts.push((m.clone(), t)); + } + } + let new_specs: Vec = files + .iter() + .filter(|(p, s, _)| s == "added" && content::is_e2e_spec(p)) + .map(|(p, _, _)| p.clone()) + .collect(); + let facts = checklist::Facts { + cases_required: checklist::acceptance_cases(&w.msg.body, &w.plan.spec), + cases_added: checklist::unit_cases_added(files), + ui: checklist::is_ui(&paths), + specs, + responsive_specs: responsive, + map_missing: checklist::missing_from_test_maps(&map_texts, &new_specs) + .into_iter() + .map(|(m, s)| format!("{m}: {s}")) + .collect(), + has_e2e: tree.iter().any(|p| content::is_e2e_spec(p)), + }; + (facts, maps) +} + +/// The team's test address for the repository (staging or a preview with +/// `{pr}`), as Tests settings keep it. +async fn test_target(state: &WorkerState, team_id: &str, repo: &str) -> Option { + let st = common::e2e::store::Store::new(&state.dynamo, &state.config.tests_table_name); + if !st.enabled() { + return None; + } + st.settings(team_id) + .await + .ok()? + .report_source(repo)? + .target_for(None) +} + +/// The sandbox part of the checklist: the root's type-check, lint and unit +/// tests, each test package outside the workspace, and the new specs run +/// [`checklist::REPEATS`] times against the team's test address. Returns +/// the items and the failures' lines. +async fn sandbox_items( + w: &super::proof::Work<'_>, + files: &[(String, String, String)], + tree: &[String], + specs: &[String], + head: &str, +) -> (Vec, Vec) { + use checklist::{Item, Status}; + let (owner, repo, branch) = (&w.msg.repo_owner, &w.msg.repo_name, w.branch); + let state = w.state; + let mut items = Vec::new(); + let mut failed = Vec::new(); + let root_pj = w + .github + .read_file(owner, repo, "package.json", branch) + .await + .ok(); + let mut steps: Vec = root_pj + .as_deref() + .map(|pj| checklist::root_steps(pj, tree)) + .unwrap_or_default(); + // Test packages outside the main workspace, checked on their own. + let changed: Vec = files + .iter() + .filter(|(_, s, _)| s != "removed") + .map(|(p, _, _)| p.clone()) + .collect(); + let pnpm = w + .github + .read_file(owner, repo, "pnpm-workspace.yaml", branch) + .await + .ok(); + let globs = test_package::workspace_globs(root_pj.as_deref(), pnpm.as_deref()); + let mut texts: std::collections::HashMap = std::collections::HashMap::new(); + for f in &changed { + if let Some(dir) = test_package::package_dir(tree, f).filter(|d| !d.is_empty()) { + let pj = format!("{dir}/package.json"); + if let std::collections::hash_map::Entry::Vacant(slot) = texts.entry(pj) { + if let Ok(t) = w.github.read_file(owner, repo, slot.key(), branch).await { + slot.insert(t); + } + } + } + } + let pkgs = test_package::packages_outside(tree, &changed, &globs, &|p| texts.get(p).cloned()); + for p in &pkgs { + if let Some(s) = test_package::check_steps(p) { + steps.extend(s); + } + } + // The new spec, repeated against a fixed test address. A preview + // address (`{pr}`) exists only once the pull request does. + let target = test_target(state, &w.msg.team_id, &format!("{owner}/{repo}")).await; + let spec_pkg = pkgs + .iter() + .find(|p| p.runner.is_some()) + .cloned() + .or_else(|| { + specs.first().and_then(|s| { + let dir = test_package::package_dir(tree, s)?; + let pj = texts + .get(&format!("{dir}/package.json")) + .cloned() + .or(root_pj.clone())?; + let mut v = + test_package::packages_outside(tree, std::slice::from_ref(s), &[], &|_| { + Some(pj.clone()) + }); + v.pop() + }) + }); + let repeat = match (&target, &spec_pkg) { + (Some(t), Some(p)) if !t.contains("{pr}") && !specs.is_empty() => { + let rel: Vec = specs + .iter() + .map(|s| { + s.strip_prefix(&format!("{}/", p.dir)) + .unwrap_or(s) + .to_string() + }) + .collect(); + test_package::repeat_cmd(p, &rel, checklist::REPEATS, Some(t)) + } + _ => None, + }; + if !specs.is_empty() && repeat.is_none() { + items.push(Item::new( + "new spec repeated", + Status::NotRun, + format!( + "run `{}` with `--repeat-each={}` against the preview once it is up", + specs.join(" "), + checklist::REPEATS + ), + )); + } + if steps.is_empty() && repeat.is_none() { + return (items, failed); + } + if state.config.sandbox_bucket_name.is_empty() || state.config.sandbox_project_name.is_empty() { + for s in &steps { + items.push(Item::new( + s.kind, + Status::NotRun, + format!("`{}`; CI runs it on the pull request", s.cmd), + )); + } + return (items, failed); + } + // The team's agent permissions decide which commands may run. + let gate = crate::agent::policy::gate( + state, + w.provider.scope.ctx(common::agent_policy::Agent::Coder), + None, + ); + let mut kept: Vec = Vec::new(); + for s in steps { + match gate + .check_command(&s.cmd, "Run the feature's verification checklist") + .await + { + common::agent_policy::Outcome::Run { .. } => kept.push(s), + common::agent_policy::Outcome::Refused { message, .. } + | common::agent_policy::Outcome::Pending { message, .. } => items.push(Item::new( + s.kind, + Status::NotRun, + format!("`{}` ({message})", s.cmd), + )), + common::agent_policy::Outcome::Stop(_) => return (items, failed), + } + } + let repeat = match repeat { + Some(cmd) => match gate.check_command(&cmd, "Repeat the new spec").await { + common::agent_policy::Outcome::Run { .. } => Some(cmd), + _ => None, + }, + None => None, + }; + let sandbox = crate::clients::sandbox::SandboxClient::new( + &state.codebuild, + &state.s3, + &state.logs, + &state.config.sandbox_bucket_name, + &state.config.sandbox_project_name, + ) + .with_egress(crate::agent::policy::sandbox_egress(state, &w.msg.team_id).await); + let source = match sandbox + .ensure_source(w.run_id, head, || { + w.github.download_tarball(owner, repo, head) + }) + .await + { + Ok(k) => k, + Err(e) => { + items.push(Item::new( + "sandbox", + Status::NotRun, + format!("the branch couldn't be prepared ({e})"), + )); + return (items, failed); + } + }; + let script = test_package::sandbox_script(&kept, repeat.as_deref()); + let node = super::detect_node_version(w.github, owner, repo, branch).await; + match sandbox + .run_checks(&source, &script, node.as_deref(), None, None) + .await + { + Ok(o) if o.ran => { + let n = kept.len() + usize::from(repeat.is_some()); + let codes = test_package::step_codes(&o.output, n); + for (s, c) in kept.iter().zip(&codes) { + let (status, verdict) = match c { + Some(0) => (Status::Pass, "passed".to_string()), + Some(c) => (Status::Fail, format!("failed (exit {c})")), + None => (Status::NotRun, "no result".to_string()), + }; + if status == Status::Fail { + failed.push(format!("{} failed: `{}`", s.kind, s.cmd)); + } + items.push(Item::new(s.kind, status, format!("`{}` {verdict}", s.cmd))); + } + if repeat.is_some() { + let r: Option = test_package::parse_repeat(&o.output); + let status = if r.is_some_and(|r| r.green()) { + Status::Pass + } else { + Status::Fail + }; + let line = r.map(|r| r.line()).unwrap_or_else(|| "no count".into()); + if status == Status::Fail { + failed.push(format!( + "the new spec repeated {} times: {line}", + checklist::REPEATS + )); + } + items.push(Item::new( + "new spec repeated", + status, + format!( + "{} x{} against {}: {line}", + specs.join(", "), + checklist::REPEATS, + target.as_deref().unwrap_or("") + ), + )); + } + if !failed.is_empty() { + failed.push(format!( + "Output:\n```\n{}\n```", + common::tail_str(&o.output, 3_000) + )); + } + } + Ok(o) => items.push(Item::new( + "sandbox", + Status::NotRun, + format!("no result ({})", o.reason), + )), + Err(e) => items.push(Item::new( + "sandbox", + Status::NotRun, + format!("couldn't run ({e})"), + )), + } + (items, failed) +} + +/// Rule 6: settles the staging content a schema change needs. `None` when +/// the change touches no CMS schema the end-to-end tests read. +async fn content_outcome( + w: &super::proof::Work<'_>, + files: &[(String, String, String)], + tree: &[String], +) -> Option { + 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(); + for (p, s, patch) in files { + if s == "removed" { + continue; + } + if content::is_e2e_spec(p) { + if let Ok(t) = w.github.read_file(owner, repo, p, w.branch).await { + specs.push((p.clone(), t)); + } + continue; + } + let lower = p.to_lowercase(); + if !(lower.contains("schema") || lower.contains("studio") || lower.contains("cms")) { + continue; + } + let Ok(text) = w.github.read_file(owner, repo, p, w.branch).await else { + continue; + }; + if content::is_schema_file(p, &text) { + changes.extend(content::schema_changes( + s, + patch, + &content::type_name(&text), + )); + } + } + if changes.is_empty() || !tree.iter().any(|p| content::is_e2e_spec(p)) { + return None; + } + let mut cms = false; + for r in tree + .iter() + .filter(|p| content::is_catch_all_path(p)) + .take(5) + { + if let Ok(t) = w.github.read_file(owner, repo, r, base).await { + if content::is_cms_catch_all(r, &t) { + cms = true; + break; + } + } + } + if !cms { + return None; + } + let needs = content::needs(&changes, &specs); + if needs.is_empty() { + return Some(content::Outcome::default()); + } + let full = format!("{owner}/{repo}"); + let conn = load_connection(w.state, &w.msg.team_id, &full).await; + let mut prod_files = Vec::new(); + for p in tree.iter().filter(|p| { + let n = p.rsplit('/').next().unwrap_or(p); + n.starts_with(".env") && n.contains("prod") + }) { + if let Ok(t) = w.github.read_file(owner, repo, p, base).await { + prod_files.push((p.clone(), t)); + } + } + let prod = common::staging_cms::production_datasets_in_code(&prod_files); + let out = content::settle( + &w.state.http, + conn.as_ref().map(|(c, t)| (c, t.as_str())), + &prod, + &needs, + ) + .await; + info!( + run_id = w.run_id, + changed = out.changed.len(), + blocking = out.blocking.len(), + "Staging content checked for the schema change" + ); + Some(out) +} + +/// The repository's staging CMS connection with its opened token. +async fn load_connection( + state: &WorkerState, + team_id: &str, + repo: &str, +) -> Option<(common::staging_cms::StagingCms, String)> { + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", super::attr_s(team_id)) + .key("sk", super::attr_s(&common::staging_cms::sk(repo))) + .send() + .await + .ok()? + .item?; + let c = common::staging_cms::StagingCms::from_item(&item)?; + let sealed = item.get(common::staging_cms::TOKEN_ATTR)?.as_s().ok()?; + let kms = common::mcp_credentials::Kms { + client: &state.kms, + key_id: &state.config.secrets_key_id, + }; + match common::staging_cms::open(&kms, team_id, repo, sealed).await { + Ok(t) => Some((c, t)), + Err(e) => { + warn!(repo, error = %e, "Could not open the staging CMS token"); + None + } + } +} + +/// The check before the pull request opens. Problems get one fix round: +/// carried-over commits and missing registrations that survive it block the +/// pull request, and so does staging content that must change and can't be +/// changed here; duplicates and checklist failures go in the description +/// (the checklist keeps the pull request a draft). `Ok(None)` when nothing +/// here applies to the run. +pub async fn gate( + w: &super::proof::Work<'_>, + evidence: &mut super::proof::RunEvidence, + usage: &mut TokenUsage, + intent: TicketIntent, + found: &prior::Found, + has_time: impl Fn() -> bool, +) -> Result, String> { + let feature = intent == TicketIntent::Feature; + let (owner, repo, base) = (&w.msg.repo_owner, &w.msg.repo_name, &w.msg.base_branch); + let tree: Vec = w + .github + .get_tree(owner, repo, base) + .await + .map(|t| { + t.into_iter() + .filter(|e| e.entry_type == "blob") + .map(|e| e.path) + .collect() + }) + .unwrap_or_default(); + let planned: Vec = plan_files::planned_files(&w.plan.tasks) + .into_iter() + .map(|f| f.path) + .collect(); + let sibling = reuse::recorded_sibling(&w.plan.design); + let mut rounds = 0; + let mut facts = PrFacts { + attempts: found.pr_lines(), + sibling: sibling.clone().filter(|_| feature), + ..Default::default() + }; + loop { + let files = diff(w).await?; + let changed: Vec = files + .iter() + .filter(|(_, s, _)| s != "removed") + .map(|(p, _, _)| p.clone()) + .collect(); + let added: Vec = files + .iter() + .filter(|(_, s, _)| s == "added") + .map(|(p, _, _)| p.clone()) + .collect(); + let head = w + .github + .get_ref(owner, repo, w.branch) + .await + .unwrap_or_default(); + let carried = prior::carried_unrelated( + &changed, + &planned, + &found.attempts, + &found.keys, + &found.words, + ); + let (missing, places) = if added.is_empty() { + (Vec::new(), 0) + } else { + registration::check( + w.github, + owner, + repo, + base, + w.branch, + &added, + &tree, + sibling.as_deref(), + ) + .await + }; + let dups = if feature { + duplicates(w, &files, usage).await + } else { + Vec::new() + }; + let (cf, maps) = if feature { + checklist_facts(w, &files, &tree).await + } else { + (checklist::Facts::default(), Vec::new()) + }; + let static_items = if feature { + checklist::static_items(&cf) + } else { + Vec::new() + }; + let static_fails = checklist::failing(&static_items); + // The sandbox runs once the cheap problems are settled. + let (sandbox, sandbox_failed) = if feature + && carried.is_empty() + && missing.is_empty() + && static_fails.is_empty() + && !changed.is_empty() + { + sandbox_items(w, &files, &tree, &cf.specs, &head).await + } else { + (Vec::new(), Vec::new()) + }; + info!( + run_id = w.run_id, + carried = carried.len(), + missing_registrations = missing.len(), + duplicates = dups.len(), + checklist_fails = static_fails.len(), + sandbox_fails = sandbox_failed.len(), + rounds, + "New-feature rules checked before the pull request" + ); + let clean = carried.is_empty() + && missing.is_empty() + && dups.is_empty() + && static_fails.is_empty() + && sandbox_failed.is_empty(); + if clean || rounds >= MAX_FIX_ROUNDS || !has_time() { + if !carried.is_empty() { + return Err(format!( + "the branch carries over changes from an earlier attempt that this ticket doesn't ask for: {}", + carried + .iter() + .map(|(p, from)| format!("`{p}` (from {from})")) + .collect::>() + .join(", ") + )); + } + // A feature's new item must be registered; for other runs the + // places are flagged in the description instead. + if !missing.is_empty() && feature { + return Err(format!( + "new items aren't registered everywhere their siblings are: {}", + missing + .iter() + .map(registration::Missing::line) + .collect::>() + .join("; ") + )); + } + let content = content_outcome(w, &files, &tree).await; + if let Some(c) = content.as_ref().filter(|c| !c.blocking.is_empty()) { + return Err(format!( + "the change makes the staging content its end-to-end tests read out of date. \ + Change this content on staging{}: {}", + if c.changed.is_empty() { + String::new() + } else { + format!(" (already changed: {})", c.changed.join("; ")) + }, + c.blocking.join("; ") + )); + } + facts.registrations_checked = places; + facts.unregistered = missing.iter().map(registration::Missing::line).collect(); + facts.duplicates = dups.iter().map(reuse::Duplicate::line).collect(); + facts.content = content; + 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.sandbox_failed = sandbox_failed; + facts.head = head; + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + &format!( + "New-feature rules checked: {} checklist item(s) failing, {} flagged duplicate(s)", + checklist::failing(&facts.checklist).len(), + facts.duplicates.len() + ), + ) + .await; + return Ok((!facts.is_empty()).then_some(facts)); + } + rounds += 1; + let mut feedback = String::new(); + if !carried.is_empty() { + feedback.push_str("\nThe branch changes files only an earlier attempt's unrelated commits touched. Undo these changes (restore each file to the default branch's version) unless this ticket needs them:\n"); + for (p, from) in &carried { + feedback.push_str(&format!("- `{p}` (from {from})\n")); + } + } + if !missing.is_empty() { + feedback.push_str(®istration::feedback(&missing)); + } + if !dups.is_empty() { + feedback.push_str("\nNew code duplicates existing exported helpers. Call the existing helper instead and remove the new one, unless it is really different (then say why in your notes):\n"); + for d in &dups { + feedback.push_str(&format!("- {}\n", d.line())); + } + } + feedback.push_str(&checklist::feedback(&static_items)); + if !sandbox_failed.is_empty() { + feedback.push_str("\nThe verification checks fail:\n"); + for f in &sandbox_failed { + feedback.push_str(&format!("{f}\n")); + } + } + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + "New-feature rules found problems, fixing", + ) + .await; + let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "implement").await; + match super::implement::run( + w.state, + w.msg, + w.github, + w.plan, + w.branch, + w.rules, + w.repo_instructions, + Some(&feedback), + "medium", + w.provider, + usage, + w.file_cache, + Some(w.run_id), + None, + // Registrations and test maps live outside the diff. + false, + ) + .await + { + Ok(r) => evidence.merge(r.evidence), + Err(e) => return Err(format!("the fix round failed: {e}")), + } + let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "review").await; + } +} + +// ── the ready check ───────────────────────────────────────────────────── + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct ReadyRecord { + run_id: String, + facts: checklist::Facts, + maps: Vec, + sandbox_failed: Vec, + sha: String, +} + +fn ready_sk(repo: &str, pr: u64) -> String { + format!("FEATURE_READY#{repo}#{pr}") +} + +/// Records a feature pull request, so leaving draft waits for its +/// checklist. +pub async fn register_pr( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + pr: u64, + f: &PrFacts, +) { + if f.checklist.is_empty() { + return; + } + let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); + let r = ReadyRecord { + run_id: run_id.to_string(), + facts: f.facts.clone(), + maps: f.maps.clone(), + sandbox_failed: f + .sandbox_failed + .iter() + .filter(|l| !l.starts_with("Output:")) + .cloned() + .collect(), + sha: f.head.clone(), + }; + let ttl = (chrono::Utc::now() + chrono::Duration::days(60)).timestamp(); + if let Err(e) = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", super::attr_s(&msg.team_id)) + .item("sk", super::attr_s(&ready_sk(&repo, pr))) + .item( + "data", + super::attr_s(&serde_json::to_string(&r).unwrap_or_default()), + ) + .item( + "ttl", + aws_sdk_dynamodb::types::AttributeValue::N(ttl.to_string()), + ) + .send() + .await + { + warn!(error = %e, "Could not save the feature's ready check"); + } +} + +/// Why a feature pull request stays a draft, read from its head now: the +/// checklist's diff items fail, or the sandbox checks failed on this same +/// head. `None` when it may leave draft (or isn't a feature pull request). +pub async fn ready_hold( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + owner: &str, + repo: &str, + pr: u64, +) -> Option { + let full = format!("{owner}/{repo}"); + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", super::attr_s(team_id)) + .key("sk", super::attr_s(&ready_sk(&full, pr))) + .send() + .await + .ok()? + .item?; + let r: ReadyRecord = serde_json::from_str(item.get("data")?.as_s().ok()?).ok()?; + let p = github.get_pull_request(owner, repo, pr).await.ok()?; + let sha = p["head"]["sha"].as_str().unwrap_or("").to_string(); + let base = p["base"]["ref"].as_str().unwrap_or("main").to_string(); + if sha == r.sha && !r.sandbox_failed.is_empty() { + return Some(r.sandbox_failed.join("; ")); + } + let files = github + .compare_files_with_patches(owner, repo, &base, &sha) + .await + .ok()?; + let mut facts = r.facts.clone(); + facts.cases_added = checklist::unit_cases_added(&files); + facts.responsive_specs.clear(); + for s in &facts.specs { + if let Ok(t) = github.read_file(owner, repo, s, &sha).await { + if checklist::responsive_checked(&t) { + facts.responsive_specs.push(s.clone()); + } + } + } + let mut maps = Vec::new(); + for m in &r.maps { + if let Ok(t) = github.read_file(owner, repo, m, &sha).await { + maps.push((m.clone(), t)); + } + } + let new_specs: Vec = files + .iter() + .filter(|(p, s, _)| s == "added" && content::is_e2e_spec(p)) + .map(|(p, _, _)| p.clone()) + .collect(); + facts.map_missing = checklist::missing_from_test_maps(&maps, &new_specs) + .into_iter() + .map(|(m, s)| format!("{m}: {s}")) + .collect(); + let fails = checklist::failing(&checklist::static_items(&facts)); + if fails.is_empty() { + None + } else { + info!(pr, fails = ?fails, "Feature checklist fails; the PR stays a draft"); + Some(fails.join("; ")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn plan(design: &str, tasks: &str) -> PlanResult { + PlanResult { + proposal: String::new(), + design: design.into(), + tasks: tasks.into(), + spec: String::new(), + repo_tasks: vec![], + fix: None, + } + } + + #[test] + fn a_feature_plan_is_sent_back_for_reuse_and_sibling() { + let p = plan( + "## Approach\nx", + "- [ ] src/blocks/Quote.tsx: [create] The block\n", + ); + let gaps = plan_gaps(&p, TicketIntent::Feature, &prior::Found::default()); + assert_eq!(gaps.len(), 2); + // A bug plan isn't held to the feature sections. + assert!(plan_gaps(&p, TicketIntent::Bug, &prior::Found::default()).is_empty()); + // Nor is a plan that changes no code. + let p = plan("", "NO_CHANGES_NEEDED: already there"); + assert!(plan_gaps(&p, TicketIntent::Feature, &prior::Found::default()).is_empty()); + } + + #[test] + fn the_planner_is_told_the_feature_rules_only_for_features() { + let f = planner_block(TicketIntent::Feature); + assert!(f.contains(reuse::REUSE_HEADING)); + assert!(f.contains(reuse::SIBLING_HEADING)); + assert!(f.contains("Open product questions")); + let b = planner_block(TicketIntent::Bug); + assert!(!b.contains(reuse::REUSE_HEADING)); + assert!(b.contains("Open product questions")); + } + + #[test] + fn the_description_states_staging_content_and_the_checklist() { + let f = PrFacts { + attempts: vec!["#41 (o/r) \"Quote block\": closed".into()], + sibling: Some("src/blocks/Cards.tsx".into()), + registrations_checked: 2, + content: Some(content::Outcome::default()), + checklist: vec![checklist::Item::new( + "lint", + checklist::Status::Pass, + "`npm run lint` passed", + )], + questions: vec!["Who sees the block?".into()], + ..Default::default() + }; + let body = shape_body("## Summary\nAdds the block.".into(), &f); + assert!(body.contains("## Earlier attempts")); + assert!(body.contains("Follows the closest sibling: `src/blocks/Cards.tsx`")); + assert!(body.contains("## Staging content\n- No staging content was changed.")); + assert!(body.contains("## Verification checklist\n- [PASS] lint")); + assert!(body.contains("## Open product questions")); + // Added once. + assert_eq!(shape_body(body.clone(), &f), body); + } + + #[test] + fn a_missing_registration_outside_a_feature_is_flagged_not_claimed() { + let f = PrFacts { + registrations_checked: 2, + unregistered: vec!["`Quote` isn't registered in `e2e/test-map.json`".into()], + ..Default::default() + }; + let s = sections(&f); + assert!(s.contains("Flagged for review: `Quote` isn't registered")); + assert!(!s.contains("Registered in every place")); + } + + #[test] + fn new_body_starts_at_the_export() { + let patch = "+import x from 'y'\n+export function formatEventDate(d) {\n+ return d\n+}\n"; + assert!(new_body(patch, "formatEventDate").starts_with("export function formatEventDate")); + } +} diff --git a/services/worker/src/passes/feature/plan_files.rs b/services/worker/src/passes/feature/plan_files.rs new file mode 100644 index 000000000..6052543c7 --- /dev/null +++ b/services/worker/src/passes/feature/plan_files.rs @@ -0,0 +1,346 @@ +//! Rule 1: what each plan task does to its file, stated by the plan. +//! +//! A feature adds files. The repo check used to read "the plan names files +//! that don't exist" as a made-up plan and planned again, so a new-feature +//! run re-planned because its new files didn't exist yet. Every task now says +//! what it does to its path, after the colon: +//! +//! ```text +//! - [ ] src/blocks/Quote.tsx: [create] The quote block component +//! - [ ] src/blocks/index.ts: [modify] Register the quote block +//! - [ ] src/old/Legacy.tsx: [delete] Remove the unused block +//! - [ ] public/robots.txt: [replace] Write the file again from scratch +//! ``` +//! +//! Only `modify`, `delete` and `replace` paths must exist; a `create` path +//! must not (a plan that overwrites an existing file says `replace`). A task +//! without a tag keeps the old reading of its words, and the check holds +//! untagged paths to the old threshold. + +use std::collections::HashMap; + +/// What a task does to its file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FileAction { + Create, + Modify, + Delete, + /// Overwrites an existing file from scratch. + Replace, +} + +impl FileAction { + pub fn as_str(self) -> &'static str { + match self { + FileAction::Create => "create", + FileAction::Modify => "modify", + FileAction::Delete => "delete", + FileAction::Replace => "replace", + } + } + + /// Whether the path must exist before the change. + pub fn needs_existing(self) -> bool { + !matches!(self, FileAction::Create) + } + + fn parse(tag: &str) -> Option { + match tag.trim().to_ascii_lowercase().as_str() { + "create" | "new" | "add" => Some(FileAction::Create), + "modify" | "edit" | "update" | "change" => Some(FileAction::Modify), + "delete" | "remove" => Some(FileAction::Delete), + "replace" | "overwrite" | "rewrite" => Some(FileAction::Replace), + _ => None, + } + } +} + +/// One file the plan changes. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlannedFile { + pub path: String, + /// The task's tag. `None`: the task has none. + pub action: Option, + /// The untagged task's words read as creating the file (the old reading). + pub reads_new: bool, +} + +impl PlannedFile { + /// The file is new: tagged `create`, or untagged and worded as new. + pub fn is_new(&self) -> bool { + match self.action { + Some(a) => a == FileAction::Create, + None => self.reads_new, + } + } +} + +/// The `[tag]` a task description starts with, and the rest. +fn split_tag(desc: &str) -> (Option, &str) { + let d = desc.trim_start(); + if let Some(rest) = d.strip_prefix('[') { + if let Some((tag, after)) = rest.split_once(']') { + if let Some(a) = FileAction::parse(tag) { + return (Some(a), after.trim_start()); + } + } + } + (None, d) +} + +fn reads_new(desc: &str) -> bool { + let d = desc.to_lowercase(); + d.contains("create") + || d.contains("new file") + || d.contains("(new)") + || d.trim_start().starts_with("new ") + || d.trim_start().starts_with("add new") +} + +/// The path a checklist line names and its description, for +/// `- [ ] path: description` (and `- [ ] [create] path: description`, a tag +/// written before the path). +fn task_line(line: &str) -> Option<(String, Option, String)> { + let l = line.trim_start(); + let rest = l + .strip_prefix("- [ ]") + .or_else(|| l.strip_prefix("- [x]")) + .or_else(|| l.strip_prefix("- [X]")) + .or_else(|| l.strip_prefix("* [ ]"))?; + let (pre_tag, rest) = split_tag(rest); + let (head, desc) = rest.split_once(':')?; + let path = head.trim().trim_matches(|c| c == '`' || c == '*').trim(); + let looks_like_path = !path.is_empty() + && path.len() < 300 + && !path.chars().any(char::is_whitespace) + && (path.contains('/') || path.contains('.')) + && !path.contains("://"); + if !looks_like_path { + return None; + } + let (tag, desc) = split_tag(desc); + Some(( + path.trim_start_matches("./").to_string(), + tag.or(pre_tag), + desc.trim().to_string(), + )) +} + +/// Every file the checklist changes, deduped, in order. A path named by +/// several tasks takes the first tag given; `create` wins over an untagged +/// reading. +pub fn planned_files(tasks: &str) -> Vec { + let mut out: Vec = Vec::new(); + for line in tasks.lines() { + let Some((path, action, desc)) = task_line(line) else { + continue; + }; + let new = reads_new(&desc); + match out.iter_mut().find(|f| f.path == path) { + Some(f) => { + f.action = f.action.or(action); + f.reads_new |= new; + } + None => out.push(PlannedFile { + path, + action, + reads_new: new, + }), + } + } + out +} + +/// What is wrong with one planned path. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Problem { + /// Tagged modify, delete or replace, but the file isn't there. + Missing { path: String, action: FileAction }, + /// Tagged create, but the file is already there. + AlreadyExists { path: String }, +} + +impl Problem { + pub fn line(&self) -> String { + match self { + Problem::Missing { path, action } => format!( + "`{path}` is tagged [{}] but doesn't exist (tag it [create] if the task adds it)", + action.as_str() + ), + Problem::AlreadyExists { path } => format!( + "`{path}` is tagged [create] but already exists (tag it [modify], or [replace] to write it again)" + ), + } + } +} + +/// The problems with the tagged paths, given which paths exist (`exists`: +/// path to whether it is there; a path not in the map wasn't looked up and is +/// skipped). Untagged paths are never a problem here. +pub fn check(files: &[PlannedFile], exists: &HashMap) -> Vec { + let mut out = Vec::new(); + for f in files { + let (Some(action), Some(&there)) = (f.action, exists.get(&f.path)) else { + continue; + }; + if action.needs_existing() && !there { + out.push(Problem::Missing { + path: f.path.clone(), + action, + }); + } else if action == FileAction::Create && there { + out.push(Problem::AlreadyExists { + path: f.path.clone(), + }); + } + } + out +} + +/// The paths to look up: every path that must exist (tagged or untagged and +/// not new), then the tagged `create` paths, each list capped at `cap`. +pub fn paths_to_look_up(files: &[PlannedFile], cap: usize) -> (Vec, Vec) { + let existing: Vec = files + .iter() + .filter(|f| !f.is_new()) + .map(|f| f.path.clone()) + .take(cap) + .collect(); + let created: Vec = files + .iter() + .filter(|f| f.action == Some(FileAction::Create)) + .map(|f| f.path.clone()) + .take(cap) + .collect(); + (existing, created) +} + +/// The note a re-plan gets. +pub fn replan_note(missing: &[String], problems: &[Problem], repo: &str) -> String { + let mut out = String::from("\n\n---\n\n**Planning note (from CoderHelm):** "); + if !missing.is_empty() { + out.push_str(&format!( + "the previous plan for this ticket named files that don't exist in {repo}: {}. ", + missing.join(", ") + )); + } + if !problems.is_empty() { + out.push_str("Its task tags don't match the repository: "); + out.push_str( + &problems + .iter() + .map(Problem::line) + .collect::>() + .join("; "), + ); + out.push_str(". "); + } + out.push_str( + "Look the paths up with your tools. Tag every task with what it does to its file \ + (`- [ ] path: [create] ...`, `[modify]`, `[delete]` or `[replace]`): new files are \ + expected for a feature and are tagged [create]; only [modify], [delete] and [replace] \ + paths must exist. If the change doesn't belong in this repository, say so instead of \ + planning code.", + ); + out +} + +/// What the planner is told about the checklist's tags. +pub const PLANNER_FORMAT: &str = "`- [ ] : [] `, where \ + is `create` (a new file; the path must not exist yet), `modify`, `delete` or `replace` \ + (overwrite an existing file); e.g. `- [ ] src/resolvers/join.ts: [modify] Add optional \ + billingAddress param to OnlineJoin mutation`, `- [ ] src/blocks/Quote.tsx: [create] The \ + quote block component`. New files are expected for a feature: tag them [create]."; + +#[cfg(test)] +mod tests { + use super::*; + + const TASKS: &str = "\ +- [ ] src/blocks/Quote.tsx: [create] The quote block component +- [ ] src/blocks/index.ts: [modify] Register the quote block +- [ ] `src/old/Legacy.tsx`: [delete] Remove the old block +- [ ] public/robots.txt: [replace] Write it again +- [ ] src/lib/format.ts: Add a date helper +- [ ] src/blocks/Card.tsx: Create the card block +- [ ] [create] src/blocks/Card.test.tsx: Tests for the card block +- [ ] Not a path: something +"; + + #[test] + fn reads_each_tasks_action_from_its_tag() { + let f = planned_files(TASKS); + let by = |p: &str| f.iter().find(|x| x.path == p).unwrap().clone(); + assert_eq!(by("src/blocks/Quote.tsx").action, Some(FileAction::Create)); + assert_eq!(by("src/blocks/index.ts").action, Some(FileAction::Modify)); + assert_eq!(by("src/old/Legacy.tsx").action, Some(FileAction::Delete)); + assert_eq!(by("public/robots.txt").action, Some(FileAction::Replace)); + assert_eq!(by("src/lib/format.ts").action, None); + assert!(!by("src/lib/format.ts").is_new()); + // Untagged, worded as new: the old reading still counts. + assert!(by("src/blocks/Card.tsx").is_new()); + // A tag before the path is read too. + assert_eq!( + by("src/blocks/Card.test.tsx").action, + Some(FileAction::Create) + ); + assert_eq!(f.len(), 7); + } + + #[test] + fn new_files_of_a_feature_are_not_a_problem() { + // The real case: a feature's plan named files that don't exist yet. + let files = planned_files( + "- [ ] src/blocks/Quote.tsx: [create] The quote block\n\ + - [ ] src/blocks/Quote.test.tsx: [create] Its tests\n\ + - [ ] src/blocks/index.ts: [modify] Register it\n", + ); + let exists = HashMap::from([ + ("src/blocks/Quote.tsx".to_string(), false), + ("src/blocks/Quote.test.tsx".to_string(), false), + ("src/blocks/index.ts".to_string(), true), + ]); + assert!(check(&files, &exists).is_empty()); + let (existing, created) = paths_to_look_up(&files, 10); + assert_eq!(existing, vec!["src/blocks/index.ts"]); + assert_eq!(created.len(), 2); + } + + #[test] + fn a_modify_path_must_exist_and_a_create_path_must_not() { + let files = planned_files( + "- [ ] src/a.ts: [modify] Change it\n\ + - [ ] src/b.ts: [create] Add it\n\ + - [ ] src/c.ts: [replace] Rewrite it\n\ + - [ ] src/d.ts: Untagged and missing\n", + ); + let exists = HashMap::from([ + ("src/a.ts".to_string(), false), + ("src/b.ts".to_string(), true), + ("src/c.ts".to_string(), true), + ("src/d.ts".to_string(), false), + ]); + let p = check(&files, &exists); + assert_eq!( + p, + vec![ + Problem::Missing { + path: "src/a.ts".into(), + action: FileAction::Modify + }, + Problem::AlreadyExists { + path: "src/b.ts".into() + }, + ] + ); + let note = replan_note(&[], &p, "o/r"); + assert!(note.contains("[replace]")); + assert!(note.contains("`src/b.ts` is tagged [create] but already exists")); + } + + #[test] + fn a_path_not_looked_up_is_skipped() { + let files = planned_files("- [ ] src/a.ts: [modify] Change it\n"); + assert!(check(&files, &HashMap::new()).is_empty()); + } +} diff --git a/services/worker/src/passes/feature/prior.rs b/services/worker/src/passes/feature/prior.rs new file mode 100644 index 000000000..11fc88862 --- /dev/null +++ b/services/worker/src/passes/feature/prior.rs @@ -0,0 +1,790 @@ +//! Rule 2: earlier attempts at the same feature, read before planning. +//! +//! The ticket's history already holds every pull request that names the +//! ticket. A feature is often tried before under another ticket (a parent, +//! a related one) or with no pull request at all, on a branch that's still +//! there. Before planning, this looks for: +//! +//! - pull requests and branches that name the ticket or a ticket its text +//! names (a parent, a related ticket); +//! - pull requests whose title is close to the ticket's; +//! - branches whose name is close to the ticket's title. +//! +//! Each attempt's commits are read with their files. A commit that neither +//! names the ticket nor shares a word or a file with the attempt's own work +//! is unrelated (a merge of the default branch, a fix for something else +//! picked up on the way) and is never carried over: the planner is told so, +//! and the check before the pull request ([`carried_unrelated`]) refuses a +//! branch that holds files only those commits touched. The run always starts +//! from the default branch ([`fresh_base`]). Where an attempt and the ticket +//! differ, the ticket wins, and the plan lists the differences under +//! [`DIFFERENCES_HEADING`]. + +use std::collections::{BTreeSet, HashSet}; + +use tracing::warn; + +use crate::clients::github::GitHubClient; +use crate::passes::ticket_history::EarlierPr; + +/// The design.md heading the plan lists differences under. +pub const DIFFERENCES_HEADING: &str = "## Differences from earlier attempts"; +/// Most attempts read for one ticket. +const MAX_ATTEMPTS: usize = 5; +/// Most commits read per attempt. +const MAX_COMMITS: usize = 15; +/// Title similarity at or above which a pull request or branch counts. +const SIMILAR: f64 = 0.6; + +/// How an attempt is linked to the ticket. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Link { + /// Names the ticket itself. + Ticket, + /// Names a ticket the ticket's text names. + Related(String), + /// Its title or branch is close to the ticket's title (percent). + Similar(u32), +} + +impl Link { + fn words(&self) -> String { + match self { + Link::Ticket => "names this ticket".into(), + Link::Related(k) => format!("names the related ticket {k}"), + Link::Similar(p) => format!("its title is {p}% like this ticket's"), + } + } +} + +/// One commit of an attempt. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AttemptCommit { + pub sha: String, + pub message: String, + pub files: Vec, + /// A merge commit (two or more parents). + pub merge: bool, +} + +impl AttemptCommit { + fn short(&self) -> &str { + self.sha.get(..7).unwrap_or(&self.sha) + } + + fn subject(&self) -> &str { + self.message.lines().next().unwrap_or("").trim() + } +} + +/// An earlier attempt: a pull request, or a branch with none. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Attempt { + pub repo: String, + pub branch: String, + /// 0 for a branch with no pull request. + pub pr: u64, + pub title: String, + /// `open`, `merged`, `closed` (without merging) or `branch`. + pub state: String, + /// Why it ended, as far as its record says (who closed it, reviews). + pub why_ended: String, + pub link: Link, + /// Whether the branch is still there. + pub branch_present: bool, + pub commits: Vec, +} + +impl Attempt { + pub fn name(&self) -> String { + if self.pr > 0 { + format!("#{} ({})", self.pr, self.repo) + } else { + format!("branch `{}` ({})", self.branch, self.repo) + } + } + + /// How the plan may name it: the pull request number or the branch. + fn marks(&self) -> Vec { + let mut m = Vec::new(); + if self.pr > 0 { + m.push(format!("#{}", self.pr)); + m.push(format!("/pull/{}", self.pr)); + } + if !self.branch.is_empty() { + m.push(self.branch.clone()); + } + m + } +} + +/// What the run found before planning: the attempts, the ticket's keys +/// (its own first) and its title's words. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Found { + pub attempts: Vec, + pub keys: Vec, + pub words: BTreeSet, +} + +impl Found { + pub fn is_empty(&self) -> bool { + self.attempts.is_empty() + } + + pub fn note(&self) -> String { + planner_note(&self.attempts, &self.keys, &self.words) + } + + /// One line per attempt, for the pull request. + pub fn pr_lines(&self) -> Vec { + self.attempts + .iter() + .map(|a| { + let (own, unrelated) = classify(a, &self.keys, &self.words); + let mut l = format!("{} \"{}\": {}", a.name(), a.title.trim(), a.state); + if !a.why_ended.trim().is_empty() && a.state != "branch" { + l.push_str(&format!( + " ({})", + common::truncate_str(a.why_ended.trim(), 200) + )); + } + if !own.is_empty() { + l.push_str(&format!("; its own work touched {} file(s)", own.len())); + } + if !unrelated.is_empty() { + l.push_str(&format!( + "; {} unrelated commit(s) not carried over", + unrelated.len() + )); + } + l + }) + .collect() + } +} + +/// Jira-style keys a text names (`ABC-123`), in order, deduped. +pub fn ticket_keys(text: &str) -> Vec { + let mut out: Vec = Vec::new(); + let bytes = text.as_bytes(); + let mut i = 0; + while i < bytes.len() { + let start_ok = i == 0 || !bytes[i - 1].is_ascii_alphanumeric(); + if start_ok && bytes[i].is_ascii_uppercase() { + let mut j = i; + while j < bytes.len() && (bytes[j].is_ascii_uppercase() || bytes[j].is_ascii_digit()) { + j += 1; + } + let prefix_len = j - i; + if (2..=10).contains(&prefix_len) && j < bytes.len() && bytes[j] == b'-' { + let mut k = j + 1; + while k < bytes.len() && bytes[k].is_ascii_digit() { + k += 1; + } + let end_ok = k == bytes.len() || !bytes[k].is_ascii_alphanumeric(); + if k > j + 1 && end_ok { + let key = text[i..k].to_string(); + if !out.contains(&key) { + out.push(key); + } + i = k; + continue; + } + } + i = j.max(i + 1); + continue; + } + i += 1; + } + out +} + +const STOP: &[&str] = &[ + "the", + "and", + "for", + "with", + "from", + "into", + "this", + "that", + "add", + "adds", + "new", + "make", + "allow", + "support", + "should", + "when", + "page", + "feat", + "feature", + "fix", + "chore", + "coderhelm", + "update", + "ticket", +]; + +/// A title's significant words: lowercase, three letters or more, no stop +/// words. Splits on anything that isn't a letter or digit, so a branch name +/// (`feat/quote-block`) reads like a title. +pub fn words(text: &str) -> BTreeSet { + text.split(|c: char| !c.is_ascii_alphanumeric()) + .map(str::to_ascii_lowercase) + .filter(|w| { + w.len() >= 3 && !STOP.contains(&w.as_str()) && !w.chars().all(|c| c.is_ascii_digit()) + }) + .collect() +} + +/// How alike two word sets are (shared over all), 0 to 1. +pub fn similarity(a: &BTreeSet, b: &BTreeSet) -> f64 { + if a.is_empty() || b.is_empty() { + return 0.0; + } + let shared = a.intersection(b).count() as f64; + shared / a.union(b).count() as f64 +} + +fn names_key(text: &str, key: &str) -> bool { + !key.is_empty() && crate::passes::mentions_ticket(text, key) +} + +/// How a pull request or branch is linked to the ticket, if it is. +pub fn link_for( + texts: &[&str], + title: &str, + ticket_id: &str, + related: &[String], + ticket_words: &BTreeSet, +) -> Option { + if texts.iter().any(|t| names_key(t, ticket_id)) { + return Some(Link::Ticket); + } + for k in related { + if texts.iter().any(|t| names_key(t, k)) { + return Some(Link::Related(k.clone())); + } + } + let s = similarity(ticket_words, &words(title)); + (s >= SIMILAR).then(|| Link::Similar((s * 100.0).round() as u32)) +} + +/// The files an attempt's own work touched, and its commits that are +/// unrelated to the ticket. A commit is the attempt's own when its message +/// names the ticket (or a related one) or shares a word with the ticket's +/// title, or when it touches a file such a commit touched or whose path +/// shares a word with the title. A merge commit is never the attempt's own. +/// When no commit qualifies, every non-merge commit is taken as its own (an +/// attempt nothing can be told apart in). +pub fn classify( + a: &Attempt, + keys: &[String], + ticket_words: &BTreeSet, +) -> (Vec, Vec) { + let own_by_words = |c: &AttemptCommit| { + keys.iter().any(|k| names_key(&c.message, k)) + || !words(c.subject()).is_disjoint(ticket_words) + || c.files.iter().any(|f| !words(f).is_disjoint(ticket_words)) + }; + let mut own: Vec<&AttemptCommit> = a + .commits + .iter() + .filter(|c| !c.merge && own_by_words(c)) + .collect(); + if own.is_empty() { + own = a.commits.iter().filter(|c| !c.merge).collect(); + } + let mut files: BTreeSet = own.iter().flat_map(|c| c.files.iter().cloned()).collect(); + // A commit that touches the attempt's own files is part of it. + loop { + let before = files.len(); + for c in a.commits.iter().filter(|c| !c.merge) { + if c.files.iter().any(|f| files.contains(f)) { + files.extend(c.files.iter().cloned()); + } + } + if files.len() == before { + break; + } + } + let unrelated: Vec = a + .commits + .iter() + .filter(|c| c.merge || !c.files.iter().any(|f| files.contains(f))) + .cloned() + .collect(); + (files.into_iter().collect(), unrelated) +} + +/// The base a run's branch is made from: always the default branch, never an +/// earlier attempt's branch. +pub fn fresh_base<'a>(base: &'a str, default_branch: &'a str, attempts: &[Attempt]) -> &'a str { + if !default_branch.is_empty() && attempts.iter().any(|a| a.branch == base) { + default_branch + } else { + base + } +} + +/// What the planner is told. Empty without attempts. +pub fn planner_note( + attempts: &[Attempt], + keys: &[String], + ticket_words: &BTreeSet, +) -> String { + if attempts.is_empty() { + return String::new(); + } + let mut out = String::from( + "\n\n## Earlier attempts at this feature (read before planning)\n\ + These pull requests and branches look like earlier work on the same feature. For each: \ + say what it did and why it ended, reuse what fits (files, helpers, tests it named), and \ + never carry over its unrelated commits. Your branch starts fresh from the default \ + branch; nothing is copied from these branches unless your tasks write it. Where an \ + attempt and this ticket differ, the ticket wins: list every difference in design.md \ + under `", + ); + out.push_str(DIFFERENCES_HEADING); + out.push_str("`, naming each attempt by its pull request number or branch.\n"); + for a in attempts { + let (files, unrelated) = classify(a, keys, ticket_words); + out.push_str(&format!( + "- {} \"{}\" on branch `{}`: {}; {}{}.\n", + a.name(), + a.title.trim(), + a.branch, + a.state, + a.link.words(), + if a.branch_present { + "" + } else { + "; the branch is gone" + } + )); + if !a.why_ended.trim().is_empty() { + out.push_str(&format!(" Why it ended: {}\n", a.why_ended.trim())); + } + if !files.is_empty() { + out.push_str(&format!( + " Its own work touched: {}\n", + files + .iter() + .take(25) + .cloned() + .collect::>() + .join(", ") + )); + } + for c in unrelated.iter().take(10) { + out.push_str(&format!( + " UNRELATED commit {} \"{}\"{} touching {}: do not carry it over.\n", + c.short(), + c.subject(), + if c.merge { " (merge)" } else { "" }, + if c.files.is_empty() { + "no files".to_string() + } else { + c.files + .iter() + .take(8) + .cloned() + .collect::>() + .join(", ") + } + )); + } + } + out +} + +/// What the plan leaves out about the attempts: the differences heading, or +/// an attempt it never names. +pub fn plan_gaps(design: &str, plan_text: &str, attempts: &[Attempt]) -> Vec { + if attempts.is_empty() { + return Vec::new(); + } + let mut out = Vec::new(); + if !design.contains(DIFFERENCES_HEADING) { + out.push(format!( + "design.md has no `{DIFFERENCES_HEADING}` section: list where the earlier attempts and \ + this ticket differ (the ticket wins), what each did, why it ended and what you reuse." + )); + } + for a in attempts { + if !a.marks().iter().any(|m| plan_text.contains(m.as_str())) { + out.push(format!( + "The plan never names the earlier attempt {}: say what it did, why it ended, and \ + what you reuse from it.", + a.name() + )); + } + } + out +} + +/// Files the run's branch changes that only an earlier attempt's unrelated +/// commits touched, and that no plan task names: carried over, never asked +/// for. As (path, the attempt and commit it came from). +pub fn carried_unrelated( + changed: &[String], + planned: &[String], + attempts: &[Attempt], + keys: &[String], + ticket_words: &BTreeSet, +) -> Vec<(String, String)> { + let planned: HashSet<&str> = planned.iter().map(String::as_str).collect(); + let mut out = Vec::new(); + for a in attempts { + let (own, unrelated) = classify(a, keys, ticket_words); + for c in &unrelated { + for f in &c.files { + if changed.contains(f) + && !planned.contains(f.as_str()) + && !own.contains(f) + && !out.iter().any(|(p, _): &(String, String)| p == f) + { + out.push(( + f.clone(), + format!("{} commit {} \"{}\"", a.name(), c.short(), c.subject()), + )); + } + } + } + } + out +} + +/// The commits of a branch or pull request, with their files. +async fn read_commits( + github: &GitHubClient, + owner: &str, + name: &str, + default_branch: &str, + branch: &str, + pr: u64, + branch_present: bool, +) -> Vec { + let raw = if branch_present { + github + .compare_commits(owner, name, default_branch, branch, MAX_COMMITS) + .await + } else if pr > 0 { + github.list_pr_commits(owner, name, pr).await + } else { + return Vec::new(); + }; + let raw = match raw { + Ok(v) => v, + Err(e) => { + warn!(branch, pr, error = %e, "Could not read an earlier attempt's commits"); + return Vec::new(); + } + }; + let mut out = Vec::new(); + for c in raw.iter().take(MAX_COMMITS) { + let sha = c["sha"].as_str().unwrap_or("").to_string(); + if sha.is_empty() { + continue; + } + let files = github + .commit_files(owner, name, &sha) + .await + .unwrap_or_default(); + out.push(AttemptCommit { + message: c["commit"]["message"].as_str().unwrap_or("").to_string(), + merge: c["parents"].as_array().is_some_and(|p| p.len() > 1), + sha, + files, + }); + } + out +} + +fn why_ended(p: &EarlierPr) -> String { + let mut parts = Vec::new(); + match p.state.as_str() { + "closed" if !p.closed_by.is_empty() => parts.push(format!( + "closed without merging by {} on {}", + p.closed_by, + p.closed_on() + )), + "closed" => parts.push("closed without merging".to_string()), + "merged" => parts.push("merged".to_string()), + _ => parts.push("still open".to_string()), + } + if let Some((author, state, text)) = p.reviews.last() { + parts.push(format!( + "last review by {author} ({state}): {}", + common::truncate_str(text.trim(), 300) + )); + } + if let Some((author, text)) = p.comments.last() { + parts.push(format!( + "last comment by {author}: {}", + common::truncate_str(text.trim(), 300) + )); + } + parts.join("; ") +} + +/// What the run looks for, from the ticket. +pub struct Search<'a> { + pub owner: &'a str, + pub name: &'a str, + pub default_branch: &'a str, + pub ticket_id: &'a str, + pub title: &'a str, + pub body: &'a str, + /// The run's own branch: it is reset from the default branch anyway. + pub own_branch: &'a str, +} + +impl Search<'_> { + /// The ticket and the tickets its text names. + pub fn keys(&self) -> Vec { + let mut k = vec![self.ticket_id.to_string()]; + for x in ticket_keys(&format!("{}\n{}", self.title, self.body)) { + if !k.contains(&x) { + k.push(x); + } + } + k.retain(|x| !x.is_empty()); + k + } + + pub fn ticket_words(&self) -> BTreeSet { + words(self.title) + } +} + +/// Finds the earlier attempts in the run's repository. `known` are the pull +/// requests the ticket's history already read in full. Best-effort and +/// bounded: a list that can't be read adds nothing. +pub async fn gather(github: &GitHubClient, s: &Search<'_>, known: &[EarlierPr]) -> Vec { + let repo = format!("{}/{}", s.owner, s.name); + let keys = s.keys(); + let related: Vec = keys.iter().skip(1).cloned().collect(); + let tw = s.ticket_words(); + let branches: Vec = github + .list_branches(s.owner, s.name, 500) + .await + .unwrap_or_else(|e| { + warn!(repo, error = %e, "Could not list branches for earlier attempts"); + Vec::new() + }); + let mut out: Vec = Vec::new(); + // An open pull request isn't an earlier attempt: the run's open-PR + // handling works on it (or asks) before anything is planned. + let add_pr = |p: &EarlierPr, link: Link, out: &mut Vec| { + if p.state == "open" || out.iter().any(|a| a.pr == p.number) { + return; + } + out.push(Attempt { + repo: repo.clone(), + branch: p.branch.clone(), + pr: p.number, + title: p.title.clone(), + state: p.state.clone(), + why_ended: why_ended(p), + link, + branch_present: branches.contains(&p.branch), + commits: Vec::new(), + }); + }; + for p in known.iter().filter(|p| p.repo == repo) { + add_pr(p, Link::Ticket, &mut out); + } + // Pull requests that name a related ticket, or read like this one. + if let Ok(v) = github.list_pull_requests(s.owner, s.name, "all", 100).await { + for p in v.as_array().into_iter().flatten() { + let number = p["number"].as_u64().unwrap_or(0); + let title = p["title"].as_str().unwrap_or(""); + let branch = p["head"]["ref"].as_str().unwrap_or(""); + let body = p["body"].as_str().unwrap_or(""); + if number == 0 || out.iter().any(|a| a.pr == number) { + continue; + } + let Some(link) = link_for(&[title, branch, body], title, s.ticket_id, &related, &tw) + else { + continue; + }; + if let Some(full) = crate::passes::ticket_history::read_pr(github, &repo, number).await + { + add_pr(&full, link, &mut out); + } + if out.len() >= MAX_ATTEMPTS { + break; + } + } + } + // Branches with no pull request that name the ticket or read like it. + for b in &branches { + if out.len() >= MAX_ATTEMPTS { + break; + } + if b == s.default_branch || b == s.own_branch || out.iter().any(|a| &a.branch == b) { + continue; + } + if let Some(link) = link_for(&[b], b, s.ticket_id, &related, &tw) { + out.push(Attempt { + repo: repo.clone(), + branch: b.clone(), + pr: 0, + title: b.clone(), + state: "branch".into(), + why_ended: "a branch with no pull request".into(), + link, + branch_present: true, + commits: Vec::new(), + }); + } + } + out.truncate(MAX_ATTEMPTS); + for a in &mut out { + a.commits = read_commits( + github, + s.owner, + s.name, + s.default_branch, + &a.branch, + a.pr, + a.branch_present, + ) + .await; + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn commit(sha: &str, msg: &str, files: &[&str]) -> AttemptCommit { + AttemptCommit { + sha: sha.into(), + message: msg.into(), + files: files.iter().map(|f| f.to_string()).collect(), + merge: false, + } + } + + fn attempt(commits: Vec) -> Attempt { + Attempt { + repo: "o/web".into(), + branch: "feat/quote-block".into(), + pr: 41, + title: "Quote block for pages".into(), + state: "closed".into(), + why_ended: "closed without merging by sam on 2026-09-01".into(), + link: Link::Similar(75), + branch_present: true, + commits, + } + } + + #[test] + fn reads_ticket_keys_from_text() { + assert_eq!( + ticket_keys("Parent: WEB-12. Related to OPS-7 and WEB-12; not abc-1 or X-9"), + vec!["WEB-12", "OPS-7"] + ); + assert!(ticket_keys("no keys here, utf-8 is not one").is_empty()); + } + + #[test] + fn links_by_ticket_then_related_then_similar_title() { + let tw = words("Add a quote block to content pages"); + let rel = vec!["WEB-12".to_string()]; + assert_eq!( + link_for(&["WEB-40 quote"], "x", "WEB-40", &rel, &tw), + Some(Link::Ticket) + ); + assert_eq!( + link_for(&["feat/WEB-12-quote"], "x", "WEB-40", &rel, &tw), + Some(Link::Related("WEB-12".into())) + ); + assert!(matches!( + link_for( + &["feat/quote-block-content"], + "feat/quote-block-content", + "WEB-40", + &rel, + &tw + ), + Some(Link::Similar(_)) + )); + assert_eq!( + link_for(&["fix/login"], "fix/login", "WEB-40", &rel, &tw), + None + ); + } + + #[test] + fn unrelated_commits_are_told_apart_from_the_attempts_own_work() { + let mut merge = commit("m1", "Merge branch 'main'", &["src/pay/checkout.ts"]); + merge.merge = true; + let a = attempt(vec![ + commit("a1", "WEB-40 add quote block", &["src/blocks/Quote.tsx"]), + commit( + "a2", + "Register it", + &["src/blocks/index.ts", "src/blocks/Quote.tsx"], + ), + commit("b1", "Fix login redirect", &["src/auth/login.ts"]), + merge, + ]); + let keys = vec!["WEB-40".to_string()]; + let tw = words("Quote block"); + let (own, unrelated) = classify(&a, &keys, &tw); + assert_eq!(own, vec!["src/blocks/Quote.tsx", "src/blocks/index.ts"]); + let shas: Vec<&str> = unrelated.iter().map(|c| c.sha.as_str()).collect(); + assert_eq!(shas, vec!["b1", "m1"]); + + let note = planner_note(std::slice::from_ref(&a), &keys, &tw); + assert!(note.contains(DIFFERENCES_HEADING)); + assert!(note.contains("UNRELATED commit b1")); + assert!(note.contains("src/auth/login.ts")); + assert!(note.contains("closed without merging by sam")); + + // A branch that carries the login fix over is caught; a planned file + // isn't. + let changed = vec![ + "src/blocks/Quote.tsx".to_string(), + "src/auth/login.ts".to_string(), + "src/pay/checkout.ts".to_string(), + ]; + let carried = carried_unrelated( + &changed, + &["src/pay/checkout.ts".to_string()], + &[a], + &keys, + &tw, + ); + assert_eq!(carried.len(), 1); + assert_eq!(carried[0].0, "src/auth/login.ts"); + } + + #[test] + fn the_run_always_starts_from_the_default_branch() { + let a = attempt(vec![]); + assert_eq!( + fresh_base("feat/quote-block", "main", std::slice::from_ref(&a)), + "main" + ); + assert_eq!(fresh_base("main", "main", &[a]), "main"); + assert_eq!(fresh_base("develop", "main", &[]), "develop"); + } + + #[test] + fn the_plan_must_list_differences_and_name_each_attempt() { + let a = attempt(vec![]); + let gaps = plan_gaps("## Design\nstuff", "stuff", std::slice::from_ref(&a)); + assert_eq!(gaps.len(), 2); + let design = format!("{DIFFERENCES_HEADING}\n- #41 used a modal; the ticket asks inline"); + assert!(plan_gaps(&design, &design, &[a]).is_empty()); + assert!(plan_gaps("", "", &[]).is_empty()); + } +} diff --git a/services/worker/src/passes/feature/questions.rs b/services/worker/src/passes/feature/questions.rs new file mode 100644 index 000000000..dbaedd3ed --- /dev/null +++ b/services/worker/src/passes/feature/questions.rs @@ -0,0 +1,94 @@ +//! Rule 8: open product questions, raised and never decided. +//! +//! A question that blocks the change stops the run (the plan's +//! `CLARIFICATION_NEEDED:`). A product decision the ticket doesn't settle, +//! that the change can go ahead without (who sees a new block, which +//! audience a rule applies to), is different: the plan lists it in +//! design.md under [`HEADING`], the coder may add one with a line starting +//! [`NOTE_MARK`], and the pull request shows them all under the same +//! heading as questions for the team, with the change keeping the current +//! behaviour rather than deciding them. + +pub const HEADING: &str = "## Open product questions"; +/// A coder's note line that raises one. +pub const NOTE_MARK: &str = "Open product question:"; + +/// What the planner is told. +pub const PLANNER: &str = "If you find a product decision the ticket doesn't settle and the \ + change can go ahead without it (for example, which audience a rule applies to), do NOT \ + decide it: list it in design.md under `## Open product questions`, one `- ` line each, \ + saying what the change does meanwhile (keep current behaviour). Only a question that stops \ + the change belongs in CLARIFICATION_NEEDED."; + +fn clean(s: &str) -> String { + s.trim() + .trim_start_matches(['-', '*']) + .split_whitespace() + .collect::>() + .join(" ") +} + +/// The questions from the plan's design and the coder's notes, deduped. +pub fn collect(design: &str, notes: &str) -> Vec { + let mut out: Vec = Vec::new(); + let mut push = |q: String| { + let none = q.is_empty() || { + let l = q.to_lowercase(); + l == "none" || l.starts_with("none.") || l.starts_with("no open") + }; + if !none && !out.iter().any(|x| x.eq_ignore_ascii_case(&q)) { + out.push(q); + } + }; + if let Some(s) = super::reuse::section(design, HEADING) { + for l in s.lines() { + let t = l.trim_start(); + if t.starts_with("- ") || t.starts_with("* ") { + push(clean(t)); + } + } + } + for l in notes.lines() { + if let Some(q) = l + .trim_start() + .trim_start_matches(['-', '*', ' ']) + .strip_prefix(NOTE_MARK) + { + push(clean(q)); + } + } + out +} + +/// The description's section. Empty without questions. +pub fn markdown(qs: &[String]) -> String { + if qs.is_empty() { + return String::new(); + } + let mut s = format!( + "{HEADING}\nThe ticket doesn't settle these; this pull request doesn't decide them and \ + keeps the current behaviour. Please answer on the pull request:\n" + ); + for q in qs { + s.push_str(&format!("- {q}\n")); + } + s +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn collects_questions_from_the_plan_and_the_coder_once_each() { + let design = "## Approach\nx\n\n## Open product questions\n- Should members see the block, or everyone? Meanwhile: everyone, as today.\n- none\n\n## Reuse\n- a/b.ts\n"; + let notes = "Done.\nOpen product question: Should members see the block, or everyone? Meanwhile: everyone, as today.\n- Open product question: Does the filter remember the last venue?\n"; + let q = collect(design, notes); + assert_eq!(q.len(), 2); + assert!(q[1].starts_with("Does the filter")); + let md = markdown(&q); + assert!(md.starts_with(HEADING)); + assert!(md.contains("doesn't decide them")); + assert!(markdown(&[]).is_empty()); + } +} diff --git a/services/worker/src/passes/feature/registration.rs b/services/worker/src/passes/feature/registration.rs new file mode 100644 index 000000000..f05a2c87e --- /dev/null +++ b/services/worker/src/passes/feature/registration.rs @@ -0,0 +1,510 @@ +//! Rule 5: a new thing of a kind that exists is registered everywhere its +//! siblings are. +//! +//! A new CMS block, page-builder block, route, job, migration or flag file +//! usually has to appear in more places than its own file: a registry, an +//! index file, a query fragment, a map, a test map, the docs. Before the pull +//! request, for each item the change adds: +//! +//! 1. its siblings are the existing items of the same kind: files with the +//! same extension in the same folder, or, for an item that is a new +//! folder (`blocks/Quote/index.tsx`), the other folders beside it; +//! 2. the places that register them are the files that name most of the +//! siblings (a registry names all of them; a page that uses two of them +//! is not a registration), found by code search on the default branch; +//! 3. every such place must name the new item on the run's branch. +//! +//! What is missing goes back to the coder once with the list; what is still +//! missing blocks the pull request with the list. + +use std::collections::BTreeSet; + +use crate::clients::github::GitHubClient; +use crate::passes::feature::reuse::name_words; + +/// Most siblings sampled per item. +const MAX_SIBLINGS: usize = 8; +/// Most candidate files read per item. +const MAX_CANDIDATES: usize = 40; + +/// A thing the change adds. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NewItem { + /// Its name: the file stem, or the folder name for a folder item. + pub id: String, + /// The folder its siblings live in. + pub parent: String, + /// A folder item (`blocks/Quote/`), else a file item. + pub folder: bool, + /// File items: the extension siblings share. + pub ext: String, + /// The path that stands for it (the file, or the folder). + pub path: String, +} + +fn split_path(p: &str) -> (&str, &str) { + match p.rsplit_once('/') { + Some((d, f)) => (d, f), + None => ("", p), + } +} + +fn stem_ext(file: &str) -> (&str, &str) { + match file.split_once('.') { + Some((s, e)) => (s, e), + None => (file, ""), + } +} + +/// File names that stand for their folder. +const FOLDER_FILES: &[&str] = &[ + "index", "page", "route", "mod", "layout", "main", "__init__", +]; + +/// Paths that are never items or registration places. +fn skipped(p: &str) -> bool { + let l = p.to_lowercase(); + let (_, f) = split_path(&l); + l.ends_with(".lock") + || f == "package-lock.json" + || f == "pnpm-lock.yaml" + || f.starts_with("changelog") + || l.contains("node_modules/") + || l.contains("/dist/") + || l.contains("/build/") + || f.ends_with(".snap") + || f.ends_with(".map") + || f.ends_with(".min.js") +} + +fn is_test(p: &str) -> bool { + let l = p.to_lowercase(); + l.contains(".test.") + || l.contains(".spec.") + || l.contains("/__tests__/") + || l.contains(".stories.") +} + +/// The items the added files make. `added` are the paths the change adds; +/// `tree` is the default branch's file list. +pub fn new_items(added: &[String], tree: &[String]) -> Vec { + let mut out: Vec = Vec::new(); + for p in added { + if skipped(p) || is_test(p) { + continue; + } + let (dir, file) = split_path(p); + let (stem, ext) = stem_ext(file); + // The folder is new when the default branch has nothing under it. + let prefix = format!("{dir}/"); + let folder_is_new = !dir.is_empty() && !tree.iter().any(|t| t.starts_with(&prefix)); + let item = if folder_is_new || FOLDER_FILES.contains(&stem) { + let (parent, name) = split_path(dir); + if name.is_empty() || name.starts_with('[') || name.starts_with('(') { + continue; + } + NewItem { + id: name.to_string(), + parent: parent.to_string(), + folder: true, + ext: String::new(), + path: dir.to_string(), + } + } else { + NewItem { + id: stem.to_string(), + parent: dir.to_string(), + folder: false, + ext: ext.to_string(), + path: p.clone(), + } + }; + if !out.iter().any(|i| i.path == item.path) { + out.push(item); + } + } + out +} + +/// The existing items of the same kind, from the default branch's tree. The +/// plan's recorded sibling, when it is one of them, comes first. +pub fn siblings(item: &NewItem, tree: &[String], recorded: Option<&str>) -> Vec { + let prefix = if item.parent.is_empty() { + String::new() + } else { + format!("{}/", item.parent) + }; + let mut out: BTreeSet = BTreeSet::new(); + for t in tree { + let Some(rest) = t.strip_prefix(&prefix) else { + continue; + }; + if skipped(t) || is_test(t) { + continue; + } + if item.folder { + if let Some((name, _)) = rest.split_once('/') { + if name != item.id + && !name.starts_with('[') + && !name.starts_with('(') + && !name.starts_with('_') + { + out.insert(name.to_string()); + } + } + } else if !rest.contains('/') { + let (stem, ext) = stem_ext(rest); + if ext == item.ext && stem != item.id && !FOLDER_FILES.contains(&stem) { + out.insert(stem.to_string()); + } + } + } + let mut list: Vec = out.into_iter().collect(); + if let Some(r) = recorded { + let (dir, file) = split_path(r.trim_end_matches('/')); + let name = if item.folder { + if FOLDER_FILES.contains(&stem_ext(file).0) { + split_path(dir).1 + } else { + file + } + } else { + stem_ext(file).0 + }; + if let Some(i) = list.iter().position(|s| s == name) { + let s = list.remove(i); + list.insert(0, s); + } + } + list.truncate(MAX_SIBLINGS); + list +} + +/// The ways code names an item: as written, PascalCase, camelCase, +/// kebab-case and snake_case. +pub fn variants(id: &str) -> Vec { + let w = name_words(id); + let mut out = vec![id.to_string()]; + if !w.is_empty() { + let cap = |s: &str| { + let mut c = s.chars(); + c.next() + .map(|f| f.to_ascii_uppercase().to_string() + c.as_str()) + .unwrap_or_default() + }; + let pascal: String = w.iter().map(|x| cap(x)).collect(); + let camel = format!( + "{}{}", + w[0], + w[1..].iter().map(|x| cap(x)).collect::() + ); + out.push(pascal); + out.push(camel); + out.push(w.join("-")); + out.push(w.join("_")); + } + out.sort(); + out.dedup(); + out +} + +/// Whether `text` names `word` on its own (not inside a longer name). +fn names_word(text: &str, word: &str) -> bool { + if word.is_empty() { + return false; + } + let ok = |c: Option| c.is_none_or(|c| !(c.is_ascii_alphanumeric() || c == '_')); + let mut from = 0; + while let Some(i) = text[from..].find(word) { + let at = from + i; + if ok(text[..at].chars().next_back()) && ok(text[at + word.len()..].chars().next()) { + return true; + } + from = at + word.len(); + } + false +} + +/// Whether `text` names the item in any of its forms. +pub fn names_item(text: &str, id: &str) -> bool { + variants(id).iter().any(|v| names_word(text, v)) +} + +/// Whether a file is one of a sibling's own files (its folder, or its file). +fn sibling_own(path: &str, item: &NewItem, sibs: &[String]) -> bool { + let prefix = if item.parent.is_empty() { + String::new() + } else { + format!("{}/", item.parent) + }; + path.strip_prefix(&prefix).is_some_and(|rest| { + let first = rest.split('/').next().unwrap_or(""); + let stem = stem_ext(first).0; + sibs.iter().any(|s| s == first || s == stem) + }) +} + +/// The files that register items of this kind: those naming most sampled +/// siblings (all of them when there are three or fewer; otherwise at least +/// three and 60% of them). `files` are (path, default-branch text). +pub fn registration_places( + item: &NewItem, + sibs: &[String], + files: &[(String, String)], +) -> Vec { + if sibs.is_empty() { + return Vec::new(); + } + let n = sibs.len(); + let need = if n <= 3 { + n + } else { + 3usize.max((n * 3).div_ceil(5)) + }; + files + .iter() + .filter(|(p, _)| !skipped(p) && !sibling_own(p, item, sibs) && *p != item.path) + .filter(|(_, text)| sibs.iter().filter(|s| names_item(text, s)).count() >= need) + .map(|(p, _)| p.clone()) + .collect() +} + +/// A place a new item is missing from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Missing { + pub item: String, + pub path: String, + /// The siblings that place names, for the message. + pub siblings: Vec, +} + +impl Missing { + pub fn line(&self) -> String { + format!( + "`{}` isn't registered in `{}` (it names {})", + self.item, + self.path, + self.siblings + .iter() + .take(3) + .map(|s| format!("`{s}`")) + .collect::>() + .join(", ") + ) + } +} + +/// The places that don't name the item on the branch. `on_branch`: path to +/// the place's text on the run's branch (`None`: removed on the branch). +pub fn missing( + item: &NewItem, + sibs: &[String], + places: &[(String, String)], + on_branch: &dyn Fn(&str) -> Option, +) -> Vec { + let mut out = Vec::new(); + for (path, base_text) in places { + let Some(text) = on_branch(path) else { + continue; + }; + if !names_item(&text, &item.id) { + out.push(Missing { + item: item.id.clone(), + path: path.clone(), + siblings: sibs + .iter() + .filter(|s| names_item(base_text, s)) + .cloned() + .collect(), + }); + } + } + out +} + +/// What the coder is told. +pub fn feedback(missing: &[Missing]) -> String { + let mut s = String::from( + "\nThe change adds items of a kind that already exists, but doesn't register them \ + everywhere their siblings are registered. Add each one to these places, following how \ + the siblings appear there, then regenerate any generated files that list them:\n", + ); + for m in missing { + s.push_str(&format!("- {}\n", m.line())); + } + s +} + +/// Checks every new item. `added` are the change's added paths; `tree` is +/// the default branch's file list. Returns what is missing and how many +/// registration places were checked. +#[allow(clippy::too_many_arguments)] +pub async fn check( + github: &GitHubClient, + owner: &str, + repo: &str, + base: &str, + branch: &str, + added: &[String], + tree: &[String], + recorded_sibling: Option<&str>, +) -> (Vec, usize) { + let mut out: Vec = Vec::new(); + let mut checked = 0usize; + for item in new_items(added, tree).into_iter().take(6) { + let sibs = siblings(&item, tree, recorded_sibling); + if sibs.is_empty() { + continue; + } + let mut candidates: Vec = Vec::new(); + for s in sibs.iter().take(3) { + if let Ok(hits) = github.search_code(owner, repo, base, s).await { + for h in hits { + if !candidates.contains(&h.path) { + candidates.push(h.path); + } + } + } + } + candidates.retain(|p| !added.contains(p)); + candidates.truncate(MAX_CANDIDATES); + let mut files: Vec<(String, String)> = Vec::new(); + for p in candidates { + if let Ok(t) = github.read_file(owner, repo, &p, base).await { + files.push((p, t)); + } + } + let places: Vec<(String, String)> = { + let keep = registration_places(&item, &sibs, &files); + files + .into_iter() + .filter(|(p, _)| keep.contains(p)) + .collect() + }; + checked += places.len(); + let mut on_branch: Vec<(String, Option)> = Vec::new(); + for (p, _) in &places { + on_branch.push(( + p.clone(), + github.read_file(owner, repo, p, branch).await.ok(), + )); + } + let lookup = |p: &str| { + on_branch + .iter() + .find(|(q, _)| q == p) + .and_then(|(_, t)| t.clone()) + }; + for m in missing(&item, &sibs, &places, &lookup) { + if !out.iter().any(|x| x.item == m.item && x.path == m.path) { + out.push(m); + } + } + } + (out, checked) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tree() -> Vec { + [ + "src/blocks/Hero.tsx", + "src/blocks/Cards.tsx", + "src/blocks/Banner.tsx", + "src/blocks/Hero.test.tsx", + "src/blocks/index.ts", + "src/blocks/registry.ts", + "src/pages/home.tsx", + "src/queries/page.groq.ts", + "cms/schemas/hero/index.ts", + "cms/schemas/cards/index.ts", + "cms/schemas/index.ts", + "e2e/test-map.json", + ] + .iter() + .map(|s| s.to_string()) + .collect() + } + + #[test] + fn reads_file_items_and_folder_items() { + let added = vec![ + "src/blocks/Quote.tsx".to_string(), + "src/blocks/Quote.test.tsx".to_string(), + "cms/schemas/quote/index.ts".to_string(), + "package-lock.json".to_string(), + ]; + let items = new_items(&added, &tree()); + assert_eq!(items.len(), 2); + assert_eq!(items[0].id, "Quote"); + assert!(!items[0].folder); + assert_eq!(items[1].id, "quote"); + assert!(items[1].folder); + assert_eq!(items[1].parent, "cms/schemas"); + assert_eq!( + siblings(&items[0], &tree(), Some("src/blocks/Cards.tsx")), + vec!["Cards", "Banner", "Hero"] + ); + assert_eq!(siblings(&items[1], &tree(), None), vec!["cards", "hero"]); + } + + #[test] + fn names_items_in_any_case_style_but_not_inside_longer_names() { + assert_eq!( + variants("quoteBlock"), + vec!["QuoteBlock", "quote-block", "quoteBlock", "quote_block"] + ); + assert!(names_item("import QuoteBlock from './x'", "quote-block")); + assert!(names_item("_type == \"quoteBlock\"", "QuoteBlock")); + assert!(!names_item("HeroBanner", "Hero")); + } + + #[test] + fn a_registry_is_a_place_and_a_page_using_two_siblings_is_not() { + let item = &new_items(&["src/blocks/Quote.tsx".to_string()], &tree())[0]; + let sibs = siblings(item, &tree(), None); + let files = vec![ + ( + "src/blocks/index.ts".to_string(), + "export { Hero } from './Hero'\nexport { Cards } from './Cards'\nexport { Banner } from './Banner'\n".to_string(), + ), + ( + "src/pages/home.tsx".to_string(), + " ".to_string(), + ), + ( + "e2e/test-map.json".to_string(), + "{\"hero\": \"hero.spec.ts\", \"cards\": \"cards.spec.ts\", \"banner\": \"b.spec.ts\"}".to_string(), + ), + ( + "src/blocks/Hero.tsx".to_string(), + "Hero Cards Banner".to_string(), + ), + ]; + let places = registration_places(item, &sibs, &files); + assert_eq!(places, vec!["src/blocks/index.ts", "e2e/test-map.json"]); + + let placed: Vec<(String, String)> = files + .into_iter() + .filter(|(p, _)| places.contains(p)) + .collect(); + // The branch registered it in the index but not in the test map. + let branch = |p: &str| -> Option { + Some(match p { + "src/blocks/index.ts" => { + "export { Quote } from './Quote'\nexport { Hero } from './Hero'".to_string() + } + _ => "{\"hero\": \"hero.spec.ts\"}".to_string(), + }) + }; + let m = missing(item, &sibs, &placed, &branch); + assert_eq!(m.len(), 1); + assert_eq!(m[0].path, "e2e/test-map.json"); + assert!(m[0] + .line() + .contains("`Quote` isn't registered in `e2e/test-map.json`")); + assert!(feedback(&m).contains("regenerate")); + } +} diff --git a/services/worker/src/passes/feature/reuse.rs b/services/worker/src/passes/feature/reuse.rs new file mode 100644 index 000000000..fe558d114 --- /dev/null +++ b/services/worker/src/passes/feature/reuse.rs @@ -0,0 +1,488 @@ +//! Rules 3 and 4: reuse before writing, and mirror the closest sibling. +//! +//! A feature plan lists, in design.md: +//! +//! - under [`REUSE_HEADING`], the existing utilities, components, constants +//! and data-fetch functions it will reuse, found by searching the code for +//! similar names and behaviour (or says what it searched and found none); +//! - under [`SIBLING_HEADING`], when it adds a component, block, route, +//! handler or any file of a kind that already exists, the closest existing +//! one, by path, and what it copies from it: props, layout wrappers, +//! overflow and scroll handling, accessibility labels. +//! +//! [`plan_gaps`] holds the plan to both in code. Before the pull request, +//! the self-review flags new code that duplicates an existing exported +//! helper: the new exports are read from the diff ([`new_exports`]), +//! existing exports with similar names are found by code search +//! ([`similar_existing`]), and a model judges each pair ([`judge`]). + +use std::collections::BTreeSet; + +use serde::Deserialize; +use tracing::warn; + +use crate::agent::provider::{self, ModelProvider}; +use crate::models::TokenUsage; +use crate::WorkerState; + +pub const REUSE_HEADING: &str = "## Reuse"; +pub const SIBLING_HEADING: &str = "## Closest sibling"; + +/// The text under a `## Heading` (to the next `## ` heading), if present. +pub fn section<'a>(text: &'a str, heading: &str) -> Option<&'a str> { + let start = text + .lines() + .scan(0usize, |off, l| { + let at = *off; + *off += l.len() + 1; + Some((at, l)) + }) + .find(|(_, l)| l.trim().eq_ignore_ascii_case(heading)) + .map(|(at, l)| at + l.len() + 1)?; + let rest = text.get(start.min(text.len())..).unwrap_or(""); + let end = rest + .lines() + .scan(0usize, |off, l| { + let at = *off; + *off += l.len() + 1; + Some((at, l)) + }) + .find(|(_, l)| l.starts_with("## ")) + .map(|(at, _)| at) + .unwrap_or(rest.len()); + Some(&rest[..end]) +} + +/// Whether a section names a repository path (`a/b.ext` or `a/b/`). +fn names_path(s: &str) -> bool { + s.split(|c: char| c.is_whitespace() || matches!(c, '`' | '(' | ')' | ',' | ';')) + .any(|t| t.contains('/') && !t.contains("://") && t.len() > 2) +} + +/// The sibling path the plan recorded, the first path in its section. +pub fn recorded_sibling(design: &str) -> Option { + let s = section(design, SIBLING_HEADING)?; + s.split(|c: char| c.is_whitespace() || matches!(c, '`' | '(' | ')' | ',' | ';')) + .find(|t| t.contains('/') && !t.contains("://") && t.len() > 2) + .map(|t| t.trim_end_matches([':', '.']).to_string()) +} + +/// What a feature plan leaves out: the reuse list, and the sibling when it +/// creates files. +pub fn plan_gaps(design: &str, creates_files: bool) -> Vec { + let mut out = Vec::new(); + match section(design, REUSE_HEADING) { + Some(s) if names_path(s) || s.to_lowercase().contains("searched") => {} + _ => out.push(format!( + "design.md has no `{REUSE_HEADING}` section listing the existing utilities, \ + components, constants and data-fetch functions this change reuses, each with its \ + path (search the code for similar names and behaviour first; if none fits, say what \ + you searched)." + )), + } + if creates_files { + match section(design, SIBLING_HEADING) { + Some(s) if names_path(s) => {} + _ => out.push(format!( + "design.md has no `{SIBLING_HEADING}` section: this plan adds files, so name the \ + closest existing file of the same kind by path, and follow its structure and \ + usage exactly (props, layout wrappers, overflow and scroll handling, \ + accessibility labels)." + )), + } + } + out +} + +/// Names a line exports, by language. +fn exported_name(line: &str, path: &str) -> Option { + let l = line.trim_start(); + let ident = |s: &str| -> Option { + let n: String = s + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$') + .collect(); + (n.len() >= 3).then_some(n) + }; + let ext = path.rsplit('.').next().unwrap_or(""); + match ext { + "ts" | "tsx" | "js" | "jsx" | "mjs" | "cjs" | "vue" | "svelte" => { + let rest = l.strip_prefix("export ")?; + let rest = rest.strip_prefix("default ").unwrap_or(rest); + let rest = rest.strip_prefix("async ").unwrap_or(rest); + for kw in ["function* ", "function ", "const ", "let ", "class "] { + if let Some(r) = rest.strip_prefix(kw) { + return ident(r.trim_start()); + } + } + None + } + "rs" => { + let rest = l.strip_prefix("pub ")?; + let rest = rest.strip_prefix("async ").unwrap_or(rest); + for kw in ["fn ", "const ", "struct ", "enum "] { + if let Some(r) = rest.strip_prefix(kw) { + return ident(r.trim_start()); + } + } + None + } + "py" => { + // Top level only, and not private. + let r = line.strip_prefix("def ")?; + ident(r).filter(|n| !n.starts_with('_')) + } + "go" => { + let r = l.strip_prefix("func ")?; + let n = ident(r)?; + n.chars() + .next() + .is_some_and(|c| c.is_ascii_uppercase()) + .then_some(n) + } + _ => None, + } +} + +fn is_test_path(p: &str) -> bool { + let l = p.to_lowercase(); + l.contains(".test.") + || l.contains(".spec.") + || l.contains("/__tests__/") + || l.contains("/tests/") + || l.contains("/e2e/") + || l.starts_with("e2e/") + || l.starts_with("tests/") + || l.ends_with("_test.go") + || l.contains("/test_") +} + +/// The names the diff's added lines export, as (path, name), outside tests. +pub fn new_exports(files: &[(String, String, String)]) -> Vec<(String, String)> { + let mut out = Vec::new(); + for (path, status, patch) in files { + if status == "removed" || is_test_path(path) { + continue; + } + let removed: BTreeSet = patch + .lines() + .filter(|l| l.starts_with('-') && !l.starts_with("---")) + .filter_map(|l| exported_name(&l[1..], path)) + .collect(); + for l in patch.lines() { + if !l.starts_with('+') || l.starts_with("+++") { + continue; + } + if let Some(n) = exported_name(&l[1..], path) { + // A moved or re-signed export isn't new. + if !removed.contains(&n) && !out.iter().any(|(_, m)| m == &n) { + out.push((path.clone(), n)); + } + } + } + } + out +} + +/// The words of an identifier: `formatEventDate` and `format_event_date` +/// are both `format event date`. +pub fn name_words(name: &str) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + let chars: Vec = name.chars().collect(); + for (i, &c) in chars.iter().enumerate() { + let sep = !c.is_ascii_alphanumeric(); + let upper_start = c.is_ascii_uppercase() + && i > 0 + && (chars[i - 1].is_ascii_lowercase() + || chars[i - 1].is_ascii_digit() + || (chars[i - 1].is_ascii_uppercase() + && chars.get(i + 1).is_some_and(|n| n.is_ascii_lowercase()))); + if (sep || upper_start) && !cur.is_empty() { + out.push(std::mem::take(&mut cur)); + } + if !sep { + cur.push(c.to_ascii_lowercase()); + } + } + if !cur.is_empty() { + out.push(cur); + } + out.retain(|w| w.len() >= 2); + out +} + +/// How alike two identifiers' words are, 0 to 1. +pub fn name_similarity(a: &str, b: &str) -> f64 { + let a: BTreeSet = name_words(a).into_iter().collect(); + let b: BTreeSet = name_words(b).into_iter().collect(); + if a.is_empty() || b.is_empty() { + return 0.0; + } + a.intersection(&b).count() as f64 / a.union(&b).count() as f64 +} + +/// The search term for a new export: its longest word. +pub fn search_term(name: &str) -> Option { + name_words(name) + .into_iter() + .filter(|w| w.len() >= 4) + .max_by_key(|w| w.len()) +} + +/// An existing exported helper close to a new one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Candidate { + pub new_path: String, + pub new_name: String, + pub path: String, + pub name: String, + pub line: usize, +} + +/// Existing exports close to `new_name` among search hits (path, fragments +/// as `line: text`), outside the files the change touches. +pub fn similar_existing( + new_path: &str, + new_name: &str, + hits: &[(String, Vec)], + changed: &[String], +) -> Vec { + let mut out = Vec::new(); + for (path, frags) in hits { + if changed.contains(path) || is_test_path(path) { + continue; + } + for f in frags { + let Some((n, text)) = f.split_once(": ") else { + continue; + }; + let Some(name) = exported_name(text, path) else { + continue; + }; + if name_similarity(new_name, &name) >= 0.5 { + out.push(Candidate { + new_path: new_path.to_string(), + new_name: new_name.to_string(), + path: path.clone(), + name, + line: n.trim().parse().unwrap_or(1), + }); + } + } + } + out.truncate(4); + out +} + +/// One new helper the judge found duplicating an existing one. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct Duplicate { + pub new: String, + pub existing: String, + pub path: String, + #[serde(default)] + pub why: String, +} + +impl Duplicate { + pub fn line(&self) -> String { + format!( + "`{}` duplicates the existing `{}` in `{}`{}", + self.new, + self.existing, + self.path, + if self.why.trim().is_empty() { + String::new() + } else { + format!(": {}", self.why.trim()) + } + ) + } +} + +#[derive(Deserialize)] +struct Judged { + #[serde(default)] + duplicates: Vec, +} + +const SYSTEM: &str = "You review a code change for new helpers that duplicate existing ones. \ +For each pair you get the new code and an existing exported helper. A pair is a duplicate only \ +when the existing helper already does what the new code does (same inputs, same result) and \ +the new code could call it instead; similar names alone are not a duplicate. Answer with JSON \ +only: {\"duplicates\":[{\"new\":\"\",\"existing\":\"\",\"path\":\"\",\"why\":\"\"}]}; \ +an empty list when none is a duplicate."; + +/// The judge's prompt: each pair with both bodies. +pub fn prompt(pairs: &[(Candidate, String, String)]) -> String { + let mut out = String::from("Pairs to judge:\n"); + for (c, new_body, old_body) in pairs { + out.push_str(&format!( + "\n### New `{}` in `{}`\n```\n{}\n```\n### Existing `{}` in `{}`\n```\n{}\n```\n", + c.new_name, + c.new_path, + common::truncate_str(new_body, 2_500), + c.name, + c.path, + common::truncate_str(old_body, 2_500) + )); + } + out +} + +/// Reads the judge's reply; only pairs that were asked about count. +pub fn parse(reply: &str, asked: &[Candidate]) -> Vec { + let block = match reply.rfind("```json") { + Some(s) => { + let after = &reply[s + 7..]; + after.find("```").map(|e| &after[..e]).unwrap_or(after) + } + None => reply, + }; + let Ok(j) = serde_json::from_str::(block.trim()) else { + return Vec::new(); + }; + j.duplicates + .into_iter() + .filter(|d| { + asked + .iter() + .any(|c| c.new_name == d.new && c.name == d.existing && c.path == d.path) + }) + .collect() +} + +/// The model's verdict. Empty when it can't answer: a judge that can't +/// answer never flags anything. +pub async fn judge( + state: &WorkerState, + provider: &ModelProvider, + usage: &mut TokenUsage, + pairs: &[(Candidate, String, String)], +) -> Vec { + if pairs.is_empty() { + return Vec::new(); + } + let asked: Vec = pairs.iter().map(|(c, _, _)| c.clone()).collect(); + match provider::converse_simple( + state, + provider, + provider.primary_model_id(), + SYSTEM, + &prompt(pairs), + usage, + ) + .await + { + Ok(r) => parse(&r, &asked), + Err(e) => { + warn!(error = %e, "Duplicate-helper check errored"); + Vec::new() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_feature_plan_lists_what_it_reuses_and_its_sibling() { + let bare = "## Approach\nBuild it."; + assert_eq!(plan_gaps(bare, true).len(), 2); + assert_eq!(plan_gaps(bare, false).len(), 1); + let full = "## Reuse\n- `src/lib/date.ts` formatDate\n\n## Closest sibling\n\ + `src/blocks/Cards.tsx`: same props and the Section wrapper\n"; + assert!(plan_gaps(full, true).is_empty()); + assert_eq!( + recorded_sibling(full).as_deref(), + Some("src/blocks/Cards.tsx") + ); + // Searched and found nothing is an answer too. + let none = "## Reuse\nSearched for date and format helpers; none fits.\n"; + assert!(plan_gaps(none, false).is_empty()); + } + + #[test] + fn reads_new_exports_from_added_lines_only() { + let files = vec![ + ( + "src/lib/date.ts".to_string(), + "modified".to_string(), + "@@\n+export function formatEventDate(d: Date) {\n-export const oldThing = 1\n+export const oldThing = 2\n+const local = 1\n".to_string(), + ), + ( + "src/lib/date.test.ts".to_string(), + "added".to_string(), + "+export function helperForTests() {}\n".to_string(), + ), + ( + "src/api/mod.rs".to_string(), + "modified".to_string(), + "+pub async fn fetch_events() {}\n+fn private() {}\n".to_string(), + ), + ]; + assert_eq!( + new_exports(&files), + vec![ + ("src/lib/date.ts".to_string(), "formatEventDate".to_string()), + ("src/api/mod.rs".to_string(), "fetch_events".to_string()), + ] + ); + } + + #[test] + fn similar_names_across_styles_are_candidates() { + assert_eq!( + name_words("formatEventDate"), + vec!["format", "event", "date"] + ); + assert_eq!( + name_words("format_event_date"), + vec!["format", "event", "date"] + ); + assert_eq!(name_words("parseHTMLDate"), vec!["parse", "html", "date"]); + assert!(name_similarity("formatEventDate", "formatDate") >= 0.5); + assert_eq!(search_term("formatEventDate").as_deref(), Some("format")); + let hits = vec![ + ( + "src/utils/dates.ts".to_string(), + vec!["12: export function formatDate(d: Date): string {".to_string()], + ), + ( + "src/lib/date.ts".to_string(), + vec!["3: export function formatEventDate(d: Date) {".to_string()], + ), + ( + "src/utils/money.ts".to_string(), + vec!["4: export function formatMoney(n: number) {".to_string()], + ), + ]; + let c = similar_existing( + "src/lib/date.ts", + "formatEventDate", + &hits, + &["src/lib/date.ts".to_string()], + ); + assert_eq!(c.len(), 1); + assert_eq!(c[0].name, "formatDate"); + assert_eq!(c[0].line, 12); + } + + #[test] + fn the_judge_only_flags_pairs_it_was_asked_about() { + let asked = vec![Candidate { + new_path: "src/lib/date.ts".into(), + new_name: "formatEventDate".into(), + path: "src/utils/dates.ts".into(), + name: "formatDate".into(), + line: 12, + }]; + let reply = "```json\n{\"duplicates\":[{\"new\":\"formatEventDate\",\"existing\":\"formatDate\",\"path\":\"src/utils/dates.ts\",\"why\":\"same output\"},{\"new\":\"x\",\"existing\":\"y\",\"path\":\"z\"}]}\n```"; + let d = parse(reply, &asked); + assert_eq!(d.len(), 1); + assert!(d[0].line().contains("duplicates the existing `formatDate`")); + assert!(parse("not json", &asked).is_empty()); + } +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 4bf3308ce..db128f8e6 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -696,6 +696,7 @@ pub mod dlq_cleanup; pub mod e2e; pub mod e2e_setup; pub mod email_events; +pub mod feature; pub mod feedback; pub mod fix_location; pub mod formatter; @@ -1658,10 +1659,47 @@ async fn run_passes( // Compute context hash to detect ticket changes (body, images) let context_hash = plan::compute_ticket_context_hash(msg); + // Earlier attempts at the same feature in the run's repository (pull + // requests and branches for the ticket, the tickets it names, similar + // titles), read before planning; the run's branch always starts from + // the default branch, never from one of them (see feature::prior). + if !is_internal_ticket(&msg.ticket_id) && msg.continuation == 0 { + history.prior = feature::find_attempts(&github, msg, "", &history.prs).await; + if history + .prior + .attempts + .iter() + .any(|a| a.branch == msg.base_branch) + { + let default_branch = github + .get_default_branch(&msg.repo_owner, &msg.repo_name) + .await + .unwrap_or_default(); + let base = feature::prior::fresh_base( + &msg.base_branch, + &default_branch, + &history.prior.attempts, + ) + .to_string(); + msg.base_branch = base; + } + } + // The ticket's history (read before the repo was chosen) goes to the // planner. - if !history.is_empty() { - msg.ticket_history_note = Some(history.planner_note()); + if !history.prior.is_empty() { + info!( + run_id, + attempts = history.prior.attempts.len(), + "Earlier attempts at this feature — the planner gets them" + ); + } + if !history.is_empty() || !history.prior.is_empty() { + msg.ticket_history_note = Some(format!( + "{}{}", + history.planner_note(), + history.prior.note() + )); info!( run_id, earlier_runs = history.runs.len(), @@ -1888,27 +1926,29 @@ async fn run_passes( fix_location::route_for_plan(plan_result.fix.as_ref(), &plan_result.tasks), fix_location::Route::Code | fix_location::Route::CodeAndOutside ); - if codes && !v.missing_files.is_empty() { + if codes && (!v.missing_files.is_empty() || !v.file_problems.is_empty()) { info!( run_id, missing = ?v.missing_files, - "Plan names files that don't exist — planning again" + tags = ?v.file_problems, + "Plan names files that don't match the repository — planning again" ); add_progress_note( state, &msg.team_id, run_id, &format!( - "Plan named {} files that don't exist in {}/{} — planning again", - v.missing_files.len(), + "Plan named {} files that don't match {}/{} (missing, or new files that already exist) — planning again", + v.missing_files.len() + v.file_problems.len(), msg.repo_owner, msg.repo_name ), ) .await; let mut corrected = msg.clone(); - corrected.body.push_str(&missing_files_note( + corrected.body.push_str(&feature::plan_files::replan_note( &v.missing_files, + &v.file_problems, &format!("{}/{}", msg.repo_owner, msg.repo_name), )); plan_was_reused = false; @@ -1939,17 +1979,26 @@ async fn run_passes( ) .await; v.switch_repo = None; - if !v.missing_files.is_empty() { - warn!(run_id, missing = ?v.missing_files, "Plan still names files that don't exist — not implementing"); + if !v.missing_files.is_empty() || !v.file_problems.is_empty() { + warn!(run_id, missing = ?v.missing_files, tags = ?v.file_problems, "Plan still names files that don't match the repository — not implementing"); let decision = fix_location::FixDecision { fix_location: fix_location::FixLocation::Unknown, cause: format!( - "The plan for this ticket names files that don't exist in {}/{} ({}), \ + "The plan for this ticket names files that don't match {}/{} ({}), \ even after planning again, so I stopped before changing any code. \ The ticket may belong in another repository.", msg.repo_owner, msg.repo_name, - v.missing_files.join(", ") + v.missing_files + .iter() + .cloned() + .chain( + v.file_problems + .iter() + .map(feature::plan_files::Problem::line) + ) + .collect::>() + .join(", ") ), ..Default::default() }; @@ -3989,6 +4038,19 @@ async fn run_passes( }) .await .map_err(|why| format!("The failing-test rules blocked the pull request: {why}"))?; + // New-feature rules: nothing carried over from an earlier attempt, + // every registration, reuse, staging content, the verification + // checklist and open product questions (see feature). + let feature_pr = feature::gate( + &work, + &mut evidence, + usage, + triage_result.intent, + &history.prior, + || has_time_for_remediation(start), + ) + .await + .map_err(|why| format!("The new-feature rules blocked the pull request: {why}"))?; // --- Create Draft PR (triggers CI) --- check_cancelled(state, &msg.team_id, run_id).await?; @@ -4031,6 +4093,7 @@ async fn run_passes( log: log_ev.as_ref(), links: &links, test_fix: test_pr.as_ref(), + feature: feature_pr.as_ref(), }, &provider, usage, @@ -4573,6 +4636,8 @@ async fn run_repo_pipeline( log: repo_ev.as_ref(), links: &links, test_fix: test_pr.as_ref(), + // Multi-repo runs: the new-feature rules check single-repo runs. + feature: None, }, provider, usage, @@ -7272,17 +7337,9 @@ struct PlanValidation { /// Files the plan changes that don't exist in the repo (and aren't /// created by a task), when enough are missing to warn about. missing_files: Vec, -} - -/// The note a re-plan gets when the plan named files that don't exist. -fn missing_files_note(missing: &[String], repo: &str) -> String { - format!( - "\n\n---\n\n**Planning note (from CoderHelm):** the previous plan for this ticket named \ - files that don't exist in {repo}: {}. Look the paths up with your tools and plan only \ - with files that exist (or tasks that create them, marked as new). If the change doesn't \ - belong in this repository, say so instead of planning code.", - missing.join(", ") - ) + /// Tasks whose create/modify/delete/replace tag doesn't match the repo + /// (see `feature::plan_files`). + file_problems: Vec, } /// A file one plan task changes, read from the `- [ ] : ` @@ -7297,40 +7354,15 @@ struct PlanTaskFile { /// Files the plan's task checklist actually changes, deduped, in order. /// Empty when the tasks don't follow the checklist format. fn plan_task_files(tasks: &str) -> Vec { - let mut out: Vec = Vec::new(); - for line in tasks.lines() { - let l = line.trim_start(); - let Some(rest) = l - .strip_prefix("- [ ]") - .or_else(|| l.strip_prefix("- [x]")) - .or_else(|| l.strip_prefix("- [X]")) - else { - continue; - }; - let Some((head, desc)) = rest.split_once(':') else { - continue; - }; - let path = head.trim().trim_matches(|c| c == '`' || c == '*').trim(); - let looks_like_path = !path.is_empty() - && path.len() < 300 - && !path.chars().any(char::is_whitespace) - && (path.contains('/') || path.contains('.')); - if !looks_like_path { - continue; - } - let path = path.trim_start_matches("./").to_string(); - let d = desc.to_lowercase(); - let is_new = d.contains("create") - || d.contains("new file") - || d.contains("(new)") - || d.trim_start().starts_with("new ") - || d.trim_start().starts_with("add new"); - match out.iter_mut().find(|f| f.path == path) { - Some(f) => f.is_new |= is_new, - None => out.push(PlanTaskFile { path, is_new }), - } - } - out + // Each task's tag (`[create]`, `[modify]`, ...) says whether its file is + // new; an untagged task keeps the old reading of its words. + feature::plan_files::planned_files(tasks) + .into_iter() + .map(|f| PlanTaskFile { + is_new: f.is_new(), + path: f.path, + }) + .collect() } /// Appended to the ticket for the one narrowed re-plan. @@ -7363,6 +7395,8 @@ async fn validate_plan( let mut switch_repo: Option = None; let mut switch_reason = String::new(); let mut missing_files: Vec = Vec::new(); + // Whether each planned path looked up exists, for the task tags' check. + let mut exists: HashMap = HashMap::new(); // Extract file paths from plan text (design + tasks) let plan_text = format!("{}\n{}", plan.design, plan.tasks); @@ -7445,9 +7479,13 @@ async fn validate_plan( let sample: Vec<&String> = existing_expected.iter().take(10).copied().collect(); let mut missing = Vec::new(); for path in &sample { - match github.read_file(repo_owner, repo_name, path, "HEAD").await { - Ok(_) => {} - Err(_) => missing.push(path.to_string()), + let there = github + .read_file(repo_owner, repo_name, path, "HEAD") + .await + .is_ok(); + exists.insert(path.to_string(), there); + if !there { + missing.push(path.to_string()); } } files_here = missing.is_empty(); @@ -7751,6 +7789,29 @@ Respond with ONLY one line: either "CORRECT" or "SWITCH owner/name"."#, } } + // A task tagged [create] must not name a file that's already there; one + // tagged [modify], [delete] or [replace] must name one that is. + let planned = feature::plan_files::planned_files(&plan.tasks); + let (_, created) = feature::plan_files::paths_to_look_up(&planned, 10); + for path in created { + let there = github + .read_file(repo_owner, repo_name, &path, "HEAD") + .await + .is_ok(); + exists.insert(path, there); + } + let file_problems = feature::plan_files::check(&planned, &exists); + if !file_problems.is_empty() { + warnings.push(format!( + "Plan task tags don't match the repository: {}", + file_problems + .iter() + .map(feature::plan_files::Problem::line) + .collect::>() + .join("; ") + )); + } + PlanValidation { warnings, blocked, @@ -7759,6 +7820,7 @@ Respond with ONLY one line: either "CORRECT" or "SWITCH owner/name"."#, mentioned_file_count: changed_files.len(), over_cap, missing_files, + file_problems, } } diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 755287cd9..6d83f5f91 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -205,9 +205,10 @@ pub async fn run( Research the codebase using the provided tools, then generate an implementation plan.\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}\"`).{instructions_block}{team_block}{tests_block}", + To explore another repo, pass `repo` as `owner/name` (e.g. `\"{default_repo}\"`).{instructions_block}{team_block}{tests_block}{feature_block}", owner = msg.repo_owner, repo = msg.repo_name, + feature_block = super::feature::planner_block(intent), ); let complexity_guidance = match triage.complexity.as_str() { @@ -297,7 +298,7 @@ Otherwise, generate four openspec files: 1. **proposal.md** — Problem statement, proposed approach, scope boundaries, risks 2. **design.md** — Technical design: which files to modify/create (use full paths from repo root e.g. `src/services/payments.ts`), patterns to follow, data flow 3. **tasks.md** — Step-by-step implementation checklist. Each task MUST follow this format: - `- [ ] : ` (e.g. `- [ ] src/resolvers/join.ts: Add optional billingAddress param to OnlineJoin mutation`) + {task_format} Tasks should be atomic and ordered. Include the full file path from the repo root in every task. \ Only include tasks that can be accomplished by writing code (creating files, editing files, updating config). \ Do NOT include manual verification tasks, post-deploy checks, browser testing, or anything requiring human interaction. @@ -335,6 +336,7 @@ After researching, output the four files using this exact format: Then the ```fix_location.json block described above."#, fix_guidance = super::fix_location::planner_guidance(intent), + task_format = super::feature::plan_files::PLANNER_FORMAT, intent = intent.as_str(), title = msg.title, summary = triage.summary, @@ -717,6 +719,10 @@ Then the ```fix_location.json block described above."#, .iter() .map(super::plan_judge::PlanFinding::line), ); + // The new-feature rules' plan sections (see feature): earlier attempts, + // reuse and the closest sibling. + let feature_gaps = super::feature::plan_gaps(&draft, intent, &ticket_history.prior); + back.extend(feature_gaps.iter().cloned()); if !back.is_empty() { info!( ticket_id = %msg.ticket_id, @@ -820,6 +826,19 @@ Then the ```fix_location.json block described above."#, } }); } + if !feature_gaps.is_empty() { + let left = super::feature::plan_gaps(&files, intent, &ticket_history.prior); + if !left.is_empty() { + warn!(ticket_id = %msg.ticket_id, gaps = ?left, "Feature plan sections still missing after one send-back"); + super::add_progress_note( + state, + &msg.team_id, + run_id, + &format!("Plan check (new-feature rules): {}", left.join(" ")), + ) + .await; + } + } // What the plan's own check still finds after the send-back stays on // the decision: the ticket, the PR and the reviewer see it. if !plan_findings.is_empty() { diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index d96d375c8..fffd7ad33 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -42,6 +42,10 @@ pub struct Proof<'a> { /// For a failing- or flaky-test fix: the failure, the counts and the /// checks (see `test_fix`). pub test_fix: Option<&'a super::test_fix::PrFacts>, + /// For a new feature: earlier attempts, reuse and registration, staging + /// content, the verification checklist and open product questions (see + /// `feature`). + pub feature: Option<&'a super::feature::PrFacts>, } /// What the writer is told about the checks CI runs on the PR: never a @@ -486,6 +490,12 @@ Return ONLY the markdown body text."#, Some(t) => super::test_fix::shape_body(body_text, t), None => body_text, }; + // A feature's checklist, staging content and open questions are + // written from what the run checked, never by the writer. + let body_text = match proof.feature { + Some(f) => super::feature::shape_body(body_text, f), + None => body_text, + }; // Add issue link for GitHub tickets. // Strip any "Closes #N" the model may have included to avoid duplication. @@ -675,6 +685,11 @@ Return ONLY the markdown body text."#, if let Some(t) = proof.test_fix { super::test_fix::register_pr(state, msg, run_id, pr_number, t).await; } + // A feature stays a draft until its verification checklist passes (see + // `feature::ready_hold`). + if let Some(f) = proof.feature { + super::feature::register_pr(state, msg, run_id, pr_number, f).await; + } // Label CoderHelm's own PR at creation — this is the PR MAKER, so it owns the // PR's labels. Two things get added here, only when the reviewer is enabled for @@ -1913,6 +1928,7 @@ mod refresh_tests { log: None, links: "", test_fix: None, + feature: None, }; let owned = super::owned_sections(&plan, &proof, "acme/infra"); let body = assemble( diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index ea33728bb..19d6d5174 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -3179,6 +3179,13 @@ pub(crate) async fn mark_pr_ready( { return; } + // A new feature stays a draft until its verification checklist passes. + if super::feature::ready_hold(state, github, team_id, repo_owner, repo_name, pr_number) + .await + .is_some() + { + return; + } // With a team commit template, the final squash keeps the message the // run's first commit was given from it; otherwise the PR title, as always. let keep_first = super::load_git_conventions(state, team_id, "") diff --git a/services/worker/src/passes/review_eval.rs b/services/worker/src/passes/review_eval.rs index 722936197..cdf77adfd 100644 --- a/services/worker/src/passes/review_eval.rs +++ b/services/worker/src/passes/review_eval.rs @@ -1461,6 +1461,7 @@ fn review_eval_replays_every_run_case() { done_hash: String::new(), prs: vec![], decisions: vec![], + prior: Default::default(), }; // What the run does: the planner's route, then the history. let route = match history.guard(case.plan.as_ref(), &case.current_hash) { diff --git a/services/worker/src/passes/ticket_history.rs b/services/worker/src/passes/ticket_history.rs index ab2901f9b..22794ee02 100644 --- a/services/worker/src/passes/ticket_history.rs +++ b/services/worker/src/passes/ticket_history.rs @@ -74,6 +74,9 @@ pub struct TicketHistory { /// Choices people made on CoderHelm's notices (see /// `ticket_state::Decision`), oldest first. pub decisions: Vec, + /// Earlier attempts at the same feature in the run's repository, found + /// before planning (see `feature::prior`). + pub prior: crate::passes::feature::prior::Found, } /// An earlier pull request for the ticket, read from GitHub: what it said, @@ -707,7 +710,7 @@ pub async fn add_earlier_prs( } /// One pull request read in full. None when it can't be read. -async fn read_pr( +pub(crate) async fn read_pr( github: &crate::clients::github::GitHubClient, repo: &str, number: u64, @@ -950,6 +953,7 @@ mod tests { done_hash: String::new(), prs: vec![], decisions: vec![], + prior: Default::default(), } } @@ -1028,6 +1032,7 @@ mod tests { done_hash: "h1".into(), prs: vec![], decisions: vec![], + prior: Default::default(), }; match h.guard(Some(&override_plan("")), "h1") { Guard::Stop { @@ -1138,6 +1143,7 @@ mod traced_guard_tests { done_hash: String::new(), prs: vec![], decisions: vec![], + prior: Default::default(), } }