diff --git a/docs/coder-loop.md b/docs/coder-loop.md index 24c710f4c..62ed64720 100644 --- a/docs/coder-loop.md +++ b/docs/coder-loop.md @@ -202,6 +202,16 @@ The causes were in the loop, not only in prompt wording: comment on the pull request, and the ledger records who moved it in. (`incidents::sl_scope_decided_once`) + What people say decides scope as they say it (`Ledger::take_people`). + When the ledger is seeded, and on each round's comments (the habits check + and the planned-work rounds), an out-of-scope entry that a person's answer + or comment asks for moves into scope and records who asked. No + `Scope change:` line is needed. From then on, a diff that takes that work + out is a breach that goes back to be put back. A comment that keeps the + item out moves nothing. One run replied "Understood" to a reviewer's answer + and then reverted the work the answer asked for + (`incidents::sn_person_answer_moves_scope`). + 10. **The description describes the head.** On every push the description is rebuilt from the head's facts (`description::build`; Problem, Changes, Risk, Verification). The written @@ -221,6 +231,45 @@ The causes were in the loop, not only in prompt wording: that asks an open product question. (`incidents::sm_description_of_the_head`) +11. **A bug is reproduced before it is planned.** + For a bug, the planner has `reproduce_on_base` (`passes::reproduce`). The + tool runs one call or command in the sandbox on the base branch's head, in + the run's test environment, and returns its exit code and output. Each run + is kept. + + design.md has a `## Reproduce` section (`common::repro_first::reproduce_gaps`) + with these fields: + - `Inputs:` lists the ticket's ids and names, with every stored variant a + read-only lookup found, and says where they came from. + - `Ran on base:` is a command this run ran with the tool. + - `Output:` quotes what that command printed. + - `Wrong line:` names the `path:line` where the existing code goes wrong. + + A run that tried and can't reproduce writes `Unverified:` with why. It is + kept as unverified, never skipped silently. + + The fix goes in the mechanism the wrong line is in (`reuse_gaps`). + `## Smallest change` names it, or says why it can't hold the fix. A plan + that adds a new resolution path beside it (a keyword match, a new + resolver) goes back. + + A question the plan decides with a default goes back unless it carries + `Looked up: ` or `No lookup settles it: `. This + applies when a page load or a query would answer it (`question_gaps`). + + After the build: + - **Diff size.** A diff that changes more than 40 lines of code (map and + list entries aside) for a ticket that names 1 to 12 records goes back to + be narrowed (`minimal_change::whole_path`). A `Wider than the ticket:` + line keeps it, with the reason. + - **Fail on the base.** Each new test runs on the base and on the head the + way CI runs it. That includes a CI loop such as `for t in tests/test_*.py; + do python "$t"` (`TestEnv::file_command`, `habits_check::file_cmd`). A + bug fix that no test was shown to fail on the base for says `Unverified:` + in its description. + + (`incidents::rp_reproduce_before_planning`) + ## What is deterministic Everything above except the model's own writing: the searches, section checks, diff --git a/docs/incidents/rp_reproduce_before_planning.md b/docs/incidents/rp_reproduce_before_planning.md new file mode 100644 index 000000000..e6d36879c --- /dev/null +++ b/docs/incidents/rp_reproduce_before_planning.md @@ -0,0 +1,31 @@ +# rp. `rp_reproduce_before_planning` + +**What happened:** A data-pipeline ticket named four camps that were filed under the wrong sport. The pipeline already had an overrides table for exactly this case, with entries for those camps. Its lookup matched exact names, though, and the vendor appends "-Half Day" or "-Full Day", so the entries never matched: the lookup returned nothing for each of the ticket's names on the base. + +The run's notes said so, then planned a keyword step beside the table. The diff was +595/-186 across the pipeline: a moved extractor, keyword matching, new logging and a fixture. It also moved other programs to another lookup, which its own reviewer flagged as out of scope, and it asked two questions on the pull request that one page load answered. + +The new test was never run on the base. The repository's CI runs each test file in a `python "$t"` loop, which CoderHelm couldn't narrow to one file, so the test was recorded as not run and the description said nothing about it. The right change stripped the suffix in the lookup and added two entries (+49/-1, mostly a test of the exact stored names), and that test fails on the base. + +Across the 53 runs audited: +- 8 of the 10 bug tickets that wrote code ran nothing before their first edit; +- 6 diffs of 300 lines or more answered a ticket that named 1 to 10 records; +- none of the 17 runs whose tests were checked had a test shown to fail on the base. + +**The guarantee:** +- **Reproduce first.** A bug plan has a `## Reproduce` section with: + - the ticket's exact inputs and their stored variants, with where they came from; + - a command this run ran on the base with `reproduce_on_base`, with its output quoted; + - the line where the existing code goes wrong. + + A run that tried and couldn't reproduce writes `Unverified:` with why. +- **Fix the mechanism found.** The fix goes in the mechanism that the wrong line is in. A new resolution path beside it goes back to the planner. +- **Look questions up first.** A question that a page load or a query answers is looked up before it is decided with a default. +- **Size the diff to the ticket.** A diff that rewrites a code path for a few named records goes back to be narrowed, unless a `Wider than the ticket:` line gives the reason. +- **Fail on the base.** Each new test runs on the base and on the head, the way CI runs it, even when CI runs it in a loop. A bug fix with no test shown to fail on the base says `Unverified:` in its description. + +**Where it's enforced:** +- `common::repro_first`; +- `passes::reproduce` (the tool, and `plan_gaps` in the plan check); +- `minimal_change::whole_path`; +- `common::test_env::TestEnv::file_command`; +- `habits_check::file_cmd` and `UNVERIFIED_FIX`. diff --git a/docs/incidents/sn_person_answer_moves_scope.md b/docs/incidents/sn_person_answer_moves_scope.md new file mode 100644 index 000000000..12f8d1fef --- /dev/null +++ b/docs/incidents/sn_person_answer_moves_scope.md @@ -0,0 +1,7 @@ +# sn. `sn_person_answer_moves_scope` + +**What happened:** A plan left a page type out of scope, decided with a default. A reviewer answered on the pull request that those pages should cover both rows. The run replied "Understood", then reverted the work on those pages as out of scope. The scope ledger was seeded only from the ticket's acceptance criteria and the plan, and a person's comment counted only when the coder itself wrote a `Scope change:` line quoting it. + +**The guarantee:** What people say decides scope as they say it. When the ledger is seeded, and on every round's comments, an out-of-scope entry that a person's answer or comment asks for moves into scope and records who asked. From then on, a diff that takes that work out is a breach that goes back to be put back. A comment that keeps the item out moves nothing. + +**Where it's enforced:** `common::scope_ledger::Ledger::take_people`, `scope_ledger::breaches` (reverted items), `passes::scope_ledger::{people, load_or_seed, held, load_with_people}`. diff --git a/services/common/src/agent_policy/registry.rs b/services/common/src/agent_policy/registry.rs index 393857d7d..5979cdf2c 100644 --- a/services/common/src/agent_policy/registry.rs +++ b/services/common/src/agent_policy/registry.rs @@ -247,6 +247,7 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("restore_file", Risk::Write), ("run_codegen", Risk::Write), ("run_checks", Risk::Write), + ("reproduce_on_base", Risk::Write), // A team skill's own script in the sandbox (read-only GitHub token at // most), and the run's outputs kept in CoderHelm. ("run_skill_script", Risk::Write), diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index d25943501..6d4638326 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -208,6 +208,9 @@ pub mod pr_template; pub mod preview; /// What a fix must show before it is committed and pushed. pub mod push_gate; +/// A bug reproduced on the base before code is planned, fixed in the +/// mechanism the reproduction lands in, questions looked up first. +pub mod repro_first; pub mod run_prs; /// Scope decided once at plan time, held in every round and in the /// description. diff --git a/services/common/src/repro_first.rs b/services/common/src/repro_first.rs new file mode 100644 index 000000000..e5e72ec55 --- /dev/null +++ b/services/common/src/repro_first.rs @@ -0,0 +1,689 @@ +//! A bug is reproduced on the base before any code is planned, and the fix +//! goes in the mechanism the reproduction lands in. +//! +//! A ticket named four camps filed under the wrong sport. The camps' names +//! carried a suffix ("Squash Camp-Half Day"), and the existing overrides +//! table matched names exactly, so its entries for those camps never +//! matched. The run's own notes said as much, then planned a keyword +//! matcher beside the table, rewrote how every camp of that source got its +//! sport, moved other programs to a different lookup and asked the team a +//! question one page load answered. The right change stripped the suffix in +//! the lookup and added two entries, with a test built from the exact names +//! stored on staging that failed on the base. +//! +//! The rules here, pure text, read by the plan check: +//! +//! - **`## Reproduce`** ([`reproduce_gaps`]): a bug plan writes the exact +//! inputs (the ticket's ids and names, with every variant a read-only +//! lookup found), the call or command it ran on the base with its actual +//! output, and the one line where the existing code goes wrong. The +//! command must be one this run ran on the base (`reproduce_on_base`, +//! [`Attempt`]), and the output is quoted from what came back. A run that +//! truly can't reproduce writes `Unverified:` with why; it is kept as +//! unverified, never skipped silently. +//! - **Fix the mechanism found** ([`reuse_gaps`]): when the wrong line is +//! in an existing lookup, table or mapping, `## Smallest change` names it +//! and changes it, or says why it can't; a plan that adds a new +//! resolution path beside it goes back. +//! - **Questions are looked up first** ([`question_gaps`]): a question the +//! plan decides with a default, about what a page shows or what the data +//! holds, carries what the lookup showed (`Looked up:`) or why no lookup +//! settles it (`No lookup settles it:`). +//! - **The ticket's records** ([`ticket_ids`]): the ids and quoted names a +//! ticket names, for the reproduction's inputs and for sizing the diff +//! against the ticket (`minimal_change`). + +use serde::{Deserialize, Serialize}; + +/// The plan's section. +pub const HEADING: &str = "## Reproduce"; +/// The planner's tool that runs a call or command on the base. +pub const TOOL: &str = "reproduce_on_base"; + +const INPUTS: &str = "inputs:"; +const RAN: &str = "ran on base:"; +const OUTPUT: &str = "output:"; +const WRONG: &str = "wrong line:"; +const UNVERIFIED: &str = "unverified:"; +const FIELDS: &[&str] = &[INPUTS, RAN, OUTPUT, WRONG, UNVERIFIED]; + +/// One run of the reproduction tool on the base tree. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Attempt { + pub command: String, + /// The command's exit code; `None` when the sandbox gave none. + #[serde(default)] + pub exit: Option, + /// What it printed (the end of it, when long). + #[serde(default)] + pub output: String, + /// Why it couldn't run, when it didn't. + #[serde(default)] + pub error: String, +} + +impl Attempt { + /// Whether the command ran and gave an answer. + pub fn ran(&self) -> bool { + self.error.is_empty() && self.exit.is_some() + } +} + +/// The plan's `## Reproduce` section, field by field. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Reproduce { + pub inputs: String, + pub ran: String, + pub output: String, + pub wrong_line: String, + pub unverified: String, +} + +fn lower(s: &str) -> String { + s.to_lowercase() +} + +fn flat(s: &str) -> String { + s.split_whitespace().collect::>().join(" ") +} + +/// A markdown section's body: from its heading to the next `## ` heading. +pub fn section<'a>(text: &'a str, heading: &str) -> Option<&'a str> { + let h = lower(heading); + let mut start = None; + let mut offset = 0; + for line in text.split_inclusive('\n') { + let t = line.trim(); + if let Some(s) = start { + if t.starts_with("## ") { + return Some(&text[s..offset]); + } + } else if lower(t) == h { + start = Some(offset + line.len()); + } + offset += line.len(); + } + start.map(|s| &text[s..]) +} + +/// Reads the section's fields. A field runs from its label to the next +/// label; fences and bullets are kept as written. +pub fn read(design: &str) -> Option { + let body = section(design, HEADING)?; + let mut out = Reproduce::default(); + let mut current: Option<&str> = None; + for line in body.lines() { + let t = line.trim().trim_start_matches(['-', '*']).trim(); + let t = t.trim_start_matches("**"); + let l = lower(t); + let label = FIELDS + .iter() + .find(|f| l.starts_with(**f) || l.replacen("**", "", 2).starts_with(**f)); + let rest = if let Some(f) = label { + current = Some(f); + let cut = t.to_lowercase().find(':').map_or(0, |i| i + 1); + t[cut..].trim().trim_start_matches("**").trim().to_string() + } else { + line.to_string() + }; + let slot = match current { + Some(INPUTS) => &mut out.inputs, + Some(RAN) => &mut out.ran, + Some(OUTPUT) => &mut out.output, + Some(WRONG) => &mut out.wrong_line, + Some(UNVERIFIED) => &mut out.unverified, + _ => continue, + }; + if !slot.is_empty() { + slot.push('\n'); + } + slot.push_str(&rest); + } + for s in [ + &mut out.inputs, + &mut out.ran, + &mut out.output, + &mut out.wrong_line, + &mut out.unverified, + ] { + *s = s.trim().to_string(); + } + Some(out) +} + +fn is_uuid(w: &str) -> bool { + let parts: Vec<&str> = w.split('-').collect(); + parts.len() == 5 + && [8, 4, 4, 4, 12] + .iter() + .zip(&parts) + .all(|(n, p)| p.len() == *n && p.chars().all(|c| c.is_ascii_hexdigit())) +} + +/// The records a ticket names: its uuids, numbered ids (`id 8204`, `#8204`, +/// `(8204)`), and backticked or quoted names, each once. +pub fn ticket_ids(ticket: &str) -> Vec { + let mut out: Vec = Vec::new(); + let mut push = |s: &str| { + let s = s.trim(); + if !s.is_empty() && !out.iter().any(|o| o.eq_ignore_ascii_case(s)) { + out.push(s.to_string()); + } + }; + let words: Vec<&str> = ticket + .split(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | ',' | ';' | '[' | ']')) + .collect(); + for (i, w) in words.iter().enumerate() { + let w = w.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '-'); + if is_uuid(w) { + push(w); + continue; + } + let digits = w.trim_start_matches('#'); + let numbered = digits.len() >= 3 && digits.chars().all(|c| c.is_ascii_digit()); + let after_id = i > 0 && { + let p = words[i - 1].to_lowercase(); + p == "id" || p == "id:" || p.ends_with("_id") || p.ends_with("id:") + }; + if numbered && (after_id || words[i].starts_with('#')) { + push(digits); + } + } + for (open, close) in [('`', '`'), ('"', '"'), ('\u{201c}', '\u{201d}')] { + let mut rest = ticket; + while let Some(i) = rest.find(open) { + let after = &rest[i + open.len_utf8()..]; + let Some(j) = after.find(close) else { break }; + let s = &after[..j]; + if (3..=80).contains(&s.trim().len()) && !s.contains('\n') && !s.contains("://") { + push(s); + } + rest = &after[j + close.len_utf8()..]; + } + } + out +} + +/// What a bug plan's `## Reproduce` misses, one line each for the +/// send-back. `ticket` is the ticket's words; `attempts` the runs of +/// [`TOOL`] this run made; `can_run` says the sandbox can run on the base; +/// `can_look_up` says the team has a data source connected. +pub fn reproduce_gaps( + design: &str, + ticket: &str, + attempts: &[Attempt], + can_run: bool, + can_look_up: bool, +) -> Vec { + let Some(r) = read(design) else { + return vec![format!( + "design.md lacks `{HEADING}`. This is a bug: before planning code, take the exact names or ids from the ticket (and every variant a read-only lookup finds in the real data), run them through the current code on the base with `{TOOL}`, and write `Inputs:`, `Ran on base:` (the command), `Output:` (what it printed) and `Wrong line:` (`path:line` and the code there that goes wrong)." + )]; + }; + let mut out = Vec::new(); + let ids = ticket_ids(ticket); + let inputs = lower(&r.inputs); + let missing: Vec<&String> = ids.iter().filter(|i| !inputs.contains(&lower(i))).collect(); + if r.inputs.is_empty() { + out.push(format!( + "`{HEADING}` has no `Inputs:`. List the exact names or ids the ticket gives, as they are stored, with every variant a read-only lookup finds." + )); + } else if !missing.is_empty() { + out.push(format!( + "`{HEADING}` `Inputs:` leaves out what the ticket names: {}. Reproduce with each of them.", + missing + .iter() + .take(6) + .map(|m| format!("`{m}`")) + .collect::>() + .join(", ") + )); + } + if can_look_up && !r.inputs.is_empty() && !cites_lookup(&r.inputs) { + out.push(format!( + "`{HEADING}` `Inputs:` doesn't say where the names came from. Query the connected data read-only for the ticket's names (a `LIKE` on the name, not an exact match) and list every variant as stored, citing the lookup." + )); + } + if !r.unverified.is_empty() { + if can_run && attempts.is_empty() { + out.push(format!( + "`{HEADING}` says `Unverified:` but this run never tried `{TOOL}`. Run the call on the base first; only a run that can't reproduce is unverified." + )); + } + if !has_location(&r.wrong_line) { + out.push(wrong_line_gap()); + } + return out; + } + if r.ran.is_empty() { + out.push(format!( + "`{HEADING}` has no `Ran on base:`. Run the ticket's inputs through the current code with `{TOOL}` (for example `python -c \"from module import fn; print(fn(''))\"`) and write the command and its output. When it truly can't run, write `Unverified: `." + )); + } else { + match matching_attempt(&r.ran, attempts) { + None => out.push(format!( + "`{HEADING}` `Ran on base:` is not a command this run ran. Run it with `{TOOL}` and quote that command." + )), + Some(a) if !a.ran() => out.push(format!( + "`{HEADING}`: `{}` didn't run on the base ({}). Fix the command and run it again, or write `Unverified: `.", + common_trunc(&a.command, 120), + if a.error.is_empty() { "no result" } else { a.error.as_str() } + )), + Some(a) => { + if r.output.is_empty() || !quoted_from(&r.output, &a.output) { + out.push(format!( + "`{HEADING}` `Output:` is not what `{}` printed. Quote its output as it came back.", + common_trunc(&a.command, 120) + )); + } + } + } + } + if !has_location(&r.wrong_line) { + out.push(wrong_line_gap()); + } + out +} + +fn wrong_line_gap() -> String { + format!( + "`{HEADING}` `Wrong line:` doesn't name where the existing code goes wrong. Write `path:line` and the code on that line (backticked), the one line the reproduction shows is wrong." + ) +} + +fn common_trunc(s: &str, n: usize) -> String { + let s = flat(s); + if s.chars().count() <= n { + s + } else { + format!("{}...", s.chars().take(n).collect::()) + } +} + +fn cites_lookup(inputs: &str) -> bool { + let l = lower(inputs); + [ + "lookup", + "looked up", + "query", + "queried", + "select ", + "database", + "staging", + "prod", + "page", + "check_url", + "probe", + "rows", + "stored", + ] + .iter() + .any(|w| l.contains(w)) + || l.split(|c: char| !c.is_ascii_alphanumeric()).any(|w| { + w.len() >= 2 && w.starts_with('l') && w[1..].chars().all(|c| c.is_ascii_digit()) + }) +} + +/// `path:line`, a file path with a line number. +fn has_location(s: &str) -> bool { + s.split(|c: char| c.is_whitespace() || c == '`' || c == '(' || c == ')') + .any(|w| { + let Some((path, line)) = w.rsplit_once(':') else { + return false; + }; + let line = line.split(['-', ',']).next().unwrap_or(""); + path.contains('.') + && !path.contains("://") + && !line.is_empty() + && line.chars().all(|c| c.is_ascii_digit()) + }) +} + +fn strip_fence(s: &str) -> String { + s.lines() + .filter(|l| !l.trim_start().starts_with("```")) + .collect::>() + .join("\n") +} + +/// The attempt a written command is: the same command once whitespace and +/// backticks are set aside. +pub fn matching_attempt<'a>(written: &str, attempts: &'a [Attempt]) -> Option<&'a Attempt> { + let w = flat(&strip_fence(written).replace('`', "")); + if w.is_empty() { + return None; + } + attempts.iter().rev().find(|a| { + let c = flat(&a.command); + !c.is_empty() && (c == w || w.contains(&c) || (c.len() >= 20 && c.contains(&w))) + }) +} + +/// Whether the written output is quoted from what the command printed: +/// each of its non-empty lines appears in the real output. +pub fn quoted_from(written: &str, real: &str) -> bool { + let real = flat(real); + let lines: Vec = strip_fence(written) + .lines() + .map(|l| flat(l.trim().trim_matches('`'))) + .filter(|l| !l.is_empty()) + .collect(); + !lines.is_empty() && lines.iter().all(|l| real.contains(l.as_str())) +} + +/// Backticked identifiers on the wrong line: the function, table or map +/// the reproduction lands in. +pub fn wrong_names(wrong_line: &str) -> Vec { + let mut out = Vec::new(); + for (i, part) in wrong_line.split('`').enumerate() { + if i % 2 == 0 { + continue; + } + for tok in part.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) { + let ident = tok.len() >= 4 + && tok + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && (tok.contains('_') || tok.chars().skip(1).any(|c| c.is_ascii_uppercase())); + if ident && !out.iter().any(|o| o == tok) { + out.push(tok.to_string()); + } + } + } + out +} + +fn wrong_path(wrong_line: &str) -> Option { + wrong_line + .split(|c: char| c.is_whitespace() || c == '`' || c == '(' || c == ')') + .find_map(|w| { + let (path, line) = w.rsplit_once(':')?; + (path.contains('.') && line.chars().next().is_some_and(|c| c.is_ascii_digit())) + .then(|| path.to_string()) + }) +} + +/// Words that put a new resolution path beside an existing lookup. +const NEW_PATH: &[&str] = &[ + "keyword match", + "keyword step", + "keyword fallback", + "substring match", + "fuzzy match", + "new resolver", + "new resolution", + "resolution path", + "new lookup", + "second lookup", + "new matching", + "rewrite the resolution", + "rewrites the resolution", + "replace the lookup", + "replaces the lookup", + "instead of the override", + "bypass the override", + "fallback chain", +]; + +const CANT: &[&str] = &["can't", "cannot", "can not", "doesn't hold", "won't hold"]; + +/// What a bug plan misses about the mechanism its reproduction landed in: +/// `## Smallest change` must name it and change it, or say why it can't, +/// and no new resolution path goes beside it. `smallest` is the plan's +/// Smallest change section; `proposing` the words that propose (proposal, +/// design without Must not change, tasks). +pub fn reuse_gaps(design: &str, smallest: &str, proposing: &str) -> Vec { + let Some(r) = read(design) else { + return Vec::new(); + }; + let names = wrong_names(&r.wrong_line); + let path = wrong_path(&r.wrong_line); + if names.is_empty() && path.is_none() { + return Vec::new(); + } + let s = lower(smallest); + let says_why = CANT.iter().any(|w| s.contains(w)); + let mut out = Vec::new(); + let named = names.iter().any(|n| s.contains(&lower(n))); + let first = names.first().cloned().or(path.clone()).unwrap_or_default(); + if !named && !says_why { + out.push(format!( + "The reproduction lands in `{first}`, and `## Smallest change` doesn't change it. Fix the lookup that already exists (its matching, or its entries) and name it there, or say why it can't hold the fix." + )); + } + let p = lower(proposing); + if let Some(w) = NEW_PATH.iter().find(|w| p.contains(*w)) { + if !says_why { + out.push(format!( + "The plan adds a new resolution path (\"{w}\") beside `{first}`, where the reproduction says the existing one goes wrong. Change `{first}` instead; a second path beside it is sent back unless `## Smallest change` says why the existing one can't hold the fix." + )); + } + } + out +} + +/// Words of a question a page load answers. +const PAGE_WORDS: &[&str] = &[ + "show", "appear", "visible", "display", "listed", "list ", "filter", "chip", "render", "page", + "see ", +]; +/// Words of a question a read-only query answers. +const DATA_WORDS: &[&str] = &[ + "active", + "inactive", + "exist", + "how many", + "count", + "stored", + "rows", + "linked", + "mapped", + "which records", + "duplicate", + "value of", + "null", +]; + +/// How a question can be settled by looking. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Lookup { + Page, + Data, +} + +/// The lookup that would answer a question, if one would. +pub fn answered_by(question: &str) -> Option { + let q = lower(question); + if PAGE_WORDS.iter().any(|w| q.contains(w)) { + Some(Lookup::Page) + } else if DATA_WORDS.iter().any(|w| q.contains(w)) { + Some(Lookup::Data) + } else { + None + } +} + +const LOOKED: &[&str] = &[ + "looked up:", + "looked up ", + "no lookup settles it", + "checked:", + "loaded ", + "queried ", + "check_url", + "probe_page", +]; + +/// Each question the plan decides with a default (or still asks) that a +/// page load or a query would answer, and that says nothing of the lookup. +/// `questions` are the question lines and the entries decided with a +/// default, as written. +pub fn question_gaps(questions: &[String]) -> Vec { + let mut out = Vec::new(); + for q in questions { + let Some(kind) = answered_by(q) else { + continue; + }; + let l = lower(q); + if LOOKED.iter().any(|w| l.contains(w)) { + continue; + } + let how = match kind { + Lookup::Page => "load the page that shows it (`check_url`, with a cache-busting parameter) and read whether it is there", + Lookup::Data => "query the connected data read-only for it", + }; + out.push(format!( + "Before deciding \"{}\", {how}. Write what it showed after it (`Looked up: `), or `No lookup settles it: `; a question a lookup answers is never asked.", + common_trunc(q.trim().trim_start_matches(['-', '*']).trim(), 140) + )); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const TICKET: &str = "Observed\nWhen filtering for Volleyball, Squash Camp-Half Day (a0000002-0000-4000-8000-000000000002) shows.\nExpected\nSquash Camp- Full Day (a0000003-0000-4000-8000-000000000003)"; + + fn design(reproduce: &str) -> String { + format!( + "## Reuse\n- `CAMP_OVERRIDES`\n\n## Reproduce\n{reproduce}\n\n## Smallest change\nx\n" + ) + } + + fn attempt(cmd: &str, out: &str) -> Attempt { + Attempt { + command: cmd.into(), + exit: Some(0), + output: out.into(), + error: String::new(), + } + } + + const CMD: &str = + "python -c \"from dags.common import get_override as g; print(g('Squash Camp-Half Day'))\""; + + fn good() -> String { + design(&format!( + "Inputs: a0000002-0000-4000-8000-000000000002, a0000003-0000-4000-8000-000000000003; staging lookup L2: `Squash Camp-Half Day`, `Squash Camp-Full Day`, `Squash Camp- Full Day`\nRan on base: `{CMD}`\nOutput:\n```\nNone\n```\nWrong line: dags/common.py:99 `return CAMP_OVERRIDES.get(normalized)` matches the whole name, suffix included." + )) + } + + #[test] + fn the_ticket_names_its_records() { + let ids = ticket_ids(TICKET); + assert_eq!( + ids, + vec![ + "a0000002-0000-4000-8000-000000000002", + "a0000003-0000-4000-8000-000000000003" + ] + ); + let ids = + ticket_ids("Group id 8204 and #8214, the `Hockey Camp` and \"Squash Camp\", not 2026."); + assert_eq!(ids, vec!["8204", "8214", "Hockey Camp", "Squash Camp"]); + } + + #[test] + fn a_reproduction_quotes_a_run_on_the_base() { + let a = vec![attempt(CMD, "===\nNone\n")]; + assert!( + reproduce_gaps(&good(), TICKET, &a, true, true).is_empty(), + "{:?}", + reproduce_gaps(&good(), TICKET, &a, true, true) + ); + // No section at all. + let g = reproduce_gaps("## Reuse\nx\n", TICKET, &a, true, true); + assert!(g[0].contains("lacks `## Reproduce`")); + // A command this run never ran. + let g = reproduce_gaps(&good(), TICKET, &[], true, true); + assert!( + g.iter().any(|l| l.contains("not a command this run ran")), + "{g:?}" + ); + // Output that isn't what came back. + let a2 = vec![attempt(CMD, "b0000001\n")]; + let g = reproduce_gaps(&good(), TICKET, &a2, true, true); + assert!(g.iter().any(|l| l.contains("is not what")), "{g:?}"); + // A ticket id left out of the inputs. + let d = good().replace("a0000003-0000-4000-8000-000000000003; ", ""); + let g = reproduce_gaps(&d, TICKET, &a, true, true); + assert!(g.iter().any(|l| l.contains("a0000003")), "{g:?}"); + // Inputs from nowhere when data could be looked up. + let d = good().replace("staging lookup L2: ", ""); + let g = reproduce_gaps(&d, TICKET, &a, true, true); + assert!( + g.iter().any(|l| l.contains("where the names came from")), + "{g:?}" + ); + assert!(reproduce_gaps(&d, TICKET, &a, true, false).is_empty()); + // No wrong line. + let d = good().replace("dags/common.py:99", "the lookup"); + let g = reproduce_gaps(&d, TICKET, &a, true, true); + assert!(g.iter().any(|l| l.contains("Wrong line:")), "{g:?}"); + } + + #[test] + fn unverified_is_kept_only_after_trying() { + let d = design("Inputs: a0000002-0000-4000-8000-000000000002 a0000003-0000-4000-8000-000000000003 from staging rows\nUnverified: the module imports Airflow, which the sandbox can't install\nWrong line: dags/common.py:99 `CAMP_OVERRIDES.get`"); + let g = reproduce_gaps(&d, TICKET, &[], true, true); + assert!(g.iter().any(|l| l.contains("never tried")), "{g:?}"); + let failed = Attempt { + command: CMD.into(), + exit: Some(1), + output: "ModuleNotFoundError".into(), + error: String::new(), + }; + assert!(reproduce_gaps(&d, TICKET, &[failed], true, true).is_empty()); + // With no sandbox it can't be tried. + assert!(reproduce_gaps(&d, TICKET, &[], false, true).is_empty()); + } + + #[test] + fn the_fix_goes_in_the_lookup_the_reproduction_lands_in() { + let d = good(); + // A new keyword step beside the override table. + let g = reuse_gaps( + &d, + "Add `resolve_camp_sport_id`: override first, then a keyword match on the name.", + "a keyword step is added after the override", + ); + assert_eq!(g.len(), 2, "{g:?}"); + assert!(g[0].contains("`CAMP_OVERRIDES`")); + assert!(g[1].contains("keyword")); + // The lookup itself, fixed. + let g = reuse_gaps( + &d, + "Strip the trailing `-Half Day`/`-Full Day` before `CAMP_OVERRIDES.get`; add 2 entries.", + "strip the suffix in the lookup", + ); + assert!(g.is_empty(), "{g:?}"); + // A stated reason keeps a new path. + let g = reuse_gaps( + &d, + "`CAMP_OVERRIDES` can't hold this: the source gives no name.", + "a keyword match", + ); + assert!(g.is_empty(), "{g:?}"); + assert_eq!( + wrong_names("dags/a.py:9 `return MAP.get(k)` in `get_sport`"), + vec!["get_sport"] + ); + } + + #[test] + fn a_question_a_lookup_answers_is_looked_up_first() { + let q = vec![ + "- Inactive Squash camps: decided with the default: they show under the filter as today".to_string(), + "- Brand colours: decided with the default: unchanged".to_string(), + "- Is the sport active in staging? Looked up: L7 shows active=false".to_string(), + ]; + let g = question_gaps(&q); + assert_eq!(g.len(), 1, "{g:?}"); + assert!(g[0].contains("check_url")); + assert_eq!(answered_by("How many rows are linked?"), Some(Lookup::Data)); + assert_eq!(answered_by("Which copy do we use?"), None); + } +} diff --git a/services/common/src/scope_ledger.rs b/services/common/src/scope_ledger.rs index 38e083454..1a5704e3b 100644 --- a/services/common/src/scope_ledger.rs +++ b/services/common/src/scope_ledger.rs @@ -111,11 +111,24 @@ pub struct Breach { pub path: String, /// The mark found (a path, or a name on an added line). pub mark: String, + /// The diff takes out an item a person or a criterion moved into + /// scope (`why` says who asked), instead of bringing back one left out. + #[serde(default)] + pub reverted: bool, } impl Breach { /// The instruction for the round that fixes it. pub fn instruction(&self) -> String { + if self.reverted { + return format!( + "`{}` takes out \"{}\" (`{}`), which is in scope: {}. Put it back; what a person asked for is never reverted as out of scope.", + self.path, + self.item.trim_end_matches('.'), + self.mark, + self.why.trim_end_matches('.'), + ); + } format!( "`{}` brings back \"{}\" (`{}`), which the plan decided is out of scope: {}. Take it out of the code and its tests, or, only when an acceptance criterion or a person's comment asks for it, add `Scope change: {}: ` to your Evidence.", self.path, @@ -646,6 +659,34 @@ impl Ledger { (accepted, refused) } + /// What people said decides scope as they say it: each out-of-scope + /// entry that a person's answer or comment asks for (`said`: who, and + /// what they wrote; matched as [`asked_by`] matches a criterion) moves + /// in, recording who asked and their words. No `Scope change:` line is + /// needed. A reviewer once answered on a pull request that the path + /// pages should cover both rows; the run replied "Understood" and + /// reverted the path-page work as out of scope. A comment that keeps an + /// item out ("leave the path pages for a later ticket") moves nothing. + /// Returns a line for each item moved in. Run at seed and on each + /// round's comments. + pub fn take_people(&mut self, said: &[(String, String)]) -> Vec { + let mut moved = Vec::new(); + for e in self.entries.iter_mut().filter(|e| e.is_out()) { + let Some((who, text)) = said.iter().find(|(_, t)| person_asks_for(e, t)) else { + continue; + }; + let words: String = one_line(text).chars().take(160).collect(); + let who = if who.trim().is_empty() { + "a person" + } else { + who.trim() + }; + e.moved_in = format!("{who} asked for it: \"{words}\""); + moved.push(format!("\"{}\" moved into scope: {}", e.item, e.moved_in)); + } + moved + } + /// The out-of-scope entry a piece of planned work names (one of its /// marks, or its item said in full): that work is not built again. pub fn covers(&self, text: &str) -> Option<&Entry> { @@ -690,6 +731,31 @@ fn significant(text: &str) -> Vec { .collect() } +/// Words of a comment that keeps an item out rather than asking for it. +const KEEPS_OUT: &[&str] = &[ + "out of scope", + "leave out", + "leave it out", + "leave them out", + "leave the", + "not needed", + "no need", + "don't", + "do not", + "skip", + "separate ticket", + "later ticket", + "another ticket", + "not in this", +]; + +/// Whether a person's words ask for an out-of-scope entry: they cite it the +/// way a criterion would, and don't keep it out. +pub fn person_asks_for(e: &Entry, text: &str) -> bool { + let l = lower(text); + !KEEPS_OUT.iter().any(|w| l.contains(w)) && asked_by(e, &[text.to_string()]).is_some() +} + /// The criterion that asks for an entry's item, when one does. pub fn asked_by<'a>(e: &Entry, criteria: &'a [String]) -> Option<&'a String> { let said = format!("{} {}", e.item, e.marks.join(" ")); @@ -753,6 +819,26 @@ pub fn breaches(ledger: &Ledger, files: &[(String, String, String)]) -> Vec Vec impl Iterator { + patch + .lines() + .filter(|l| l.starts_with('-') && !l.starts_with("---")) + .map(|l| &l[1..]) +} + /// Phrases of a task that reach past the files it names. const OPEN_ENDED: &[&str] = &[ "any other caller", @@ -1400,6 +1494,7 @@ mod tests { why: "one id".into(), path: "apps/web/src/services/classService.ts".into(), mark: "/classes/".into(), + reverted: false, }]; let changed = vec![ "apps/web/src/services/classService.ts".to_string(), diff --git a/services/common/src/test_env.rs b/services/common/src/test_env.rs index 46fe275c7..1271837c5 100644 --- a/services/common/src/test_env.rs +++ b/services/common/src/test_env.rs @@ -284,13 +284,19 @@ pub fn from_workflows_for( let dir = s(step.get("working-directory")) .trim_start_matches("./") .to_string(); + // A step that runs tests keeps its whole script (a loop's + // body, a counter it sets), so a test file can be run the + // way the step runs it (`TestEnv::file_command`). + let step_tests = lines_of(&run) + .iter() + .any(|l| crate::ci_cover::is_check_command(l) && !is_install(l)); 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) { + if step_tests && !is_install(&line) { seen_test = true; env.test.push(line); env.env.extend(plain_env(step.get("env"))); @@ -367,6 +373,62 @@ fn common_step_dir(test: &[String]) -> String { } } +/// Interpreters that run a test file given its path. +const SCRIPT_RUNNERS: &[&str] = &["python", "python3", "node", "bash", "sh"]; + +/// A test step without its `(cd && ...)` wrapper: (dir, command). +fn unwrap_cd(line: &str) -> (String, String) { + if let Some(rest) = line.strip_prefix("(cd ") { + if let Some((dir, cmd)) = rest.split_once(" && ") { + let cmd = cmd.strip_suffix(')').unwrap_or(cmd); + return ( + dir.trim().trim_end_matches('/').to_string(), + cmd.trim().to_string(), + ); + } + } + (String::new(), line.trim().to_string()) +} + +/// A shell loop's head, `for in ; do`: its variable and globs. +fn loop_head(line: &str) -> Option<(String, Vec)> { + let rest = line.trim().strip_prefix("for ")?; + let (var, rest) = rest.split_once(" in ")?; + let list = rest.split(';').next()?.trim_end_matches(" do").trim(); + let globs: Vec = list + .split_whitespace() + .map(|g| { + g.trim_matches(['"', '\'']) + .trim_start_matches("./") + .to_string() + }) + .filter(|g| !g.is_empty() && !g.contains('$')) + .collect(); + let var = var.trim(); + (!var.is_empty() && !globs.is_empty()).then(|| (var.to_string(), globs)) +} + +/// The interpreter a loop body runs the loop's file with: `python "$t"` +/// gives `python`. +fn runs_var(line: &str, var: &str) -> Option { + let line = line.trim(); + for form in [ + format!("\"${var}\""), + format!("\"${{{var}}}\""), + format!("${{{var}}}"), + format!("${var}"), + ] { + if let Some(i) = line.find(&form) { + let runner = line[..i].trim(); + let first = runner.split_whitespace().next().unwrap_or(""); + if SCRIPT_RUNNERS.contains(&first) && !runner.contains(['|', ';', '&']) { + return Some(runner.to_string()); + } + } + } + None +} + fn quote(s: &str) -> String { format!("'{}'", s.replace('\'', "'\\''")) } @@ -497,6 +559,90 @@ bash -c {cmd}"#, ) } + /// The command that runs one test file (`file`, from the repository + /// root) the way CI runs its tests, or `None` when no test step can be + /// narrowed to it. CI may run a runner (`pytest`, `python -m + /// unittest`), a loop over test files (`for t in tests/test_*.py; do + /// python "$t"`), or the file by name. A data-pipeline repository ran + /// its tests with that loop, no runner CoderHelm knew, so a bug fix's + /// new test was never run on the base and the pull request said + /// nothing about it. + pub fn file_command(&self, file: &str) -> Option { + let safe = !file.is_empty() + && file + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '/')) + && !file.contains(".."); + if !safe { + return None; + } + let steps: Vec<(String, String)> = self.test.iter().map(|l| unwrap_cd(l)).collect(); + let in_dir = |dir: &str, cmd: String| -> Option { + if dir.is_empty() { + return Some(cmd); + } + let rel = file.strip_prefix(&format!("{}/", dir.trim_end_matches('/')))?; + Some(format!("(cd {dir} && {})", cmd.replace(file, rel))) + }; + // A runner that takes file paths. + for (dir, line) in &steps { + let low = line.to_ascii_lowercase(); + for runner in ["pytest", "-m unittest"] { + if let Some(i) = low.find(runner) { + let prefix = line[..i + runner.len()].trim(); + if let Some(c) = in_dir(dir, format!("{prefix} {file}")) { + return Some(c); + } + } + } + } + // A loop over test files, its body running each one. + for (i, (dir, line)) in steps.iter().enumerate() { + let Some((var, globs)) = loop_head(line) else { + continue; + }; + let rel = if dir.is_empty() { + file + } else { + match file.strip_prefix(&format!("{dir}/")) { + Some(r) => r, + None => continue, + } + }; + if !globs.iter().any(|g| { + crate::skill_apply::glob_match(g, rel) && g.contains('/') == rel.contains('/') + }) { + continue; + } + // The body: the rest of this line after `do`, then the lines + // that follow it. + let after_do = line.split_once("; do").map(|(_, b)| b.to_string()); + let body = after_do + .into_iter() + .chain(steps.iter().skip(i + 1).map(|(_, l)| l.clone())); + for b in body { + if let Some(runner) = runs_var(&b, &var) { + return in_dir(dir, format!("{runner} {file}")); + } + if b.trim_start().starts_with("done") { + break; + } + } + } + // The file by name. + for (dir, line) in &steps { + let words: Vec<&str> = line.split_whitespace().collect(); + if words.len() == 2 + && SCRIPT_RUNNERS.contains(&words[0]) + && (format!("{dir}/{}", words[1]).trim_start_matches('/') == file + || words[1] == file) + { + return in_dir(dir, line.replace(words[1], file)); + } + } + None + } + /// What the coder is told: the environment is ready in every command, /// and how the tests run. pub fn coder_note(&self) -> String { @@ -628,6 +774,69 @@ jobs: .is_none()); } + /// A data-pipeline repository's CI: a loop runs each test file with + /// `python`, no runner CoderHelm knew. + const LOOP: &str = r#" +name: Tests +on: [pull_request] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - run: uv pip install --quiet "apache-airflow[postgres]==2.10.3" -r requirement.txt + - name: Run tests + env: + PYTHONHASHSEED: "0" + run: | + failed=0 + for t in tests/test_*.py; do + echo "::group::$t" + python "$t" || failed=1 + echo "::endgroup::" + done + exit $failed +"#; + + #[test] + fn one_test_file_runs_the_way_ci_runs_its_tests() { + let e = from_workflows(&[("t.yml".into(), LOOP.into())], &[]).unwrap(); + assert!( + e.test.iter().any(|t| t.contains("python \"$t\"")), + "{:?}", + e.test + ); + assert_eq!( + e.file_command("tests/test_camp_sport.py").as_deref(), + Some("python tests/test_camp_sport.py") + ); + // A file the loop doesn't run, and a path that isn't safe. + assert_eq!(e.file_command("dags/camp_sport.py"), None); + assert_eq!(e.file_command("tests/test_a.py; rm -rf /"), None); + // A runner takes the file. + let e = from_workflows(&[("t.yml".into(), PY.into())], &[]).unwrap(); + assert_eq!( + e.file_command("tests/test_a.py").as_deref(), + Some("python -m pytest tests/test_a.py") + ); + // A one-line loop, in a folder. + let mut e = TestEnv { + test: vec![ + "(cd etl && for t in tests/test_*.py; do python3 \"$t\" || exit 1; done)".into(), + ], + ..Default::default() + }; + assert_eq!( + e.file_command("etl/tests/test_a.py").as_deref(), + Some("(cd etl && python3 tests/test_a.py)") + ); + assert_eq!(e.file_command("tests/test_a.py"), None); + e.test = vec!["npm run build".into()]; + assert_eq!(e.file_command("tests/test_a.py"), 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). diff --git a/services/common/src/tool_registry.rs b/services/common/src/tool_registry.rs index e59329b5f..1c0ccccea 100644 --- a/services/common/src/tool_registry.rs +++ b/services/common/src/tool_registry.rs @@ -117,6 +117,7 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("restore_file", Risk::Write), ("run_codegen", Risk::Write), ("run_checks", Risk::Write), + ("reproduce_on_base", Risk::Write), // A team skill's own script in the sandbox (read-only GitHub token at // most), and the run's outputs kept in CoderHelm. ("run_skill_script", Risk::Write), diff --git a/services/worker/src/passes/habits_check.rs b/services/worker/src/passes/habits_check.rs index ad5828f18..8a4789a4d 100644 --- a/services/worker/src/passes/habits_check.rs +++ b/services/worker/src/passes/habits_check.rs @@ -252,6 +252,33 @@ pub fn scoped_cmd(base_cmd: &str, file: &str) -> Option { .map(|c| c.replace(" --passWithNoTests", "")) } +/// The command that runs one test file on its own: the CI test command +/// CoderHelm knows, narrowed to the file, else the file run the way the CI +/// job's test step runs it (`TestEnv::file_command`). `Err` says why none +/// can, and the test is then recorded as not run, never as passing. +pub fn file_cmd( + ci_cmd: Option<&str>, + env: Option<&common::test_env::TestEnv>, + file: &str, +) -> Result { + if let Some(c) = ci_cmd.and_then(|c| scoped_cmd(c, file)) { + return Ok(c); + } + if let Some(c) = env.and_then(|e| e.file_command(file)) { + return Ok(c); + } + Err(match (ci_cmd, env) { + (Some(c), _) => format!("the test command `{c}` can't be narrowed to `{file}`"), + (None, Some(e)) => format!( + "the CI test step ({}) doesn't run `{file}` on its own", + e.source + ), + (None, None) => { + "the repository's CI runs no unit test command CoderHelm can read".to_string() + } + }) +} + /// The output of each failing step of a sandbox script, in step order. pub fn failing_outputs(output: &str, kind: &str) -> Vec { let mark = format!("--- {kind} failed (exit "); @@ -469,6 +496,10 @@ fn repro_waived(plan: &PlanResult) -> bool { .is_some_and(|d| !d.habits.repro.not_feasible.trim().is_empty()) } +/// The pull request's line for a bug fix that no test was shown to fail on +/// the base for. +pub const UNVERIFIED_FIX: &str = "Unverified: no test of this fix was shown to fail on the base code, so the reported failure is not reproduced here."; + /// The line for a change no changed test proves. pub const UNPROVEN: &str = "No changed test fails without the change, so nothing proves it. Write a test that fails on the base code and passes with the change (a unit test, or an end-to-end spec when the behaviour is what a person sees in the browser), through code that exists on the base."; @@ -616,6 +647,11 @@ pub fn open_findings(f: &PrFacts, plan: &PlanResult) -> Vec { w.point(), "CoderHelm makes the change smaller in its next round on this pull request.", ) + } else if l.contains("what a person asked for is never reverted") { + ( + "A person's ask taken out", + "CoderHelm puts it back in its next round on this pull request.", + ) } else if l.contains("decided is out of scope") { ( "Out of scope brought back", @@ -703,6 +739,12 @@ pub fn section(plan: &PlanResult, f: &PrFacts) -> String { out.push_str(&test_line(t)); out.push('\n'); } + // A bug fix no test was shown to fail on the base for says so, in + // so many words: it is unverified, never quietly proven by CI. + if f.bug && !f.tests.iter().any(|t| t.verdict == Verdict::Proven) { + out.push_str(UNVERIFIED_FIX); + out.push('\n'); + } out.push('\n'); } else if let Some(r) = repro.filter(|r| f.bug && !r.not_feasible.trim().is_empty()) { out.push_str(&format!( @@ -916,9 +958,7 @@ const KIND: &str = "unit"; impl Bench for SandboxBench<'_> { async fn run(&self, files: &[String]) -> Result { let r = &self.runner; - let base_cmd = super::detect_ci_test(r.github, r.owner, r.repo, self.base_branch) - .await - .ok_or("the repository's CI runs no unit test command CoderHelm can read")?; + let ci_cmd = super::detect_ci_test(r.github, r.owner, r.repo, self.base_branch).await; let mut steps: Vec = Vec::new(); let tree: Vec = r .github @@ -928,6 +968,16 @@ impl Bench for SandboxBench<'_> { .into_iter() .map(|e| e.path) .collect(); + // A test step CoderHelm's runner list doesn't know (a loop running + // each file with `python`) still runs the file the way CI does. + let narrowed = |f: &String| ci_cmd.as_deref().and_then(|c| scoped_cmd(c, f)); + let env = if files.iter().all(|f| narrowed(f).is_some()) { + None + } else { + let workflows = + super::preview::workflows(r.github, r.owner, r.repo, self.base_branch).await; + common::test_env::from_workflows_for(&workflows, &tree, files) + }; let install: Vec = files .first() .and_then(|f| test_package::package_of(&tree, f, &|_| None)) @@ -937,9 +987,7 @@ impl Bench for SandboxBench<'_> { let installs = install.len(); steps.extend(install); for f in files { - let cmd = scoped_cmd(&base_cmd, f).ok_or_else(|| { - format!("the test command `{base_cmd}` can't be narrowed to one file") - })?; + let cmd = file_cmd(ci_cmd.as_deref(), env.as_ref(), f)?; steps.push(Step { kind: KIND, cmd }); } let head = r @@ -1196,10 +1244,17 @@ async fn check_and_fix( // A page whose state a test branch reads is probed again while // there is time: an arm that couldn't run before is re-checked. facts.live = super::live_guard::facts_for(w, &diff, &evidence.notes, !short).await; - let mut ledger = - super::scope_ledger::load_or_seed(w.state, &w.msg.team_id, w.run_id, w.msg, w.plan) - .await; let comments = super::scope_ledger::comments(w.github, w.msg, w.branch).await; + let people = super::scope_ledger::people(w.msg, &comments); + let mut ledger = super::scope_ledger::load_or_seed( + w.state, + &w.msg.team_id, + w.run_id, + w.msg, + w.plan, + &people, + ) + .await; facts.out_of_scope = super::scope_ledger::held( w.state, &w.msg.team_id, @@ -1207,6 +1262,7 @@ async fn check_and_fix( &mut ledger, &evidence.notes, &super::scope_ledger::sources(w.msg, &comments), + &people, &diff, ) .await; diff --git a/services/worker/src/passes/incidents/rp_reproduce_before_planning.rs b/services/worker/src/passes/incidents/rp_reproduce_before_planning.rs new file mode 100644 index 000000000..22decfeaf --- /dev/null +++ b/services/worker/src/passes/incidents/rp_reproduce_before_planning.rs @@ -0,0 +1,263 @@ +//! rp. A data-pipeline ticket named four camps of a vendor's booking +//! system filed under the wrong sport ("Squash Camp-Half Day" listed under +//! volleyball, "Total Skills Hockey Camp-Full Day" missing from hockey). +//! The pipeline already had a table for exactly this, `CAMP_SPORT_OVERRIDES`, +//! with entries for "squash camp" and "total skills hockey camp". Its lookup +//! matched exact names, and the vendor appends "-Half Day" / "-Full Day", so +//! the entries never matched: the lookup returned `None` for every one of +//! the ticket's names on the base. The run's own notes said so, then +//! planned "a keyword step after the override": +595/-186 across the +//! pipeline, a moved extractor, keyword matching, new logging, a fixture, +//! other programs moved to another lookup (its own reviewer flagged that), +//! and two questions on the pull request that one page load answered. The +//! new test was never run on the base: the repository's CI runs each test +//! file with a `python "$t"` loop, which CoderHelm couldn't narrow, so the +//! test was recorded as not run and the description said nothing of it. +//! The right change stripped the suffix in the lookup and added two +//! entries, +49/-1, mostly a test of the exact names stored on staging that +//! fails on the base. Across the 53 runs audited, 8 of 10 bug tickets that +//! wrote code ran nothing before their first edit, 6 diffs of 300+ lines +//! answered a ticket naming 1 to 10 records, and none of the 17 runs whose +//! tests were checked had a test shown to fail on the base. +//! +//! Guarantee: a bug plan reproduces before it plans (`## Reproduce`: the +//! ticket's exact inputs and their stored variants, a command this run ran +//! on the base with `reproduce_on_base` and its quoted output, the wrong +//! line), or says `Unverified:` after trying. The fix goes in the mechanism +//! the wrong line is in; a new resolution path beside it goes back. A +//! question a page load or a query answers is looked up before it is +//! decided. A diff that rewrites a path for a few named records goes back +//! to be narrowed (`minimal_change::whole_path`). Each new test runs on the +//! base and the head the way CI runs it, and a bug fix no test was shown to +//! fail for says `Unverified:` in its description. + +use crate::passes::habits_check::{self, FileRun, PrFacts, TestResult, Verdict}; +use crate::passes::minimal_change::{self, Kind}; +use crate::passes::plan::PlanResult; +use crate::passes::reproduce; +use common::repro_first::{self, Attempt}; +use common::test_env; + +const TICKET: &str = "Update sport categorization for summer camps\nObserved\nThe hockey filter only catches the preschool hockey class, not the Total Skills Hockey Camp-Full Day (a0000001-0000-4000-8000-000000000001)\nWhen filtering for Volleyball, Squash Camp-Half Day (a0000002-0000-4000-8000-000000000002) shows\nExpected\nSquash Camp-Half Day (a0000002-0000-4000-8000-000000000002)\nSquash Camp- Full Day (a0000003-0000-4000-8000-000000000003)\nSquash High-Performance Camp (a0000004-0000-4000-8000-000000000004)"; + +/// The call that reproduces it on the base, and what it printed. +const CALL: &str = "cd dags && python -c \"from utils.schedule_common import get_camp_sport_override as g; [print(n, g(n)) for n in ['Squash Camp-Half Day', 'Squash Camp-Full Day', 'Squash Camp- Full Day', 'Total Skills Hockey Camp-Full Day']]\""; +const PRINTED: &str = "Squash Camp-Half Day None\nSquash Camp-Full Day None\nSquash Camp- Full Day None\nTotal Skills Hockey Camp-Full Day None"; + +fn ran() -> Vec { + vec![Attempt { + command: CALL.into(), + exit: Some(0), + output: PRINTED.into(), + error: String::new(), + }] +} + +const REUSE: &str = "## Reuse\n- `CAMP_SPORT_OVERRIDES` and `get_camp_sport_override` in dags/utils/schedule_common.py\n\n## Must not change\nOther programs' sport lookups; logging.\n\n## Measure first\nNone: the change stays inside this repository.\n"; + +/// The plan as the run wrote it. +fn plan_as_run() -> PlanResult { + PlanResult { + proposal: "## Problem\nCamps sit on the wrong sport.\n\n## Approach\nExact keys miss suffixed names, so a keyword step is added after the override, and booking programs move to the active-only sport map.".into(), + design: format!("{REUSE}\n## Smallest change\nAdd `resolve_camp_sport_id` and `build_sport_name_map`: the override first, then a keyword match on the camp name, for every camp the activities path loads.\n\n## Proof\n`tests/test_camp_sport.py` over 116 live camp names.\n\n## Out of scope\n- Inactive Squash camps: decided with the default: they show under the squash filter as today\n"), + tasks: "- [ ] dags/utils/schedule_common.py: [modify] add resolve_camp_sport_id\n- [ ] dags/camp_pipeline.py: [modify] use it for every camp\n- [ ] tests/test_camp_sport.py: [create] the test\n".into(), + ..Default::default() + } +} + +/// The plan the gates ask for. +fn plan_right() -> PlanResult { + PlanResult { + proposal: "## Problem\nCamps sit on the wrong sport.\n".into(), + design: format!("{REUSE}\n## Reproduce\nInputs: a0000001-0000-4000-8000-000000000001, a0000002-0000-4000-8000-000000000002, a0000003-0000-4000-8000-000000000003, a0000004-0000-4000-8000-000000000004; staging lookup L2 (name LIKE '%squash camp%'): `Squash Camp- Full Day`, `Squash Camp-Full Day`, `Squash Camp-Half Day`, `Summer Squash Camp Plus`\nRan on base: `{CALL}`\nOutput:\n```\n{PRINTED}\n```\nWrong line: dags/utils/schedule_common.py:99 `return CAMP_SPORT_OVERRIDES.get(normalized)` matches the whole name, suffix included.\n\n## Smallest change\nStrip a trailing `-Half Day` / `-Full Day` before `CAMP_SPORT_OVERRIDES.get` in `get_camp_sport_override`; add 2 entries.\n\n## Proof\nOne test of the four stored names; it fails on the base.\n\n## Out of scope\n- Inactive Squash camps: decided with the default: they show as today. Looked up: the summer camps page already shows a squash chip\n"), + tasks: "- [ ] tests/test_camp_sport.py: [create] the stored names map to squash\n- [ ] dags/utils/schedule_common.py: [modify] strip the suffix in get_camp_sport_override\n".into(), + ..Default::default() + } +} + +#[test] +fn the_plan_reproduces_on_the_base_and_fixes_the_lookup_it_lands_in() { + let g = reproduce::plan_gaps(&plan_as_run(), true, TICKET, &[], true, true); + let all = g.join("\n"); + assert!(all.contains("lacks `## Reproduce`"), "{all}"); + // The question one page load answers is looked up first. + assert!( + all.contains("Inactive Squash camps") && all.contains("check_url"), + "{all}" + ); + + // The plan the send-back asks for passes, with the run it quotes. + let g = reproduce::plan_gaps(&plan_right(), true, TICKET, &ran(), true, true); + assert!(g.is_empty(), "{g:?}"); + // The same section with nothing run behind it goes back. + let g = reproduce::plan_gaps(&plan_right(), true, TICKET, &[], true, true); + assert!( + g.iter().any(|l| l.contains("not a command this run ran")), + "{g:?}" + ); + + // A reproduction that lands in the overrides lookup, with the keyword + // step planned beside it, goes back. + let mut beside = plan_right(); + beside.design = beside.design.replace( + "Strip a trailing `-Half Day` / `-Full Day` before `CAMP_SPORT_OVERRIDES.get` in `get_camp_sport_override`; add 2 entries.", + "Add `resolve_camp_sport_id`: the override first, then a keyword match on the name.", + ); + let g = reproduce::plan_gaps(&beside, true, TICKET, &ran(), true, true); + assert!( + g.iter() + .any(|l| l.contains("`CAMP_SPORT_OVERRIDES`") && l.contains("doesn't change it")), + "{g:?}" + ); + assert!(g.iter().any(|l| l.contains("keyword match")), "{g:?}"); + + // The plan check calls it, on the draft and on the revision. + let src = include_str!("../plan.rs"); + assert_eq!(src.matches("super::reproduce::plan_gaps(").count(), 2); + assert!(src.contains("super::reproduce::tool()")); + // Its inputs are the ticket's own records. + assert_eq!(repro_first::ticket_ids(TICKET).len(), 4); +} + +fn patch(sign: char, lines: &[String]) -> String { + lines + .iter() + .map(|l| format!("{sign}{l}")) + .collect::>() + .join("\n") +} + +#[test] +fn a_whole_path_rewrite_for_four_camps_goes_back_and_the_lookup_fix_does_not() { + // The run's diff, in shape: the pipeline that loads every camp rewritten. + let added: Vec = (0..300) + .map(|i| format!(" sport_id = resolve_camp_sport_id(row, names_{i}, sport_map)")) + .collect(); + let removed: Vec = (0..90) + .map(|i| format!(" sport_id = group_sport.get(row['group_{i}'])")) + .collect(); + let wide = vec![( + "dags/camp_pipeline.py".to_string(), + "modified".to_string(), + format!("{}\n{}", patch('+', &added), patch('-', &removed)), + )]; + let found = minimal_change::check(&wide, &[], TICKET, false); + let w = found + .iter() + .find(|w| w.kind == Kind::WholePath) + .expect("whole path"); + assert!( + w.what.contains("390 changed code lines") && w.what.contains("4 record(s)"), + "{}", + w.what + ); + assert!(w.instruction().contains("Narrow it")); + + // The right change: the suffix stripped in the lookup, two entries. + let narrow = vec![ + ( + "dags/utils/schedule_common.py".to_string(), + "modified".to_string(), + "- normalized = re.sub(r\"\\s+\", \" \", str(name).strip().lower())\n+ normalized = re.sub(r\"\\s*-\\s*(half|full) day$\", \"\", re.sub(r\"\\s+\", \" \", str(name).strip().lower()))\n+ 'summer squash camp plus': 'b0000001-0000-4000-8000-00000000000a',\n+ 'squash high-performance camp': 'b0000001-0000-4000-8000-00000000000a',".to_string(), + ), + ( + "tests/test_camp_sport.py".to_string(), + "added".to_string(), + patch('+', &(0..45).map(|i| format!(" assert_case({i})")).collect::>()), + ), + ]; + let found = minimal_change::check(&narrow, &[], TICKET, false); + assert!(found.is_empty(), "{found:?}"); + // A reason the narrower change can't work keeps a wide one. + assert!(minimal_change::standing( + &minimal_change::check(&wide, &[], TICKET, false), + "Wider than the ticket: dags/camp_pipeline.py: the vendor gives no name for these camps" + ) + .is_empty()); +} + +const CI: &str = r#" +name: Tests +on: [pull_request] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - run: uv pip install --quiet "apache-airflow[postgres]==2.10.3" -r requirement.txt + - name: Run tests + run: | + failed=0 + for t in tests/test_*.py; do + echo "::group::$t" + python "$t" || failed=1 + echo "::endgroup::" + done + exit $failed +"#; + +#[test] +fn the_new_test_runs_on_the_base_the_way_ci_runs_it() { + let env = test_env::from_workflows(&[(".github/workflows/tests.yml".into(), CI.into())], &[]) + .expect("the test job"); + // CoderHelm's runner list knows no command here; the loop runs the file. + assert_eq!( + habits_check::file_cmd(None, Some(&env), "tests/test_camp_sport.py").as_deref(), + Ok("python tests/test_camp_sport.py") + ); + assert!( + habits_check::file_cmd(None, None, "tests/test_camp_sport.py") + .unwrap_err() + .contains("no unit test command") + ); + // Fails on the base with the reported names, passes on the head. + let base = FileRun { + code: Some(1), + output: "AssertionError: 'Squash Camp-Half Day' maps to None, expected squash".into(), + }; + let head = FileRun { + code: Some(0), + output: String::new(), + }; + assert_eq!(habits_check::verdict(&head, &base).0, Verdict::Proven); + // A test that passes on the base goes back to the coder. + let plan = PlanResult { + tasks: "- [ ] tests/test_camp_sport.py: [create] x\n".into(), + ..Default::default() + }; + let either = PrFacts { + bug: true, + tests: vec![TestResult { + path: "tests/test_camp_sport.py".into(), + verdict: habits_check::verdict(&head, &head).0, + detail: String::new(), + }], + ..Default::default() + }; + assert!(habits_check::blocking(&either, &plan) + .iter() + .any(|l| l.contains("passes with the change taken out"))); + // A bug fix whose test never ran both ways says so in its description. + let not_run = PrFacts { + bug: true, + tests: vec![TestResult { + path: "tests/test_camp_sport.py".into(), + verdict: Verdict::NotRun, + detail: "the sandbox gave no result for it".into(), + }], + ..Default::default() + }; + assert!(habits_check::section(&plan, ¬_run).contains(habits_check::UNVERIFIED_FIX)); + let proven = PrFacts { + bug: true, + tests: vec![TestResult { + path: "tests/test_camp_sport.py".into(), + verdict: Verdict::Proven, + detail: "AssertionError".into(), + }], + ..Default::default() + }; + assert!(!habits_check::section(&plan, &proven).contains("Unverified")); +} diff --git a/services/worker/src/passes/incidents/sn_person_answer_moves_scope.rs b/services/worker/src/passes/incidents/sn_person_answer_moves_scope.rs new file mode 100644 index 000000000..d375ce63e --- /dev/null +++ b/services/worker/src/passes/incidents/sn_person_answer_moves_scope.rs @@ -0,0 +1,113 @@ +//! sn. The duplicated filter-chip ticket again (see `sl`). The plan left +//! the `/classes/` path pages out of scope, decided with a default. +//! A reviewer, sam, answered on the pull request that the path pages should +//! cover both rows. The run replied "Understood" and then reverted the +//! path-page work as out of scope: the scope ledger was seeded from the +//! ticket's criteria and the plan only, and a person's comment counted only +//! when the coder itself wrote a `Scope change:` line quoting it. +//! +//! Guarantee: what people say decides scope as they say it. At seed and on +//! every round's comments, an out-of-scope entry a person's answer or +//! comment asks for moves in, recording who asked +//! (`Ledger::take_people`, `scope_ledger::people`, `load_or_seed`, `held`, +//! `load_with_people`). From then on the path-page work is in scope, and a +//! diff that takes it out is a breach that goes back to be put back. A +//! comment that keeps the item out moves nothing. + +use crate::passes::habits_check::{self, PrFacts}; +use crate::passes::stop_judge::acceptance; +use common::scope_ledger::{self, Ledger}; + +const TICKET: &str = "Observed\nTwo Multi-Sport filters show\nAcceptance Criteria\nOnly one multi-sport filter to show"; +const PROPOSAL: &str = "## Problem\nTwo Multi-Sport chips.\n"; +const DESIGN: &str = "## Out of scope\n- Merging the two schedule API rows: a data change in another repository\n- `/classes/` path pages (`selectedSport`, `findNormalizedSport`): decided with the default: one id, as today\n"; +const TASKS: &str = "- [ ] apps/web/src/utils/filterMaps.ts: [modify] Add slugToIds\n"; + +/// sam's answer on the pull request, as written. +const ANSWER: &str = "The `/classes/` path pages should cover both rows too, so classes from either Multi-Sport row show there."; + +fn ledger() -> Ledger { + Ledger::from_ticket_and_plan(&acceptance(TICKET), PROPOSAL, DESIGN, TASKS) +} + +fn said(text: &str) -> Vec<(String, String)> { + vec![("sam".to_string(), text.to_string())] +} + +/// The round that built the path pages after sam's answer. +fn path_pages_built() -> Vec<(String, String, String)> { + vec![( + "apps/web/src/services/classService.ts".into(), + "modified".into(), + "+ // A /classes/ path page filters by every row sharing the slug\n+ const ids = selectedSport ? slugToIds(all, selectedSport.slug) : [];".into(), + )] +} + +/// The later revert that took them out "as out of scope". +fn path_pages_reverted() -> Vec<(String, String, String)> { + vec![( + "apps/web/src/services/classService.ts".into(), + "modified".into(), + "- // A /classes/ path page filters by every row sharing the slug\n- const ids = selectedSport ? slugToIds(all, selectedSport.slug) : [];\n+ const ids = [];".into(), + )] +} + +#[test] +fn the_answer_moves_the_path_pages_in_and_a_revert_is_a_breach() { + // Before the answer the path pages are out, and building them breaches. + let l = ledger(); + assert_eq!(scope_ledger::breaches(&l, &path_pages_built()).len(), 1); + + // sam's answer moves them in on its own: no `Scope change:` line. + let mut l = ledger(); + let moved = l.take_people(&said(ANSWER)); + assert_eq!(moved.len(), 1, "{moved:?}"); + let e = l + .entries + .iter() + .find(|e| e.item.contains("/classes/")) + .unwrap(); + assert!(!e.is_out() && e.moved_in.starts_with("sam asked for it")); + // The other entry stays out. + assert_eq!(l.outs().count(), 1); + // Building them is no breach now. + assert!(scope_ledger::breaches(&l, &path_pages_built()).is_empty()); + + // Taking them out again is the breach, and it goes back. + let b = scope_ledger::breaches(&l, &path_pages_reverted()); + assert_eq!(b.len(), 1, "{b:?}"); + assert!(b[0].reverted); + let plan = crate::passes::plan::PlanResult { + tasks: TASKS.into(), + ..Default::default() + }; + let f = PrFacts { + out_of_scope: b, + ..Default::default() + }; + let lines = habits_check::blocking(&f, &plan); + assert!( + lines + .iter() + .any(|x| x.contains("takes out") && x.contains("sam asked for it")), + "{lines:?}" + ); + let open = habits_check::open_findings(&f, &plan); + assert!(open.iter().any(|o| o.point == "A person's ask taken out")); +} + +#[test] +fn the_answer_counts_at_seed_and_a_comment_keeping_it_out_moves_nothing() { + // An answer the run already had when the plan was made: in scope from + // the start, never written as out of scope. + let mut l = ledger(); + l.take_people(&said(ANSWER)); + assert!(l.outs().all(|e| !e.item.contains("/classes/"))); + // A comment that keeps the path pages out leaves them out. + let mut l = ledger(); + let moved = l.take_people(&said( + "Leave the `/classes/` path pages for a separate ticket.", + )); + assert!(moved.is_empty()); + assert_eq!(l.outs().count(), 2); +} diff --git a/services/worker/src/passes/minimal_change.rs b/services/worker/src/passes/minimal_change.rs index 76789b846..c6d66f43a 100644 --- a/services/worker/src/passes/minimal_change.rs +++ b/services/worker/src/passes/minimal_change.rs @@ -56,6 +56,7 @@ pub enum Kind { TestSize, InventedPayload, MadeUpIds, + WholePath, } /// One way the change is wider than its ticket. @@ -78,6 +79,7 @@ impl Widening { Kind::TestSize => "A test out of proportion to the change", Kind::InventedPayload => "A test payload nobody observed", Kind::MadeUpIds => "Made-up ids where the run looked up real ones", + Kind::WholePath => "A whole code path rewritten for a few named records", } } @@ -128,6 +130,10 @@ impl Widening { "`{}` uses made-up ids ({}) while this run looked up the real records' ids. Use the ids the lookups returned, so the test is about the records the bug is about.", self.path, self.what ), + Kind::WholePath => format!( + "The change rewrites how every record of its kind is processed ({}), while the ticket names only a few. Narrow it to those records and things exactly like them: fix the lookup, table or mapping they go through (its matching or its entries) and leave the shared path as it is.", + self.what + ), }; format!("{what}{why}") } @@ -948,6 +954,87 @@ pub fn invented_payloads(diff: &Diff, has_probe: bool) -> Vec { out } +// ── A whole path rewritten for a few records ─────────────────────────────── + +/// Changed code lines (added and removed, not entries of a map or list, not +/// comments) past which a change for a few named records rewrites a path. +pub const WHOLE_PATH_LINES: usize = 40; +/// Up to this many records named, a ticket is about those records. +pub const FEW_RECORDS: usize = 12; + +/// Ticket words that ask for every record of a kind. +const EVERY_ASKS: &[&str] = &[ + "all records", + "all camps", + "every record", + "every camp", + "for all ", + "for every ", + "across all", + "refactor", + "rewrite", +]; + +/// A changed line that is an entry of a map or list, a bracket, or a +/// comment: what a lookup fix adds without changing how records flow. +fn entry_line(line: &str) -> bool { + let t = line.trim(); + if t.is_empty() + || t.starts_with('#') + || t.starts_with("//") + || t.starts_with("--") + || t.chars() + .all(|c| matches!(c, '{' | '}' | '[' | ']' | '(' | ')' | ',' | ';')) + { + return true; + } + let quoted = t.starts_with('\'') || t.starts_with('"'); + quoted && (t.contains("':") || t.contains("\":") || t.ends_with("',") || t.ends_with("\",")) +} + +/// A change that rewrites a code path while its ticket names a few records +/// (`common::repro_first::ticket_ids`): more than [`WHOLE_PATH_LINES`] +/// changed code lines that are no entries of a map or list. A ticket that +/// named four camps filed under the wrong sport got 900 changed lines +/// across the pipeline that loads every camp; the fix was a suffix +/// stripped in the existing lookup and two entries. A `Wider than the +/// ticket:` line keeps it, with the reason the narrower change can't work. +pub fn whole_path(diff: &Diff, ticket: &str) -> Vec { + let named = common::repro_first::ticket_ids(ticket).len(); + if named == 0 || named > FEW_RECORDS || ticket_asks(ticket, EVERY_ASKS) { + return Vec::new(); + } + let mut lines = 0; + let mut files: Vec<(&str, usize)> = Vec::new(); + for (path, status, patch) in diff { + if status == "removed" || !code_file(path) || is_test(path) { + continue; + } + let n = lines_of(patch, '+') + .into_iter() + .chain(lines_of(patch, '-')) + .filter(|l| !entry_line(l)) + .count(); + if n > 0 { + lines += n; + files.push((path, n)); + } + } + if lines <= WHOLE_PATH_LINES { + return Vec::new(); + } + files.sort_by_key(|f| std::cmp::Reverse(f.1)); + vec![Widening { + kind: Kind::WholePath, + path: files[0].0.to_string(), + what: format!( + "{lines} changed code lines across {} file(s), most in `{}`, for a ticket that names {named} record(s)", + files.len(), + files[0].0 + ), + }] +} + // ── The check ────────────────────────────────────────────────────────────── /// Everything a diff adds past its ticket. `base` holds the base text of @@ -972,6 +1059,7 @@ pub fn check( out.extend(test_size(diff)); out.extend(repeated_cases(diff)); out.extend(invented_payloads(diff, has_probe)); + out.extend(whole_path(diff, ticket)); out } diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 6d43d8302..75a30911c 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1369,6 +1369,8 @@ mod replay; #[cfg(test)] mod reply_eval; pub(crate) mod repo_pick; +/// The planner reproduces a bug on the base before it plans code. +mod reproduce; mod resolve; mod resolved; pub mod restack; @@ -3164,7 +3166,15 @@ async fn run_passes( add_progress_note(state, &msg.team_id, run_id, "Plan generated").await; // Scope is decided once, here, from the ticket's criteria and the // plan, before any code; every later round is held to it. - scope_ledger::load_or_seed(state, &msg.team_id, run_id, msg, &plan_result).await; + scope_ledger::load_or_seed( + state, + &msg.team_id, + run_id, + msg, + &plan_result, + &scope_ledger::people(msg, &[]), + ) + .await; } if !plan_final { if !plan_was_reused { diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 33605f4ec..1e05bc222 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -743,6 +743,27 @@ Then the ```fix_location.json block described above."#, ); tools.push(super::web_check::tool()); full_system.push_str(&web.prompt_section()); + // A bug is reproduced on the base before code is planned: the planner + // runs the ticket's inputs through the current code (`reproduce`). + let is_bug = intent == super::triage::TicketIntent::Bug; + let reproducer = super::reproduce::Reproducer::new( + super::test_bug::Runner { + state, + github, + owner: &msg.repo_owner, + repo: &msg.repo_name, + team_id: &msg.team_id, + run_id, + provider, + }, + &msg.base_branch, + ); + if is_bug { + if reproducer.can_run() { + tools.push(super::reproduce::tool()); + } + full_system.push_str(&super::reproduce::prompt_section(reproducer.can_run())); + } let ops = super::ops_tools::OpsTools::load( state, &msg.team_id, @@ -834,6 +855,7 @@ Then the ```fix_location.json block described above."#, knowledge: knowledge.as_ref(), web: Some(&web), abilities: Some(&abilities), + repro: is_bug.then_some(&reproducer), state, }; @@ -978,6 +1000,16 @@ Then the ```fix_location.json block described above."#, &ticket_words, &write_facts, )); + // Reproduced on the base, fixed in the mechanism the reproduction lands + // in, questions looked up first (`reproduce`, `common::repro_first`). + shape_gaps.extend(super::reproduce::plan_gaps( + &draft, + is_bug, + &ticket_words, + &reproducer.attempts(), + reproducer.can_run(), + can_look_up, + )); 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())); @@ -1475,6 +1507,14 @@ Then the ```fix_location.json block described above."#, ) .await; left.extend(super::plan_shape::write_gaps(&files, &ticket_words, &facts)); + left.extend(super::reproduce::plan_gaps( + &files, + is_bug, + &ticket_words, + &reproducer.attempts(), + reproducer.can_run(), + can_look_up, + )); 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( @@ -2492,6 +2532,8 @@ struct CombinedToolExecutor<'a> { skills: Option<&'a super::skills::TeamSkills>, /// Knowledge bases attached to the planner. knowledge: Option<&'a super::knowledge::KnowledgeTools>, + /// `reproduce_on_base`, for a bug. + repro: Option<&'a super::reproduce::Reproducer<'a>>, state: &'a WorkerState, } @@ -2502,6 +2544,11 @@ impl<'a> ToolExecutor for CombinedToolExecutor<'a> { name: &str, input: &serde_json::Value, ) -> Result> { + if let Some(r) = self.repro { + if let Some(out) = r.handle(name, input).await { + return Ok(serde_json::json!(out)); + } + } if let Some(k) = self.knowledge { if let Some(out) = k.handle(self.state, name, input).await { return Ok(serde_json::json!(out)); diff --git a/services/worker/src/passes/plan_shape.rs b/services/worker/src/passes/plan_shape.rs index e90016df8..0e28ffd57 100644 --- a/services/worker/src/passes/plan_shape.rs +++ b/services/worker/src/passes/plan_shape.rs @@ -216,7 +216,7 @@ const TEST_TO_VENDOR: &[&str] = &[ /// The plan's words that propose things, without its Must not change /// section (where "no deletes" is said). -fn proposing_text(files: &PlanResult) -> String { +pub(crate) 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(), diff --git a/services/worker/src/passes/reproduce.rs b/services/worker/src/passes/reproduce.rs new file mode 100644 index 000000000..1baf69252 --- /dev/null +++ b/services/worker/src/passes/reproduce.rs @@ -0,0 +1,257 @@ +//! The planner reproduces a bug on the base before it plans code +//! (`common::repro_first` has the rules and why). +//! +//! - [`Reproducer`]: the planner's `reproduce_on_base` tool. It runs one +//! call or command in the sandbox on the base branch's head, in the run's +//! test environment, and returns its exit code and output. Each run is +//! kept ([`Reproducer::attempts`]), so the plan check can hold the plan's +//! `## Reproduce` to a command that ran and to what it printed. +//! - [`plan_gaps`]: the plan check's lines: the reproduction, the fix in +//! the mechanism it landed in, and questions looked up before they are +//! decided with a default. A gap goes back with the plan's one send-back; +//! what is still open stays on the decision. + +use std::sync::Mutex; + +use common::repro_first::{self, Attempt}; +use serde_json::{json, Value}; + +use super::plan::PlanResult; +use crate::agent::llm::ToolDefinition; + +/// Runs of the tool a plan may make. +pub const MAX_RUNS: usize = 6; +const OUT_MARK: &str = "===CODERHELM_REPRO_OUT==="; +const EXIT_MARK: &str = "===CODERHELM_REPRO_EXIT"; +/// The output kept of one run. +const KEEP: usize = 3000; + +/// The tool's definition. +pub fn tool() -> ToolDefinition { + ToolDefinition { + name: repro_first::TOOL.to_string(), + description: format!( + "Run one call or command on the BASE branch, before any change, in a sandbox with the \ + repository's test environment installed, and get its exit code and output. Use it to \ + reproduce a bug: put the ticket's exact names or ids (and each variant the data holds) \ + through the code path the bug is in, for example `python -c \"from dags.utils.common \ + import get_override; print(get_override('Camp-Half Day'))\"`, or run the nearest \ + existing test. Quote the command and its output in `## Reproduce`. Read-only: \ + nothing it writes is kept. At most {MAX_RUNS} runs." + ), + input_schema: json!({ + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The shell command, run from the repository root" + }, + "inputs": { + "type": "string", + "description": "The exact names or ids it feeds the code, and where each came from (the ticket, a lookup)" + } + }, + "required": ["command"] + }), + } +} + +/// The planner's lines about the tool. +pub fn prompt_section(can_run: bool) -> String { + if can_run { + format!( + "\n\n## Reproduce a bug before planning (`{}`)\nFor a bug, before you plan code: take the exact names or ids from the ticket, find every variant the real data holds with a read-only lookup (a `LIKE` on the name), and run them through the current code on the base with `{}`. Write `## Reproduce` in design.md with `Inputs:`, `Ran on base:` (the command, as you ran it), `Output:` (what it printed, quoted) and `Wrong line:` (`path:line` and the code on it, backticked). The fix goes in that line's mechanism.\n", + repro_first::TOOL, + repro_first::TOOL + ) + } else { + "\n\n## Reproduce a bug before planning\nFor a bug, write `## Reproduce` in design.md: `Inputs:` (the ticket's exact names or ids, with every variant a read-only lookup finds), `Unverified:` (no sandbox here to run the code on the base) and `Wrong line:` (`path:line` and the code on it, backticked). The fix goes in that line's mechanism.\n".to_string() + } +} + +/// A command's output from the script's: the exit code and what it printed. +pub fn read_output(output: &str) -> (Option, String) { + let exit = output.lines().rev().find_map(|l| { + l.trim() + .strip_prefix(EXIT_MARK) + .and_then(|r| r.trim().parse::().ok()) + }); + let body = output + .split_once(OUT_MARK) + .map(|(_, b)| b) + .unwrap_or(output); + let body = body.split(EXIT_MARK).next().unwrap_or(body).trim(); + let start = body.len().saturating_sub(KEEP); + let start = (start..=body.len()) + .find(|i| body.is_char_boundary(*i)) + .unwrap_or(body.len()); + (exit, body[start..].to_string()) +} + +/// The sandbox script for one command: its output and exit code, always +/// printed (a call that prints `None` and exits 0 is the reproduction). +pub fn script(command: &str) -> String { + format!( + "( {command} ) > /tmp/ch-repro.log 2>&1; ch_r=$?\necho \"{OUT_MARK}\"\ntail -c {KEEP} /tmp/ch-repro.log\necho\necho \"{EXIT_MARK} $ch_r\"\ntrue" + ) +} + +/// The planner's tool, on one run. +pub struct Reproducer<'a> { + pub runner: super::test_bug::Runner<'a>, + pub base_branch: &'a str, + attempts: Mutex>, +} + +impl<'a> Reproducer<'a> { + pub fn new(runner: super::test_bug::Runner<'a>, base_branch: &'a str) -> Self { + Self { + runner, + base_branch, + attempts: Mutex::new(Vec::new()), + } + } + + /// Whether a sandbox is set up to run on the base. + pub fn can_run(&self) -> bool { + let c = &self.runner.state.config; + !c.sandbox_bucket_name.is_empty() && !c.sandbox_project_name.is_empty() + } + + /// Every run so far. + pub fn attempts(&self) -> Vec { + self.attempts.lock().map(|a| a.clone()).unwrap_or_default() + } + + /// The tool's answer, or `None` for another tool. + pub async fn handle(&self, name: &str, input: &Value) -> Option { + if name != repro_first::TOOL { + return None; + } + let command = input["command"].as_str().unwrap_or("").trim().to_string(); + if command.is_empty() { + return Some("No command given.".into()); + } + if self.attempts().len() >= MAX_RUNS { + return Some(format!( + "Not run: this plan has used its {MAX_RUNS} runs. Write `## Reproduce` from the runs you made." + )); + } + let r = &self.runner; + let attempt = match r.github.get_ref(r.owner, r.repo, self.base_branch).await { + Err(e) => Attempt { + command: command.clone(), + error: format!("the base branch couldn't be read ({e})"), + ..Default::default() + }, + Ok(sha) => match r.run_script_at(&sha, &[&command], &script(&command)).await { + Ok(out) => { + let (exit, output) = read_output(&out); + Attempt { + command: command.clone(), + exit, + output, + error: String::new(), + } + } + Err(e) => Attempt { + command: command.clone(), + error: e, + ..Default::default() + }, + }, + }; + let answer = if attempt.error.is_empty() { + format!( + "Ran on the base ({}): exit {}\nOutput:\n{}", + self.base_branch, + attempt + .exit + .map_or("unknown".to_string(), |c| c.to_string()), + attempt.output + ) + } else { + format!("Didn't run: {}", attempt.error) + }; + if let Ok(mut a) = self.attempts.lock() { + a.push(attempt); + } + Some(answer) + } +} + +/// The plan's out-of-scope entries decided with a default and its question +/// lines: what a lookup may have to settle first. +fn questions(files: &PlanResult) -> Vec { + let mut out: Vec = + common::scope_ledger::Ledger::from_plan(&files.proposal, &files.design, "") + .entries + .into_iter() + .filter(|e| e.why.to_lowercase().contains("default")) + .map(|e| format!("{}: {}", e.item, e.why)) + .collect(); + for l in format!("{}\n{}", files.proposal, files.design).lines() { + let t = l.trim().trim_start_matches(['-', '*']).trim(); + if t.ends_with('?') && !out.iter().any(|o| o.contains(t)) { + out.push(t.to_string()); + } + } + out +} + +/// What the plan check sends back about reproducing, the mechanism and +/// questions. `is_bug` from triage; `ticket` the ticket's words; `attempts` +/// the tool's runs. +pub fn plan_gaps( + files: &PlanResult, + is_bug: bool, + ticket: &str, + attempts: &[Attempt], + can_run: bool, + can_look_up: bool, +) -> Vec { + let t = files.tasks.trim_start(); + if t.is_empty() || super::plan_sections::directive(t) { + return Vec::new(); + } + let mut out = Vec::new(); + if is_bug { + out.extend(repro_first::reproduce_gaps( + &files.design, + ticket, + attempts, + can_run, + can_look_up, + )); + let smallest = + super::feature::reuse::section(&files.design, super::plan_shape::SMALLEST_CHANGE) + .unwrap_or(""); + out.extend(repro_first::reuse_gaps( + &files.design, + smallest, + &super::plan_shape::proposing_text(files), + )); + } + out.extend(repro_first::question_gaps(&questions(files))); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_output_is_read_whatever_the_exit() { + let out = "===CODERHELM_ENV_RESTORED===\ninstall noise\n===CODERHELM_REPRO_OUT===\nNone\n\n===CODERHELM_REPRO_EXIT 0\n"; + assert_eq!(read_output(out), (Some(0), "None".to_string())); + let (exit, body) = read_output( + "===CODERHELM_REPRO_OUT===\nTraceback\nImportError\n===CODERHELM_REPRO_EXIT 1", + ); + assert_eq!(exit, Some(1)); + assert!(body.ends_with("ImportError")); + assert_eq!(read_output("nothing").0, None); + let s = script("python -c 'print(1)'"); + assert!(s.starts_with("( python -c 'print(1)' )") && s.contains(EXIT_MARK)); + assert_eq!(tool().name, "reproduce_on_base"); + } +} diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 2963308f1..0505d458f 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -5192,7 +5192,18 @@ async fn start_planned_work( let items = super::finish_planned::listed(&body); // What the plan decided is out of scope is not built again // (`common::scope_ledger`). - let items = match super::scope_ledger::load(state, &msg.team_id, &msg.run_id).await { + let items = match super::scope_ledger::load_with_people( + state, + &ctx.github, + &ctx.ticket_msg, + &msg.team_id, + &msg.run_id, + pr.owner, + pr.repo, + pr.number, + ) + .await + { Some(l) => { let (keep, gone) = super::scope_ledger::drop_covered(&l, items); if !gone.is_empty() { @@ -5334,7 +5345,18 @@ async fn recheck_planned_work( ) .await; // Nor what the plan decided is out of scope (`common::scope_ledger`). - let found = match super::scope_ledger::load(state, &msg.team_id, &msg.run_id).await { + let found = match super::scope_ledger::load_with_people( + state, + &ctx.github, + &ctx.ticket_msg, + &msg.team_id, + &msg.run_id, + pr.owner, + pr.repo, + pr.number, + ) + .await + { Some(l) => { let (keep, gone): (Vec<_>, Vec<_>) = found .into_iter() diff --git a/services/worker/src/passes/scope_ledger.rs b/services/worker/src/passes/scope_ledger.rs index 597ad62dc..02c9fe86e 100644 --- a/services/worker/src/passes/scope_ledger.rs +++ b/services/worker/src/passes/scope_ledger.rs @@ -71,17 +71,30 @@ pub(crate) async fn load_or_seed( run_id: &str, msg: &TicketMessage, plan: &PlanResult, + people: &[(String, String)], ) -> Ledger { if let Some(l) = load(state, team_id, run_id).await { return l; } - let l = Ledger::from_ticket_and_plan( + let mut l = Ledger::from_ticket_and_plan( &super::stop_judge::acceptance(&msg.body), &plan.proposal, &plan.design, &plan.tasks, ); + // What people already answered or commented is in scope from the + // start: the plan never writes a person's ask as out of scope. + let moved = l.take_people(people); save(state, team_id, run_id, &l).await; + if !moved.is_empty() { + super::add_progress_note( + state, + team_id, + run_id, + &format!("In scope because a person asked: {}", moved.join(" ")), + ) + .await; + } if !l.is_empty() { super::add_progress_note( state, @@ -97,25 +110,77 @@ pub(crate) async fn load_or_seed( l } +/// The ledger on the run with the people's answers and the comments on +/// pull request `number` taken in (`Ledger::take_people`), saved when one +/// moved an item in. A planned-work round reads scope through this, so a +/// person's answer since the last check is never built around. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn load_with_people( + state: &WorkerState, + github: &crate::clients::github::GitHubClient, + msg: &TicketMessage, + team_id: &str, + run_id: &str, + owner: &str, + repo: &str, + number: u64, +) -> Option { + let mut l = load(state, team_id, run_id).await?; + let comments = match github.list_issue_comments(owner, repo, number).await { + Ok(c) => super::review_pr::human_comments(&c, 30), + Err(_) => Vec::new(), + }; + let moved = l.take_people(&people(msg, &comments)); + if !moved.is_empty() { + save(state, team_id, run_id, &l).await; + super::add_progress_note( + state, + team_id, + run_id, + &format!("Scope changed: {}", moved.join(" ")), + ) + .await; + } + Some(l) +} + /// What a scope change may cite: the ticket's acceptance criteria, the /// answers people gave, and the people's `comments` (bodies). -pub(crate) fn sources(msg: &TicketMessage, comments: &[String]) -> Vec { +pub(crate) fn sources(msg: &TicketMessage, comments: &[(String, String)]) -> Vec { let mut out = super::stop_judge::acceptance(&msg.body); out.extend( msg.answers .iter() .map(|a| format!("{} {}", a.question, a.answer)), ); + out.extend(comments.iter().map(|(_, b)| b.clone())); + out +} + +/// What people said that decides scope, as (who, words): the answers +/// they gave the run's questions (an answer that says no is left out, its +/// question's words are not an ask) and their `comments`. +pub(crate) fn people(msg: &TicketMessage, comments: &[(String, String)]) -> Vec<(String, String)> { + let mut out: Vec<(String, String)> = msg + .answers + .iter() + .filter(|a| { + let l = a.answer.trim().to_lowercase(); + !(l == "no" || l.starts_with("no,") || l.starts_with("no.") || l.starts_with("no ")) + }) + .map(|a| (a.author.clone(), format!("{} {}", a.question, a.answer))) + .collect(); out.extend(comments.iter().cloned()); out } -/// The people's comments on the run's pull request, when it has one. +/// The people's comments on the run's pull request, when it has one, as +/// (author, body). pub(crate) async fn comments( github: &crate::clients::github::GitHubClient, msg: &TicketMessage, branch: &str, -) -> Vec { +) -> Vec<(String, String)> { let Ok(Some(pr)) = github .find_open_pr_for_branch(&msg.repo_owner, &msg.repo_name, branch) .await @@ -129,10 +194,7 @@ pub(crate) async fn comments( .list_issue_comments(&msg.repo_owner, &msg.repo_name, number) .await { - Ok(c) => super::review_pr::human_comments(&c, 30) - .into_iter() - .map(|(_, body)| body) - .collect(), + Ok(c) => super::review_pr::human_comments(&c, 30), Err(_) => Vec::new(), } } @@ -149,9 +211,14 @@ pub(crate) async fn held( ledger: &mut Ledger, notes: &str, sources: &[String], + people: &[(String, String)], diff: &[(String, String, String)], ) -> Vec { - let (accepted, refused) = ledger.apply_changes(notes, sources); + // A person's answer or comment moves its item in on its own, every + // round; the coder's `Scope change:` lines come after. + let mut accepted = ledger.take_people(people); + let (by_coder, refused) = ledger.apply_changes(notes, sources); + accepted.extend(by_coder); if !accepted.is_empty() { save(state, team_id, run_id, ledger).await; info!(run_id, moved = ?accepted, "Scope changed with a cited reason; the ledger records it"); diff --git a/services/worker/src/passes/test_bug.rs b/services/worker/src/passes/test_bug.rs index 615de9c02..05bae27f1 100644 --- a/services/worker/src/passes/test_bug.rs +++ b/services/worker/src/passes/test_bug.rs @@ -46,6 +46,26 @@ impl Runner<'_> { steps: &[Step], repeat: Option<&str>, ) -> Result<(Vec>, String), String> { + let cmds: Vec<&str> = steps + .iter() + .map(|s| s.cmd.as_str()) + .chain(repeat.iter().copied()) + .collect(); + let script = test_package::sandbox_script(steps, repeat); + let output = self.run_script_at(sha, &cmds, &script).await?; + let n = steps.len() + usize::from(repeat.is_some()); + Ok((test_package::step_codes(&output, n), output)) + } + + /// Runs `script` on commit `sha` in the sandbox, in the run's test + /// environment, once each of `cmds` (the commands it runs) passes the + /// team's agent permissions: the output. `Err` says why nothing ran. + pub async fn run_script_at( + &self, + sha: &str, + cmds: &[&str], + script: &str, + ) -> Result { if !self.sandbox_on() { return Err("no sandbox is set up here".into()); } @@ -57,11 +77,7 @@ impl Runner<'_> { self.provider.scope.ctx(common::agent_policy::Agent::Coder), None, ); - let cmds = steps - .iter() - .map(|s| s.cmd.as_str()) - .chain(repeat.iter().copied()); - for cmd in cmds { + for cmd in cmds.iter().copied() { match gate.check_command(cmd, "Check a failing test").await { common::agent_policy::Outcome::Run { .. } => {} common::agent_policy::Outcome::Refused { message, .. } @@ -105,15 +121,11 @@ impl Runner<'_> { .await .map_err(|e| format!("the commit couldn't be prepared ({e})"))?; let node = super::detect_node_version(self.github, self.owner, self.repo, sha).await; - let script = test_package::sandbox_script(steps, repeat); match sandbox - .run_checks(&source, &script, node.as_deref(), None, None) + .run_checks(&source, script, node.as_deref(), None, None) .await { - Ok(o) if o.ran => { - let n = steps.len() + usize::from(repeat.is_some()); - Ok((test_package::step_codes(&o.output, n), o.output)) - } + Ok(o) if o.ran => Ok(o.output), Ok(o) => Err(format!("the sandbox gave no result ({})", o.reason)), Err(e) => Err(format!("the sandbox couldn't run ({e})")), }