diff --git a/docs/coder-loop.md b/docs/coder-loop.md new file mode 100644 index 000000000..dbc1a5a98 --- /dev/null +++ b/docs/coder-loop.md @@ -0,0 +1,145 @@ +# The coder's loop + +How CoderHelm turns a ticket into a change: explore, measure, plan the smallest +change, implement, review it against the ticket, prove it. Each step has a check +in code, so the loop holds whatever the model writes. + +## Why + +Two pull requests show what went wrong. + +- **A data-pipeline ticket** asked to link four camps to a second sport. The plan + added a second map and helpers beside the existing overrides map, and made an + insert-only link sync replace and delete links. The build added warnings, three + counters and a log level change in shared code, plus a 432-line test with fake + hooks and an invented payload. The right change was four map entries, an insert + that does nothing on conflict, and one small test. +- **A web ticket's** end-to-end tests for a vendor's embedded portal were rewritten + three times, each time on a guess about the vendor's page. When a criterion met + the vendor's behaviour, the test was changed instead of the page. + +The causes were in the loop, not only in prompt wording: + +- The planner was told to use "2-4 tool calls" on a simple ticket and not to read + whole files. It never saw the map it should have extended. +- The data rules told every change that touched a pipeline to add counters and a + warning for each skip, and a fix round enforced it. +- Nothing compared the diff with the ticket. The scope checks compared files with + the plan, and the plan was already too wide. +- Nothing stopped the coder writing before it searched, or adding a twin of a + structure that was already there. +- Outside pages were never measured, and nothing caught a test bent to a vendor + against a criterion. + +## The loop + +1. **Explore.** Before the planner runs, the worker searches the repository for the + ticket's own names (backticked code, identifiers, quoted names, capitalised + names) and gives the planner the hits (`plan_shape::existing_for_ticket`). + The planner is told to read the structure it extends in full, along with its + writers and readers. + +2. **Measure.** The plan has a `## Measure first` section listing every outside + system the change or its tests rest on, and how each was measured: `probe_page` + for a page (from #734), a read-only lookup for data, or `None`. A plan for a + ticket about an embed, vendor, portal, webhook or partner that measured nothing + is sent back. + +3. **Plan the smallest change.** design.md has five sections: + - `## Reuse` + - `## Must not change` + - `## Measure first` + - `## Smallest change` + - `## Proof` + + `plan_shape::plan_gaps` sends the plan back when a section is missing. It also + sends it back when the plan: + - adds a name parallel to one it reuses or one the search found; + - deletes, overwrites, upserts or prunes when the ticket asks for none of that; + - changes logging or adds reporting the ticket doesn't ask for; + - would change a test to match an outside system while the ticket's acceptance + criteria say what the product must do. + + The Reuse section also says, for each helper that writes data, whether it + only inserts or replaces and deletes. The worker reads each reused helper's + body (`minimal_change::write_semantics`: a `DELETE`, an `ON CONFLICT DO + UPDATE`, a delete-then-insert, a relation `.set(`). A plan that reuses a + replacing helper on a path that only inserts today is sent back unless the + ticket asks to replace. The camps run's plan named the right map, then + reused the link helper that deletes every link it isn't given. + + Whatever is still open after the one send-back stays on the decision. + +4. **Implement.** In the coder's tool loop (`explore_guard`): + - The first write of a build is refused until a search has run and the write + names what it reuses (`reuses`). + - An edit that adds a top-level map, helper or config beside a similar existing + one is refused unless it says why (`why_new`). + + Both are kept as evidence lines. The coder's prompt carries the same rules + (`SMALLEST_CHANGE_RULES`). The data rules ask for reporting on a skip only when + the ticket asks for it. + +5. **Review against the ticket.** After the build, the habits check reads the diff + against the base and the ticket (`minimal_change::check`). It flags: + - parallel structures; + - deleting or overwriting semantics where the base only added; + - log level changes; + - new counters and log calls nobody asked for; + - tests out of proportion to the code; + - large fake payloads with no probe record. + + Each goes to the fix round as "make it smaller". A `Wider than the ticket: + : ` line keeps an item, except deletes and invented payloads: only + the ticket can ask for those. The reviewer runs the same check. Deletes, an + unobserved payload, and a test assertion flipped to an outside page's + behaviour against an acceptance criterion are required findings + (`review_rules::SMALLEST_RULE`). + +6. **Prove.** + The first round works out how the repository's CI installs and + runs its tests (`common::test_env`: the test job's working folder, Python + and Node versions, install steps and test steps). It records this on the + run (`test_setup`). Every sandbox build of every later round, and the proof + step's runs, restore that install from a cache named by the install steps + and the manifests' blob ids. Only the first build installs and saves it. + The coder is told the environment is ready and how the tests run. One run + reinstalled its dependencies eighteen times, about 25 minutes of builds. + + Each new or changed test runs in the sandbox with and without the + change (`habits_check`). A test the runner finds nothing in goes back to the + coder, and the coder quotes the run's output in its Evidence. End-to-end code + against another company's page uses only what a probe observed (#734). + +## What is deterministic + +Everything above except the model's own writing: the searches, section checks, +word checks, definition parsing, diff checks and refusals are plain code with unit +tests. `incidents::bz_smallest_change` replays both pull requests through the plan +gate, the coder's guard, the habits check and the reviewer. The plans and diffs +as they were are sent back; the small ones pass. + +## Sources + +- Claude Code best practices: explore, then plan, then code; give the agent a way + to verify; review against the spec. https://code.claude.com/docs/en/best-practices +- Claude prompting best practices: the minimum complexity the task needs; don't + touch code you weren't asked to change; tests check correctness and don't define + the solution. + https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices +- Building effective agents: ground truth from the environment at each step; tools + that are hard to misuse. https://www.anthropic.com/engineering/building-effective-agents +- SWE-agent: search tools, a bounded file viewer, and edits checked as they are + made. https://arxiv.org/abs/2405.15793 +- OpenHands: agents that browse and run code in a sandbox to see the real system. + https://arxiv.org/abs/2407.16741 +- Agentless: find the files, then the functions, then the lines, before editing; + keep only reproduction tests that fail on the original code. + https://arxiv.org/abs/2407.01489 +- Aider: a repository map so the model reuses what exists; edits that send only + the changed parts. https://aider.chat/docs/repomap.html, + https://aider.chat/docs/more/edit-formats.html +- Google engineering practices: one self-contained change per CL; reviewers look + for over-engineering and features nobody asked for. + https://google.github.io/eng-practices/review/developer/small-cls.html, + https://google.github.io/eng-practices/review/reviewer/looking-for.html diff --git a/docs/incidents/bz_smallest_change.md b/docs/incidents/bz_smallest_change.md new file mode 100644 index 000000000..f7cfdc7fc --- /dev/null +++ b/docs/incidents/bz_smallest_change.md @@ -0,0 +1,27 @@ +# bz. `bz_smallest_change` + +**What happened:** Two pull requests did far more than their tickets, and guessed where they should have measured. + +- **The camps ticket:** a data-pipeline ticket asked to link four camps to a second sport. + - The plan named the right overrides map, then reused the link helper that deletes every link it isn't given, on a sync that only inserted. Links nobody asked about were deleted. + - The build wrote a second map and helpers beside the existing one. + - It added counters, warnings and a log level change in shared code, because the data rules asked for reporting on any skip. + - It added a 432-line test with fake hooks and an invented payload. + - Every round reinstalled the test dependencies, about 25 minutes of builds in one run. +- **The portal ticket:** a web ticket's vendor end-to-end tests were written before anyone looked at the vendor's page, then rewritten on guesses. A criterion ("no double scrollbars") was met by changing the test to expect the vendor's behaviour instead of changing the page. + +**The guarantee:** + +- **Before planning:** the ticket's own names are searched and the hits go to the planner. +- **The plan:** it writes Reuse, Must not change, Measure first, Smallest change and Proof. + - The Reuse section says what each reused helper does to stored rows. This is read from the helper's body. + - The plan is sent back when it proposes: + - a structure parallel to an existing one; + - a replacing helper on a path that only inserts; + - deletes, overwrites, logging or reporting the ticket doesn't ask for; + - outside-page behaviour with nothing measured; + - a test change where a criterion says the product must change. +- **The coder:** its first write follows a search and names what it reuses. An edit that adds a twin of an existing map or helper is refused unless it says why. +- **After the build:** a diff wider than its ticket goes back to be made smaller. Only the ticket can excuse deletes where the base only added, or a payload no probe observed. +- **The reviewer:** it finds the same. A test bent to an outside page against a criterion is a required finding. +- **The test environment:** CI's install is found once per run, and every later sandbox build restores the cached install instead of installing again. diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 42463647e..b627a55ad 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -292,6 +292,7 @@ pub mod stop_judge; pub mod stop_rules; /// A team's run and PR-reviewed counts, each added exactly once. pub mod team_counts; +pub mod test_env; pub mod ticket_comments; /// A ticket's comments as CoderHelm read them, and whether its work is done. pub mod ticket_state; diff --git a/services/common/src/test_env.rs b/services/common/src/test_env.rs new file mode 100644 index 000000000..59603fd5f --- /dev/null +++ b/services/common/src/test_env.rs @@ -0,0 +1,575 @@ +//! How a repository's CI installs and runs its tests, found once and reused +//! by every sandbox command of the run. +//! +//! A data-pipeline run reinstalled its test dependencies eighteen times in +//! one run, about 25 minutes of sandbox builds. Each round started over: it +//! ran the test file bare, read the CI workflow, then tried `pip install` +//! lines until one worked. Each sandbox command is a fresh build, so nothing +//! carried over. +//! +//! Now: +//! +//! - [`from_workflows`] reads the CI job that runs the tests: its working +//! directory, Python and Node versions, the install steps before its first +//! test step, the test steps, and the plain environment values it sets. +//! - [`TestEnv::fingerprint`] names that install, from its steps and the +//! dependency manifests' blob ids. A changed requirements or lock file is +//! a new fingerprint and a fresh install. +//! - [`TestEnv::wrap`] puts a command inside the environment. With a cached +//! environment (`ENV_CACHE_GET_URL`) it is restored, and a Python install is +//! not run again; without one the install runs once and the result is +//! saved (`ENV_CACHE_PUT_URL`) for every later command, round and proof +//! step of the run. Python installs go into one virtual environment and +//! Node package managers keep their download store there, so the archive +//! is one folder. +//! - [`TestEnv::coder_note`] tells the coder the environment is ready, so it +//! runs the tests directly instead of reinstalling. + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +/// Where the environment lives in the sandbox; a test may move it. +pub const ENV_ROOT: &str = "/tmp/coderhelm-env"; + +/// The printed lines that say what the wrapper did. +pub const RESTORED: &str = "===CODERHELM_ENV_RESTORED==="; +pub const INSTALLED: &str = "===CODERHELM_ENV_INSTALLED==="; +pub const SAVED: &str = "===CODERHELM_ENV_SAVED==="; + +/// The language whose packages the install fills. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + Python, + Node, + #[default] + Other, +} + +/// How the repository's CI installs and runs its tests. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct TestEnv { + /// The workflow and job it came from. + pub source: String, + /// The folder the steps run in; "" for the repository root. + pub dir: String, + pub kind: Kind, + pub python: String, + pub node: String, + /// Plain `NAME=value` settings of the job (never an expression). + pub env: Vec<(String, String)>, + pub install: Vec, + pub test: Vec, + /// Files whose content decides the install (requirements, locks). + pub manifests: Vec, +} + +const INSTALL_WORDS: &[&str] = &[ + "pip install", + "pip3 install", + "uv pip install", + "uv sync", + "poetry install", + "pipenv install", + "npm ci", + "npm install", + "pnpm install", + "yarn install", + "bun install", + "corepack enable", +]; + +const LOCKS: &[&str] = &[ + "requirements.txt", + "requirement.txt", + "requirements-dev.txt", + "constraints.txt", + "pyproject.toml", + "poetry.lock", + "uv.lock", + "Pipfile.lock", + "package.json", + "package-lock.json", + "pnpm-lock.yaml", + "yarn.lock", + "bun.lockb", +]; + +fn s(v: Option<&serde_yaml::Value>) -> String { + match v { + Some(serde_yaml::Value::String(x)) => x.trim().to_string(), + Some(serde_yaml::Value::Number(n)) => n.to_string(), + _ => String::new(), + } +} + +fn plain_env(v: Option<&serde_yaml::Value>) -> Vec<(String, String)> { + let mut out = Vec::new(); + if let Some(m) = v.and_then(|x| x.as_mapping()) { + for (k, val) in m { + let (k, val) = (s(Some(k)), s(Some(val))); + let safe_key = + !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); + let low = k.to_ascii_lowercase(); + let secretish = ["token", "secret", "password", "key", "auth"] + .iter() + .any(|w| low.contains(w)); + if safe_key && !secretish && !val.contains("${{") && !val.contains('\n') { + out.push((k, val)); + } + } + } + out +} + +fn lines_of(run: &str) -> Vec { + run.lines() + .map(str::trim) + .filter(|l| !l.is_empty() && !l.starts_with('#')) + .map(str::to_string) + .collect() +} + +fn is_install(line: &str) -> bool { + let l = line.to_ascii_lowercase(); + INSTALL_WORDS.iter().any(|w| l.contains(w)) +} + +/// Files an install line reads (`-r`, `-c`, `--constraint`, `--requirement`). +fn named_files(line: &str) -> Vec { + let t: Vec<&str> = line.split_whitespace().collect(); + let mut out = Vec::new(); + for (i, w) in t.iter().enumerate() { + let next = t.get(i + 1).map(|x| x.trim_matches(['"', '\''])); + match *w { + "-r" | "-c" | "--constraint" | "--requirement" => { + if let Some(f) = next.filter(|f| !f.contains("://") && !f.contains('$')) { + out.push(f.to_string()); + } + } + _ => {} + } + } + out +} + +fn join(dir: &str, f: &str) -> String { + let f = f.trim_start_matches("./"); + if dir.is_empty() || f.starts_with('/') { + f.to_string() + } else { + format!("{}/{f}", dir.trim_end_matches('/')) + } +} + +/// The repository's test environment, from its workflow files +/// (`(path, text)`): the first job with a test step, its setup before that +/// step, and its test steps. `None` when no job runs tests. +pub fn from_workflows(workflows: &[(String, String)], tree: &[String]) -> Option { + for (path, text) in workflows { + let Ok(doc) = serde_yaml::from_str::(text) else { + continue; + }; + let Some(jobs) = doc.get("jobs").and_then(|j| j.as_mapping()) else { + continue; + }; + for (name, job) in jobs { + let Some(steps) = job.get("steps").and_then(|x| x.as_sequence()) else { + continue; + }; + let mut env = TestEnv { + source: format!("{path} ({})", s(Some(name))), + dir: s(job + .get("defaults") + .and_then(|d| d.get("run")) + .and_then(|r| r.get("working-directory"))) + .trim_start_matches("./") + .trim_end_matches('/') + .to_string(), + env: plain_env(doc.get("env")), + ..Default::default() + }; + env.env.extend(plain_env(job.get("env"))); + let mut seen_test = false; + for step in steps { + let uses = s(step.get("uses")).to_ascii_lowercase(); + if uses.starts_with("actions/setup-python") { + env.python = s(step.get("with").and_then(|w| w.get("python-version"))); + } + if uses.starts_with("actions/setup-node") { + env.node = s(step.get("with").and_then(|w| w.get("node-version"))); + } + let run = s(step.get("run")); + if run.is_empty() || run.contains("${{") { + continue; + } + let dir = s(step.get("working-directory")) + .trim_start_matches("./") + .to_string(); + for line in lines_of(&run) { + let line = if dir.is_empty() { + line + } else { + format!("(cd {dir} && {line})") + }; + if crate::ci_cover::is_check_command(&line) && !is_install(&line) { + seen_test = true; + env.test.push(line); + env.env.extend(plain_env(step.get("env"))); + } else if is_install(&line) && !seen_test { + env.install.push(line); + } + } + } + if env.test.is_empty() { + continue; + } + let all = format!("{} {}", env.install.join(" "), env.test.join(" ")).to_lowercase(); + env.kind = if !env.python.is_empty() + || ["pip", "pytest", "python", "poetry", "uv "] + .iter() + .any(|w| all.contains(w)) + { + Kind::Python + } else if !env.node.is_empty() + || ["npm", "pnpm", "yarn", "npx", "vitest", "jest"] + .iter() + .any(|w| all.contains(w)) + { + Kind::Node + } else { + Kind::Other + }; + let mut manifests: Vec = env + .install + .iter() + .flat_map(|l| named_files(l)) + .map(|f| join(&env.dir, &f)) + .collect(); + for l in LOCKS { + let p = join(&env.dir, l); + if tree.iter().any(|t| t == &p) { + manifests.push(p); + } + } + manifests.sort(); + manifests.dedup(); + env.manifests = manifests; + env.env.sort(); + env.env.dedup(); + return Some(env); + } + } + None +} + +fn quote(s: &str) -> String { + format!("'{}'", s.replace('\'', "'\\''")) +} + +impl TestEnv { + /// The install's name: its steps, versions and the manifests' blob ids + /// (`shas`: `(path, blob sha)` from the tree at the head). + pub fn fingerprint(&self, shas: &[(String, String)]) -> String { + let mut h = Sha256::new(); + h.update(self.dir.as_bytes()); + h.update(self.python.as_bytes()); + h.update(self.node.as_bytes()); + for l in &self.install { + h.update(l.as_bytes()); + h.update(b"\n"); + } + for m in &self.manifests { + let sha = shas + .iter() + .find(|(p, _)| p == m) + .map(|(_, s)| s.as_str()) + .unwrap_or("-"); + h.update(format!("{m}={sha}\n").as_bytes()); + } + hex::encode(&h.finalize()[..12]) + } + + /// Whether a restored environment is complete: a Python install lives + /// whole in the virtual environment; a Node install keeps only the + /// package store there and runs again (fast, from the store). + pub fn restore_is_complete(&self) -> bool { + self.kind == Kind::Python + } + + fn activate(&self) -> String { + let mut out = vec![format!( + "export E=\"${{CODERHELM_ENV:-{ENV_ROOT}}}\"; mkdir -p \"$E\"" + )]; + for (k, v) in &self.env { + out.push(format!("export {k}={}", quote(v))); + } + match self.kind { + Kind::Python => { + if !self.python.is_empty() { + out.push(format!( + "(command -v pyenv >/dev/null 2>&1 && pyenv global {} >/dev/null 2>&1) || true", + quote(&self.python) + )); + } + out.push( + "[ -x \"$E/venv/bin/python\" ] || python3 -m venv \"$E/venv\"; . \"$E/venv/bin/activate\"" + .to_string(), + ); + } + Kind::Node => { + out.push( + "export npm_config_cache=\"$E/npm\" npm_config_store_dir=\"$E/pnpm-store\" YARN_CACHE_FOLDER=\"$E/yarn\"" + .to_string(), + ); + if !self.node.is_empty() { + out.push(format!( + "n {} >/dev/null 2>&1 || true; hash -r", + quote(&self.node) + )); + } + } + Kind::Other => {} + } + out.join("\n") + } + + /// `command` run inside the environment. The script restores the cached + /// environment when `ENV_CACHE_GET_URL` is set and fetches, installs + /// otherwise (or after a Node restore), saves a fresh install when + /// `ENV_CACHE_PUT_URL` is set, then runs `command` and exits with its + /// code. + pub fn wrap(&self, command: &str) -> String { + self.wrap_with(command, self.restore_is_complete()) + } + + /// [`Self::wrap`], saying whether a restored environment is complete. + pub fn wrap_with(&self, command: &str, complete: bool) -> String { + let install = if self.install.is_empty() { + "true".to_string() + } else { + self.install.join(" && ") + }; + let cd = if self.dir.is_empty() { + String::new() + } else { + format!("cd {} || exit 1\n", quote(&self.dir)) + }; + let complete = if complete { "1" } else { "" }; + format!( + r#"export E="${{CODERHELM_ENV:-{ENV_ROOT}}}"; mkdir -p "$E" +ROOT="$PWD" +RESTORED="" +if [ -n "$ENV_CACHE_GET_URL" ] && curl -fsS --retry 2 --noproxy "*" -o /tmp/coderhelm-env.tgz "$ENV_CACHE_GET_URL" 2>/dev/null && tar xzf /tmp/coderhelm-env.tgz -C "$E"; then + RESTORED=1; echo "{RESTORED}" +fi +{activate} +{cd}if [ -z "$RESTORED" ] || [ -z "{complete}" ]; then + ( {install} ) >/tmp/coderhelm-install.log 2>&1; ICODE=$?; tail -5 /tmp/coderhelm-install.log + if [ $ICODE -eq 0 ] && [ -z "$RESTORED" ]; then + echo "{INSTALLED}" + if [ -n "$ENV_CACHE_PUT_URL" ] && tar czf /tmp/coderhelm-env-out.tgz -C "$E" . && curl -fsS --retry 2 --noproxy "*" -T /tmp/coderhelm-env-out.tgz "$ENV_CACHE_PUT_URL"; then echo "{SAVED}"; fi + fi +fi +cd "$ROOT" +bash -c {cmd}"#, + activate = self.activate(), + cmd = quote(command), + ) + } + + /// What the coder is told: the environment is ready in every command, + /// and how the tests run. + pub fn coder_note(&self) -> String { + format!( + "\n\n## The test environment (from CI: {})\nEvery sandbox command you run starts with this repository's test environment installed (CoderHelm installs it once per run and reuses it in every round). Don't reinstall dependencies: run the tests directly{}:\n{}\n", + self.source, + if self.dir.is_empty() { + String::new() + } else { + format!(" from `{}`", self.dir) + }, + self.test + .iter() + .map(|t| format!("- `{t}`")) + .collect::>() + .join("\n") + ) + } + + /// One line for the run's notes. + pub fn summary(&self) -> String { + format!( + "Test environment from {}: install `{}`; tests `{}`", + self.source, + if self.install.is_empty() { + "nothing".to_string() + } else { + self.install.join(" && ") + }, + self.test.join(" && ") + ) + } +} + +/// The S3 key of a cached environment: one per team, repository and +/// fingerprint, so later rounds and runs of the same install reuse it. +pub fn cache_key(team: &str, repo: &str, fingerprint: &str) -> String { + let safe = |x: &str| -> String { + x.chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '-' { + c + } else { + '_' + } + }) + .collect() + }; + format!("env-cache/{}/{}/{fingerprint}.tgz", safe(team), safe(repo)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const PY: &str = r#" +name: Tests +on: [pull_request] +env: + PYTHONHASHSEED: "0" + GH_TOKEN: ${{ secrets.X }} +jobs: + tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - run: | + pip install 'apache-airflow[postgres]==2.10.3' -c dags/constraints-3.11.txt + pip install -r requirement.txt + - run: for t in tests/test_*.py; do python "$t" || exit 1; done + name: Run tests + - run: python -m pytest tests +"#; + + #[test] + fn the_test_job_is_read_from_ci() { + let tree = vec![ + "requirement.txt".to_string(), + "dags/constraints-3.11.txt".to_string(), + ]; + let e = + from_workflows(&[(".github/workflows/tests.yml".into(), PY.into())], &tree).unwrap(); + assert_eq!(e.kind, Kind::Python); + assert_eq!(e.python, "3.11"); + assert_eq!(e.install.len(), 2); + assert!(e.test.iter().any(|t| t.contains("pytest"))); + assert_eq!(e.env, vec![("PYTHONHASHSEED".to_string(), "0".to_string())]); + assert_eq!( + e.manifests, + vec!["dags/constraints-3.11.txt", "requirement.txt"] + ); + // A changed requirements file is a new install. + let a = e.fingerprint(&[("requirement.txt".into(), "aaa".into())]); + let b = e.fingerprint(&[("requirement.txt".into(), "bbb".into())]); + assert_ne!(a, b); + assert_eq!( + a, + e.fingerprint(&[("requirement.txt".into(), "aaa".into())]) + ); + assert!(e.coder_note().contains("Don't reinstall")); + assert!(cache_key("TEAM#x", "o/r", &a).starts_with("env-cache/TEAM_x/o_r/")); + } + + #[test] + fn a_node_job_with_a_working_directory() { + let wf = "jobs:\n web:\n defaults:\n run:\n working-directory: ./apps/web\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: 20\n - run: corepack enable && pnpm install --frozen-lockfile\n - run: pnpm vitest run\n"; + let e = from_workflows( + &[("ci.yml".into(), wf.into())], + &["apps/web/pnpm-lock.yaml".to_string()], + ) + .unwrap(); + assert_eq!(e.kind, Kind::Node); + assert_eq!(e.dir, "apps/web"); + assert_eq!(e.node, "20"); + assert_eq!(e.manifests, vec!["apps/web/pnpm-lock.yaml"]); + assert!(!e.restore_is_complete()); + assert!(e.wrap("pnpm vitest run").contains("cd 'apps/web'")); + // No job with a test step: nothing. + assert!(from_workflows( + &[( + "d.yml".into(), + "jobs:\n d:\n steps:\n - run: echo hi\n".into() + )], + &[] + ) + .is_none()); + } + + /// The second round restores the first round's install instead of + /// installing again. Runs the real script with bash, tar and curl (file + /// URLs stand in for the presigned ones). + #[test] + fn a_second_round_restores_instead_of_reinstalling() { + for tool in ["bash", "tar", "curl"] { + if std::process::Command::new(tool) + .arg("--version") + .output() + .is_err() + { + return; + } + } + let dir = std::env::temp_dir().join(format!("coderhelm-env-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("repo")).unwrap(); + let log = dir.join("installs.log"); + let cache = dir.join("cache.tgz"); + let env = TestEnv { + source: "ci.yml (tests)".into(), + kind: Kind::Other, + install: vec![format!( + "echo install >> {} && echo ready > \"$E/marker\"", + log.display() + )], + test: vec!["true".into()], + ..Default::default() + }; + // A complete restore (as for Python), without needing Python here. + let script = env.wrap_with("cat \"$E/marker\"", true); + let run = |get: Option<&std::path::Path>, put: Option<&std::path::Path>, env_root: &str| { + let mut c = std::process::Command::new("bash"); + c.arg("-c") + .arg(&script) + .current_dir(dir.join("repo")) + .env("CODERHELM_ENV", dir.join(env_root)); + match get { + Some(p) => c.env("ENV_CACHE_GET_URL", format!("file://{}", p.display())), + None => c.env_remove("ENV_CACHE_GET_URL"), + }; + match put { + Some(p) => c.env("ENV_CACHE_PUT_URL", format!("file://{}", p.display())), + None => c.env_remove("ENV_CACHE_PUT_URL"), + }; + let o = c.output().unwrap(); + String::from_utf8_lossy(&o.stdout).to_string() + }; + // Round one: nothing cached, so it installs and saves. + let first = run(None, Some(&cache), "env1"); + assert!(first.contains(INSTALLED), "{first}"); + assert!(first.contains(SAVED), "{first}"); + assert!(first.contains("ready"), "{first}"); + // Round two, a fresh build: restored, not installed again. + let second = run(Some(&cache), None, "env2"); + assert!(second.contains(RESTORED), "{second}"); + assert!(!second.contains(INSTALLED), "{second}"); + assert!(second.contains("ready"), "{second}"); + let installs = std::fs::read_to_string(&log).unwrap(); + assert_eq!(installs.lines().count(), 1, "installed {installs}"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/services/worker/src/clients/sandbox.rs b/services/worker/src/clients/sandbox.rs index 1f31e44f7..b88543577 100644 --- a/services/worker/src/clients/sandbox.rs +++ b/services/worker/src/clients/sandbox.rs @@ -471,6 +471,10 @@ pub struct SandboxClient<'a> { generator_hosts: Vec, /// The commands that run the repository's generators. generator_cmds: Vec, + /// The run's test environment and its install's cache key + /// (`common::test_env`): every check build runs inside it, restoring + /// the cached install or saving the first one. + test_env: Option<(common::test_env::TestEnv, String)>, } /// The allowlist one build gets: the team's list (None: the network is @@ -572,9 +576,44 @@ impl<'a> SandboxClient<'a> { egress: None, generator_hosts: Vec::new(), generator_cmds: Vec::new(), + test_env: None, } } + /// Runs every check build inside the run's test environment + /// (`passes::test_setup::for_run`), so no round installs it again. + pub fn with_test_env(mut self, env: Option<(common::test_env::TestEnv, String)>) -> Self { + self.test_env = env; + self + } + + /// The command a check build runs and the variable that restores or + /// saves the cached install: restore when it exists, save when not. + async fn in_test_env( + &self, + checks_cmd: &str, + ) -> Result<(String, Option), Box> + { + let Some((env, key)) = &self.test_env else { + return Ok((checks_cmd.to_string(), None)); + }; + let cached = self + .s3 + .head_object() + .bucket(self.bucket) + .key(key) + .send() + .await + .is_ok(); + let var = if cached { + env_var("ENV_CACHE_GET_URL", &self.presigned_get(key).await?)? + } else { + env_var("ENV_CACHE_PUT_URL", &self.presigned_put(key).await?)? + }; + info!(key = %key, cached, "sandbox: the run's test environment"); + Ok((env.wrap(checks_cmd), Some(var))) + } + /// Is the sandbox configured (both bucket and project set)? pub fn is_enabled(&self) -> bool { !self.bucket.is_empty() && !self.project.is_empty() @@ -1019,10 +1058,12 @@ impl<'a> SandboxClient<'a> { terraform_version: Option<&str>, deadline: Option, ) -> Result> { + let (cmd, cache) = self.in_test_env(checks_cmd).await?; let mut env = vec![ env_var("SANDBOX_GET_URL", &self.presigned_get(key).await?)?, - env_var("CHECKS_CMD", checks_cmd)?, + env_var("CHECKS_CMD", &cmd)?, ]; + env.extend(cache); env.extend(self.egress_env(Some(checks_cmd))?); // The buildspec switches Node to this via `n` before running checks, so // "green in the sandbox" tracks the repo's real toolchain (it defaults diff --git a/services/worker/src/passes/explore_guard.rs b/services/worker/src/passes/explore_guard.rs new file mode 100644 index 000000000..3a2bf262b --- /dev/null +++ b/services/worker/src/passes/explore_guard.rs @@ -0,0 +1,231 @@ +//! Explore before the first edit; extend what exists instead of adding a +//! twin beside it. +//! +//! A build once wrote a second overrides map and two helpers next to the +//! map that already did the job, in its first edit, without one search. +//! In the coder's loop now: +//! +//! - **The first write of a build names what it reuses.** It carries +//! [`REUSES_INPUT`]: the existing maps, helpers, config and tests the +//! change extends, by path, or `none: searched `; and a search +//! (`search_code`, a graph lookup, a `grep`) has run in the round. Until +//! both hold, the write is refused with what to do. The list is kept as +//! the coder's evidence (`Reuses: ...`). +//! - **A new map, helper or config beside an existing equivalent is +//! refused** ([`ExploreGuard::check_edit`]): an edit whose new top-level +//! definition parallels one already in the file (`minimal_change`) needs +//! [`WHY_NEW_INPUT`], saying why the existing one can't hold the change. +//! The reason is kept as the habits check's line `Wider than the ticket:`. +//! +//! The refusals are the same every time; no count of tries opens them. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; + +use super::minimal_change; + +/// The write tools' field naming what the change reuses. +pub const REUSES_INPUT: &str = "reuses"; +/// The write tools' field saying why a parallel structure is needed. +pub const WHY_NEW_INPUT: &str = "why_new"; + +/// The tools that count as a search of the code. +pub fn is_search(tool: &str, input: &serde_json::Value) -> bool { + match tool { + "search_code" | "find_references" | "find_symbol" | "find_definition" | "who_calls" + | "code_graph" => true, + "bash" => input + .get("command") + .and_then(|c| c.as_str()) + .is_some_and(|c| { + let c = c.trim_start(); + ["grep ", "rg ", "git grep", "ag ", "find "] + .iter() + .any(|p| c.starts_with(p) || c.contains(&format!("| {p}"))) + }), + t => t.starts_with("graph_") || t.contains("search"), + } +} + +fn text_input<'a>(input: &'a serde_json::Value, key: &str) -> Option<&'a str> { + input + .get(key) + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty()) +} + +/// The schema fields the write tools take for the guard. +pub fn offer_fields(schema: &mut serde_json::Value) { + if let Some(props) = schema.get_mut("properties").and_then(|p| p.as_object_mut()) { + props.insert( + REUSES_INPUT.to_string(), + serde_json::json!({ + "type": "string", + "description": "Required on the first write of a build: the existing maps, helpers, constants, config and tests this change extends, each with its path (found by search_code), or `none: searched `." + }), + ); + props.insert( + WHY_NEW_INPUT.to_string(), + serde_json::json!({ + "type": "string", + "description": "Only when this edit adds a map, helper or config next to an existing similar one: why the existing one can't hold the change." + }), + ); + } +} + +/// The guard of one coder round. +#[derive(Debug, Default)] +pub struct ExploreGuard { + /// The round must name what it reuses before its first write. + require: bool, + searched: AtomicBool, + reuses: Mutex>, + kept: Mutex>, +} + +impl ExploreGuard { + /// A build round: the first write names what it reuses. + pub fn for_build() -> Self { + Self { + require: true, + ..Default::default() + } + } + + /// A fix round: the parallel check only. + pub fn for_fix() -> Self { + Self::default() + } + + /// Records a tool call the coder made. + pub fn saw(&self, tool: &str, input: &serde_json::Value) { + if is_search(tool, input) { + self.searched.store(true, Ordering::Relaxed); + } + } + + /// Whether a write may go ahead: `Err` is the refusal the coder reads. + pub fn check_first_write(&self, input: &serde_json::Value) -> Result<(), String> { + if !self.require || self.reuses.lock().unwrap().is_some() { + return Ok(()); + } + let searched = self.searched.load(Ordering::Relaxed); + match (searched, text_input(input, REUSES_INPUT)) { + (true, Some(r)) => { + *self.reuses.lock().unwrap() = Some(r.to_string()); + Ok(()) + } + (false, _) => Err(format!( + "Not written: search before the first edit. Run `search_code` for the ticket's names and for the kind of structure you are about to add (a map, a helper, a config key, a test of the same code), read what it finds, then write again with `{REUSES_INPUT}` naming what you extend, by path." + )), + (true, None) => Err(format!( + "Not written: the first write of a build names what it reuses. Call it again with `{REUSES_INPUT}`: the existing maps, helpers, config and tests this change extends, each with its path, or `none: searched `." + )), + } + } + + /// Whether an edit of an existing file may add the definitions it adds: + /// one parallel to an existing definition in the file needs a reason. + pub fn check_edit( + &self, + path: &str, + old: &str, + new: &str, + input: &serde_json::Value, + ) -> Result<(), String> { + let pairs = minimal_change::parallel_in_edit(path, old, new); + if pairs.is_empty() { + return Ok(()); + } + if let Some(why) = text_input(input, WHY_NEW_INPUT) { + self.kept + .lock() + .unwrap() + .push((path.to_string(), why.to_string())); + return Ok(()); + } + let list = pairs + .iter() + .map(|(n, e)| format!("`{}` next to the existing `{}`", n.name, e.name)) + .collect::>() + .join(", "); + Err(format!( + "Not written: this edit adds {list} in `{path}`. Extend the existing one instead (add the entries, or a parameter to the helper). If a separate one is really needed, call again with `{WHY_NEW_INPUT}` saying why the existing one can't hold the change." + )) + } + + /// The coder's evidence lines: what it reuses, and each kept parallel + /// with its reason (read by the habits check). + pub fn evidence_lines(&self) -> String { + let mut out = String::new(); + if let Some(r) = self.reuses.lock().unwrap().as_ref() { + out.push_str(&format!("Reuses: {r}\n")); + } + for (p, why) in self.kept.lock().unwrap().iter() { + out.push_str(&format!("Wider than the ticket: {p}: {why}\n")); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn the_first_write_follows_a_search_and_names_what_it_reuses() { + let g = ExploreGuard::for_build(); + let w = json!({"path": "dags/camps.py"}); + assert!(g + .check_first_write(&w) + .unwrap_err() + .contains("search before the first edit")); + g.saw("read_file", &json!({})); + assert!(g.check_first_write(&w).is_err()); + g.saw("bash", &json!({"command": "grep -rn OVERRIDES dags"})); + assert!(g.check_first_write(&w).unwrap_err().contains("`reuses`")); + let named = json!({"path": "dags/camps.py", "reuses": "`CAMP_OVERRIDES` in dags/camps.py"}); + assert!(g.check_first_write(&named).is_ok()); + // Later writes go ahead. + assert!(g.check_first_write(&w).is_ok()); + assert!(g.evidence_lines().starts_with("Reuses: `CAMP_OVERRIDES`")); + // A fix round asks for none of it. + assert!(ExploreGuard::for_fix().check_first_write(&w).is_ok()); + } + + #[test] + fn a_twin_beside_the_existing_map_needs_a_reason() { + let g = ExploreGuard::for_fix(); + let old = "CAMP_SPORT_OVERRIDES = {\n \"a\": [\"x\"],\n}\n"; + let twin = format!("{old}CAMP_SWIM_SPORT_OVERRIDES = {{\n}}\n"); + let e = g + .check_edit("dags/camps.py", old, &twin, &json!({})) + .unwrap_err(); + assert!( + e.contains("`CAMP_SWIM_SPORT_OVERRIDES` next to the existing `CAMP_SPORT_OVERRIDES`") + ); + // Entries in the existing map are the change it should make. + let entries = old.replace("}\n", " \"b\": [\"x\", \"swimming\"],\n}\n"); + assert!(g + .check_edit("dags/camps.py", old, &entries, &json!({})) + .is_ok()); + // A stated reason is let through and kept. + assert!(g + .check_edit( + "dags/camps.py", + old, + &twin, + &json!({"why_new": "a different key type"}) + ) + .is_ok()); + assert!(g + .evidence_lines() + .contains("Wider than the ticket: dags/camps.py: a different key type")); + let mut schema = json!({"type": "object", "properties": {}}); + offer_fields(&mut schema); + assert!(schema["properties"]["reuses"].is_object()); + } +} diff --git a/services/worker/src/passes/feature/data_rules.rs b/services/worker/src/passes/feature/data_rules.rs index fac28621b..d6f47a3a7 100644 --- a/services/worker/src/passes/feature/data_rules.rs +++ b/services/worker/src/passes/feature/data_rules.rs @@ -59,10 +59,11 @@ find any other path that makes the same choice (full and incremental, batch and and live) and name it with its ordering key under `### Same selection elsewhere` (or what you \ searched when none exists). Both paths use the identical ordering key, tie-breaks and null \ handling included; plan a test with ties and nulls in both modes.\n\ -- Unexpected data: records without the expected shape are collected and reported in ONE warning \ -per run naming their ids (deduplicated, capped), with counts in the run's summary; never a log \ -line per row and never a silent skip. Expected exclusions are counted, not warned. Where the \ -repository or the team's instructions already set a format, follow it.\n\ +- Unexpected data: a record the change skips is handled the way the surrounding code already \ +handles a skipped record. Plan new reporting (ONE warning per run naming the ids, counts in the \ +run's summary) only when the ticket asks for it; never a log line per row, never a change to \ +existing log levels. Where the repository or the team's instructions already set a format, \ +follow it.\n\ - Real data: when the change affects stored data and a read-only data source is connected, plan \ to read the records the ticket names and the edge cases the change touches (ties, nulls, missing \ records) before and after, for the pull request's Verification section.\n"; @@ -72,7 +73,7 @@ pub const CODER_RULES: &str = " ## Changes to stored data (every change that reads or writes it) - Cursor columns: when you change how a timestamp, sequence or version column is written (set it conditionally, stop advancing it, move it back), first search for every reader of that column: SQL `MAX(col)`, `GREATEST(... col ...)`, `WHERE col >`, `ORDER BY col`, and code that compares it. List them in your notes. Keep the column advancing (`GREATEST(existing, new)`), even when another column must stay stable, and add a test proving it still advances. - Same selection everywhere: when code picks a winner, latest or first among rows and another path makes the same choice (full and incremental sync, batch and stream, backfill and live), use the identical ordering key in both, tie-breaks and null handling included (a shared function where you can). Add a test with ties and nulls that both modes pass. -- Unexpected data: collect records that don't have the expected shape and report them in ONE warning per run naming their ids (deduplicated, capped), with counts in the run's summary. Never a log line per row, never a silent `continue`. Expected exclusions (filtered-out categories) are counted, not warned. Follow the repository's or team's format when one is set. +- Unexpected data: a record your change skips is handled the way the surrounding code already handles a skipped record. Add reporting (ONE warning per run naming the ids, counts in the run's summary) only when the ticket asks for it. Never a log line per row, and never change an existing log level. Follow the repository's or team's format when one is set. "; /// A code or SQL file whose lines count. @@ -939,6 +940,11 @@ pub struct Facts { pub others: Vec, pub skips: Vec, pub reports_once: bool, + /// The ticket asks for no reporting: a skip follows the surrounding + /// code's own handling, and only a log line per row is a problem (a + /// change once grew counters, a warning and a log level change in + /// shared code for a four-entry fix, to settle this item). + pub quiet_skips: bool, /// The test text the diff adds ([`tests_added`]). pub tests: String, } @@ -1104,7 +1110,7 @@ pub fn items(f: &Facts, text: &str) -> Vec { .filter(|s| !s.counted) .map(|s| format!("`{}`: `{}`", s.path, s.line)) .collect(); - if !silent.is_empty() { + if !silent.is_empty() && !f.quiet_skips { problems.push(format!("skipped silently: {}", shown(&silent))); } let per_row: Vec = f @@ -1116,7 +1122,7 @@ pub fn items(f: &Facts, text: &str) -> Vec { if !per_row.is_empty() { problems.push(format!("a log line per row: {}", shown(&per_row))); } - if f.skips.iter().any(|s| s.collected) && !f.reports_once { + if f.skips.iter().any(|s| s.collected) && !f.reports_once && !f.quiet_skips { problems .push("records are collected but no single WARNING per run names them".to_string()); } @@ -1566,6 +1572,20 @@ mod tests { let per_row = vec![file("pipeline/sync_items.py", PER_ROW)]; let it = items(&Facts::from_diff(&per_row), ""); assert!(it[0].detail.contains("a log line per row"), "{it:?}"); + // A ticket that asks for no reporting: the skip follows the + // surrounding code; only a log line per row is still a problem. + let quiet = Facts { + quiet_skips: true, + ..Facts::from_diff(&silent) + }; + assert_eq!(items(&quiet, "")[0].status, Status::Pass); + let quiet_per_row = Facts { + quiet_skips: true, + ..Facts::from_diff(&per_row) + }; + assert!(items(&quiet_per_row, "")[0] + .detail + .contains("a log line per row")); let once = vec![file("pipeline/sync_items.py", ONCE)]; let f = Facts::from_diff(&once); assert!(f.reports_once); diff --git a/services/worker/src/passes/feature/mod.rs b/services/worker/src/passes/feature/mod.rs index af86bf712..faf9d42aa 100644 --- a/services/worker/src/passes/feature/mod.rs +++ b/services/worker/src/passes/feature/mod.rs @@ -399,6 +399,12 @@ async fn data_facts( ) -> data_rules::Facts { let (owner, repo, base) = (&w.msg.repo_owner, &w.msg.repo_name, &w.msg.base_branch); let mut facts = data_rules::Facts::from_diff(files); + // A skip follows the surrounding code unless the ticket asks for + // reporting (`minimal_change`). + facts.quiet_skips = !crate::passes::minimal_change::ticket_asks( + &format!("{}\n{}", w.msg.title, w.msg.body), + crate::passes::minimal_change::REPORT_ASKS, + ); let mut cols: Vec = Vec::new(); for c in facts.writes.iter().map(|x| x.column.clone()) { if !cols.contains(&c) { diff --git a/services/worker/src/passes/habits_check.rs b/services/worker/src/passes/habits_check.rs index 9ae18da7e..24a5931f3 100644 --- a/services/worker/src/passes/habits_check.rs +++ b/services/worker/src/passes/habits_check.rs @@ -96,6 +96,13 @@ pub struct PrFacts { /// no spec is needed or one is there. #[serde(default)] pub e2e_missing: String, + /// Where the change is wider than its ticket and the coder gave no + /// reason it may keep (`minimal_change`): a parallel structure, + /// deleting or overwriting where the code only added, a log level, + /// reporting nobody asked for, tests out of proportion, a payload + /// nobody observed. + #[serde(default)] + pub wider: Vec, } /// Why the check didn't give a result. @@ -528,6 +535,21 @@ pub fn blocking(f: &PrFacts, plan: &PlanResult) -> Vec { if !f.e2e_missing.is_empty() { out.push(f.e2e_missing.clone()); } + // A test that never ran proves nothing, whatever CI says later. + for t in f + .tests + .iter() + .filter(|t| t.verdict == Verdict::NotRun && t.detail.contains("found no tests")) + { + out.push(format!( + "`{}`: {}. Make it run under the repository's test command, run it, and quote its output in your Evidence.", + t.path, t.detail + )); + } + // The change is held to the ticket: smaller, not wider. + for w in &f.wider { + out.push(w.instruction()); + } if f.bug && f.tests.is_empty() && !repro_waived(plan) && f.no_tests.contains("no test file") { out.push("This is a bug fix and the change has no test that fails without it. Add the test that reproduces the reported failure (it must fail on the base code and pass with the fix).".to_string()); } @@ -548,7 +570,7 @@ pub fn blocking(f: &PrFacts, plan: &PlanResult) -> Vec { /// The fix round's instructions. pub fn fix_feedback(lines: &[String]) -> String { format!( - "The check after the build ran each new or changed test with and without your change, and compared the changed files with the plan. Fix every item:\n{}\nDo not delete or skip a test to settle an item.", + "The check after the build ran each new or changed test with and without your change, compared the changed files with the plan, and compared the change with the ticket. Fix every item; where the change is wider than the ticket, make it smaller:\n{}\nDo not delete or skip a test to settle an item.", lines .iter() .map(|l| format!("- {l}")) @@ -566,7 +588,13 @@ pub fn open_findings(f: &PrFacts, plan: &PlanResult) -> Vec { lines .into_iter() .map(|l| { - let (point, settle) = if l.contains("no task of the plan") { + let wider = f.wider.iter().find(|w| w.instruction() == l); + let (point, settle) = if let Some(w) = wider { + ( + w.point(), + "CoderHelm makes the change smaller in its next round on this pull request.", + ) + } else if l.contains("no task of the plan") { ( "Changed outside the plan", "CoderHelm restores it or records why the change needs it in its next round on this pull request.", @@ -1019,6 +1047,46 @@ async fn e2e_missing(w: &super::proof::Work<'_>, paths: &[String]) -> String { .unwrap_or_default() } +/// Where the change is wider than its ticket (`minimal_change`), read +/// against the base text of the changed code files and the ticket's own +/// words, less what the coder's notes keep with a reason. +async fn wider( + w: &super::proof::Work<'_>, + diff: &Diff, + notes: &str, +) -> Vec { + let (owner, repo) = (&w.msg.repo_owner, &w.msg.repo_name); + let mut base = Vec::new(); + for (path, _, _) in diff + .iter() + .filter(|(p, s, _)| s == "modified" && !is_test_path(p)) + .take(12) + { + if let Ok(text) = w + .github + .read_file(owner, repo, path, &w.msg.base_branch) + .await + { + base.push((path.clone(), text)); + } + } + let has_probe = match w.github.get_tree(owner, repo, w.branch).await { + Ok(t) => t.iter().any(|e| common::e2e::probe::is_record(&e.path)), + Err(_) => false, + }; + let ticket = format!( + "{}\n{}{}", + w.msg.title, + w.msg.body, + common::run_questions::answers_note(&w.msg.answers) + ); + let found = super::minimal_change::check(diff, &base, &ticket, has_probe); + super::minimal_change::standing(&found, notes) + .into_iter() + .cloned() + .collect() +} + /// A bench for a step with no time for the sandbox: nothing runs, and each /// test says so. struct NoTime; @@ -1092,6 +1160,7 @@ async fn check_and_fix( ) .await; facts.e2e_missing = e2e_missing(w, &paths).await; + facts.wider = wider(w, &diff, &evidence.notes).await; let blocking = blocking(&facts, w.plan); info!( run_id = w.run_id, diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index d60fbf597..9058566b1 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -217,8 +217,26 @@ pub async fn run( repo_instructions }; let instructions_block = super::format_instructions_block(trimmed_instructions); + // How the repository's CI installs and runs its tests, found once per + // run and reused by every round's sandbox builds (`test_setup`). + let test_env = match run_id { + Some(rid) => { + super::test_setup::for_run( + state, + github, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + &msg.base_branch, + branch, + rid, + ) + .await + } + None => None, + }; let tests_block = format!( - "{}{}", + "{}{}{}", if super::review_pr::tests_required(state, &msg.team_id, &msg.repo_owner, &msg.repo_name) .await { @@ -226,7 +244,11 @@ pub async fn run( } else { "" }, - super::E2E_CODER_SECTION + super::E2E_CODER_SECTION, + test_env + .as_ref() + .map(|(e, _)| e.coder_note()) + .unwrap_or_default() ); // The team's instructions are never trimmed: they are its working rules. // What outcomes taught the coder here (lessons naming what people @@ -356,7 +378,8 @@ pub async fn run( &state.config.sandbox_bucket_name, &state.config.sandbox_project_name, ) - .with_egress(crate::agent::policy::sandbox_egress(state, &msg.team_id).await), + .with_egress(crate::agent::policy::sandbox_egress(state, &msg.team_id).await) + .with_test_env(test_env.clone()), ) } else { None @@ -504,6 +527,21 @@ pub async fn run( all_tools() }; + // The build searches before its first write and names what it reuses; + // every round explains a new structure beside an existing one + // (`explore_guard`). + let explore = if round_for == super::write_guard::RoundFor::Build { + super::explore_guard::ExploreGuard::for_build() + } else { + super::explore_guard::ExploreGuard::for_fix() + }; + for t in tools + .iter_mut() + .filter(|t| matches!(t.name.as_str(), "write_file" | "edit_file" | "batch_write")) + { + super::explore_guard::offer_fields(&mut t.input_schema); + } + // A bounded round's write tools take the reason for an edit outside // its files. if scope_guard.bounded() { @@ -842,6 +880,7 @@ pub async fn run( codegen_cmd, codegen_env, scope_guard, + explore, run_id: run_id.map(|s| s.to_string()), node_version, terraform_version, @@ -1295,6 +1334,12 @@ pub async fn run( lines if lines.is_empty() => closing.trim().to_string(), lines => format!("{}\n{lines}", closing.trim()), }; + // What the build reused, and each structure it kept beside an existing + // one with why (the habits check reads these lines). + let notes = match executor.write_executor.explore.evidence_lines() { + lines if lines.is_empty() => notes, + lines => format!("{notes}\n{}", lines.trim_end()), + }; // A file this round (or the rounds before it) changed and then put // back leaves no commit of its own on the pull request. super::round::fold_churn(github, &msg.repo_owner, &msg.repo_name, branch).await; @@ -1392,10 +1437,11 @@ pub(super) fn task_prompt(p: &TaskPrompt) -> String { {design}{continuation}{openspec}{files_hint}{feedback}{issue} ## Instructions — SIMPLE CHANGE -Go DIRECTLY to the target files listed in the OpenSpec. -- Use `read_file_lines` on the exact section, make the change with `edit_file`, done. +Go to the target files listed in the OpenSpec. +- `search_code` once for the structure the change extends (the map, helper or query the plan names under Reuse), read that section, make the change with `edit_file`, done. - Use `edit_file` for modifying existing files (search/replace). Only use `write_file` for new files. -- You should need 2-5 tool calls total, plus any lookups the rules below call for. +- You should need 3-6 tool calls total, plus any lookups the rules below call for. +{smallest} - Only implement the listed tasks. Do not add extras. - Write each file as soon as its change is done; never hold finished changes back for one write at the end. - NEVER leave placeholder text like TODO, FIXME, REPLACE_ME, or stub implementations. Every line you write must be complete, working code. @@ -1414,6 +1460,7 @@ Go DIRECTLY to the target files listed in the OpenSpec. evidence_output = super::proof::EVIDENCE_OUTPUT, proof_rules = super::proof::CODER_RULES, data_rules = super::feature::data_rules::CODER_RULES, + smallest = SMALLEST_CHANGE_RULES, ) } else { format!( @@ -1434,6 +1481,7 @@ Go DIRECTLY to the target files listed in the OpenSpec. - {commit} - {evidence_output} - Only implement the listed tasks. Do not add extras. +{smallest} {proof_rules}{data_rules}{schema_rules}"#, number = p.number, title = p.title, @@ -1447,10 +1495,18 @@ Go DIRECTLY to the target files listed in the OpenSpec. proof_rules = super::proof::CODER_RULES, data_rules = super::feature::data_rules::CODER_RULES, schema_rules = SCHEMA_CHANGE_RULES, + smallest = SMALLEST_CHANGE_RULES, ) } } +/// The smallest change, as the coder's loop and the habits check hold it +/// (`explore_guard`, `minimal_change`). +pub(crate) const SMALLEST_CHANGE_RULES: &str = "- The smallest change that does the ticket: before the first write, `search_code` for the structure you would add and pass `reuses` naming what you extend. Add entries to the existing map, a parameter to the existing helper, a key to the existing config; never a second one beside it. +- Never widen behaviour past the ticket: an insert-only path stays insert-only (no `DELETE`, no `ON CONFLICT DO UPDATE`, no replacing sync), log levels and shared logging stay as they are, and no counters or reports the ticket doesn't ask for. +- Tests sized to the change: the new behaviour and that nothing else changed, through the real entry point. Never invent another system's payload, page or test ids: probe it (`probe_page`) or reuse an existing fixture. Run the tests and quote their output in your Evidence. +- When an acceptance criterion and an outside system disagree, change the product so the criterion holds; never change the test to expect the outside behaviour without the measured reason."; + /// What a change to a table's schema, constraints, ids or stored data must /// do before it is written. Each rule is a way such a change shipped broken. const SCHEMA_CHANGE_RULES: &str = " @@ -2074,6 +2130,8 @@ struct WriteToolExecutor<'a> { /// Which existing files the round may edit, by what it is for /// (`write_guard`). No boundary on the build and a person's ask. scope_guard: super::write_guard::ScopeGuard, + /// Search before the first write; no twin beside an existing structure. + explore: super::explore_guard::ExploreGuard, /// Node major version to switch the sandbox to (None -> buildspec default). node_version: Option, /// Exact Terraform version the sandbox installs (None when the repo has @@ -2126,9 +2184,18 @@ impl<'a> ToolExecutor for WriteToolExecutor<'a> { name: &str, input: &serde_json::Value, ) -> Result> { + self.explore.saw(name, input); if name == "bash" { return Box::pin(self.bash(input)).await; } + if matches!(name, "write_file" | "edit_file" | "batch_write") { + if let Err(refusal) = self.explore.check_first_write(input) { + note(LogOutcome::soft_fail( + "not written: search and name what it reuses first", + )); + return Ok(json!(refusal)); + } + } let out = self.execute_tool(name, input).await; let out = match out { Ok(serde_json::Value::String(text)) if is_write_tool(name) => { @@ -2423,6 +2490,12 @@ impl<'a> WriteToolExecutor<'a> { ))); return Ok(json!(refusal)); } + if let Err(refusal) = self.explore.check_edit(path, old, content, input) { + note(LogOutcome::soft_fail( + "not written: a twin of an existing structure", + )); + return Ok(json!(refusal)); + } if let Some(problem) = validate_edit_safety(old, content, path) { note(LogOutcome::soft_fail("rejected: it would gut the file")); return Ok(json!(format!( @@ -2556,6 +2629,16 @@ impl<'a> WriteToolExecutor<'a> { Read the file again and retry with a corrected edit." ))); } + // A new map or helper beside an existing equivalent. + if let Err(refusal) = + self.explore + .check_edit(path, &original_content, &content, input) + { + note(LogOutcome::soft_fail( + "not edited: a twin of an existing structure", + )); + return Ok(json!(refusal)); + } // Deletion guardrail: reject edits that gut the file if let Some(problem) = validate_edit_safety(&original_content, &content, path) { note(LogOutcome::soft_fail("rejected: it would gut the file")); diff --git a/services/worker/src/passes/incidents/bz_smallest_change.rs b/services/worker/src/passes/incidents/bz_smallest_change.rs new file mode 100644 index 000000000..f3ad770f3 --- /dev/null +++ b/services/worker/src/passes/incidents/bz_smallest_change.rs @@ -0,0 +1,326 @@ +//! bz. Two pull requests did far more than their tickets, and guessed +//! where they should have measured. +//! +//! A data-pipeline ticket asked to link four full-day camps to Swimming as +//! well as their own sport. The plan added a second overrides map and two +//! helpers beside the existing `CAMP_MULTI_SPORT_OVERRIDES`, and switched +//! the insert-only link sync to a replacing upsert that deleted links +//! nobody asked about. The build added warnings, three summary counters +//! and an INFO-to-DEBUG change in shared code (the data rules' "report +//! unexpected data once per run" item asked for them on a four-entry fix), +//! and a 432-line test with fake hooks and an invented payload. The right +//! change: four map entries; an insert with `ON CONFLICT DO NOTHING` in the +//! three write branches; one small test. +//! +//! A web ticket embedded a vendor's booking portal in a frame. Its vendor +//! end-to-end tests were rewritten three times on guesses (no inner +//! scroll, a click that adds to an order, invented test ids), and when the +//! criterion "no double scrollbars on desktop" met the vendor's behaviour, +//! the test was changed to expect the vendor's behaviour instead of the +//! page losing its footer and bottom padding. +//! +//! Guarantee: the plan writes Reuse, Must not change, Measure first, +//! Smallest change and Proof, and is sent back when it proposes a +//! structure parallel to an existing one, deleting or overwriting the +//! ticket doesn't ask for, logging changes, reporting, assertions about an +//! outside page with nothing measured, or a test change where a criterion +//! says the product must change (`plan_shape`). The coder's first write +//! follows a search and names what it reuses, and an edit that adds a twin +//! of an existing map or helper is refused without a reason +//! (`explore_guard`). After the build, a diff wider than its ticket goes +//! back to the coder to be made smaller, deletes where the base only added +//! with no excuse but the ticket (`minimal_change`, `habits_check`); the +//! reviewer finds the same, and a test bent to an outside page against a +//! criterion is a required finding (`review_rules`). + +use crate::passes::explore_guard::ExploreGuard; +use crate::passes::habits_check::{self, PrFacts}; +use crate::passes::minimal_change::{self, Kind}; +use crate::passes::plan::PlanResult; +use crate::passes::plan_shape; +use crate::passes::review_rules; +use serde_json::json; + +const MAP_FILE: &str = "dags/camps/sports.py"; +const SYNC_FILE: &str = "dags/camps/sync_links.py"; + +const CAMP_TICKET: &str = "Link four full-day camps to Swimming\n\nThese full-day camps should show under Swimming as well as their own sport: \"Aqua Day Camp\", \"Swim and Sail\", \"Pool Explorers\", \"Splash Week\"."; + +const PORTAL_TICKET: &str = "Embed the booking portal on the camps page\n\nShow the vendor's booking portal in an iframe on the camps page.\n\nAcceptance criteria:\n- The portal loads inside the page\n- No double scrollbars on desktop\n"; + +const BASE_MAP: &str = "CAMP_MULTI_SPORT_OVERRIDES = {\n \"sports academy break camp\": [\"multi-sport\"],\n}\n\n\ndef get_camp_multi_sport_names(name):\n return CAMP_MULTI_SPORT_OVERRIDES.get(name.lower(), [])\n"; + +const BASE_SYNC: &str = "def write_links(cur, camp_id, sports):\n for sport_id in sports:\n cur.execute(\n \"INSERT INTO camp_sports (camp_id, sport_id) VALUES (%s, %s) ON CONFLICT DO NOTHING\",\n (camp_id, sport_id),\n )\n"; + +fn plan(design: &str, tasks: &str) -> PlanResult { + PlanResult { + design: design.into(), + tasks: tasks.into(), + ..Default::default() + } +} + +/// The plan the run wrote for the camps ticket, in its shape. +fn camps_plan_before() -> PlanResult { + plan( + "## Approach\nAdd `CAMP_SWIMMING_OVERRIDES` and `get_camp_swimming_names` to hold the swimming links. \ + The link sync upserts each camp's links and deletes stale ones so the table matches. \ + Report skipped camps once per run with summary counters, and move the per-record INFO log to debug.\n", + &format!("- [ ] {MAP_FILE}: add the swimming map and helper\n- [ ] {SYNC_FILE}: replace links per camp\n- [ ] tests/test_sync_links.py: cover the sync"), + ) +} + +/// The small, correct plan. +fn camps_plan_after() -> PlanResult { + plan( + "## Reuse\n- `CAMP_MULTI_SPORT_OVERRIDES` and `get_camp_multi_sport_names` in dags/camps/sports.py\n\n\ + ## Must not change\nNo deletes: existing links stay. Logging and the other pipelines stay as they are.\n\n\ + ## Measure first\nNone: the change stays inside this repository.\n\n\ + ## Smallest change\n4 entries in `CAMP_MULTI_SPORT_OVERRIDES`; in the 3 write branches insert links for \ + `get_camp_multi_sport_names` with ON CONFLICT DO NOTHING.\n\n\ + ## Proof\nOne test: the 4 names get Swimming and their own sport, others only their own, nothing deleted.\n", + &format!("- [ ] {MAP_FILE}: 4 entries\n- [ ] {SYNC_FILE}: insert the extra links\n- [ ] tests/test_sports.py: one test"), + ) +} + +fn portal_plan_before() -> PlanResult { + plan( + "## Reuse\n- `CampsPage` in web/src/pages/camps.tsx\n\n## Must not change\nThe header.\n\n\ + ## Measure first\nThe vendor portal renders in an iframe with no inner scroll; clicking a camp adds it to the order summary.\n\n\ + ## Smallest change\nAn iframe block on the camps page.\n\n\ + ## Proof\ne2e spec for the portal. If the frame scrolls, update the test to match the vendor.\n", + "- [ ] web/src/pages/camps.tsx: embed\n- [ ] e2e/portal.spec.ts: spec", + ) +} + +fn portal_plan_after() -> PlanResult { + plan( + "## Reuse\n- `CampsPage` in web/src/pages/camps.tsx and its layout\n\n## Must not change\nThe header and other pages.\n\n\ + ## Measure first\nprobe_page on the portal at 1280x900: the embed script caps the frame at the window height below its top (663px) and the portal scrolls inside it; every camp button is disabled until registration opens; weeks are `program-portals-segment-tag-guest-N`.\n\n\ + ## Smallest change\nAn iframe block on the camps page; drop the footer and bottom padding there so the frame fills the window, as the vendor's embed docs recommend.\n\n\ + ## Proof\nOne e2e spec from the probe record: the page itself has no scrollbar at 1280x900, the frame is 663px, week tags are listed.\n", + "- [ ] web/src/pages/camps.tsx: embed, no footer\n- [ ] e2e/portal.spec.ts: spec from the probe", + ) +} + +#[test] +fn the_plans_are_sent_back_until_they_are_the_small_change() { + let existing = vec!["CAMP_MULTI_SPORT_OVERRIDES".to_string()]; + // Before: the camps plan has no sections, a parallel map, a replacing + // sync, a log change and reporting. + let g = plan_shape::plan_gaps(&camps_plan_before(), CAMP_TICKET, false, &existing); + let all = g.join("\n"); + assert!(all.contains("lacks `## Reuse`"), "{all}"); + assert!( + all.contains("`CAMP_SWIMMING_OVERRIDES` next to the existing `CAMP_MULTI_SPORT_OVERRIDES`"), + "{all}" + ); + assert!(all.contains("delete or overwrite"), "{all}"); + assert!(all.contains("changes logging"), "{all}"); + assert!(all.contains("adds reporting"), "{all}"); + // After: nothing to send back. + assert!(plan_shape::plan_gaps(&camps_plan_after(), CAMP_TICKET, false, &existing).is_empty()); + // The portal plan guessed the outside page and planned to bend the + // test to the vendor against a criterion. + let g = plan_shape::plan_gaps(&portal_plan_before(), PORTAL_TICKET, false, &[]); + let all = g.join("\n"); + assert!(all.contains("plans no measurement"), "{all}"); + assert!( + all.contains("product change that meets the criterion first"), + "{all}" + ); + assert!(plan_shape::plan_gaps(&portal_plan_after(), PORTAL_TICKET, false, &[]).is_empty()); + // The planner is told the sections, and the ticket's own words are + // searched before it plans. + assert!(plan_shape::PLANNER.contains("## Must not change")); + let terms = plan_shape::ticket_terms("Link four full-day camps to Swimming", CAMP_TICKET); + assert!(terms.contains(&"Swimming".to_string()), "{terms:?}"); + assert!(terms.contains(&"Aqua Day Camp".to_string()), "{terms:?}"); +} + +#[test] +fn the_coder_searches_first_and_never_adds_a_twin() { + let g = ExploreGuard::for_build(); + let twin = format!( + "{BASE_MAP}\nCAMP_SWIMMING_OVERRIDES = {{\n \"aqua day camp\": [\"swimming\"],\n}}\n" + ); + // The run's first write came before any search. + let first = json!({"path": MAP_FILE, "edits": []}); + assert!(g.check_first_write(&first).is_err()); + g.saw("search_code", &json!({"query": "Swimming"})); + let named = + json!({"path": MAP_FILE, "reuses": "`CAMP_MULTI_SPORT_OVERRIDES` in dags/camps/sports.py"}); + assert!(g.check_first_write(&named).is_ok()); + // A second map beside the first is refused; entries in it are not. + assert!(g.check_edit(MAP_FILE, BASE_MAP, &twin, &named).is_err()); + let entries = BASE_MAP.replace( + " \"sports academy break camp\": [\"multi-sport\"],\n", + " \"sports academy break camp\": [\"multi-sport\"],\n \"aqua day camp\": [\"swimming\", \"sailing\"],\n", + ); + assert!(g.check_edit(MAP_FILE, BASE_MAP, &entries, &named).is_ok()); +} + +fn diff_before() -> Vec<(String, String, String)> { + let map = "@@ -1,3 +1,14 @@\n CAMP_MULTI_SPORT_OVERRIDES = {\n+CAMP_SWIMMING_OVERRIDES = {\n+ \"aqua day camp\": [\"swimming\"],\n+}\n+def get_camp_swimming_names(name):\n+ return CAMP_SWIMMING_OVERRIDES.get(name.lower(), [])\n"; + let sync = "@@ -1,6 +1,20 @@\n def write_links(cur, camp_id, sports):\n- for sport_id in sports:\n+ cur.execute(\"DELETE FROM camp_sports WHERE camp_id = %s AND NOT (sport_id = ANY(%s))\", (camp_id, sports))\n+ for sport_id in sports:\n cur.execute(\n- \"INSERT INTO camp_sports (camp_id, sport_id) VALUES (%s, %s) ON CONFLICT DO NOTHING\",\n+ \"INSERT INTO camp_sports (camp_id, sport_id) VALUES (%s, %s) ON CONFLICT (camp_id, sport_id) DO UPDATE SET sport_id = EXCLUDED.sport_id\",\n+ linked += 1\n+ skipped += 1\n+ log.warning(\"skipped camps: %s\", skipped_ids)\n"; + let log = "@@ -1,3 +1,3 @@\n-logger.setLevel(logging.INFO)\n+logger.setLevel(logging.DEBUG)\n"; + let test: String = std::iter::once("+class FakePostgresHook:\n".to_string()) + .chain((0..16).map(|i| format!("+ \"camp_field_{i}\": \"value\",\n"))) + .chain((0..420).map(|i| format!("+ assert rows[{i}]\n"))) + .collect(); + vec![ + (MAP_FILE.into(), "modified".into(), map.into()), + (SYNC_FILE.into(), "modified".into(), sync.into()), + ("dags/common/logs.py".into(), "modified".into(), log.into()), + ("tests/test_sync_links.py".into(), "added".into(), test), + ] +} + +fn diff_after() -> Vec<(String, String, String)> { + let map = "@@ -1,3 +1,7 @@\n CAMP_MULTI_SPORT_OVERRIDES = {\n \"sports academy break camp\": [\"multi-sport\"],\n+ \"aqua day camp\": [\"swimming\", \"sailing\"],\n+ \"swim and sail\": [\"swimming\", \"sailing\"],\n+ \"pool explorers\": [\"swimming\", \"multi-sport\"],\n+ \"splash week\": [\"swimming\", \"multi-sport\"],\n }\n"; + let sync = "@@ -1,6 +1,11 @@\n def write_links(cur, camp_id, sports):\n- for sport_id in sports:\n+ for sport_id in sports + extra_sports(camp_name):\n cur.execute(\n \"INSERT INTO camp_sports (camp_id, sport_id) VALUES (%s, %s) ON CONFLICT DO NOTHING\",\n"; + let test: String = (0..24) + .map(|i| format!("+ assert links[{i}]\n")) + .collect(); + vec![ + (MAP_FILE.into(), "modified".into(), map.into()), + (SYNC_FILE.into(), "modified".into(), sync.into()), + ("tests/test_sports.py".into(), "added".into(), test), + ] +} + +#[test] +fn the_wider_diff_goes_back_and_the_small_one_passes() { + let base = vec![ + (MAP_FILE.to_string(), BASE_MAP.to_string()), + (SYNC_FILE.to_string(), BASE_SYNC.to_string()), + ]; + let found = minimal_change::check(&diff_before(), &base, CAMP_TICKET, false); + let kinds: Vec = found.iter().map(|w| w.kind).collect(); + for k in [ + Kind::Parallel, + Kind::Replacing, + Kind::LogLevel, + Kind::Reporting, + Kind::TestSize, + Kind::InventedPayload, + ] { + assert!(kinds.contains(&k), "{k:?} not found in {found:?}"); + } + // The habits check's fix round gets each as a line to make smaller; + // a reason excuses neither the deletes nor the invented payload. + let notes = format!( + "Wider than the ticket: {SYNC_FILE}: keeps the table in step\nWider than the ticket: tests/test_sync_links.py: thorough" + ); + let facts = PrFacts { + wider: minimal_change::standing(&found, ¬es) + .into_iter() + .cloned() + .collect(), + ..Default::default() + }; + let lines = habits_check::blocking(&facts, &PlanResult::default()); + assert!( + lines + .iter() + .any(|l| l.contains("deletes or overwrites stored data")), + "{lines:?}" + ); + assert!( + lines.iter().any(|l| l.contains("payload nobody observed")), + "{lines:?}" + ); + assert!(habits_check::fix_feedback(&lines).contains("make it smaller")); + let open = habits_check::open_findings(&facts, &PlanResult::default()); + assert!(open + .iter() + .any(|f| f.point == "Deletes or overwrites where the code only added")); + // The reviewer finds the same; the deletes block by rule. + let review = review_rules::wider_findings(&found); + let deletes = review + .iter() + .find(|f| f.title == "Deletes or overwrites where the code only added") + .unwrap(); + assert_eq!( + review_rules::mandatory(deletes), + Some(review_rules::REQUIRED_WHY) + ); + // The right change passes every check. + assert!( + minimal_change::check(&diff_after(), &base, CAMP_TICKET, false).is_empty(), + "{:?}", + minimal_change::check(&diff_after(), &base, CAMP_TICKET, false) + ); +} + +#[test] +fn a_test_bent_to_the_vendor_against_a_criterion_is_a_required_finding() { + let patch = "@@ -10,4 +10,4 @@\n const frame = page.frameLocator('iframe');\n- expect(await pageScrolls(page)).toBe(false);\n+ expect(await pageScrolls(page)).toBe(true);\n"; + let criteria = crate::passes::stop_judge::acceptance(PORTAL_TICKET); + let flips = minimal_change::vendor_flips("e2e/portal.spec.ts", patch, true, &criteria); + assert_eq!(flips.len(), 1); + assert_eq!(flips[0].criterion, "No double scrollbars on desktop"); + let f = review_rules::vendor_flip_findings(&flips); + assert_eq!( + review_rules::mandatory(&f[0]), + Some(review_rules::REQUIRED_WHY) + ); + assert!(f[0].body.contains("Change the product side first")); +} + +/// The shape the data-pipeline run really had: its plan named the right +/// map, then reused the existing multi-sport link helper, which deletes +/// every link it isn't given, on a sync path that only inserted. The run +/// deleted links nobody asked about. The helper's body says what it does, +/// so the plan is sent back; the plan that inserts with `ON CONFLICT DO +/// NOTHING` and reuses only the read-only lookup passes. +#[test] +fn a_replacing_helper_reused_on_an_insert_only_path_is_sent_back() { + const HELPERS: &str = "CAMP_MULTI_SPORT_OVERRIDES = {\n \"sports academy break camp\": [\"multi-sport\"],\n}\n\n\ndef get_camp_multi_sport_names(name):\n return CAMP_MULTI_SPORT_OVERRIDES.get(name.lower(), [])\n\n\ndef upsert_multi_sport_links(cur, group_id, sport_ids):\n cur.execute(\"DELETE FROM camp_sports WHERE camp_id = %s AND NOT (sport_id = ANY(%s))\", (group_id, sport_ids))\n for sport_id in sport_ids:\n cur.execute(\"INSERT INTO camp_sports VALUES (%s, %s) ON CONFLICT DO NOTHING\", (group_id, sport_id))\n"; + let reuse_replacing = plan( + "## Reuse\n- `CAMP_MULTI_SPORT_OVERRIDES` and `upsert_multi_sport_links` in dags/camps/sports.py (the other two sources already use them)\n\n\ + ## Must not change\nSingle-sport camps.\n\n## Measure first\nNone: the change stays inside this repository.\n\n\ + ## Smallest change\n4 entries in `CAMP_MULTI_SPORT_OVERRIDES`; call `upsert_multi_sport_links` in the 3 write branches.\n\n\ + ## Proof\nOne test of the links per camp.\n", + &format!("- [ ] {MAP_FILE}: 4 entries\n- [ ] {SYNC_FILE}: link the extra sports\n- [ ] tests/test_sports.py: one test"), + ); + let sources = |p: &PlanResult| -> Vec<(String, String, String)> { + plan_shape::reused_functions(p) + .into_iter() + .map(|n| (n, MAP_FILE.to_string(), HELPERS.to_string())) + .collect() + }; + let planned = vec![ + (MAP_FILE.to_string(), HELPERS.to_string()), + (SYNC_FILE.to_string(), BASE_SYNC.to_string()), + ]; + let facts = plan_shape::write_facts(&sources(&reuse_replacing), &planned); + assert!(facts.path_inserts_only, "{facts:?}"); + let g = plan_shape::write_gaps(&reuse_replacing, CAMP_TICKET, &facts); + assert!( + g.iter() + .any(|l| l.contains("`upsert_multi_sport_links` without what it does to stored rows")), + "{g:?}" + ); + assert!( + g.iter() + .any(|l| l.contains("on a path that only inserts today")), + "{g:?}" + ); + // Saying it replaces isn't enough when the ticket asks for no + // replacement; a ticket that asks to replace the links may. + let said = plan( + &reuse_replacing.design.replace( + "(the other two sources already use them)", + "(it replaces a camp's links: DELETE then insert)", + ), + &reuse_replacing.tasks, + ); + let g = plan_shape::write_gaps(&said, CAMP_TICKET, &facts); + assert_eq!(g.len(), 1, "{g:?}"); + assert!(plan_shape::write_gaps(&said, "Replace each camp's sport links", &facts).is_empty()); + // The small plan reuses only the map and the read-only lookup. + let small = camps_plan_after(); + let facts = plan_shape::write_facts(&sources(&small), &planned); + assert!(plan_shape::write_gaps(&small, CAMP_TICKET, &facts).is_empty()); +} diff --git a/services/worker/src/passes/minimal_change.rs b/services/worker/src/passes/minimal_change.rs new file mode 100644 index 000000000..90eb458a0 --- /dev/null +++ b/services/worker/src/passes/minimal_change.rs @@ -0,0 +1,1219 @@ +//! The change is the smallest one that does what the ticket asks. +//! +//! A ticket asked to link four camps to a second sport. The pull request +//! added a second map and helpers beside the existing overrides map, turned +//! an insert-only link sync into a replacing upsert that deleted links +//! nobody asked to delete, added warnings, three summary counters and a log +//! level change in code other pipelines share, and a 432-line test with +//! fake hooks and a payload nobody had seen. The right change was four map +//! entries, an insert that does nothing on conflict in the three write +//! branches, and one small test. +//! +//! Each way the change grew is read here from the diff, with no model: +//! +//! - **A parallel structure** ([`Kind::Parallel`]): a new top-level map, +//! list, constant table or helper whose name shares its words with an +//! existing one in the same file (or another changed file). Extend the +//! existing one. +//! - **Replacing where the base was additive** ([`Kind::Replacing`]): the +//! diff adds deleting or overwriting semantics (`DELETE`, `ON CONFLICT DO +//! UPDATE`, `TRUNCATE TABLE`, `REPLACE INTO`, an ORM delete) the base +//! didn't have there. It blocks unless the ticket asks to delete, replace +//! or overwrite; no reason in the coder's notes excuses it. +//! - **A log level changed** ([`Kind::LogLevel`]): the same log line or +//! logger setting at another level. Other code reads those logs. +//! - **Reporting nobody asked for** ([`Kind::Reporting`]): new counters and +//! log calls in a change whose ticket asks for no report, count or log. +//! - **A test out of proportion** ([`Kind::TestSize`]): many more test +//! lines than changed code lines. +//! - **An invented outside payload** ([`Kind::InventedPayload`]): a test +//! that fakes an outside call with a large payload literal while no probe +//! record (`common::e2e::probe`) shows what the outside system returns. +//! +//! The coder may keep a [`Kind::Parallel`], [`Kind::LogLevel`], +//! [`Kind::Reporting`] or [`Kind::TestSize`] item by saying why on a line +//! `Wider than the ticket: : ` in its notes ([`reasons`]). +//! +//! [`vendor_flips`] is the reviewer's check for a test assertion changed to +//! match another company's page while an acceptance criterion of the ticket +//! says otherwise: the product side changes first. + +use serde::{Deserialize, Serialize}; + +use super::feature::reuse::{name_similarity, name_words}; + +/// Changed files: (path, status, patch), as the compare API gives them. +pub type Diff = [(String, String, String)]; + +/// How a change grew past its ticket. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + Parallel, + Replacing, + LogLevel, + Reporting, + TestSize, + InventedPayload, +} + +/// One way the change is wider than its ticket. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Widening { + pub kind: Kind, + pub path: String, + /// What the diff shows, in a few words (names, the line). + pub what: String, +} + +impl Widening { + /// The heading a report shows it under. + pub fn point(&self) -> &'static str { + match self.kind { + Kind::Parallel => "A parallel structure next to an existing one", + Kind::Replacing => "Deletes or overwrites where the code only added", + Kind::LogLevel => "A log level changed", + Kind::Reporting => "Reporting the ticket doesn't ask for", + Kind::TestSize => "A test out of proportion to the change", + Kind::InventedPayload => "A test payload nobody observed", + } + } + + /// Whether a reason in the coder's notes may keep it. + pub fn excusable(&self) -> bool { + !matches!(self.kind, Kind::Replacing | Kind::InventedPayload) + } + + /// What the coder is told to do, one line. + pub fn instruction(&self) -> String { + let why = if self.excusable() { + format!( + " If the ticket truly needs it, say why on a line `Wider than the ticket: {}: `.", + self.path + ) + } else { + String::new() + }; + let what = match self.kind { + Kind::Parallel => format!( + "`{}` adds {}. Extend the existing one (add the entries or the parameter there) and remove the new one.", + self.path, self.what + ), + Kind::Replacing => format!( + "`{}` now deletes or overwrites stored data ({}) where the base only added, and the ticket doesn't ask for that. Keep the write additive (insert, `ON CONFLICT DO NOTHING`) and remove the delete or overwrite.", + self.path, self.what + ), + Kind::LogLevel => format!( + "`{}` changes a log level ({}). Other code and people read those logs; put it back.", + self.path, self.what + ), + Kind::Reporting => format!( + "`{}` adds reporting the ticket doesn't ask for ({}). Remove the new counters and log lines; follow how the surrounding code already handles the case.", + self.path, self.what + ), + Kind::TestSize => format!( + "The tests are {} for this change. Cut them to the cases the ticket names: the new behaviour and that nothing else changed, through the code's real entry point.", + self.what + ), + Kind::InventedPayload => format!( + "`{}` fakes an outside call with a payload nobody observed ({}). Build the fixture from a real response (probe it, or copy an existing fixture in the repository), or test the change below the outside call.", + self.path, self.what + ), + }; + format!("{what}{why}") + } +} + +// ── Words ────────────────────────────────────────────────────────────────── + +/// Whether the ticket's words ask for any of `words`. +pub fn ticket_asks(ticket: &str, words: &[&str]) -> bool { + let t = ticket.to_lowercase(); + words.iter().any(|w| t.contains(w)) +} + +/// Ticket words that ask to delete, replace or overwrite. +pub const REPLACE_ASKS: &[&str] = &[ + "delete", + "remove", + "replace", + "overwrite", + "prune", + "purge", + "clean up", + "cleanup", + "dedup", + "upsert", + "update existing", + "resync", + "re-sync", + "truncate", + "unlink", + "no longer", + "drop ", +]; + +/// Ticket words that ask about logging. +pub const LOG_ASKS: &[&str] = &["log", "verbose", "noisy", "debug"]; + +/// Ticket words that ask for reporting. +pub const REPORT_ASKS: &[&str] = &[ + "report", "count", "metric", "summary", "warn", "alert", "log", "monitor", "observab", +]; + +const OUTSIDE_LINE: &str = "wider than the ticket:"; + +/// The coder's reasons for keeping a wider change, from its notes +/// (`Wider than the ticket: : `). +pub fn reasons(notes: &str) -> Vec<(String, String)> { + notes + .lines() + .filter_map(|l| { + let l = l.trim().trim_start_matches(['-', '*']).trim(); + let at = l.to_ascii_lowercase().find(OUTSIDE_LINE)?; + let rest = l[at + OUTSIDE_LINE.len()..].trim(); + let (path, why) = rest.split_once(": ")?; + let path = path.trim().trim_matches('`').trim(); + let why = why.trim(); + (!path.is_empty() && !why.is_empty()).then(|| (path.to_string(), why.to_string())) + }) + .collect() +} + +// ── Files and lines ──────────────────────────────────────────────────────── + +fn is_test(path: &str) -> bool { + super::habits::is_test_path(path) + || path.to_ascii_lowercase().contains("/e2e/") + || path.to_ascii_lowercase().starts_with("e2e/") + || path.contains("/fixtures/") + || path.contains("/__fixtures__/") + || path.contains("/testdata/") +} + +fn code_file(path: &str) -> bool { + let l = path.to_lowercase(); + [ + ".sql", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".py", ".rb", ".go", ".rs", ".kt", ".java", + ".cs", ".php", ".scala", + ] + .iter() + .any(|e| l.ends_with(e)) + && !l.contains(".d.ts") + && !l.contains("/generated/") +} + +fn ext(path: &str) -> &str { + path.rsplit('.').next().unwrap_or("") +} + +/// A patch's added (`+`) or removed (`-`) lines, without headers. +fn lines_of(patch: &str, sign: char) -> Vec<&str> { + let header = if sign == '+' { "+++" } else { "---" }; + patch + .lines() + .filter(|l| l.starts_with(sign) && !l.starts_with(header)) + .map(|l| &l[1..]) + .collect() +} + +/// A patch's unchanged context lines. +fn context_of(patch: &str) -> Vec<&str> { + patch + .lines() + .filter(|l| l.starts_with(' ')) + .map(|l| &l[1..]) + .collect() +} + +fn non_blank(lines: &[&str]) -> usize { + lines.iter().filter(|l| !l.trim().is_empty()).count() +} + +// ── Definitions ──────────────────────────────────────────────────────────── + +/// What a top-level definition is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DefKind { + /// A map, list, set or object literal: a lookup table or config. + Table, + /// A function or method at the top level. + Function, +} + +/// A top-level definition. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Def { + pub name: String, + pub kind: DefKind, +} + +fn ident(s: &str) -> Option { + let n: String = s + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$') + .collect(); + (n.len() >= 3 && !n.chars().next().is_some_and(|c| c.is_ascii_digit())).then_some(n) +} + +fn table_value(v: &str) -> bool { + let v = v.trim_start(); + [ + "{", + "[", + "(", + "dict(", + "frozenset(", + "set(", + "mappingproxytype(", + "new map", + "new set", + "object.freeze(", + "map[", + "phf_map!", + "hashmap", + "btreemap", + "&[", + ] + .iter() + .any(|p| v.to_lowercase().starts_with(p)) +} + +/// The definition a line makes at the top level of a file, by language. +/// Indented lines (inside a class or function) define nothing here. +pub fn top_level_def(line: &str, path: &str) -> Option { + if line.starts_with([' ', '\t']) || line.trim().is_empty() { + return None; + } + let l = line.trim_end(); + match ext(path) { + "py" => { + if let Some(r) = l + .strip_prefix("def ") + .or_else(|| l.strip_prefix("async def ")) + { + return ident(r).map(|name| Def { + name, + kind: DefKind::Function, + }); + } + let (lhs, rhs) = l.split_once('=')?; + if rhs.starts_with('=') || lhs.contains('(') { + return None; + } + let name = ident(lhs.split(':').next()?.trim())?; + table_value(rhs).then_some(Def { + name, + kind: DefKind::Table, + }) + } + "ts" | "tsx" | "js" | "jsx" | "mjs" | "cjs" => { + let r = l.strip_prefix("export ").unwrap_or(l); + let r = r.strip_prefix("default ").unwrap_or(r); + let r = r.strip_prefix("async ").unwrap_or(r); + if let Some(f) = r.strip_prefix("function ") { + return ident(f.trim_start_matches('*').trim_start()).map(|name| Def { + name, + kind: DefKind::Function, + }); + } + let decl = ["const ", "let ", "var "] + .iter() + .find_map(|k| r.strip_prefix(k))?; + let name = ident(decl)?; + let rhs = decl.split_once('=')?.1.trim_start(); + let rhs_l = rhs.to_lowercase(); + if rhs_l.starts_with("(") && (rhs_l.contains("=>") || rhs_l.starts_with("(async")) + || rhs_l.starts_with("async") + || rhs_l.starts_with("function") + { + return Some(Def { + name, + kind: DefKind::Function, + }); + } + table_value(rhs).then_some(Def { + name, + kind: DefKind::Table, + }) + } + "rs" => { + let r = l + .strip_prefix("pub(crate) ") + .or_else(|| l.strip_prefix("pub(super) ")) + .or_else(|| l.strip_prefix("pub ")) + .unwrap_or(l); + let r = r.strip_prefix("async ").unwrap_or(r); + if let Some(f) = r.strip_prefix("fn ") { + return ident(f).map(|name| Def { + name, + kind: DefKind::Function, + }); + } + let decl = ["static ", "const "] + .iter() + .find_map(|k| r.strip_prefix(k))?; + let name = ident(decl)?; + let (ty, rhs) = decl.split_once('=').unwrap_or((decl, "")); + let ty = ty.to_lowercase(); + (ty.contains("map") || ty.contains('[') || ty.contains("set") || table_value(rhs)) + .then_some(Def { + name, + kind: DefKind::Table, + }) + } + "go" => { + if let Some(f) = l.strip_prefix("func ") { + return ident(f).map(|name| Def { + name, + kind: DefKind::Function, + }); + } + let decl = l.strip_prefix("var ")?; + let name = ident(decl)?; + let rhs = decl.split_once('=')?.1; + table_value(rhs).then_some(Def { + name, + kind: DefKind::Table, + }) + } + "rb" => { + let (lhs, rhs) = l.split_once('=')?; + let name = ident(lhs.trim())?; + (name + .chars() + .all(|c| c.is_ascii_uppercase() || c == '_' || c.is_ascii_digit()) + && table_value(rhs)) + .then_some(Def { + name, + kind: DefKind::Table, + }) + } + _ => None, + } +} + +/// Every top-level definition in `text`. +pub fn defs(text: &str, path: &str) -> Vec { + text.lines() + .filter_map(|l| top_level_def(l, path)) + .collect() +} + +/// Whether a new definition parallels an existing one: the same kind, and +/// names that share at least two words and half of the smaller name's. +pub fn parallels(new: &Def, old: &Def) -> bool { + if new.kind != old.kind || new.name == old.name { + return false; + } + let a = name_words(&new.name); + let b = name_words(&old.name); + let shared = a.iter().filter(|w| b.contains(w)).count(); + let smaller = a.len().min(b.len()).max(1); + shared >= 2 && shared * 2 >= smaller && name_similarity(&new.name, &old.name) >= 0.34 +} + +/// The new definitions of an edit that parallel one already in the file, +/// as (new, existing). An existing one the edit removes was renamed, not +/// paralleled. +pub fn parallel_in_edit(path: &str, old: &str, new: &str) -> Vec<(Def, Def)> { + let before = defs(old, path); + let after = defs(new, path); + let mut out = Vec::new(); + for d in after + .iter() + .filter(|d| !before.iter().any(|b| b.name == d.name)) + { + if let Some(e) = before + .iter() + .filter(|b| after.iter().any(|a| a.name == b.name)) + .find(|b| parallels(d, b)) + { + out.push((d.clone(), e.clone())); + } + } + out +} + +/// The parallel structures a diff adds: new top-level definitions next to +/// a similar existing one in the same file's base (`base`, by path) or its +/// patch's context, or in another changed file's base. +pub fn parallel_structures(diff: &Diff, base: &[(String, String)]) -> Vec { + let mut out = Vec::new(); + for (path, status, patch) in diff { + if status == "removed" || !code_file(path) || is_test(path) { + continue; + } + let removed: Vec = lines_of(patch, '-') + .into_iter() + .filter_map(|l| top_level_def(l, path)) + .collect(); + let mut existing: Vec = base + .iter() + .filter(|(p, _)| p == path) + .flat_map(|(_, t)| defs(t, path)) + .collect(); + existing.extend( + context_of(patch) + .into_iter() + .filter_map(|l| top_level_def(l, path)), + ); + existing.retain(|e| !removed.iter().any(|r| r.name == e.name)); + for d in lines_of(patch, '+') + .into_iter() + .filter_map(|l| top_level_def(l, path)) + { + if existing.iter().any(|e| e.name == d.name) { + continue; + } + if let Some(e) = existing.iter().find(|e| parallels(&d, e)) { + let what = format!("`{}` next to the existing `{}`", d.name, e.name); + if !out.iter().any(|w: &Widening| w.what == what) { + out.push(Widening { + kind: Kind::Parallel, + path: path.clone(), + what, + }); + } + } + } + } + out +} + +// ── Replacing semantics ──────────────────────────────────────────────────── + +/// Statements that delete or overwrite stored rows, with how a report +/// names each. +const REPLACING: &[(&str, &str)] = &[ + ("do update", "`ON CONFLICT DO UPDATE`"), + ("on_conflict_do_update", "`on_conflict_do_update`"), + ("delete from", "`DELETE FROM`"), + ("truncate table", "`TRUNCATE TABLE`"), + ("insert or replace", "`INSERT OR REPLACE`"), + ("replace into", "`REPLACE INTO`"), + ("when matched then update", "`MERGE ... UPDATE`"), + ("when matched then delete", "`MERGE ... DELETE`"), + ( + "when not matched by source", + "`MERGE ... NOT MATCHED BY SOURCE`", + ), + (".delete()", "an ORM delete"), + ("delete_many(", "`delete_many`"), + ("destroy_all", "`destroy_all`"), + ("bulk_delete", "a bulk delete"), + ("drop table", "`DROP TABLE`"), +]; + +fn count(lines: &[&str], token: &str) -> usize { + lines + .iter() + .filter(|l| { + let t = l.trim_start(); + !(t.starts_with("--") || t.starts_with('#') || t.starts_with("//")) + }) + .map(|l| l.to_lowercase().matches(token).count()) + .sum() +} + +/// Deleting or overwriting statements the diff adds where its base had +/// none of that kind: an insert-only path made replacing. +pub fn replacing(diff: &Diff, base: &[(String, String)]) -> Vec { + let mut out = Vec::new(); + for (path, status, patch) in diff { + if status == "removed" || !code_file(path) || is_test(path) { + continue; + } + let added = lines_of(patch, '+'); + let removed = lines_of(patch, '-'); + let base_text = base + .iter() + .find(|(p, _)| p == path) + .map(|(_, t)| t.as_str()); + let mut found = Vec::new(); + for (token, name) in REPLACING { + let a = count(&added, token); + if a == 0 || a <= count(&removed, token) { + continue; + } + // The base file had none of it: the path was additive. In a new + // file every one is new. + let had = base_text + .map(|t| t.to_lowercase().matches(token).count()) + .unwrap_or_else(|| count(&context_of(patch), token)); + if status == "added" || had == 0 { + found.push(*name); + } + } + if !found.is_empty() { + out.push(Widening { + kind: Kind::Replacing, + path: path.clone(), + what: found.join(", "), + }); + } + } + out +} + +// ── What a helper does to stored rows ────────────────────────────────────── + +/// What a function does to rows already stored. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Writes { + /// It adds rows and leaves existing ones as they are. + InsertOnly, + /// It deletes, overwrites or replaces existing rows; the statements + /// that show it. + Replacing(Vec), + /// It writes nothing the check can see. + None, +} + +const INSERTS: &[&str] = &[ + "insert into", + "do nothing", + "on_conflict_do_nothing", + "bulk_create(", + "insert_many(", + "insert_one(", + ".add(", + ".create(", + "get_or_create(", +]; + +/// The text of the top-level definition `name` in `text`: from its line to +/// the next top-level definition (or a line back at the left margin that +/// isn't a closing bracket or a decorator). +pub fn body_of(text: &str, path: &str, name: &str) -> Option { + let lines: Vec<&str> = text.lines().collect(); + let start = lines + .iter() + .position(|l| top_level_def(l, path).is_some_and(|d| d.name == name))?; + let mut out = vec![lines[start]]; + for l in &lines[start + 1..] { + let t = l.trim_start(); + let at_margin = !l.is_empty() && !l.starts_with([' ', '\t']); + if at_margin && !(t.starts_with('}') || t.starts_with(')') || t.starts_with(']')) { + break; + } + out.push(l); + } + Some(out.join("\n")) +} + +/// What a function body does to stored rows: deleting or overwriting +/// statements (or a delete followed by an insert, a `.set(` that replaces a +/// relation) make it replacing; an insert with none of them, insert only. +pub fn write_semantics(body: &str) -> Writes { + let lines: Vec<&str> = body + .lines() + .filter(|l| { + let t = l.trim_start(); + !(t.starts_with('#') || t.starts_with("//") || t.starts_with("--")) + }) + .collect(); + let low = lines.join("\n").to_lowercase(); + let mut how: Vec = REPLACING + .iter() + .filter(|(t, _)| low.contains(t)) + .map(|(_, n)| n.to_string()) + .collect(); + let writes_db = [ + "execute(", "query(", ".save(", "insert", "session.", "cursor", + ] + .iter() + .any(|w| low.contains(w)); + if low.contains(".set(") && writes_db { + how.push("a `.set(` that replaces a relation".to_string()); + } + let delete = low.find("delete ").or_else(|| low.find("delete(")); + let insert = low.rfind("insert"); + if let (Some(d), Some(i)) = (delete, insert) { + if d < i && !how.iter().any(|h| h.contains("DELETE")) { + how.push("a delete followed by an insert".to_string()); + } + } + if !how.is_empty() { + return Writes::Replacing(how); + } + if INSERTS.iter().any(|t| low.contains(t)) { + return Writes::InsertOnly; + } + Writes::None +} + +/// Whether the code paths in `texts` only insert: at least one insert and +/// no deleting or overwriting statement. +pub fn inserts_only(texts: &[&str]) -> bool { + let all = texts.join("\n"); + matches!(write_semantics(&all), Writes::InsertOnly) +} + +// ── Logging and reporting ────────────────────────────────────────────────── + +const LEVELS: &[&str] = &[ + "warning", "critical", "debug", "info", "warn", "error", "fatal", "trace", +]; + +fn level_free(line: &str) -> String { + let mut s = line.trim().to_lowercase(); + for l in LEVELS { + s = s.replace(l, ""); + } + s +} + +fn has_level(line: &str) -> bool { + let l = line.to_lowercase(); + LEVELS.iter().any(|w| l.contains(w)) + && (l.contains("log") || l.contains("!(") || l.contains("setlevel") || l.contains("level")) +} + +/// Log lines and logger settings the diff keeps but moves to another level. +pub fn log_levels(diff: &Diff) -> Vec { + let mut out = Vec::new(); + for (path, status, patch) in diff { + if status == "removed" || is_test(path) { + continue; + } + let removed: Vec<&str> = lines_of(patch, '-') + .into_iter() + .filter(|l| has_level(l)) + .collect(); + for a in lines_of(patch, '+').into_iter().filter(|l| has_level(l)) { + if let Some(r) = removed.iter().find(|r| { + level_free(r) == level_free(a) && r.trim().to_lowercase() != a.trim().to_lowercase() + }) { + out.push(Widening { + kind: Kind::LogLevel, + path: path.clone(), + what: format!( + "`{}` became `{}`", + common::truncate_str(r.trim(), 80), + common::truncate_str(a.trim(), 80) + ), + }); + break; + } + } + } + out +} + +fn is_counter(line: &str) -> bool { + let l = line.to_lowercase().replace(' ', ""); + l.contains("+=1") + || l.contains("++;") + || l.contains(".inc(") + || l.contains("counter(") + || l.contains("fetch_add(") +} + +fn is_log_call(line: &str) -> bool { + let l = line.trim_start().to_lowercase(); + [ + "logger.", + "logging.", + "log.", + "self.log.", + "warn!(", + "info!(", + "debug!(", + "console.warn(", + "console.info(", + "console.debug(", + "warnings.warn(", + ] + .iter() + .any(|p| l.starts_with(p) || l.contains(&format!(" {p}")) || l.contains(&format!("({p}"))) +} + +/// New counters and log calls in non-test code: (counters, log calls). +pub fn reporting_added(diff: &Diff) -> Vec<(String, usize, usize)> { + diff.iter() + .filter(|(p, s, _)| s != "removed" && code_file(p) && !is_test(p)) + .map(|(p, _, patch)| { + let added = lines_of(patch, '+'); + let removed = lines_of(patch, '-'); + let counters = added.iter().filter(|l| is_counter(l)).count(); + let logs = added.iter().filter(|l| is_log_call(l)).count(); + let was_counters = removed.iter().filter(|l| is_counter(l)).count(); + let was_logs = removed.iter().filter(|l| is_log_call(l)).count(); + ( + p.clone(), + counters.saturating_sub(was_counters), + logs.saturating_sub(was_logs), + ) + }) + .filter(|(_, c, l)| *c > 0 || *l > 0) + .collect() +} + +/// Reporting the diff adds that the ticket doesn't ask for: two or more new +/// counters, a counter and a log call, or three or more log calls in a file. +pub fn reporting(diff: &Diff) -> Vec { + reporting_added(diff) + .into_iter() + .filter(|(_, c, l)| *c >= 2 || (*c >= 1 && *l >= 1) || *l >= 3) + .map(|(path, c, l)| Widening { + kind: Kind::Reporting, + path, + what: format!("{c} new counter(s), {l} new log call(s)"), + }) + .collect() +} + +// ── Tests ────────────────────────────────────────────────────────────────── + +/// Added test lines against added code lines: a test of more than 200 +/// lines and twice the code, or more than 120 lines and four times it. +pub fn test_size(diff: &Diff) -> Vec { + let mut tests = 0; + let mut code = 0; + let mut biggest = (String::new(), 0usize); + for (path, status, patch) in diff { + if status == "removed" { + continue; + } + let n = non_blank(&lines_of(patch, '+')); + if is_test(path) { + tests += n; + if n > biggest.1 { + biggest = (path.clone(), n); + } + } else if code_file(path) { + code += n; + } + } + let out_of_proportion = (tests > 200 && tests > 2 * code) || (tests > 120 && tests > 4 * code); + if !out_of_proportion { + return Vec::new(); + } + vec![Widening { + kind: Kind::TestSize, + path: biggest.0, + what: format!("{tests} added lines against {code} lines of changed code"), + }] +} + +const FAKES: &[&str] = &[ + "class fake", + "class mock", + "class stub", + "magicmock(", + "mock.patch(", + "@patch(", + "monkeypatch.setattr(", + "responses.add(", + "nock(", + "route.fulfill(", + "jest.mock(", + "vi.mock(", + "mockresolvedvalue(", + "mockreturnvalue(", + "httpretty.register_uri(", + "requests_mock", +]; + +fn payload_key(line: &str) -> bool { + let t = line.trim_start(); + let Some(q) = t.chars().next().filter(|c| matches!(c, '"' | '\'')) else { + return false; + }; + let rest = &t[1..]; + let Some(end) = rest.find(q) else { + return false; + }; + let key = &rest[..end]; + !key.is_empty() + && key + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')) + && rest[end + 1..].trim_start().starts_with(':') +} + +/// Tests that fake an outside call with a large payload literal (twelve or +/// more keys), or add a JSON fixture of that size, while no probe record +/// shows what the outside system returns. +pub fn invented_payloads(diff: &Diff, has_probe: bool) -> Vec { + if has_probe { + return Vec::new(); + } + let mut out = Vec::new(); + for (path, status, patch) in diff { + if status == "removed" || !is_test(path) { + continue; + } + let added = lines_of(patch, '+'); + let keys = added.iter().filter(|l| payload_key(l)).count(); + let low = added.join("\n").to_lowercase(); + let fakes = FAKES.iter().filter(|f| low.contains(*f)).count(); + let fixture = path.ends_with(".json") && status == "added"; + if keys >= 12 && (fakes > 0 || fixture) { + out.push(Widening { + kind: Kind::InventedPayload, + path: path.clone(), + what: format!( + "{keys} payload keys{}", + if fakes > 0 { + format!(" behind {fakes} kind(s) of fake") + } else { + " in a new fixture".to_string() + } + ), + }); + } + } + out +} + +// ── The check ────────────────────────────────────────────────────────────── + +/// Everything a diff adds past its ticket. `base` holds the base text of +/// changed files where read; `ticket` is the ticket's own words (title, +/// body, people's answers); `has_probe` says a probe record is in the tree. +pub fn check( + diff: &Diff, + base: &[(String, String)], + ticket: &str, + has_probe: bool, +) -> Vec { + let mut out = parallel_structures(diff, base); + if !ticket_asks(ticket, REPLACE_ASKS) { + out.extend(replacing(diff, base)); + } + if !ticket_asks(ticket, LOG_ASKS) { + out.extend(log_levels(diff)); + } + if !ticket_asks(ticket, REPORT_ASKS) { + out.extend(reporting(diff)); + } + out.extend(test_size(diff)); + out.extend(invented_payloads(diff, has_probe)); + out +} + +/// What still stands after the coder's reasons: an excusable item with a +/// reason for its path is kept as said, the rest go back. +pub fn standing<'a>(found: &'a [Widening], notes: &str) -> Vec<&'a Widening> { + let why = reasons(notes); + found + .iter() + .filter(|w| !(w.excusable() && why.iter().any(|(p, _)| p.trim() == w.path.trim()))) + .collect() +} + +// ── Test assertions changed to match another company's page ──────────────── + +/// An assertion a test change flipped to what an outside page does, while +/// an acceptance criterion of the ticket says otherwise. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VendorFlip { + pub path: String, + pub removed: String, + pub added: String, + pub criterion: String, +} + +impl VendorFlip { + /// The review finding's text. + pub fn body(&self) -> String { + format!( + "`{}` changes `{}` to `{}`, matching what the outside page does, while the ticket's acceptance criterion says \"{}\". Change the product side first (the layout around the frame, the page's own code, the vendor's documented embed options) so the criterion holds, and keep the assertion. Change the test only when the product can't meet the criterion, with the measured reason in the plan and the pull request.", + self.path, + common::truncate_str(self.removed.trim(), 120), + common::truncate_str(self.added.trim(), 120), + self.criterion + ) + } +} + +/// The subject of an `expect(...)` and the rest of the assertion. +fn assertion(line: &str) -> Option<(String, String)> { + let at = line.find("expect(")?; + let rest = &line[at + 7..]; + let mut depth = 1; + for (i, c) in rest.char_indices() { + match c { + '(' => depth += 1, + ')' => { + depth -= 1; + if depth == 0 { + return Some(( + rest[..i].trim().to_string(), + rest[i + 1..].trim().to_string(), + )); + } + } + _ => {} + } + } + None +} + +/// Assertions a patch changed: a removed and an added `expect` on the same +/// subject with another matcher or value. +pub fn assertion_flips(patch: &str) -> Vec<(String, String)> { + let removed: Vec<&str> = lines_of(patch, '-'); + let mut out = Vec::new(); + for a in lines_of(patch, '+') { + let Some((sa, ra)) = assertion(a) else { + continue; + }; + if let Some(r) = removed + .iter() + .find(|r| assertion(r).is_some_and(|(sr, rr)| sr == sa && rr != ra)) + { + out.push((r.to_string(), a.to_string())); + } + } + out +} + +const CODE_WORDS: &[&str] = &[ + "expect", + "await", + "const", + "locator", + "frame", + "frames", + "tobe", + "true", + "false", + "toequal", + "page", + "getbytestid", + "evaluate", + "document", + "window", + "toBeVisible", + "tohave", +]; + +fn stems(text: &str) -> Vec { + text.split(|c: char| !c.is_ascii_alphanumeric()) + .flat_map(name_words) + .filter(|w| w.len() >= 5 && !CODE_WORDS.iter().any(|c| c.eq_ignore_ascii_case(w))) + .map(|w| w.chars().take(5).collect()) + .collect() +} + +/// The vendor flips in a changed test file: `outside` says the file drives +/// another company's page; each flipped assertion is matched to the +/// acceptance criterion it shares words with. +pub fn vendor_flips( + path: &str, + patch: &str, + outside: bool, + criteria: &[String], +) -> Vec { + if !outside || criteria.is_empty() { + return Vec::new(); + } + let mut out = Vec::new(); + for (removed, added) in assertion_flips(patch) { + let words = stems(&format!("{removed} {added}")); + let best = criteria + .iter() + .map(|c| { + let cw = stems(c); + (words.iter().filter(|w| cw.contains(w)).count(), c) + }) + .filter(|(n, _)| *n > 0) + .max_by_key(|(n, _)| *n); + if let Some((_, c)) = best { + out.push(VendorFlip { + path: path.to_string(), + removed, + added, + criterion: c.clone(), + }); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn d(path: &str, status: &str, patch: &str) -> (String, String, String) { + (path.into(), status.into(), patch.into()) + } + + #[test] + fn definitions_by_language() { + let py = + "CAMP_MULTI_SPORT_OVERRIDES = {\ndef get_camp_multi_sport_names(name):\n X = {}"; + let got = defs(py, "dags/camps.py"); + assert_eq!(got.len(), 2); + assert_eq!(got[0].kind, DefKind::Table); + assert_eq!(got[1].kind, DefKind::Function); + let ts = "export const SPORT_MAP: Record = {\nexport function sportFor(x) {\nconst handler = async (e) => {"; + let got = defs(ts, "src/a.ts"); + assert_eq!( + got.iter().map(|d| d.name.as_str()).collect::>(), + vec!["SPORT_MAP", "sportFor", "handler"] + ); + let rs = "pub const RULES: &[&str] = &[\npub(crate) fn rules_for() {}"; + assert_eq!(defs(rs, "a.rs").len(), 2); + } + + #[test] + fn a_second_map_next_to_the_first_is_a_parallel_structure() { + let base = vec![( + "dags/camps.py".to_string(), + "CAMP_MULTI_SPORT_OVERRIDES = {\n \"a\": [\"Soccer\"],\n}\n\ndef get_camp_multi_sport_names(name):\n return CAMP_MULTI_SPORT_OVERRIDES.get(name, [])\n".to_string(), + )]; + let patch = "@@ -1,3 +1,9 @@\n CAMP_MULTI_SPORT_OVERRIDES = {\n+CAMP_SWIMMING_OVERRIDES = {\n+ \"b\": [\"Swimming\"],\n+}\n+def get_camp_swimming_names(name):\n+ return CAMP_SWIMMING_OVERRIDES.get(name, [])\n"; + let w = parallel_structures(&[d("dags/camps.py", "modified", patch)], &base); + assert_eq!(w.len(), 2, "{w:?}"); + assert!(w[0].what.contains("CAMP_SWIMMING_OVERRIDES")); + assert!(w[0].what.contains("CAMP_MULTI_SPORT_OVERRIDES")); + assert!(w[1].what.contains("get_camp_multi_sport_names")); + // Four new entries in the existing map are no new structure. + let small = "@@ -1,3 +1,7 @@\n CAMP_MULTI_SPORT_OVERRIDES = {\n+ \"c\": [\"Swimming\", \"Tennis\"],\n"; + assert!(parallel_structures(&[d("dags/camps.py", "modified", small)], &base).is_empty()); + // A rename is not a parallel. + let rename = "-CAMP_MULTI_SPORT_OVERRIDES = {\n+CAMP_SPORT_OVERRIDES = {\n"; + assert!(parallel_structures(&[d("dags/camps.py", "modified", rename)], &base).is_empty()); + } + + #[test] + fn insert_only_made_replacing_blocks_unless_asked() { + let patch = "- ON CONFLICT (camp_id, sport_id) DO NOTHING\n+ ON CONFLICT (camp_id, sport_id) DO UPDATE SET sport_id = EXCLUDED.sport_id\n+DELETE FROM camp_sports WHERE camp_id = %s AND sport_id <> ALL(%s)\n"; + let base = vec![( + "dags/sync.py".to_string(), + "INSERT INTO camp_sports VALUES (%s, %s) ON CONFLICT (camp_id, sport_id) DO NOTHING" + .to_string(), + )]; + let diff = [d("dags/sync.py", "modified", patch)]; + let w = check( + &diff, + &base, + "Link these four camps to Swimming as well", + false, + ); + let r: Vec<&Widening> = w.iter().filter(|w| w.kind == Kind::Replacing).collect(); + assert_eq!(r.len(), 1); + assert!(r[0].what.contains("DO UPDATE") && r[0].what.contains("DELETE FROM")); + assert!(!r[0].excusable()); + assert!(standing(&w, "Wider than the ticket: dags/sync.py: cleaner").len() == w.len()); + // A ticket that asks to remove stale links may. + assert!( + check(&diff, &base, "Remove links that no longer apply", false) + .iter() + .all(|w| w.kind != Kind::Replacing) + ); + // An additive insert is fine. + let add = "+ INSERT INTO camp_sports VALUES (%s, %s) ON CONFLICT DO NOTHING\n"; + assert!(replacing(&[d("dags/sync.py", "modified", add)], &base).is_empty()); + } + + #[test] + fn log_levels_and_new_reporting() { + let patch = "-logger.setLevel(logging.INFO)\n+logger.setLevel(logging.DEBUG)\n+ skipped += 1\n+ linked += 1\n+ log.warning(\"skipped %s\", ids)\n"; + let diff = [d("dags/common/log.py", "modified", patch)]; + let w = check(&diff, &[], "Link four camps to Swimming", false); + assert!(w.iter().any(|w| w.kind == Kind::LogLevel), "{w:?}"); + assert!(w.iter().any(|w| w.kind == Kind::Reporting), "{w:?}"); + // A reason keeps an excusable item. + let kept = standing( + &w, + "Wider than the ticket: dags/common/log.py: the ticket's comment asks for the count", + ); + assert!(kept.is_empty()); + // A ticket that asks for logging gets it. + assert!(check(&diff, &[], "Log how many camps were skipped", false).is_empty()); + // One new log line in a change is ordinary. + let one = [d("a.py", "modified", "+ log.info(\"done\")\n")]; + assert!(reporting(&one).is_empty()); + } + + #[test] + fn tests_in_proportion_and_payloads_observed() { + let code: String = (0..20).map(|i| format!("+ x{i} = 1\n")).collect(); + let test: String = (0..430).map(|i| format!("+ assert y{i}\n")).collect(); + let diff = [ + d("dags/sync.py", "modified", &code), + d("tests/test_sync.py", "added", &test), + ]; + let w = test_size(&diff); + assert_eq!(w.len(), 1); + assert!(w[0].what.contains("430 added lines against 20")); + let small: String = (0..30).map(|i| format!("+ assert y{i}\n")).collect(); + assert!(test_size(&[ + d("dags/sync.py", "modified", &code), + d("tests/test_sync.py", "added", &small) + ]) + .is_empty()); + + let payload: String = std::iter::once("+class FakeVendorHook:\n".to_string()) + .chain((0..14).map(|i| format!("+ \"field_{i}\": \"v\",\n"))) + .collect(); + let diff = [d("tests/test_sync.py", "added", &payload)]; + assert_eq!(invented_payloads(&diff, false).len(), 1); + assert!(invented_payloads(&diff, true).is_empty()); + } + + #[test] + fn a_test_flipped_to_the_vendor_while_a_criterion_says_otherwise() { + let patch = "- expect(await frameScrolls(page)).toBe(false);\n+ expect(await frameScrolls(page)).toBe(true);\n"; + let criteria = vec![ + "The portal loads inside the page".to_string(), + "No double scrollbars on desktop".to_string(), + ]; + let f = vendor_flips("e2e/portal.spec.ts", patch, true, &criteria); + assert_eq!(f.len(), 1); + assert_eq!(f[0].criterion, "No double scrollbars on desktop"); + assert!(f[0].body().contains("Change the product side first")); + // Our own page, or no criterion, is a test's own business. + assert!(vendor_flips("e2e/portal.spec.ts", patch, false, &criteria).is_empty()); + assert!(vendor_flips("e2e/portal.spec.ts", patch, true, &[]).is_empty()); + } + + #[test] + fn what_a_helper_does_to_existing_rows() { + let text = "def upsert_multi_sport_links(cur, group_id, sport_ids):\n cur.execute(\"DELETE FROM group_sport WHERE group_id = %s AND NOT (sport_id = ANY(%s))\", (group_id, sport_ids))\n for s in sport_ids:\n cur.execute(\"INSERT INTO group_sport VALUES (%s, %s) ON CONFLICT DO NOTHING\", (group_id, s))\n\n\ndef upsert_group_sport_link(cur, group_id, sport_id):\n cur.execute(\"INSERT INTO group_sport VALUES (%s, %s) ON CONFLICT DO NOTHING\", (group_id, sport_id))\n\n\ndef sport_names(name):\n return OVERRIDES.get(name, [])\n"; + let replacing = body_of(text, "a.py", "upsert_multi_sport_links").unwrap(); + assert!(!replacing.contains("def upsert_group_sport_link")); + assert_eq!( + write_semantics(&replacing), + Writes::Replacing(vec!["`DELETE FROM`".to_string()]) + ); + let insert = body_of(text, "a.py", "upsert_group_sport_link").unwrap(); + assert_eq!(write_semantics(&insert), Writes::InsertOnly); + let read = body_of(text, "a.py", "sport_names").unwrap(); + assert_eq!(write_semantics(&read), Writes::None); + assert!(inserts_only(&[&insert])); + assert!(!inserts_only(&[&insert, &replacing])); + // An upsert that overwrites, and a relation replaced with `.set(`. + assert!(matches!( + write_semantics("INSERT INTO t VALUES (1) ON CONFLICT (id) DO UPDATE SET v = 1"), + Writes::Replacing(_) + )); + assert!(matches!( + write_semantics("group.sports.set(ids)\ngroup.save()"), + Writes::Replacing(_) + )); + assert_eq!(write_semantics("cache.set(k, v)"), Writes::None); + // A TypeScript helper body ends at its closing brace. + let ts = "export function linkAll(db, ids) {\n return db.query('DELETE FROM l WHERE id = $1', ids);\n}\nexport const other = 1;\n"; + assert!(matches!( + write_semantics(&body_of(ts, "a.ts", "linkAll").unwrap()), + Writes::Replacing(_) + )); + } + + #[test] + fn an_edit_that_adds_a_parallel_helper() { + let old = "SPORT_OVERRIDES = {\n}\ndef sport_overrides_for(n):\n pass\n"; + let new = format!("{old}SWIM_SPORT_OVERRIDES = {{\n}}\n"); + let p = parallel_in_edit("a.py", old, &new); + assert_eq!(p.len(), 1); + assert_eq!(p[0].1.name, "SPORT_OVERRIDES"); + assert!(parallel_in_edit("a.py", old, old).is_empty()); + } +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 66c58ea2e..e4dc198dd 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1277,6 +1277,7 @@ pub mod e2e_attribution; pub mod e2e_reads; pub mod e2e_setup; pub mod email_events; +mod explore_guard; pub mod feature; pub mod feedback; pub mod file_claims; @@ -1316,6 +1317,7 @@ mod log_fix_checks; #[cfg(test)] mod log_fix_eval; pub mod log_look; +pub mod minimal_change; pub mod model_check; #[cfg(test)] mod model_route_eval; @@ -1336,6 +1338,7 @@ pub(crate) mod plan_coverage; pub mod plan_execute; mod plan_judge; pub(crate) mod plan_sections; +mod plan_shape; /// Plugin runs, publishing, source sync and results. pub mod plugins; mod pr; @@ -1422,6 +1425,7 @@ pub(crate) mod terraform; mod test; pub mod test_bug; pub mod test_fix; +pub(crate) mod test_setup; pub mod ticket_base; pub mod ticket_comments; pub mod ticket_history; diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 40e1dedf3..1566089a4 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -305,11 +305,12 @@ pub async fn run( that CoderHelm carries out to the end, verification included.\n\n\ You have access to these repos:\n{repos_list}\n\n\ All tools default to {owner}/{repo} when the `repo` parameter is omitted. \ - To explore another repo, pass `repo` as `owner/name` (e.g. `\"{default_repo}\"`).{cross_repo}{instructions_block}{team_block}{tests_block}{feature_block}", + To explore another repo, pass `repo` as `owner/name` (e.g. `\"{default_repo}\"`).{cross_repo}{instructions_block}{team_block}{tests_block}{feature_block}{smallest}", owner = msg.repo_owner, repo = msg.repo_name, stance = super::ownership::planner_stance(), feature_block = super::feature::planner_block(intent), + smallest = super::plan_shape::PLANNER, cross_repo = if team_repos.len() > 1 { super::cross_repo::PLANNER_LINE } else { @@ -321,10 +322,10 @@ pub async fn run( "simple" => { r#"## Complexity: SIMPLE (1-3 files) -This is a simple change. Be extremely efficient: -- Use 1-2 `search_code` calls to locate the relevant file(s) and line numbers -- Use `read_file_lines` on the specific section (max 100 lines), NOT whole files -- You should need 2-4 tool calls total, then output the plan +This is a simple change. Be efficient, but read what the change extends: +- Use `search_code` to locate the relevant file(s), and once more for the structure the change would add (an existing map, helper or config that already does part of it) +- Use `read_file_lines` on that structure in full (the whole map, function or query) and on its writers +- You should need 3-6 tool calls, then output the plan - The plan usually has 1-2 tasks; when the change needs more files, list every one"# } "medium" => { @@ -833,6 +834,18 @@ Then the ```fix_location.json block described above."#, state, }; + // Explore before planning: what the ticket's own words find in the + // repository goes to the planner with the ticket, so the plan extends + // it (a plan once added a second map beside the one it needed). + let found = super::plan_shape::existing_for_ticket( + &executor.read_only, + &default_repo, + &msg.title, + &msg.body, + ) + .await; + let existing_names = super::plan_shape::existing_names(&found); + let prompt = format!("{prompt}{}", super::plan_shape::existing_block(&found)); let mut content_blocks = vec![serde_json::json!({"type": "text", "text": prompt})]; for img in &msg.image_attachments { if let Some(b64) = @@ -934,6 +947,34 @@ Then the ```fix_location.json block described above."#, // reuse and the closest sibling. let feature_gaps = super::feature::plan_gaps(&draft, intent, &ticket_history.prior); back.extend(feature_gaps.iter().cloned()); + // The smallest correct change (see plan_shape): its five sections, no + // parallel structure, no widening the ticket doesn't ask for, outside + // systems measured, the product changed before a test. + let ticket_words = format!( + "{}\n{}{}", + msg.title, + msg.body, + common::run_questions::answers_note(&msg.answers) + ); + let is_feature = intent == super::triage::TicketIntent::Feature; + let mut shape_gaps = + super::plan_shape::plan_gaps(&draft, &ticket_words, is_feature, &existing_names); + // What the reused helpers do to stored rows, read from their bodies: a + // replacing helper on a path that only inserts deleted rows nobody asked + // about. + let write_facts = super::plan_shape::read_write_facts( + &executor.read_only, + github, + (&msg.repo_owner, &msg.repo_name, &msg.base_branch), + &draft, + ) + .await; + shape_gaps.extend(super::plan_shape::write_gaps( + &draft, + &ticket_words, + &write_facts, + )); + back.extend(shape_gaps.iter().cloned()); // A decision that stops without a fix names the one step a person takes. back.extend(super::fix_location::next_step_gaps(draft.fix.as_ref())); // What a careful engineer settles before code (see habits): the worker @@ -1419,6 +1460,31 @@ Then the ```fix_location.json block described above."#, } } } + if !shape_gaps.is_empty() { + let mut left = + super::plan_shape::plan_gaps(&files, &ticket_words, is_feature, &existing_names); + let facts = super::plan_shape::read_write_facts( + &executor.read_only, + github, + (&msg.repo_owner, &msg.repo_name, &msg.base_branch), + &files, + ) + .await; + left.extend(super::plan_shape::write_gaps(&files, &ticket_words, &facts)); + if !left.is_empty() { + warn!(ticket_id = %msg.ticket_id, gaps = ?left, "Plan is still not the smallest change after one send-back"); + super::add_progress_note( + state, + &msg.team_id, + run_id, + &format!("Plan check (smallest change): {}", left.join(" ")), + ) + .await; + if let Some(d) = files.fix.as_mut() { + d.open_gaps.extend(left); + } + } + } // The habits, read again on the plan as it now stands (a revision names // new files and new names to search for). { diff --git a/services/worker/src/passes/plan_shape.rs b/services/worker/src/passes/plan_shape.rs new file mode 100644 index 000000000..af70c4462 --- /dev/null +++ b/services/worker/src/passes/plan_shape.rs @@ -0,0 +1,761 @@ +//! The plan is the smallest correct change, and says so in five sections. +//! +//! Two plans went wrong before a line was written. One, for linking four +//! camps to a second sport, planned a new map and helpers beside the +//! existing overrides map and a sync that "replaces" links, so the build +//! deleted links nobody asked about. The other, for embedding a vendor's +//! portal, planned end-to-end assertions about the vendor's page from +//! guesses, and when the vendor's page broke a criterion ("no double +//! scrollbars") it planned to change the test instead of the page. +//! +//! Each plan now writes, in design.md: +//! +//! - [`REUSE`]: the existing maps, helpers, config and tests it extends, +//! by path (found by search; the worker also hands the planner what the +//! ticket's own words find, [`existing_block`]); +//! - [`MUST_NOT_CHANGE`]: behaviour that stays as it is (no deletes where +//! the code only adds, shared logging, other pipelines); +//! - [`MEASURE_FIRST`]: what outside systems it measures before writing +//! against them (a `probe_page` record, a lookup), or that there are none; +//! - [`SMALLEST_CHANGE`]: the change in a few lines, and why nothing +//! smaller does it; +//! - [`PROOF`]: the one test (or the check) that shows it, in proportion. +//! +//! [`plan_gaps`] holds the draft to them and rejects a plan that proposes a +//! structure parallel to one it names under Reuse, replacing or deleting +//! semantics or log changes the ticket doesn't ask for, assertions about an +//! outside page with nothing measured, or a test change where a criterion +//! says the product must change. What is missing goes back to the planner +//! in the plan's one send-back. + +use super::cross_repo::RepoSearch; +use super::feature::reuse::section; +use super::minimal_change::{self, Def, DefKind}; +use super::plan::PlanResult; + +pub const REUSE: &str = super::feature::reuse::REUSE_HEADING; +pub const MUST_NOT_CHANGE: &str = "## Must not change"; +pub const MEASURE_FIRST: &str = "## Measure first"; +pub const SMALLEST_CHANGE: &str = "## Smallest change"; +pub const PROOF: &str = "## Proof"; + +/// What the planner is told, for every ticket kind. +pub const PLANNER: &str = "\n\n## The smallest correct change (CoderHelm checks these)\n\ +Before you plan, read the code the change extends: the whole map, function or query, and its \ +writers and readers. Then write these sections in design.md:\n\ +- `## Reuse`: the existing maps, helpers, constants, config and tests this change extends, each \ +with its path (search the ticket's names and the structure you would add). For each helper that \ +writes data, read its body and say what it does to rows already stored: `inserts only` or \ +`replaces/deletes` (a `DELETE`, an `ON CONFLICT DO UPDATE`, a delete-then-insert). A helper that \ +replaces is never reused on a path that only inserts unless the ticket asks to replace. Add entries to an \ +existing map or a parameter to an existing helper; never a second map or helper beside it.\n\ +- `## Must not change`: what stays as it is. A path that only inserts keeps only inserting (no \ +`DELETE`, no `ON CONFLICT DO UPDATE`, no replacing sync) unless the ticket asks for it; log \ +levels, shared logging and other pipelines stay untouched; no new counters or reports the \ +ticket doesn't ask for.\n\ +- `## Measure first`: every outside system the change or its tests rest on (a vendor page or \ +embed, an API, a webhook payload) and how you measure it before writing against it: the \ +`probe_page` tool for a page (its test ids, sizes, what is enabled), a read-only lookup for \ +data. Write `None: the change stays inside this repository` when there are none. Never plan \ +selectors, fields or behaviour of another company's system from a guess.\n\ +- `## Smallest change`: the change in a few lines (for example \"4 entries in \ +`CAMP_OVERRIDES`; an insert with `ON CONFLICT DO NOTHING` in the 3 write branches\"), and why \ +nothing smaller does it.\n\ +- `## Proof`: the one test or check that shows it, sized to the change: the new behaviour and \ +that nothing else changed, through the real entry point, with real or probed data. When an \ +acceptance criterion and an outside system disagree, plan the product change that meets the \ +criterion first; a test is changed to match the outside system only with the measured reason.\n"; + +fn names_something(s: &str) -> bool { + s.contains('`') + || s.split_whitespace() + .any(|t| t.contains('/') && !t.contains("://")) + || s.to_lowercase().contains("searched") + || s.to_lowercase().contains("none") +} + +fn stops(files: &PlanResult) -> bool { + let t = files.tasks.trim_start(); + t.is_empty() || t.starts_with("NO_CHANGES_NEEDED") || t.starts_with("CLARIFICATION_NEEDED") +} + +/// Backticked identifiers in `text` (names of code, not paths or prose). +fn backticked(text: &str) -> Vec { + let mut out = Vec::new(); + for (i, part) in text.split('`').enumerate() { + if i % 2 == 0 { + continue; + } + let p = part.trim().trim_end_matches("()"); + let ok = p.len() >= 4 + && p.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + && (p.contains('_') || p.chars().skip(1).any(|c| c.is_ascii_uppercase())); + if ok && !out.iter().any(|o| o == p) { + out.push(p.to_string()); + } + } + out +} + +fn as_def(name: &str) -> Def { + let table = name + .chars() + .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'); + Def { + name: name.to_string(), + kind: if table { + DefKind::Table + } else { + DefKind::Function + }, + } +} + +const NEW_STRUCTURE: &[&str] = &[ + "new map", + "new dict", + "new mapping", + "separate map", + "separate mapping", + "separate dict", + "parallel map", + "second map", + "new lookup", + "new override", + "new constant", + "new helper", + "new config", +]; + +const REPLACING_WORDS: &[&str] = &[ + "upsert", + "do update", + "delete ", + "deletes ", + "deleting", + "replace the", + "replaces the", + "replacing", + "overwrite", + "truncate", + "prune", + "purge", + "remove stale", + "removes stale", + "sync removals", +]; + +const LOG_WORDS: &[&str] = &[ + "log level", + "to debug", + "to info", + "setlevel", + "info to debug", + "debug to info", +]; + +const REPORT_WORDS: &[&str] = &[ + "summary counter", + "counters", + "count of skipped", + "warning per run", + "report the skipped", + "report skipped", +]; + +const OUTSIDE_WORDS: &[&str] = &[ + "iframe", + "embed", + "vendor", + "third-party", + "third party", + "portal", + "widget", + "webhook", + "external api", + "partner", +]; + +const MEASURED_WORDS: &[&str] = &[ + "probe", + "measured", + "observed", + "lookup", + "looked up", + "fetched", + "curl", + "none:", + "none.", +]; + +const TEST_TO_VENDOR: &[&str] = &[ + "update the test to match", + "update the tests to match", + "change the test to", + "change the assertion", + "adjust the assertion", + "relax the assertion", + "expect the vendor", + "accept the vendor", + "match the vendor", + "match the portal", +]; + +/// The plan's words that propose things, without its Must not change +/// section (where "no deletes" is said). +fn proposing_text(files: &PlanResult) -> String { + let design = match section(&files.design, MUST_NOT_CHANGE) { + Some(s) => files.design.replace(s, ""), + None => files.design.clone(), + }; + format!("{}\n{}\n{}", files.proposal, design, files.tasks).to_lowercase() +} + +fn found<'a>(text: &str, words: &'a [&str]) -> Option<&'a str> { + words.iter().find(|w| text.contains(*w)).copied() +} + +/// What a draft misses or proposes past its ticket, one line each for the +/// send-back. `ticket` is the ticket's own words (title, body, answers); +/// `is_feature` skips the Reuse section, which the new-feature rules +/// already ask for; `existing` holds names the worker found for the +/// ticket's words. +pub fn plan_gaps( + files: &PlanResult, + ticket: &str, + is_feature: bool, + existing: &[String], +) -> Vec { + if stops(files) { + return Vec::new(); + } + let mut out = Vec::new(); + let design = &files.design; + let mut need = vec![MUST_NOT_CHANGE, MEASURE_FIRST, SMALLEST_CHANGE, PROOF]; + if !is_feature { + need.insert(0, REUSE); + } + let missing: Vec<&str> = need + .into_iter() + .filter(|h| !section(design, h).is_some_and(|s| !s.trim().is_empty())) + .collect(); + if !missing.is_empty() { + out.push(format!( + "design.md lacks {}. Write each: Reuse (existing structures by path), Must not change, Measure first (outside systems and how they are measured, or `None`), Smallest change (the change in a few lines), Proof (the one test or check).", + missing + .iter() + .map(|h| format!("`{h}`")) + .collect::>() + .join(", ") + )); + } + let reuse = section(design, REUSE).unwrap_or(""); + if !reuse.trim().is_empty() && !names_something(reuse) { + out.push(format!( + "`{REUSE}` names no existing structure. Search the ticket's names and the structure you would add, and list what you extend by path, or say what you searched." + )); + } + let text = proposing_text(files); + // A new structure beside an existing one. + let mut known: Vec = backticked(reuse); + known.extend(existing.iter().cloned()); + let proposed: Vec = backticked(&format!("{}\n{}", files.tasks, files.design)) + .into_iter() + .filter(|n| !known.contains(n)) + .collect(); + let mut parallel: Vec<(String, String)> = Vec::new(); + for p in &proposed { + if let Some(k) = known + .iter() + .find(|k| minimal_change::parallels(&as_def(p), &as_def(k))) + { + parallel.push((p.clone(), k.clone())); + } + } + if let Some((p, k)) = parallel.first() { + out.push(format!( + "The plan adds `{p}` next to the existing `{k}`. Extend `{k}` (add the entries or a parameter there) instead of a parallel structure." + )); + } else if let Some(w) = found(&text, NEW_STRUCTURE) { + if !known.is_empty() { + out.push(format!( + "The plan proposes a {w} while `{REUSE}` names `{}`. Extend the existing one, or say under `{SMALLEST_CHANGE}` why it can't hold this.", + known[0] + )); + } + } + if !minimal_change::ticket_asks(ticket, minimal_change::REPLACE_ASKS) { + if let Some(w) = found(&text, REPLACING_WORDS) { + out.push(format!( + "The plan would delete or overwrite (\"{}\") but the ticket asks for no deletes or replacements. Keep the write additive (insert, `ON CONFLICT DO NOTHING`) and list the existing rows under `{MUST_NOT_CHANGE}`.", + w.trim() + )); + } + } + if !minimal_change::ticket_asks(ticket, minimal_change::LOG_ASKS) { + if let Some(w) = found(&text, LOG_WORDS) { + out.push(format!( + "The plan changes logging (\"{}\") the ticket doesn't ask about. Leave log levels and shared logging as they are.", + w.trim() + )); + } + } + if !minimal_change::ticket_asks(ticket, minimal_change::REPORT_ASKS) { + if let Some(w) = found(&text, REPORT_WORDS) { + out.push(format!( + "The plan adds reporting (\"{}\") the ticket doesn't ask for. Leave it out.", + w.trim() + )); + } + } + let ticket_l = ticket.to_lowercase(); + let outside = found(&ticket_l, OUTSIDE_WORDS).or_else(|| found(&text, OUTSIDE_WORDS)); + if let Some(w) = outside { + let measured = section(design, MEASURE_FIRST) + .map(|s| found(&s.to_lowercase(), MEASURED_WORDS).is_some()) + .unwrap_or(false); + if !measured { + out.push(format!( + "The change rests on an outside system (\"{w}\") and `{MEASURE_FIRST}` plans no measurement. Probe it first (`probe_page` for a page: its test ids, frame size and scrolling, what is enabled; a read-only lookup for data) and plan the code and tests from what it shows." + )); + } + let criteria = super::stop_judge::acceptance(ticket); + if !criteria.is_empty() { + if let Some(w) = found(&text, TEST_TO_VENDOR) { + out.push(format!( + "The plan would change a test to match the outside system (\"{w}\") while the ticket's criteria say what the product must do. Plan the product change that meets the criterion first; change the test only with the measured reason it can't." + )); + } + } + } + out +} + +// ── What reused helpers do to stored rows ────────────────────────────────── + +/// A helper the plan reuses, and what it does to stored rows. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Helper { + pub name: String, + pub path: String, + pub writes: minimal_change::Writes, +} + +/// What the plan's reused helpers and the planned files do to stored rows. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct WriteFacts { + pub helpers: Vec, + /// The planned code files, without the reused helpers' own bodies, only + /// insert today. + pub path_inserts_only: bool, +} + +/// The function-like names under the plan's Reuse section. +pub fn reused_functions(files: &PlanResult) -> Vec { + let reuse = section(&files.design, REUSE).unwrap_or(""); + backticked(reuse) + .into_iter() + .filter(|n| n.chars().any(|c| c.is_ascii_lowercase())) + .collect() +} + +/// The facts from the helpers' sources (`(name, path, file text)`) and the +/// planned code files' base texts (`(path, text)`). +pub fn write_facts( + sources: &[(String, String, String)], + planned: &[(String, String)], +) -> WriteFacts { + let mut helpers = Vec::new(); + let mut bodies: Vec = Vec::new(); + for (name, path, text) in sources { + if let Some(body) = minimal_change::body_of(text, path, name) { + helpers.push(Helper { + name: name.clone(), + path: path.clone(), + writes: minimal_change::write_semantics(&body), + }); + bodies.push(body); + } + } + let rest: Vec = planned + .iter() + .map(|(_, t)| { + let mut t = t.clone(); + for b in &bodies { + t = t.replace(b.as_str(), ""); + } + t + }) + .collect(); + let refs: Vec<&str> = rest.iter().map(String::as_str).collect(); + WriteFacts { + helpers, + path_inserts_only: !refs.is_empty() && minimal_change::inserts_only(&refs), + } +} + +const SAYS_REPLACES: &[&str] = &["replace", "delete", "overwrite", "do update", "prune"]; + +/// What the plan misses about the rows its reused helpers touch: a +/// replacing helper the Reuse section doesn't say replaces, and a replacing +/// helper reused where the code only inserts, when the ticket asks for no +/// replacement. +pub fn write_gaps(files: &PlanResult, ticket: &str, facts: &WriteFacts) -> Vec { + if stops(files) { + return Vec::new(); + } + let reuse = section(&files.design, REUSE).unwrap_or("").to_lowercase(); + let mut out = Vec::new(); + for h in &facts.helpers { + let minimal_change::Writes::Replacing(how) = &h.writes else { + continue; + }; + let line = reuse + .lines() + .find(|l| l.contains(&h.name.to_lowercase())) + .unwrap_or(""); + if !SAYS_REPLACES.iter().any(|w| line.contains(w)) { + out.push(format!( + "`{REUSE}` names `{}` without what it does to stored rows: it replaces them ({}, in `{}`). Say so next to it.", + h.name, + how.join(", "), + h.path + )); + } + if facts.path_inserts_only + && !minimal_change::ticket_asks(ticket, minimal_change::REPLACE_ASKS) + { + out.push(format!( + "The plan reuses `{}`, which replaces stored rows ({}), on a path that only inserts today, and the ticket asks for no replacement. Keep the path additive: insert the new rows with `ON CONFLICT DO NOTHING` (or the insert-only helper the path already uses), and list the existing rows under `{MUST_NOT_CHANGE}`.", + h.name, + how.join(", ") + )); + } + } + out +} + +/// Reads the facts: each reused function's definition (found by search, +/// read at `base`) and the planned code files at `base`. +pub async fn read_write_facts( + search: &dyn RepoSearch, + github: &crate::clients::github::GitHubClient, + (owner, repo, base): (&str, &str, &str), + files: &PlanResult, +) -> WriteFacts { + let own = format!("{owner}/{repo}"); + let mut sources = Vec::new(); + for name in reused_functions(files).into_iter().take(6) { + let Ok(hits) = search.search(&own, &name).await else { + continue; + }; + let defining = hits.iter().find_map(|h| { + let path = h.lines().next()?.to_string(); + let defines = [ + format!("def {name}("), + format!("function {name}"), + format!("fn {name}"), + format!("const {name} ="), + ]; + h.lines() + .skip(1) + .any(|l| defines.iter().any(|d| l.contains(d.as_str()))) + .then_some(path) + }); + let Some(path) = defining else { + continue; + }; + if let Ok(text) = github.read_file(owner, repo, &path, base).await { + sources.push((name, path, text)); + } + } + let mut planned = Vec::new(); + for f in super::feature::plan_files::planned_files(&files.tasks) + .into_iter() + .filter(|f| !super::habits::is_test_path(&f.path)) + .take(8) + { + if let Ok(text) = github.read_file(owner, repo, &f.path, base).await { + planned.push((f.path.clone(), text)); + } + } + write_facts(&sources, &planned) +} + +// ── What the ticket's words find, before the plan ────────────────────────── + +const STOP: &[&str] = &[ + "The", + "This", + "That", + "These", + "Those", + "When", + "Then", + "Given", + "And", + "But", + "For", + "With", + "From", + "Add", + "Make", + "Update", + "Change", + "Fix", + "Remove", + "Link", + "Please", + "Should", + "Acceptance", + "Criteria", + "Ticket", + "Summary", + "Description", + "Steps", + "Expected", + "Actual", +]; + +/// The search terms a ticket's own words give: code names in backticks, +/// identifiers, quoted names and capitalised names mid-sentence, at most +/// six, the most specific first. +pub fn ticket_terms(title: &str, body: &str) -> Vec { + let text = format!("{title}\n{body}"); + let mut ids: Vec = backticked(&text); + for w in text.split(|c: char| c.is_whitespace() || matches!(c, ',' | ';' | '(' | ')' | ':')) { + let w = w.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '_'); + let id = w.len() >= 5 + && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + && (w.contains('_') || w.chars().skip(1).any(|c| c.is_ascii_uppercase())) + && w.chars().any(|c| c.is_ascii_lowercase() || c == '_'); + if id && !ids.iter().any(|i| i == w) { + ids.push(w.to_string()); + } + } + let mut quoted = Vec::new(); + for q in ['"', '\u{201c}'] { + let close = if q == '"' { '"' } else { '\u{201d}' }; + let mut rest = text.as_str(); + while let Some(i) = rest.find(q) { + let after = &rest[i + q.len_utf8()..]; + let Some(j) = after.find(close) else { break }; + let s = after[..j].trim(); + if (3..=40).contains(&s.len()) && !s.contains('\n') && !quoted.iter().any(|x| x == s) { + quoted.push(s.to_string()); + } + rest = &after[j + close.len_utf8()..]; + } + } + let mut proper = Vec::new(); + for sentence in text.split(['.', '\n', '!', '?']) { + for (i, w) in sentence.split_whitespace().enumerate() { + let w = w.trim_matches(|c: char| !c.is_ascii_alphanumeric()); + if i > 0 + && w.len() >= 4 + && w.chars().next().is_some_and(|c| c.is_ascii_uppercase()) + && w.chars().skip(1).all(|c| c.is_ascii_lowercase()) + && !STOP.contains(&w) + && !proper.iter().any(|p| p == w) + { + proper.push(w.to_string()); + } + } + } + ids.into_iter() + .chain(quoted) + .chain(proper) + .take(6) + .collect() +} + +/// What the ticket's words find in the repository, as (term, hits), at +/// most eight hits a term. +pub async fn existing_for_ticket( + search: &dyn RepoSearch, + repo: &str, + title: &str, + body: &str, +) -> Vec<(String, Vec)> { + let mut out = Vec::new(); + for t in ticket_terms(title, body) { + if let Ok(hits) = search.search(repo, &t).await { + if !hits.is_empty() { + out.push((t, hits.into_iter().take(8).collect())); + } + } + } + out +} + +/// The top-level names the hits show (maps, helpers), for the plan gate. +pub fn existing_names(found: &[(String, Vec)]) -> Vec { + let mut out: Vec = Vec::new(); + for (_, hits) in found { + for h in hits { + let path = h.lines().next().unwrap_or(""); + for line in h.lines().skip(1) { + // A match may carry its line number: `12: CODE`. + let line = match line.split_once(": ") { + Some((n, l)) if n.trim().chars().all(|c| c.is_ascii_digit()) => l, + _ => line, + }; + if let Some(d) = minimal_change::top_level_def(line, path) { + if !out.contains(&d.name) { + out.push(d.name); + } + } + } + } + } + out +} + +/// The planner's block for what the ticket's words found: read these +/// first, and extend them. +pub fn existing_block(found: &[(String, Vec)]) -> String { + if found.is_empty() { + return String::new(); + } + let mut s = String::from( + "\n\n## Existing code the ticket's words find (read it before planning)\nCoderHelm searched the repository for the ticket's own names. Read each hit that the change touches in full (the whole map, function or query) and extend it; list it under `## Reuse`.\n", + ); + for (term, hits) in found { + s.push_str(&format!("\n### `{term}`\n")); + for h in hits { + s.push_str(&format!("- {}\n", common::truncate_str(h.trim(), 300))); + } + } + s +} + +#[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(), + ..Default::default() + } + } + + const GOOD: &str = "## Reuse\n- `CAMP_MULTI_SPORT_OVERRIDES` and `get_camp_multi_sport_names` in dags/camps/sports.py\n\n## Must not change\nNo deletes: existing links stay. Logging stays as it is.\n\n## Measure first\nNone: the change stays inside this repository.\n\n## Smallest change\n4 entries in `CAMP_MULTI_SPORT_OVERRIDES`; in the 3 write branches insert links for `get_camp_multi_sport_names` with ON CONFLICT DO NOTHING.\n\n## Proof\nOne test: the 4 names get Swimming and their own sport, others only their own, nothing deleted.\n"; + + #[test] + fn the_small_plan_passes() { + let p = plan( + GOOD, + "- [ ] dags/camps/sports.py: add 4 entries\n- [ ] tests/test_sports.py: one test", + ); + assert!(plan_gaps( + &p, + "Link four camps to Swimming as well as their sport", + false, + &[] + ) + .is_empty()); + } + + #[test] + fn missing_sections_go_back() { + let p = plan("## Overview\nstuff", "- [ ] a.py: x"); + let g = plan_gaps(&p, "x", false, &[]); + assert_eq!(g.len(), 1); + for h in [ + REUSE, + MUST_NOT_CHANGE, + MEASURE_FIRST, + SMALLEST_CHANGE, + PROOF, + ] { + assert!(g[0].contains(h), "{h}"); + } + // A plan that stops plans nothing. + assert!(plan_gaps(&plan("", "NO_CHANGES_NEEDED: done"), "x", false, &[]).is_empty()); + } + + #[test] + fn a_parallel_map_and_a_replacing_sync_are_rejected() { + let design = GOOD.replace( + "## Smallest change\n", + "## Smallest change\nAdd `CAMP_SWIMMING_OVERRIDES` and `get_camp_swimming_names`; the sync upserts links and deletes stale ones. Change the INFO log to debug.\n", + ); + let g = plan_gaps( + &plan(&design, "- [ ] dags/camps/sports.py: x"), + "Link four camps to Swimming", + false, + &[], + ); + assert!( + g.iter().any(|l| l.contains( + "`CAMP_SWIMMING_OVERRIDES` next to the existing `CAMP_MULTI_SPORT_OVERRIDES`" + )), + "{g:?}" + ); + assert!(g.iter().any(|l| l.contains("delete or overwrite")), "{g:?}"); + assert!(g.iter().any(|l| l.contains("changes logging")), "{g:?}"); + } + + #[test] + fn an_outside_page_is_measured_and_the_product_changes_first() { + let design = GOOD.replace( + "None: the change stays inside this repository.", + "The vendor portal is loaded in an iframe; we assume it has no inner scroll.", + ) + "\nIf the vendor scrolls, update the test to match the vendor.\n"; + let ticket = "Embed the booking portal.\n\nAcceptance criteria:\n- No double scrollbars on desktop\n"; + let g = plan_gaps( + &plan(&design, "- [ ] e2e/portal.spec.ts: x"), + ticket, + false, + &[], + ); + assert!( + g.iter().any(|l| l.contains("plans no measurement")), + "{g:?}" + ); + assert!( + g.iter() + .any(|l| l.contains("product change that meets the criterion first")), + "{g:?}" + ); + let measured = design + .replace( + "we assume it has no inner scroll", + "probe_page measured the frame and its test ids", + ) + .replace( + "If the vendor scrolls, update the test to match the vendor.", + "", + ); + assert!(plan_gaps( + &plan(&measured, "- [ ] e2e/portal.spec.ts: x"), + ticket, + false, + &[] + ) + .is_empty()); + } + + #[test] + fn the_tickets_words_become_searches() { + let t = ticket_terms( + "Link full-day camps to Swimming", + "These camps should also show under Swimming: \"Aqua Day Camp\", \"Swim Week\". See `CAMP_MULTI_SPORT_OVERRIDES`.", + ); + assert_eq!(t[0], "CAMP_MULTI_SPORT_OVERRIDES"); + assert!(t.contains(&"Aqua Day Camp".to_string())); + assert!(t.contains(&"Swimming".to_string())); + let names = existing_names(&[( + "Swimming".into(), + vec!["dags/camps/sports.py\nCAMP_MULTI_SPORT_OVERRIDES = {".into()], + )]); + assert_eq!(names, vec!["CAMP_MULTI_SPORT_OVERRIDES"]); + assert!( + existing_block(&[("Swimming".into(), vec!["dags/a.py".into()])]).contains("## Reuse") + ); + } +} diff --git a/services/worker/src/passes/preview.rs b/services/worker/src/passes/preview.rs index 889e5fa13..3ee18abb0 100644 --- a/services/worker/src/passes/preview.rs +++ b/services/worker/src/passes/preview.rs @@ -163,7 +163,7 @@ fn covering_results( } /// The workflow files at `git_ref`, with their text. -async fn workflows( +pub(crate) async fn workflows( gh: &GitHubClient, owner: &str, repo: &str, diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index cf6a9dd47..8432275a8 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -228,6 +228,72 @@ async fn probe_gaps( super::review_rules::probe_findings(&common::e2e::probe::unprobed(&files, &probes, &own)) } +/// The review's findings for a change wider than its ticket +/// (`minimal_change`) and for test assertions changed to match another +/// company's page against an acceptance criterion. `ticket` is the +/// ticket's words the review has (its context and the PR body). +async fn smallest_change_gaps( + state: &WorkerState, + github: &GitHubClient, + (team_id, owner, repo): (&str, &str, &str), + head_sha: &str, + compare: &serde_json::Value, + tree: &[String], + ticket: &str, +) -> Vec { + let files: Vec<(String, String, String)> = compare["files"] + .as_array() + .into_iter() + .flatten() + .take(80) + .map(|f| { + ( + f["filename"].as_str().unwrap_or("").to_string(), + f["status"].as_str().unwrap_or("").to_string(), + f["patch"].as_str().unwrap_or("").to_string(), + ) + }) + .filter(|(p, _, _)| !p.is_empty()) + .collect(); + let mut base = Vec::new(); + if let Some(sha) = compare["merge_base_commit"]["sha"].as_str() { + for (p, _, _) in files + .iter() + .filter(|(p, s, _)| s == "modified" && !super::habits::is_test_path(p)) + .take(12) + { + if let Ok(text) = github.read_file(owner, repo, p, sha).await { + base.push((p.clone(), text)); + } + } + } + let has_probe = tree.iter().any(|p| common::e2e::probe::is_record(p)); + let mut out = super::review_rules::wider_findings(&super::minimal_change::check( + &files, &base, ticket, has_probe, + )); + let criteria = super::stop_judge::acceptance(ticket); + if !criteria.is_empty() { + let own = super::web_check::team_domains(state, team_id).await; + let mut flips = Vec::new(); + for (path, _, patch) in files.iter().filter(|(p, s, patch)| { + s != "removed" && super::habits::is_test_path(p) && patch.contains("expect(") + }) { + let full = github + .read_file(owner, repo, path, head_sha) + .await + .unwrap_or_else(|_| patch.clone()); + let outside = !common::e2e::probe::outside_origins(&full, &own).is_empty() + || full.contains("frameLocator(") + || full.contains("contentFrame("); + flips.extend(super::minimal_change::vendor_flips( + path, patch, outside, &criteria, + )); + } + out.extend(super::review_rules::vendor_flip_findings(&flips)); + } + out +} + /// True when the repo turned on "Require tests" (and review isn't off/killed). /// The same switch makes the reviewer block untested behavior changes and makes /// CoderHelm's own coding passes write those tests. @@ -3447,6 +3513,23 @@ async fn run_once( findings.retain(|x| x.title != f.title || x.file != f.file); findings.push(f); } + // The change does what its ticket asks and no more, and a test is + // never bent to another company's page against a criterion. + for f in smallest_change_gaps( + state, + &github, + (&msg.team_id, &msg.repo_owner, &msg.repo_name), + &head_sha, + &compare, + &tree, + &format!("{ticket_context}\n{pr_body}"), + ) + .await + { + info!(pr = msg.pr_number, file = %f.file, title = %f.title, "Wider than the ticket: must fix"); + findings.retain(|x| x.title != f.title || x.file != f.file); + findings.push(f); + } } review_agent::enforce_source_data_override(&mut findings); // A request to test something by hand is a note, never a block. diff --git a/services/worker/src/passes/review_rules.rs b/services/worker/src/passes/review_rules.rs index 292455cba..4248bcbd0 100644 --- a/services/worker/src/passes/review_rules.rs +++ b/services/worker/src/passes/review_rules.rs @@ -91,6 +91,57 @@ pub fn probe_findings(gaps: &[common::e2e::probe::Unprobed]) -> Vec { .collect() } +/// The rule every change is held to: it does what its ticket asks and no +/// more (`minimal_change`). +pub const SMALLEST_RULE: &str = "the change does what the ticket asks and no more: no deletes or overwrites where the code only added, no test payload nobody observed, no test changed to match another company's page against an acceptance criterion"; + +/// The review's findings for a change wider than its ticket. Deleting or +/// overwriting where the base only added, and a payload nobody observed, +/// block by rule; the rest block as verified defects the fix round makes +/// smaller. +pub fn wider_findings(found: &[super::minimal_change::Widening]) -> Vec { + use super::minimal_change::Kind; + found + .iter() + .map(|w| Finding { + file: w.path.clone(), + severity: "blocking".into(), + category: match w.kind { + Kind::TestSize | Kind::InventedPayload => "tests", + Kind::Replacing => "data", + _ => "scope", + } + .into(), + title: w.point().to_string(), + body: w.instruction(), + evidence: Some("verified-defect".into()), + caused_by_diff: Some(true), + required: (!w.excusable()).then(|| SMALLEST_RULE.to_string()), + ..Default::default() + }) + .collect() +} + +/// The review's findings for test assertions changed to match another +/// company's page while an acceptance criterion says otherwise: the +/// product changes first. +pub fn vendor_flip_findings(flips: &[super::minimal_change::VendorFlip]) -> Vec { + flips + .iter() + .map(|f| Finding { + file: f.path.clone(), + severity: "blocking".into(), + category: "tests".into(), + title: "A test changed to the outside page's behaviour against a criterion".into(), + body: f.body(), + evidence: Some("verified-defect".into()), + caused_by_diff: Some(true), + required: Some(SMALLEST_RULE.to_string()), + ..Default::default() + }) + .collect() +} + /// Why a required rule broken blocks. pub const REQUIRED_WHY: &str = "a rule this repository requires is broken"; /// Why a failing check blocks. @@ -625,6 +676,9 @@ pub fn mandatory_label(f: &Finding) -> Option { REQUIRED_WHY if f.required.as_deref() == Some(E2E_RULE) => { "Blocking (required: end-to-end test)".to_string() } + REQUIRED_WHY if f.required.as_deref() == Some(SMALLEST_RULE) => { + "Blocking (required: the ticket's scope)".to_string() + } REQUIRED_WHY => "Blocking (required rule)".to_string(), FAILING_CHECK_WHY => "Blocking (failing check)".to_string(), MAIN_PATH_WHY if f.evidence() == super::review_agent::Evidence::VerifiedDefect => { @@ -652,6 +706,38 @@ pub fn settles(thread_body: &str, status: &str) -> bool { mod e2e_rule_tests { use super::*; + #[test] + fn wider_than_the_ticket_and_vendor_flips_are_findings() { + use crate::passes::minimal_change::{Kind, VendorFlip, Widening}; + let f = wider_findings(&[ + Widening { + kind: Kind::Replacing, + path: "dags/sync.py".into(), + what: "`DELETE FROM`".into(), + }, + Widening { + kind: Kind::Parallel, + path: "dags/camps.py".into(), + what: "`A_MAP` next to the existing `B_MAP`".into(), + }, + ]); + assert_eq!(mandatory(&f[0]), Some(REQUIRED_WHY)); + assert_eq!( + mandatory_label(&f[0]).as_deref(), + Some("Blocking (required: the ticket's scope)") + ); + assert!(f[1].required.is_none()); + assert_eq!(f[1].severity, "blocking"); + let v = vendor_flip_findings(&[VendorFlip { + path: "e2e/portal.spec.ts".into(), + removed: "expect(x).toBe(false)".into(), + added: "expect(x).toBe(true)".into(), + criterion: "No double scrollbars on desktop".into(), + }]); + assert_eq!(mandatory(&v[0]), Some(REQUIRED_WHY)); + assert!(v[0].body.contains("No double scrollbars")); + } + #[test] fn unobserved_outside_selectors_are_a_must_fix() { let code = diff --git a/services/worker/src/passes/test_bug.rs b/services/worker/src/passes/test_bug.rs index 1d7cf11f6..cd4d69a6f 100644 --- a/services/worker/src/passes/test_bug.rs +++ b/services/worker/src/passes/test_bug.rs @@ -80,7 +80,21 @@ impl Runner<'_> { &self.state.config.sandbox_bucket_name, &self.state.config.sandbox_project_name, ) - .with_egress(crate::agent::policy::sandbox_egress(self.state, self.team_id).await); + .with_egress(crate::agent::policy::sandbox_egress(self.state, self.team_id).await) + // The proof step runs in the run's test environment too. + .with_test_env( + super::test_setup::for_run( + self.state, + self.github, + self.team_id, + self.owner, + self.repo, + sha, + sha, + self.run_id, + ) + .await, + ); let source = sandbox .ensure_source(self.run_id, sha, || { self.github.download_tarball(self.owner, self.repo, sha) diff --git a/services/worker/src/passes/test_setup.rs b/services/worker/src/passes/test_setup.rs new file mode 100644 index 000000000..91bec4482 --- /dev/null +++ b/services/worker/src/passes/test_setup.rs @@ -0,0 +1,107 @@ +//! The run's test environment (`common::test_env`), found once and reused. +//! +//! The first round that has a sandbox reads the repository's CI workflows +//! and records how its tests install and run on the run, in the sandbox +//! bucket (`env-cache/runs/.json`), with one line in the run's notes. +//! Every later round, continuation and proof step reads that record instead +//! of working it out again. Each one names the install by its fingerprint, so +//! every sandbox build restores the cached install, or saves it when it is +//! the first (`SandboxClient::with_test_env`). + +use common::test_env::{self, TestEnv}; +use tracing::{info, warn}; + +use crate::clients::github::GitHubClient; +use crate::WorkerState; + +/// Where the run's record lives in the sandbox bucket. +pub fn record_key(run_id: &str) -> String { + let safe: String = run_id + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') + .collect(); + format!("env-cache/runs/{safe}.json") +} + +async fn read_record(state: &WorkerState, run_id: &str) -> Option { + let obj = state + .s3 + .get_object() + .bucket(&state.config.sandbox_bucket_name) + .key(record_key(run_id)) + .send() + .await + .ok()?; + let bytes = obj.body.collect().await.ok()?.into_bytes(); + serde_json::from_slice(&bytes).ok() +} + +async fn write_record(state: &WorkerState, run_id: &str, env: &TestEnv) { + let Ok(body) = serde_json::to_vec(env) else { + return; + }; + if let Err(e) = state + .s3 + .put_object() + .bucket(&state.config.sandbox_bucket_name) + .key(record_key(run_id)) + .body(aws_sdk_s3::primitives::ByteStream::from(body)) + .content_type("application/json") + .send() + .await + { + warn!(run_id, error = %e, "Could not record the run's test environment"); + } +} + +/// The run's test environment and the cache key of its install at +/// `git_ref`, or `None` without a sandbox or a CI job that runs tests. +#[allow(clippy::too_many_arguments)] +pub async fn for_run( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + owner: &str, + repo: &str, + base_branch: &str, + git_ref: &str, + run_id: &str, +) -> Option<(TestEnv, String)> { + if state.config.sandbox_bucket_name.is_empty() || state.config.sandbox_project_name.is_empty() { + return None; + } + let tree: Vec<(String, String)> = github + .get_tree(owner, repo, git_ref) + .await + .ok()? + .into_iter() + .filter(|e| e.entry_type == "blob") + .map(|e| (e.path, e.sha)) + .collect(); + let env = match read_record(state, run_id).await { + Some(env) => env, + None => { + let workflows = super::preview::workflows(github, owner, repo, base_branch).await; + let paths: Vec = tree.iter().map(|(p, _)| p.clone()).collect(); + let env = test_env::from_workflows(&workflows, &paths)?; + write_record(state, run_id, &env).await; + super::add_progress_note(state, team_id, run_id, &env.summary()).await; + env + } + }; + let fp = env.fingerprint(&tree); + let key = test_env::cache_key(team_id, &format!("{owner}/{repo}"), &fp); + info!(run_id, key = %key, "The run's test environment"); + Some((env, key)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_record_per_run() { + assert_eq!(record_key("01ABC"), "env-cache/runs/01ABC.json"); + assert_eq!(record_key("../x"), "env-cache/runs/x.json"); + } +}