diff --git a/docs/incidents.md b/docs/incidents.md index fd64dcd99..bb5333eea 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -62,6 +62,7 @@ pipeline still calls it there. | ae. `ae_budget_rounds` | Two loops of fix rounds still stopped on their own budget after the supervisor took every other ending. At eight automatic pushes the CI-only rounds on a finished run's pull request marked it ready, completed the run with its checks red and said a comment naming a change would start the next round, even while each round turned another red check green; at two rounds the self-review on CoderHelm's own pull request said the same and left its findings holding the draft, even while each round closed one. | Both loops follow `supervisor::next_round`: rounds go on while they make progress (checks that were red turn green, findings close), past the cap up to twice it and below the spend ceiling; a round without progress changes approach (one item, a fresh context with small edits, a re-split, the strongest model). When the rounds end, the findings left move to "Deferred" with the reason and stop holding the draft, and the run finishes; red checks are reverted to the last green head and deferred, or, when nothing can come out, the run fails with what fails and why. No message asks for a comment to go on: the phrases are on the `ownership` hand-off list. | | af. `af_lockfiles_out_of_sync` | A security update's pull request changed three `package.json` files (a pnpm workspace root and two npm packages with their own lockfiles) and none of the lockfiles, so every CI job failed at its frozen install. A retry planned its bumps by rule, then handed the red pull request to a model instead of building the plan. The model changed nothing; landing "nothing" removed the round's work branch, so the next attempt wrote to a branch that was gone (every write a 404, a hand edit of a lockfile among them). The round was called unfinished and the run ended failed after one attempt of three, with the same vague sentence twice. | A lockfile out of sync with its manifest is repaired by code before any model round, for any ticket and every package manager CoderHelm writes lockfiles for: each manager writes its own lockfile in the sandbox (with another mode and the LTS Node as fallbacks), one commit, and one that can't be written never hides the others. Any run that changes a manifest gets its lockfile written before the pull request opens. A retry of a dependency fix rebuilds its change from its plan on the same branch. A model's write to a lockfile is refused and pointed to the regenerate tool. Every attempt of a CI fix round opens its work branch first; a fault inside the round (no work branch, a compare or push GitHub refuses, a sandbox failure, anything else) is classified and has a way around it, and the catch-all runs the round again from a clean state, then once in a fresh step, before the supervisor's ending is asked. An attempt that changed nothing is followed by the repairs by code, then fresh evidence, then the strongest model. A run about to complete with red checks goes back to its CI fix round first, and an ending for red checks names the recorded cause, once. | | ag. `ag_red_ci_ships_what_passes` | Three ways were left for a run to end badly over red checks or a refused landing. A dependency fix whose CI stayed red was taken apart by planned task (one task per lockfile, so a lockfile went back without its manifest), and after three reverts the run ended failed with bumps left in that passed on their own. A run stopped after its work opened its pull request with manifests changed and lockfiles unwritten, and waited for CI to fail first. A review fix or feedback round whose finished work GitHub refused to land was recorded as unfinished at once. | Red checks after every fix take out only what breaks them. A dependency fix takes out its newest commit of verified bumps, defers those bumps with what CI printed, holds their findings out of later bundles and keeps the commits before it, again while CI stays red, never emptying the pull request. Any other run is taken apart task by task (up to eight reverts) down to the part that passes; what ships is green with the rest under "Deferred". A stopped run's lockfiles are written by their package managers before its pull request opens, and one that can't be written is named without stopping it. Every kind of fix round takes one classified decision about a fault (`round::plan_for_fault`): while it may continue it runs again in a fresh step, keeping its work when only the landing failed and starting from the pull request's head otherwise. | +| ah. `ah_coder_habits` | A bug fix was right on its face and wrong four ways. Its plan named two files and nothing about them. The fix was written first and its test after, and the test passed with or without the fix. It rounded per line, an approach one pull request had shipped and another had reverted two months earlier, with the reason one commit list away. It changed a response field another of the team's repositories read and never named that repository. Its one real doubt (half up or half even) was listed at the bottom of the finished pull request, and a helper file no task named was reformatted along the way. | Before code, a bug's plan names the test that fails on the code as it is (or why none can and the next best proof), and that test is the first task. The worker itself reads the commits of the files the plan modifies and what depends on them (the code graph, a search of the team's other repositories for each changed name); a revert must be answered by name, and every dependent is updated by a task or called safe with the reason. A doubt that changes what is built is asked at planning time with the default the run builds. After the build each new or changed test runs with and without the change: one that passes either way, a bug's test that can't build on the base, a changed file outside the plan with no reason and a planned dependent left untouched all go back to the coder. The pull request carries the failing and the passing result, the history, and who the change affects. | ## Adding a case diff --git a/services/worker/src/passes/fix_location.rs b/services/worker/src/passes/fix_location.rs index ad0abdf64..becc9359e 100644 --- a/services/worker/src/passes/fix_location.rs +++ b/services/worker/src/passes/fix_location.rs @@ -377,6 +377,12 @@ pub struct FixDecision { /// planner again for the block, or fell back from the plan itself). #[serde(default, skip_serializing_if = "String::is_empty")] pub planner_failure: String, + /// What a careful engineer settles before writing code: how a bug is + /// reproduced first, what the touched files' history shows, who the + /// change affects, and what is asked early with a default (see + /// `habits`). + #[serde(default)] + pub habits: super::habits::Habits, } /// One step of the whole job, and who does it. @@ -963,7 +969,10 @@ pub fn planner_guidance(intent: TicketIntent) -> String { TicketIntent::Feature | TicketIntent::Chore => NEW_WORK_GUIDANCE.to_string(), TicketIntent::Question => format!("{QUESTION_GUIDANCE}\n\n{MISSING_DATA_GUIDANCE}"), }; - format!("{framing}\n\n{EVERY_PLAN_GUIDANCE}\n\n{CHECKLIST_GUIDANCE}") + format!( + "{framing}\n\n{EVERY_PLAN_GUIDANCE}\n\n{CHECKLIST_GUIDANCE}\n\n{}", + super::habits::planner_guidance(intent.is_bug()) + ) } /// For a ticket about data that is missing or wrong (a record that should diff --git a/services/worker/src/passes/habits.rs b/services/worker/src/passes/habits.rs new file mode 100644 index 000000000..7f501b00f --- /dev/null +++ b/services/worker/src/passes/habits.rs @@ -0,0 +1,1396 @@ +//! What a careful engineer settles before writing code, as part of the plan. +//! +//! A plan once named the files to change and nothing about them: whether an +//! earlier attempt at the same change had been reverted, which other code +//! (in this repository or another of the team's) used what it changed, how +//! a bug would be shown to exist before its fix, and which of its doubts +//! changed what gets built. Each is a field of the plan's decision here +//! ([`Habits`], the `habits` object of the `fix_location.json` block), and +//! each is held to what code can check: +//! +//! - **Reproduce first** ([`Repro`]): a bug's plan names the test that fails +//! on the code as it is, and that test's task is moved to the top of the +//! checklist ([`put_repro_first`]) so it is written before the fix. When +//! no failing test is feasible the plan says why and names the next best +//! proof. +//! - **Read the history** ([`AreaHistory`]): the worker itself reads the +//! commits of the files the plan modifies ([`read_history`]) and hands the +//! planner what it found. A revert on one of them must be answered by +//! name. +//! - **Know who it affects** ([`Affected`]): the worker asks the code graph +//! what the planned files reach and searches the team's other +//! repositories for each name the plan says it changes +//! ([`find_dependents`]). Every other repository with a hit, and the +//! callers in this one, are accounted for: updated by a task, or safe with +//! the reason. +//! - **Ask early** ([`EarlyQuestion`]): a doubt that changes what gets built +//! is asked at planning time with a proposed default, and the default is +//! what the run builds meanwhile ([`fold_questions`]). +//! +//! What a draft lacks goes back to the planner in the plan's one send-back +//! ([`plan_gaps`]); what is still open after it stays on the decision's open +//! gaps. The coder reads the result in design.md ([`design_section`]), and +//! the check after the build (`habits_check`) holds the change to it. + +use serde::de::DeserializeOwned; +use serde::{Deserialize, Deserializer, Serialize}; + +use super::cross_repo::RepoSearch; +use super::feature::plan_files::{planned_files, FileAction}; +use super::fix_location::{FixDecision, FixLocation}; +use super::plan::PlanResult; +use crate::clients::github::GitHubClient; + +/// Files whose history the worker reads for one plan. +pub const MAX_HISTORY_FILES: usize = 8; +/// Commits read per file. +const HISTORY_COMMITS: u32 = 30; +/// Names searched for in the team's other repositories for one plan. +pub const MAX_SURFACES: usize = 6; +/// Other repositories searched. +const MAX_OTHER_REPOS: usize = 8; +/// Hits kept per repository and name. +const MAX_HITS: usize = 5; +/// In-repository dependents named to the planner. +const MAX_IN_REPO: usize = 25; + +/// A field that reads loosely: a value of the wrong shape is left empty, so +/// one malformed habit never costs the plan its whole decision. +fn lenient<'de, D: Deserializer<'de>, T: DeserializeOwned + Default>(d: D) -> Result { + let v = serde_json::Value::deserialize(d)?; + Ok(serde_json::from_value(v).unwrap_or_default()) +} + +/// The `habits` object of the planner's decision. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Habits { + #[serde(default, deserialize_with = "lenient")] + pub repro: Repro, + #[serde(default, deserialize_with = "lenient")] + pub area_history: Vec, + /// Each name other code may depend on that the change alters: an + /// exported function or type, an API route, a response or event field, + /// a table column, a config key. + #[serde(default, deserialize_with = "lenient")] + pub surfaces: Vec, + /// When the change alters nothing other code can depend on: why. + #[serde(default, deserialize_with = "lenient")] + pub no_outside_use: String, + #[serde(default, deserialize_with = "lenient")] + pub affected: Vec, + #[serde(default, deserialize_with = "lenient")] + pub ask_early: Vec, +} + +/// How a bug is shown to exist before it is fixed. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Repro { + /// The test file that fails on the code as it is (a task of the plan). + #[serde(default)] + pub test: String, + /// Why it fails there: the reported failure, as the test will show it. + #[serde(default)] + pub fails_with: String, + /// When no failing test can be written: why (no test setup, a pure + /// configuration change). + #[serde(default)] + pub not_feasible: String, + /// The next best proof, when there is no failing test. + #[serde(default)] + pub next_best: String, +} + +/// What the history of one touched file shows. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct AreaHistory { + #[serde(default)] + pub path: String, + /// What past pull requests, reverts and blame show. + #[serde(default)] + pub found: String, + /// The pull requests and commits it rests on (`#123`, a short sha). + #[serde(default, deserialize_with = "lenient")] + pub refs: Vec, + /// What it changes about this plan. + #[serde(default)] + pub bearing: String, +} + +/// One caller or dependent of what the change touches. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Affected { + /// Where it is: `owner/repo:path`, or a path of this repository. + #[serde(default, rename = "where")] + pub where_: String, + /// What it uses of the change. + #[serde(default)] + pub uses: String, + /// `update` (a task changes it) or `safe`. + #[serde(default)] + pub action: String, + /// Why it is safe, or what the update is. + #[serde(default)] + pub why: String, +} + +impl Affected { + /// The repository it names (`owner/repo`), when it names one. + pub fn repo(&self) -> Option<&str> { + let (repo, _) = self.where_.trim().split_once(':')?; + (repo.matches('/').count() == 1 && !repo.contains(' ')).then_some(repo) + } + + /// Its path, without the repository. + pub fn path(&self) -> &str { + match self.repo() { + Some(_) => self.where_.trim().split_once(':').map_or("", |(_, p)| p), + None => self.where_.trim(), + } + .trim() + } + + pub fn updates(&self) -> bool { + self.action.trim().eq_ignore_ascii_case("update") + } + + fn is_safe(&self) -> bool { + self.action.trim().eq_ignore_ascii_case("safe") + } +} + +/// A doubt that changes what gets built, asked while the plan is made. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct EarlyQuestion { + #[serde(default)] + pub question: String, + /// What the run builds until someone answers. + #[serde(default)] + pub default: String, + /// The plan's files that would change with another answer. + #[serde(default, deserialize_with = "lenient")] + pub depends_on: Vec, +} + +// ── What the worker reads itself ─────────────────────────────────────────── + +/// A revert among a file's commits. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Revert { + pub sha: String, + pub date: String, + pub subject: String, +} + +/// The recent history of one file the plan modifies. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FileHistory { + pub path: String, + pub commits: usize, + pub reverts: Vec, + /// Pull requests its commits name (`(#123)`), newest first. + pub prs: Vec, + /// Its newest commits, one line each. + pub recent: Vec, +} + +fn pr_numbers(subject: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = subject; + while let Some(i) = rest.find('#') { + rest = &rest[i + 1..]; + let digits: String = rest.chars().take_while(char::is_ascii_digit).collect(); + if let Ok(n) = digits.parse::() { + if !out.contains(&n) { + out.push(n); + } + } + } + out +} + +/// Whether a commit subject takes an earlier change back out. +pub fn is_revert(subject: &str) -> bool { + let low = subject.trim().to_ascii_lowercase(); + low.starts_with("revert") + || low.contains("reverts commit") + || low.contains("revert \"") + || low.starts_with("back out") + || low.starts_with("backout") + || low.starts_with("roll back") + || low.starts_with("rollback") +} + +/// One file's history from GitHub's commit list for its path. +pub fn file_history(path: &str, commits: &[serde_json::Value]) -> FileHistory { + let mut h = FileHistory { + path: path.to_string(), + commits: commits.len(), + ..Default::default() + }; + for c in commits { + let sha: String = c["sha"].as_str().unwrap_or("").chars().take(7).collect(); + let message = c["commit"]["message"].as_str().unwrap_or(""); + let subject = message.lines().next().unwrap_or("").trim(); + let date: String = c["commit"]["committer"]["date"] + .as_str() + .or_else(|| c["commit"]["author"]["date"].as_str()) + .unwrap_or("") + .chars() + .take(10) + .collect(); + for n in pr_numbers(subject) { + if !h.prs.contains(&n) { + h.prs.push(n); + } + } + if h.recent.len() < 5 { + h.recent.push(format!( + "{sha} {date} {}", + common::truncate_str(subject, 120) + )); + } + if is_revert(subject) || message.contains("This reverts commit") { + h.reverts.push(Revert { + sha, + date, + subject: common::truncate_str(subject, 160).to_string(), + }); + } + } + h +} + +/// The tasks of the run's own repository: its group in a plan that spans +/// several, else the whole checklist. +fn own_tasks<'a>(files: &'a PlanResult, own_repo: &str) -> &'a str { + files + .repo_tasks + .iter() + .find(|r| format!("{}/{}", r.owner, r.name).eq_ignore_ascii_case(own_repo)) + .map_or(files.tasks.as_str(), |r| r.tasks.as_str()) +} + +/// The existing files of this repository the plan changes (never the ones +/// it creates, never its tests). +pub fn modified_paths(files: &PlanResult, own_repo: &str) -> Vec { + planned_files(own_tasks(files, own_repo)) + .into_iter() + .filter(|f| !f.is_new() && f.action != Some(FileAction::Create)) + .map(|f| f.path) + .filter(|p| !is_test_path(p)) + .collect() +} + +/// Whether the plan writes code at all. +fn plans_code(files: &PlanResult) -> bool { + let t = files.tasks.trim_start(); + let stops = t.is_empty() + || t.starts_with("NO_CHANGES_NEEDED:") + || t.starts_with("CLARIFICATION_NEEDED:") + || t.starts_with(super::fix_location::NO_CODE_CHANGE); + !stops + && files.fix.as_ref().is_some_and(|d| { + matches!( + d.effective_location(), + FixLocation::Code | FixLocation::Both + ) + }) +} + +/// Reads the commits of the files the plan modifies. A file GitHub can't +/// list is left out: the check never fails a plan on a read error. +pub async fn read_history( + github: &GitHubClient, + owner: &str, + repo: &str, + files: &PlanResult, +) -> Vec { + if !plans_code(files) { + return Vec::new(); + } + let mut out = Vec::new(); + for path in modified_paths(files, &format!("{owner}/{repo}")) + .into_iter() + .take(MAX_HISTORY_FILES) + { + match github + .commits_for_path(owner, repo, &path, None, HISTORY_COMMITS) + .await + { + Ok(commits) if !commits.is_empty() => out.push(file_history(&path, &commits)), + Ok(_) => {} + Err(e) => { + tracing::warn!(path = %path, error = %e, "Could not read a planned file's history") + } + } + } + out +} + +/// What depends on the planned change, as the worker found it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Dependents { + /// Files of this repository that import a planned file or reference a + /// name it defines, with why. + pub in_repo: Vec<(String, String)>, + /// Hits in the team's other repositories: repository, the name + /// searched, the matching lines. + pub other_repos: Vec<(String, String, Vec)>, + /// The team has other repositories connected. + pub has_other_repos: bool, +} + +/// A name worth a code search: long enough and specific enough that a hit +/// means a use. +pub fn searchable(surface: &str) -> Option { + let s = surface.trim().trim_matches('`').trim(); + let ok = s.len() >= 4 && s.len() <= 80 && !s.contains('\n'); + ok.then(|| s.to_string()) +} + +/// Asks the code graph what the planned files reach, and searches the +/// team's other repositories for each name the plan says it changes. +pub async fn find_dependents( + state: &crate::WorkerState, + graph: Option<&super::code_graph::Graph>, + search: &dyn RepoSearch, + own_repo: &str, + team_repos: &[String], + files: &PlanResult, +) -> Dependents { + let others: Vec<&String> = team_repos + .iter() + .filter(|r| !r.eq_ignore_ascii_case(own_repo)) + .take(MAX_OTHER_REPOS) + .collect(); + let mut out = Dependents { + has_other_repos: !others.is_empty(), + ..Default::default() + }; + if !plans_code(files) { + return out; + } + let paths = modified_paths(files, own_repo); + if let Some(g) = graph { + let planned: Vec = planned_files(own_tasks(files, own_repo)) + .into_iter() + .map(|f| f.path) + .collect(); + out.in_repo = g + .impacted_by(state, &paths) + .await + .into_iter() + .filter(|(f, _)| !planned.contains(f) && !is_test_path(f)) + .collect(); + } + let surfaces: Vec = files + .fix + .as_ref() + .map(|d| { + d.habits + .surfaces + .iter() + .filter_map(|s| searchable(s)) + .collect() + }) + .unwrap_or_default(); + for surface in surfaces.iter().take(MAX_SURFACES) { + for repo in &others { + match search.search(repo, surface).await { + Ok(hits) if !hits.is_empty() => out.other_repos.push(( + repo.to_string(), + surface.clone(), + hits.into_iter().take(MAX_HITS).collect(), + )), + Ok(_) => {} + Err(e) => { + tracing::warn!(repo = %repo, error = %e, "Could not search a repository for dependents") + } + } + } + } + out +} + +/// What the worker read for one draft. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Facts { + pub own_repo: String, + pub history: Vec, + pub dependents: Dependents, +} + +/// Where the worker reads a draft's facts. +pub struct Reader<'a> { + pub state: &'a crate::WorkerState, + pub github: &'a GitHubClient, + pub graph: Option<&'a super::code_graph::Graph>, + pub search: &'a dyn RepoSearch, + pub owner: &'a str, + pub repo: &'a str, + pub team_repos: &'a [String], +} + +impl Reader<'_> { + /// The history of the files a draft modifies and what depends on them. + pub async fn facts(&self, files: &PlanResult) -> Facts { + let own_repo = format!("{}/{}", self.owner, self.repo); + Facts { + history: read_history(self.github, self.owner, self.repo, files).await, + dependents: find_dependents( + self.state, + self.graph, + self.search, + &own_repo, + self.team_repos, + files, + ) + .await, + own_repo, + } + } +} + +/// What the check still finds after the plan's one send-back, kept on the +/// decision: each gap as an open gap, and each use in another repository +/// the plan never accounted for listed among those it affects, marked as +/// not checked, so the pull request names it either way. +pub fn keep_open(d: &mut FixDecision, facts: &Facts, left: &[String]) { + for (repo, surface, hits) in &facts.dependents.other_repos { + let known = d + .habits + .affected + .iter() + .any(|a| a.repo().is_some_and(|r| r.eq_ignore_ascii_case(repo))); + if known { + continue; + } + let path = hits + .first() + .and_then(|h| h.split(':').next()) + .map(str::trim) + .unwrap_or(""); + d.habits.affected.push(Affected { + where_: format!("{repo}:{path}"), + uses: format!("`{surface}`"), + action: UNCHECKED.to_string(), + why: String::new(), + }); + } + d.open_gaps.extend( + left.iter() + .map(|g| common::truncate_str(g.lines().next().unwrap_or(g), 400).to_string()), + ); +} + +/// The action of a dependent the worker found and the plan never settled. +pub const UNCHECKED: &str = "unchecked"; + +// ── The plan's check ─────────────────────────────────────────────────────── + +fn mentions(text: &str, r: &Revert) -> bool { + let low = text.to_ascii_lowercase(); + (!r.sha.is_empty() && low.contains(&r.sha.to_ascii_lowercase())) + || pr_numbers(&r.subject) + .iter() + .any(|n| super::ticket_history::names_pr(text, *n)) +} + +fn history_text(h: &AreaHistory) -> String { + format!("{} {} {}", h.found, h.refs.join(" "), h.bearing) +} + +fn history_lines(history: &[FileHistory]) -> String { + history + .iter() + .map(|h| { + let mut s = format!(" - `{}`: {} recent commit(s)", h.path, h.commits); + if !h.prs.is_empty() { + let prs: Vec = h.prs.iter().take(6).map(|n| format!("#{n}")).collect(); + s.push_str(&format!(", pull requests {}", prs.join(", "))); + } + for r in &h.reverts { + s.push_str(&format!( + "\n - REVERT {} {}: {}", + r.sha, r.date, r.subject + )); + } + for l in h.recent.iter().take(3) { + s.push_str(&format!("\n - {l}")); + } + s + }) + .collect::>() + .join("\n") +} + +fn same_path(a: &str, b: &str) -> bool { + let n = |p: &str| { + p.trim() + .trim_matches('`') + .trim_start_matches("./") + .to_string() + }; + let (a, b) = (n(a), n(b)); + !a.is_empty() && (a == b || a.ends_with(&format!("/{b}")) || b.ends_with(&format!("/{a}"))) +} + +fn is_task(files: &PlanResult, own_repo: &str, path: &str) -> bool { + planned_files(own_tasks(files, own_repo)) + .iter() + .any(|f| same_path(&f.path, path)) +} + +/// Whether the plan gives `repo` work of its own: a task group or an +/// end-to-end step. +fn plans_repo(files: &PlanResult, repo: &str) -> bool { + files + .repo_tasks + .iter() + .any(|r| format!("{}/{}", r.owner, r.name).eq_ignore_ascii_case(repo)) + || files.fix.as_ref().is_some_and(|d| { + d.end_to_end + .iter() + .any(|s| s.repo.trim().eq_ignore_ascii_case(repo)) + }) +} + +/// What a draft still lacks, as instructions for the planner (empty when +/// nothing is missing). Each carries what the worker read, so the planner +/// answers facts and never has to be trusted to have looked. +pub fn plan_gaps(files: &PlanResult, facts: &Facts) -> Vec { + let Some(d) = files.fix.as_ref().filter(|_| plans_code(files)) else { + return Vec::new(); + }; + let h = &d.habits; + let mut out = Vec::new(); + + // Reproduce first. + if d.intent.is_bug() { + let r = &h.repro; + let test = r.test.trim(); + if test.is_empty() && (r.not_feasible.trim().is_empty() || r.next_best.trim().is_empty()) { + out.push("This is a bug: say how it is shown to exist before the fix (`habits.repro`). Name the test file that fails on the code as it is for the reported reason (`test`, with `fails_with`), and give that file a task in tasks.md. Only when no failing test can be written (the repository has no test setup for this code, the change is pure configuration), say why in `not_feasible` and name the next best proof in `next_best` (the exact command, query or page that shows the failure before and its absence after).".to_string()); + } else if !test.is_empty() && !is_task(files, &facts.own_repo, test) { + out.push(format!( + "`habits.repro.test` names `{test}`, but tasks.md has no task for that file. Add the task that writes the failing test (it is written before the fix)." + )); + } + } + + // Read the history. + let unanswered: Vec<&FileHistory> = facts + .history + .iter() + .filter(|f| { + f.reverts.iter().any(|r| { + !h.area_history + .iter() + .any(|a| same_path(&a.path, &f.path) && mentions(&history_text(a), r)) + }) + }) + .collect(); + if !unanswered.is_empty() { + out.push(format!( + "A file you plan to change had a change taken back out. Read each revert below (`github_history` with `kind: pull` or `commits`, and the pull request's discussion) and answer it in `habits.area_history`: an entry for that path whose `refs` name the revert's commit or pull request, `found` saying what was tried and why it was reverted, and `bearing` saying how this plan differs. A plan that repeats a reverted approach is wrong.\n{}", + history_lines(&unanswered.into_iter().cloned().collect::>()) + )); + } else if !facts.history.is_empty() && h.area_history.is_empty() { + out.push(format!( + "Record what the history of the files you change shows (`habits.area_history`: one entry per file that has history worth knowing, with the pull requests or commits in `refs`, what they show in `found` and what it changes about this plan in `bearing`). This is their recent history; read further with `github_history` (`commits` with `path`, `blame`, `pull`) where a commit bears on the change:\n{}", + history_lines(&facts.history) + )); + } + for a in &h.area_history { + if !a.path.trim().is_empty() && a.found.trim().is_empty() { + out.push(format!( + "`habits.area_history` lists `{}` without `found`: say what its history shows.", + a.path.trim() + )); + } + } + + // Know who it affects. + let dep = &facts.dependents; + let missing: Vec<&(String, String, Vec)> = dep + .other_repos + .iter() + .filter(|(repo, _, _)| { + !h.affected + .iter() + .any(|a| a.repo().is_some_and(|r| r.eq_ignore_ascii_case(repo))) + }) + .collect(); + if !missing.is_empty() { + let lines: Vec = missing + .iter() + .map(|(repo, surface, hits)| { + format!( + " - {repo} uses `{surface}`:\n{}", + hits.iter() + .map(|l| format!(" {}", common::truncate_str(l.trim(), 200))) + .collect::>() + .join("\n") + ) + }) + .collect(); + out.push(format!( + "Another of the team's repositories uses what this plan changes. Read each use below (pass `repo` to `read_file_lines`) and account for it in `habits.affected` (`where`: `owner/repo:path`, `uses`, `action`: `update` or `safe`, `why`). `update` needs that repository's tasks (a `## owner/repo` group in tasks.md); `safe` needs the reason it keeps working.\n{}", + lines.join("\n") + )); + } + let in_repo_named = h + .affected + .iter() + .any(|a| a.repo().is_none() && !a.path().is_empty()); + if !dep.in_repo.is_empty() && !in_repo_named { + let lines: Vec = dep + .in_repo + .iter() + .take(MAX_IN_REPO) + .map(|(f, why)| format!(" - `{f}` ({why})")) + .collect(); + let more = dep.in_repo.len().saturating_sub(MAX_IN_REPO); + out.push(format!( + "The code graph shows these files of this repository use what the plan changes{}. Account for them in `habits.affected`: one entry per file that must change (`action`: `update`, with a task in tasks.md) and one per group that keeps working (`action`: `safe`, `why`: for example the signature and return shape are unchanged). Read a caller before calling it safe.\n{}", + if more > 0 { format!(" ({more} more not listed; `graph_impact` lists all)") } else { String::new() }, + lines.join("\n") + )); + } + if dep.has_other_repos + && !modified_paths(files, &facts.own_repo).is_empty() + && h.surfaces.iter().filter_map(|s| searchable(s)).count() == 0 + && h.no_outside_use.trim().is_empty() + { + out.push("The team has other repositories connected and this plan changes existing code. List in `habits.surfaces` each name other code may depend on that the change alters (an exported function or type, an API route, a response or event field, a table column, a config key), so each is searched for across those repositories; or say in `habits.no_outside_use` why nothing outside this repository can depend on the change.".to_string()); + } + for a in &h.affected { + let w = a.where_.trim(); + if w.is_empty() { + continue; + } + if a.action.trim() == UNCHECKED { + continue; + } + if !a.updates() && !a.is_safe() { + out.push(format!( + "`habits.affected` lists `{w}` without a decision: set `action` to `update` or `safe`." + )); + } else if a.is_safe() && a.why.trim().is_empty() { + out.push(format!( + "`habits.affected` calls `{w}` safe without `why`: say what keeps it working." + )); + } else if a.updates() { + let planned = match a.repo() { + Some(r) if !r.eq_ignore_ascii_case(&facts.own_repo) => plans_repo(files, r), + _ => is_task(files, &facts.own_repo, a.path()), + }; + if !planned { + out.push(format!( + "`habits.affected` says `{w}` is updated, but tasks.md has no task for it. Add the task (under its `## owner/repo` group when it is another repository), or make it `safe` with the reason." + )); + } + } + } + + // Ask early. + for q in &h.ask_early { + if !q.question.trim().is_empty() && q.default.trim().is_empty() { + out.push(format!( + "`habits.ask_early` asks \"{}\" without a `default`: say what you build until someone answers, and plan that.", + common::truncate_str(q.question.trim(), 160) + )); + } + } + out +} + +/// The line an early question becomes in the decision's questions. +pub fn question_line(q: &EarlyQuestion) -> String { + let question = q.question.trim(); + let mark = if question.ends_with('?') { "" } else { "?" }; + let mut s = format!( + "{question}{mark} Proposed default: {}. I am building the default now; a different answer changes it", + q.default.trim().trim_end_matches('.') + ); + let deps: Vec<&str> = q + .depends_on + .iter() + .map(|d| d.trim()) + .filter(|d| !d.is_empty()) + .take(6) + .collect(); + if deps.is_empty() { + s.push('.'); + } else { + s.push_str(&format!(" in {}.", deps.join(", "))); + } + s +} + +/// Puts every early question that has a default among the decision's +/// questions, so it is asked on the ticket while the run builds (the run +/// never waits on those) and listed in the pull request. A question already +/// there in the same words is replaced by the line with its default. +pub fn fold_questions(d: &mut FixDecision) { + for q in d.habits.ask_early.clone() { + let question = q.question.trim(); + if question.is_empty() || q.default.trim().is_empty() { + continue; + } + let line = question_line(&q); + if d.questions.iter().any(|x| x.trim() == line) { + continue; + } + let stem = question.trim_end_matches('?').to_ascii_lowercase(); + d.questions + .retain(|x| !x.to_ascii_lowercase().contains(&stem)); + d.questions.push(line); + } +} + +/// Moves the reproducing test's task to the top of the checklist (of its +/// repository's group, in a plan that spans several), so it is written and +/// committed before the fix. `None` when nothing moves. +pub fn put_repro_first(tasks: &str, test: &str) -> Option { + let test = test.trim(); + if test.is_empty() { + return None; + } + let lines: Vec<&str> = tasks.lines().collect(); + let is_task_line = |l: &str| l.trim_start().starts_with("- ["); + let at = lines.iter().position(|l| { + is_task_line(l) + && planned_files(l) + .first() + .is_some_and(|f| same_path(&f.path, test)) + })?; + // The first task of the same group: back to the group's heading. + let group_start = lines[..at] + .iter() + .rposition(|l| l.trim_start().starts_with("## ")) + .map_or(0, |i| i + 1); + let first = (group_start..at).find(|i| is_task_line(lines[*i]))?; + let mut out: Vec<&str> = lines.clone(); + let line = out.remove(at); + out.insert(first, line); + let mut s = out.join("\n"); + if tasks.ends_with('\n') { + s.push('\n'); + } + Some(s) +} + +/// The heading of the section design.md gains. +pub const DESIGN_HEADING: &str = "## How this change is built"; + +/// What the coder must hold to, from the plan's habits, as a section of +/// design.md: always the plan's own files (the check after the build holds +/// every change to them), and what the plan settled before code. +pub fn design_section(d: &FixDecision) -> String { + let h = &d.habits; + let mut out = String::new(); + let r = &h.repro; + if !r.test.trim().is_empty() { + out.push_str(&format!( + "- **Reproduce first.** Write `{}` before any other task and commit it on its own. It must fail on the code as it is{}. Test through code that already exists (the entry point the bug is reported at), so the test builds and fails on its assertion without the fix; never weaken it to make it pass. After the build, every new or changed test is run without the fix: one that passes either way comes back to you.\n", + r.test.trim(), + if r.fails_with.trim().is_empty() { String::new() } else { format!(": {}", r.fails_with.trim().trim_end_matches('.')) } + )); + } else if !r.not_feasible.trim().is_empty() { + out.push_str(&format!( + "- **No failing test for this one:** {}. Proof instead: {}. Record that proof's result before and after the change in your Evidence.\n", + r.not_feasible.trim().trim_end_matches('.'), + r.next_best.trim().trim_end_matches('.') + )); + } + for a in h.area_history.iter().filter(|a| !a.found.trim().is_empty()) { + out.push_str(&format!( + "- **History of `{}`:** {}{}\n", + a.path.trim(), + a.found.trim(), + if a.bearing.trim().is_empty() { + String::new() + } else { + format!(" For this change: {}", a.bearing.trim()) + } + )); + } + for a in h.affected.iter().filter(|a| a.updates()) { + out.push_str(&format!( + "- **Update with it:** `{}`{}.\n", + a.where_.trim(), + if a.why.trim().is_empty() { + String::new() + } else { + format!(" ({})", a.why.trim().trim_end_matches('.')) + } + )); + } + // Only a doubt still among the decision's questions: one the ticket + // already settles was dropped from them, and is not built as a default. + let asked = |q: &EarlyQuestion| { + let stem = q.question.trim().trim_end_matches('?').to_ascii_lowercase(); + !stem.is_empty() + && !q.default.trim().is_empty() + && d.questions + .iter() + .any(|x| x.to_ascii_lowercase().contains(&stem)) + }; + for q in h.ask_early.iter().filter(|q| asked(q)) { + out.push_str(&format!( + "- **Asked on the ticket, build the default:** {} Build: {}. Keep that choice in one place so another answer is a small change.\n", + q.question.trim(), + q.default.trim().trim_end_matches('.') + )); + } + out.push_str("- **Stay inside the plan.** Change only the files the tasks name, their tests, and what those need to build. When the change truly needs another file, say so in your Evidence on a line `Outside the plan: : `; a changed file with no such line is put back.\n"); + format!("{DESIGN_HEADING}\n{out}") +} + +/// design.md with the section, once, for a plan whose tasks name files. +pub fn with_design_section(design: &str, d: &FixDecision, tasks: &str) -> String { + if planned_files(tasks).is_empty() || design.contains(DESIGN_HEADING) { + return design.to_string(); + } + let section = design_section(d); + format!("{}\n\n{section}", design.trim_end()) +} + +/// The planner's instructions for the `habits` object, by what the ticket +/// asks for. +pub fn planner_guidance(is_bug: bool) -> String { + let repro = if is_bug { + "- **Reproduce first (`repro`).** Before the fix, a test must fail on the code as it is, for the reason the ticket reports. Name that test file in `repro.test` (find the nearest existing test for the code and follow it), say in `fails_with` what it will show, and give the file its own task. Only when no failing test can be written (no test setup reaches this code, a pure configuration change) leave `test` empty, say why in `not_feasible` and name the next best proof in `next_best`: the exact command, query or page that shows the failure before the change and its absence after.\n" + } else { + "" + }; + format!( + "## Before any code (the `habits` object of the block, every plan that changes code)\n\n{repro}\ +- **Read the history (`area_history`).** Before you plan a change to an existing file, read what was done to it: `github_history` with `kind: commits` and `path`, `kind: blame` on the lines you change, and `kind: pull` for a pull request a commit names. Look for the same change tried before, a revert, and the reason a line is the way it is. Record what bears on this plan, with the pull requests or commits in `refs`. A reverted approach is never planned again without saying what differs.\n\ +- **Know who it affects (`surfaces`, `affected`).** List in `surfaces` each name other code may depend on that the change alters (an exported function or type, an API route, a response or event field, a table column, a config key). Find its users: `graph_callers` and `graph_impact` in this repository, and `search_code` with `repo` in each of the team's other repositories. Record each user that must change (`action: update`, with a task for it; another repository's under its `## owner/repo` group) and each group that keeps working (`action: safe`, with the reason). When nothing outside the repository can depend on the change, say why in `no_outside_use`.\n\ +- **Ask early (`ask_early`).** When the ticket reads two ways that lead to different code, or leaves a product decision open, don't build one reading and list the doubt at the end: write the question with the `default` you propose, plan the default, and list in `depends_on` the files that would change with another answer. The question is asked on the ticket now and the run keeps building. Never ask what the code, the data, the history or a lookup can answer: find it out.\n\n\ +Add this to the block:\n\ +```\n\ +\"habits\": {{\n\ + \"repro\": {{\"test\": \"path of the test file that fails before the fix (bugs)\", \"fails_with\": \"what it shows on the code as it is\", \"not_feasible\": \"why no failing test can be written; empty when test is set\", \"next_best\": \"the next best proof, when there is no test\"}},\n\ + \"area_history\": [{{\"path\": \"a file the plan changes\", \"found\": \"what its pull requests, reverts and blame show\", \"refs\": [\"#123\", \"a1b2c3d\"], \"bearing\": \"what it changes about this plan\"}}],\n\ + \"surfaces\": [\"each name other code may depend on that the change alters\"],\n\ + \"no_outside_use\": \"why nothing outside this repository can depend on the change; empty when surfaces lists any\",\n\ + \"affected\": [{{\"where\": \"owner/repo:path, or a path of this repository\", \"uses\": \"what it uses of the change\", \"action\": \"update | safe\", \"why\": \"the update, or why it keeps working\"}}],\n\ + \"ask_early\": [{{\"question\": \"one decision only a person can make\", \"default\": \"what you build until someone answers\", \"depends_on\": [\"files that would change with another answer\"]}}]\n\ +}}\n\ +```" + ) +} + +/// Whether a path is a test, by the conventions of the common ecosystems. +pub fn is_test_path(path: &str) -> bool { + let p = path.to_ascii_lowercase(); + let base = p.rsplit('/').next().unwrap_or(&p); + base.contains(".test.") + || base.contains(".spec.") + || base.contains("_test.") + || base.contains("_spec.") + || base.starts_with("test_") + || base.ends_with("test.java") + || base.ends_with("tests.java") + || base.ends_with("test.kt") + || base.ends_with("tests.cs") + || ["__tests__/", "tests/", "test/", "spec/", "__snapshots__/"] + .iter() + .any(|d| p.starts_with(d) || p.contains(&format!("/{d}"))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::passes::fix_location::{self, EndToEndStep}; + use crate::passes::plan::RepoTasks; + use crate::passes::triage::TicketIntent; + use serde_json::json; + + const OWN: &str = "acme/shop-api"; + + fn plan(tasks: &str, intent: TicketIntent, habits: Habits) -> PlanResult { + PlanResult { + proposal: String::new(), + design: "## Design\nChange the total.".into(), + tasks: tasks.into(), + spec: String::new(), + repo_tasks: Vec::new(), + fix: Some(FixDecision { + intent, + habits, + ..Default::default() + }), + } + } + + fn facts() -> Facts { + Facts { + own_repo: OWN.into(), + ..Default::default() + } + } + + const TASKS: &str = "- [ ] src/cart/total.ts: [modify] Round per line, not per cart\n- [ ] src/cart/total.test.ts: [modify] A cart with three lines of 0.335\n"; + + fn commit(sha: &str, date: &str, message: &str) -> serde_json::Value { + json!({"sha": sha, "commit": {"message": message, "committer": {"date": date}}}) + } + + #[test] + fn the_block_reads_habits_and_a_malformed_one_never_costs_the_decision() { + let reply = r#"```fix_location.json +{"fix_location": "code", "cause": "c", "habits": { + "repro": {"test": "src/cart/total.test.ts", "fails_with": "total is 1.00, expected 1.01"}, + "area_history": "nothing found", + "surfaces": ["cartTotal"], + "affected": [{"where": "acme/storefront:src/checkout.ts", "uses": "total", "action": "safe", "why": "reads the same field"}], + "ask_early": [{"question": "Round half up or half even?", "default": "half up", "depends_on": ["src/cart/total.ts"]}] +}} +```"#; + let d = fix_location::parse(reply).expect("a decision"); + assert_eq!(d.habits.repro.test, "src/cart/total.test.ts"); + assert!( + d.habits.area_history.is_empty(), + "the wrong shape is left empty" + ); + assert_eq!(d.habits.surfaces, vec!["cartTotal"]); + assert_eq!(d.habits.affected[0].repo(), Some("acme/storefront")); + assert_eq!(d.habits.affected[0].path(), "src/checkout.ts"); + assert_eq!(d.habits.ask_early[0].default, "half up"); + // A decision written before the field existed still reads. + let old = "```fix_location.json\n{\"fix_location\": \"code\", \"cause\": \"c\"}\n```"; + assert_eq!(fix_location::parse(old).unwrap().habits, Habits::default()); + } + + #[test] + fn a_bug_plan_names_its_failing_test_or_says_why_there_is_none() { + let none = plan(TASKS, TicketIntent::Bug, Habits::default()); + let gaps = plan_gaps(&none, &facts()); + assert!(gaps.iter().any(|g| g.contains("habits.repro")), "{gaps:?}"); + + let named = plan( + TASKS, + TicketIntent::Bug, + Habits { + repro: Repro { + test: "src/cart/total.test.ts".into(), + fails_with: "1.00 instead of 1.01".into(), + ..Default::default() + }, + ..Default::default() + }, + ); + assert!(plan_gaps(&named, &facts()).is_empty()); + + let untasked = plan( + "- [ ] src/cart/total.ts: [modify] Round per line\n", + TicketIntent::Bug, + named.fix.as_ref().unwrap().habits.clone(), + ); + let gaps = plan_gaps(&untasked, &facts()); + assert!(gaps[0].contains("no task for that file"), "{gaps:?}"); + + let config = plan( + "- [ ] config/limits.yml: [modify] Raise the limit\n", + TicketIntent::Bug, + Habits { + repro: Repro { + not_feasible: "a value in a YAML file no test loads".into(), + next_best: "GET /limits returns 50 before and 100 after".into(), + ..Default::default() + }, + ..Default::default() + }, + ); + assert!(plan_gaps(&config, &facts()).is_empty()); + // Why without a next best proof is half an answer. + let mut half = config; + half.fix.as_mut().unwrap().habits.repro.next_best.clear(); + assert_eq!(plan_gaps(&half, &facts()).len(), 1); + } + + #[test] + fn new_work_and_plans_without_code_need_no_reproduction() { + let feature = plan(TASKS, TicketIntent::Feature, Habits::default()); + assert!(plan_gaps(&feature, &facts()).is_empty()); + let stop = plan( + "CLARIFICATION_NEEDED:\n- question: Which one?", + TicketIntent::Bug, + Habits::default(), + ); + assert!(plan_gaps(&stop, &facts()).is_empty()); + let mut outside = plan("NO_CODE_CHANGE: data", TicketIntent::Bug, Habits::default()); + outside.fix.as_mut().unwrap().fix_location = FixLocation::Unknown; + assert!(plan_gaps(&outside, &facts()).is_empty()); + } + + #[test] + fn the_reproducing_test_is_written_first() { + let moved = put_repro_first(TASKS, "src/cart/total.test.ts").expect("it moves"); + assert!( + moved.starts_with("- [ ] src/cart/total.test.ts:"), + "{moved}" + ); + assert!(moved.ends_with('\n')); + assert_eq!(moved.lines().count(), 2); + // Already first, or not a task: nothing moves. + assert_eq!(put_repro_first(&moved, "src/cart/total.test.ts"), None); + assert_eq!(put_repro_first(TASKS, "src/other.test.ts"), None); + // In a plan that spans repositories it stays in its own group. + let multi = "## acme/shop-api\n- [ ] a.ts: [modify] x\n- [ ] a.test.ts: [create] y\n## acme/storefront\n- [ ] b.ts: [modify] z\n- [ ] b.test.ts: [create] w\n"; + let moved = put_repro_first(multi, "b.test.ts").unwrap(); + let lines: Vec<&str> = moved.lines().collect(); + assert_eq!(lines[1], "- [ ] a.ts: [modify] x"); + assert_eq!(lines[4], "- [ ] b.test.ts: [create] w"); + } + + #[test] + fn a_files_history_reads_its_reverts_and_pull_requests() { + let commits = vec![ + commit( + "aaaaaaa1111", + "2026-03-04T10:00:00Z", + "Cache totals per cart (#88)", + ), + commit( + "bbbbbbb2222", + "2026-02-11T09:00:00Z", + "Revert \"Round per line (#71)\" (#74)\n\nThis reverts commit ccccccc.", + ), + commit( + "ccccccc3333", + "2026-02-10T09:00:00Z", + "Round per line (#71)", + ), + ]; + let h = file_history("src/cart/total.ts", &commits); + assert_eq!(h.commits, 3); + assert_eq!(h.prs, vec![88, 71, 74]); + assert_eq!(h.reverts.len(), 1); + assert_eq!(h.reverts[0].sha, "bbbbbbb"); + assert_eq!(h.reverts[0].date, "2026-02-11"); + assert!(is_revert("Back out the retry change")); + assert!(!is_revert("Add a revert button to the editor")); + } + + fn with_history() -> Facts { + Facts { + own_repo: OWN.into(), + history: vec![file_history( + "src/cart/total.ts", + &[ + commit( + "bbbbbbb2222", + "2026-02-11T09:00:00Z", + "Revert \"Round per line (#71)\" (#74)", + ), + commit( + "ccccccc3333", + "2026-02-10T09:00:00Z", + "Round per line (#71)", + ), + ], + )], + ..Default::default() + } + } + + #[test] + fn a_revert_on_a_planned_file_must_be_answered_by_name() { + let silent = plan(TASKS, TicketIntent::Feature, Habits::default()); + let gaps = plan_gaps(&silent, &with_history()); + assert_eq!(gaps.len(), 1); + assert!(gaps[0].contains("REVERT bbbbbbb 2026-02-11"), "{}", gaps[0]); + assert!(gaps[0].contains("taken back out")); + + // An entry for the file that doesn't name the revert doesn't answer it. + let vague = plan( + TASKS, + TicketIntent::Feature, + Habits { + area_history: vec![AreaHistory { + path: "src/cart/total.ts".into(), + found: "Touched a few times this year.".into(), + ..Default::default() + }], + ..Default::default() + }, + ); + assert_eq!(plan_gaps(&vague, &with_history()).len(), 1); + + let answered = plan( + TASKS, + TicketIntent::Feature, + Habits { + area_history: vec![AreaHistory { + path: "src/cart/total.ts".into(), + found: "Per-line rounding shipped in #71 and was reverted in #74: invoices no longer matched the ledger export.".into(), + refs: vec!["#71".into(), "#74".into()], + bearing: "This plan rounds per line and updates the export in the same change.".into(), + }], + ..Default::default() + }, + ); + assert!(plan_gaps(&answered, &with_history()).is_empty()); + } + + #[test] + fn history_without_a_revert_is_handed_to_the_planner_once() { + let mut f = with_history(); + f.history[0].reverts.clear(); + let silent = plan(TASKS, TicketIntent::Feature, Habits::default()); + let gaps = plan_gaps(&silent, &f); + assert_eq!(gaps.len(), 1); + assert!(gaps[0].contains("`src/cart/total.ts`: 2 recent commit(s), pull requests #71, #74")); + } + + fn uses_elsewhere() -> Facts { + Facts { + own_repo: OWN.into(), + dependents: Dependents { + in_repo: vec![("src/invoice/pdf.ts".into(), "references `cartTotal`".into())], + other_repos: vec![( + "acme/storefront".into(), + "cartTotal".into(), + vec!["src/checkout.ts:41: const total = cart.cartTotal.amount".into()], + )], + has_other_repos: true, + }, + ..Default::default() + } + } + + #[test] + fn every_dependent_the_worker_found_is_accounted_for() { + let h = Habits { + surfaces: vec!["cartTotal".into()], + ..Default::default() + }; + let silent = plan(TASKS, TicketIntent::Feature, h.clone()); + let gaps = plan_gaps(&silent, &uses_elsewhere()); + assert_eq!(gaps.len(), 2, "{gaps:?}"); + assert!(gaps[0].contains("acme/storefront uses `cartTotal`")); + assert!(gaps[0].contains("src/checkout.ts:41")); + assert!(gaps[1].contains("`src/invoice/pdf.ts` (references `cartTotal`)")); + + // Safe needs its reason; update needs its task. + let mut loose = h.clone(); + loose.affected = vec![ + Affected { + where_: "acme/storefront:src/checkout.ts".into(), + action: "update".into(), + ..Default::default() + }, + Affected { + where_: "src/invoice/pdf.ts".into(), + action: "safe".into(), + ..Default::default() + }, + ]; + let gaps = plan_gaps( + &plan(TASKS, TicketIntent::Feature, loose.clone()), + &uses_elsewhere(), + ); + assert_eq!(gaps.len(), 2, "{gaps:?}"); + assert!(gaps[0].contains("no task for it")); + assert!(gaps[1].contains("safe without `why`")); + + loose.affected[1].why = "reads `amount`, which keeps its type".into(); + let mut settled = plan(TASKS, TicketIntent::Feature, loose); + settled.repo_tasks = vec![ + RepoTasks { + owner: "acme".into(), + name: "shop-api".into(), + tasks: TASKS.into(), + }, + RepoTasks { + owner: "acme".into(), + name: "storefront".into(), + tasks: "- [ ] src/checkout.ts: [modify] Read the per-line total".into(), + }, + ]; + assert!(plan_gaps(&settled, &uses_elsewhere()).is_empty()); + // An end-to-end step in that repository plans it too. + settled.repo_tasks.clear(); + settled.fix.as_mut().unwrap().end_to_end = vec![EndToEndStep { + step: "Storefront reads the new total".into(), + by: "other_repo".into(), + repo: "acme/storefront".into(), + ..Default::default() + }]; + assert!(plan_gaps(&settled, &uses_elsewhere()).is_empty()); + } + + #[test] + fn a_team_with_other_repositories_gets_the_changed_names_or_the_reason_there_are_none() { + let f = Facts { + own_repo: OWN.into(), + dependents: Dependents { + has_other_repos: true, + ..Default::default() + }, + ..Default::default() + }; + let silent = plan(TASKS, TicketIntent::Feature, Habits::default()); + assert!(plan_gaps(&silent, &f)[0].contains("habits.surfaces")); + let internal = plan( + TASKS, + TicketIntent::Feature, + Habits { + no_outside_use: "a private helper of one module".into(), + ..Default::default() + }, + ); + assert!(plan_gaps(&internal, &f).is_empty()); + // A plan that only adds files changes nothing others use. + let adds = plan( + "- [ ] src/new.ts: [create] A new helper\n", + TicketIntent::Feature, + Habits::default(), + ); + assert!(plan_gaps(&adds, &f).is_empty()); + assert_eq!(searchable(" `id` "), None, "too short to mean a use"); + } + + #[test] + fn an_early_question_carries_its_default_and_is_asked_once() { + let q = EarlyQuestion { + question: "Round half up or half even".into(), + default: "half up, as the invoice module does.".into(), + depends_on: vec!["src/cart/total.ts".into()], + }; + let mut d = FixDecision { + questions: vec![ + "Round half up or half even?".into(), + "Which currency?".into(), + ], + habits: Habits { + ask_early: vec![q.clone()], + ..Default::default() + }, + ..Default::default() + }; + fold_questions(&mut d); + fold_questions(&mut d); + assert_eq!(d.questions.len(), 2, "{:?}", d.questions); + assert_eq!(d.questions[0], "Which currency?"); + assert_eq!( + d.questions[1], + "Round half up or half even? Proposed default: half up, as the invoice module does. I am building the default now; a different answer changes it in src/cart/total.ts." + ); + // The line is fit to ask: it names what was considered and recommended. + let asked = common::run_questions::from_lines(&d.questions); + assert!(common::run_questions::too_open(&asked[1]).is_none()); + + let bare = plan( + TASKS, + TicketIntent::Feature, + Habits { + ask_early: vec![EarlyQuestion { + question: "Which rounding?".into(), + ..Default::default() + }], + ..Default::default() + }, + ); + assert!(plan_gaps(&bare, &facts())[0].contains("without a `default`")); + let mut d = bare.fix.unwrap(); + fold_questions(&mut d); + assert!( + d.questions.is_empty(), + "a question without a default isn't asked as one" + ); + } + + #[test] + fn the_coder_reads_the_habits_in_the_design() { + let d = FixDecision { + habits: Habits { + repro: Repro { + test: "src/cart/total.test.ts".into(), + fails_with: "1.00, expected 1.01".into(), + ..Default::default() + }, + affected: vec![Affected { + where_: "src/invoice/pdf.ts".into(), + action: "update".into(), + why: "prints the total".into(), + ..Default::default() + }], + ask_early: vec![EarlyQuestion { + question: "Half up or half even?".into(), + default: "half up".into(), + ..Default::default() + }], + ..Default::default() + }, + ..Default::default() + }; + let mut d = d; + fold_questions(&mut d); + let design = with_design_section("## Design\nx\n", &d, TASKS); + assert!(design.contains(DESIGN_HEADING)); + assert!(design.contains("Write `src/cart/total.test.ts` before any other task")); + assert!(design.contains("**Update with it:** `src/invoice/pdf.ts` (prints the total)")); + assert!(design.contains("build the default")); + assert!(design.contains("Outside the plan: ")); + assert_eq!( + with_design_section(&design, &d, TASKS), + design, + "added once" + ); + // A plan with no habits still tells the coder the scope it is held to; + // a plan that names no files has none. + let bare = with_design_section("d", &FixDecision::default(), TASKS); + assert!(bare.contains("Outside the plan: "), "{bare}"); + assert_eq!( + with_design_section("d", &FixDecision::default(), "NO_CODE_CHANGE: data"), + "d" + ); + } + + #[test] + fn the_planner_is_told_each_habit_and_only_a_bug_reproduces() { + let bug = planner_guidance(true); + for field in [ + "repro", + "area_history", + "surfaces", + "affected", + "ask_early", + "no_outside_use", + ] { + assert!(bug.contains(&format!("\"{field}\"")), "{field}"); + } + assert!(bug.contains("Reproduce first")); + assert!(!planner_guidance(false).contains("Reproduce first")); + // The example in the guidance is the shape the block reads. + assert!(fix_location::planner_guidance(TicketIntent::Bug).contains("\"habits\"")); + } + + #[test] + fn tests_are_told_from_code_across_ecosystems() { + for p in [ + "src/cart/total.test.ts", + "web/__tests__/cart.tsx", + "pkg/cart/total_test.go", + "tests/test_total.py", + "app/test_total.py", + "spec/models/cart_spec.rb", + "src/test/java/CartTest.java", + ] { + assert!(is_test_path(p), "{p}"); + } + for p in [ + "src/cart/total.ts", + "src/contest/latest.ts", + "pkg/attest/sign.go", + ] { + assert!(!is_test_path(p), "{p}"); + } + } +} diff --git a/services/worker/src/passes/habits_check.rs b/services/worker/src/passes/habits_check.rs new file mode 100644 index 000000000..83254243a --- /dev/null +++ b/services/worker/src/passes/habits_check.rs @@ -0,0 +1,1380 @@ +//! After the build, the change is held to the plan's habits (see `habits`). +//! +//! - **Tests that mean something.** Each new or changed test file is run in +//! the sandbox twice: on the branch, and on the base with only the test +//! files added (the fix taken out). A test that passes both ways proves +//! nothing about the change; one that fails before any assertion runs +//! doesn't show a bug's reported failure. Both go back to the coder, never +//! to a person. For a bug the two results are the proof the pull request +//! carries: failing before, passing after. When no test can show it, the +//! plan's reason and its next best proof are recorded instead. +//! - **Stay inside the plan.** A changed file that is no task of the plan, +//! no test, lockfile or generated output, and that the coder gave no +//! reason for, goes back to be restored or justified. +//! - **Dependents.** A dependent the plan said it updates, and the branch +//! doesn't touch, goes back too. +//! +//! The sandbox runs take up to its full wait, so the check asks for a step +//! of its own when this one has too little time left +//! ([`GateStop::NeedsTime`]), once; a run that still has none records the +//! tests as not run, with why. Like every check on the open pull request it +//! runs once on a head, keeps its rounds in the run's ledger, and what it +//! leaves goes under Open items. + +use serde::{Deserialize, Serialize}; +use tracing::{info, warn}; + +use super::habits::{self, is_test_path}; +use super::plan::PlanResult; +use super::proof::Finding; +use common::e2e::test_package::{self, Step}; + +pub const MAX_FIX_ROUNDS: u32 = 2; +/// Test files run on their own; the rest are named as not run. +pub const MAX_TEST_FILES: usize = 8; +/// What the two sandbox runs need of a step: the sandbox's longest wait and +/// room to record the result. +pub const SANDBOX_STEP_SECS: u64 = 760; + +pub const START: &str = ""; +pub const END: &str = ""; + +/// What running a test with and without the change showed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Verdict { + /// Fails without the change, passes with it. + Proven, + /// Passes with and without the change. + PassesEitherWay, + /// Fails without the change before any assertion runs (it can't build + /// or import there): it shows the code is new, not that the bug existed. + FailsBeforeAsserting, + /// Fails with the change too. + FailsWithChange, + /// Couldn't be run here. + NotRun, +} + +/// One test file's result. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct TestResult { + pub path: String, + pub verdict: Verdict, + /// The failure it printed without the change, or why it didn't run. + #[serde(default)] + pub detail: String, +} + +/// A changed file that is no part of the plan. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct OutsidePlan { + pub path: String, + /// The coder's reason; empty when it gave none. + #[serde(default)] + pub why: String, +} + +/// What the check found, for the pull request. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PrFacts { + #[serde(default)] + pub bug: bool, + #[serde(default)] + pub tests: Vec, + /// Why no test was run at all, when none was. + #[serde(default)] + pub no_tests: String, + #[serde(default)] + pub outside_plan: Vec, + /// Dependents the plan updates that the branch doesn't touch. + #[serde(default)] + pub not_updated: Vec, +} + +/// Why the check didn't give a result. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GateStop { + /// The sandbox runs need a step of their own. + NeedsTime, + /// The check couldn't read the change. + Why(String), +} + +/// One test file's run: its exit code and, when it failed, what it printed. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FileRun { + pub code: Option, + pub output: String, +} + +/// Both runs of the changed test files, in the files' order. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Runs { + pub with: Vec, + pub without: Vec, +} + +/// Where the test files are run with and without the change. +#[async_trait::async_trait] +pub trait Bench: Send + Sync { + /// Runs each file on its own on the branch and on the base with only + /// these files added. `Err` says why nothing ran. + async fn run(&self, files: &[String]) -> Result; +} + +const NOT_FOUND_MARKS: &[&str] = &[ + "no tests found", + "no test files found", + "no tests ran", + "no test suite found", + "no tests to run", + "[no test files]", + "collected 0 items", +]; + +const BEFORE_ASSERT_MARKS: &[&str] = &[ + "cannot find module", + "failed to resolve import", + "does not provide an export named", + "is not exported", + "modulenotfounderror", + "importerror", + "cannot import name", + "syntaxerror", + "error ts", + "undefined:", + "has no member named", + "cannot find symbol", + "unresolved import", + "build failed", +]; + +fn has_any(text: &str, marks: &[&str]) -> bool { + let low = text.to_ascii_lowercase(); + marks.iter().any(|m| low.contains(m)) +} + +/// The first line of a failing run that says what failed. +fn excerpt(output: &str) -> String { + let lines: Vec<&str> = output + .lines() + .map(str::trim) + .filter(|l| !l.is_empty() && !l.starts_with("---")) + .collect(); + let with_any = |words: &[&str]| { + lines.iter().find(|l| { + let low = l.to_ascii_lowercase(); + words.iter().any(|w| low.contains(w)) + }) + }; + let line = with_any(&["expected", "assert", "error", "panic", "received"]) + .or_else(|| with_any(&["fail"])) + .or(lines.first()) + .copied() + .unwrap_or(""); + common::truncate_str(line, 200).replace('`', "'") +} + +/// What one file's two runs show. +pub fn verdict(with: &FileRun, without: &FileRun) -> (Verdict, String) { + match (with.code, without.code) { + (None, _) | (_, None) => ( + Verdict::NotRun, + "the sandbox gave no result for it".to_string(), + ), + (Some(w), _) if w != 0 && has_any(&with.output, NOT_FOUND_MARKS) => ( + Verdict::NotRun, + "the test command, scoped to this file, found no tests in it".to_string(), + ), + (Some(w), _) if w != 0 => (Verdict::FailsWithChange, excerpt(&with.output)), + (Some(_), Some(0)) => (Verdict::PassesEitherWay, String::new()), + (Some(_), Some(_)) if has_any(&without.output, NOT_FOUND_MARKS) => ( + Verdict::NotRun, + "the test command found no tests in it without the change".to_string(), + ), + (Some(_), Some(_)) if has_any(&without.output, BEFORE_ASSERT_MARKS) => { + (Verdict::FailsBeforeAsserting, excerpt(&without.output)) + } + (Some(_), Some(_)) => (Verdict::Proven, excerpt(&without.output)), + } +} + +/// A repository's unit test command narrowed to one test file, or `None` +/// when CoderHelm can't narrow that runner. Never passes with no tests: a +/// filter that matches nothing must not read as a test that passes. +pub fn scoped_cmd(base_cmd: &str, 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 low = base_cmd.to_ascii_lowercase(); + if low.contains("pytest") { + return Some(format!("{base_cmd} {file}")); + } + if low.trim_start().starts_with("go test") { + let dir = file.rsplit_once('/').map_or(".", |(d, _)| d); + return Some(format!("go test ./{dir}/")); + } + super::build_scoped_test_cmd(base_cmd, &[file.to_string()]) + .map(|c| c.replace(" --passWithNoTests", "")) +} + +/// 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 "); + output + .split(&mark) + .skip(1) + .map(|block| { + let body = block.split_once('\n').map_or("", |(_, b)| b); + let end = body + .find(&format!("--- {kind} failed")) + .or_else(|| body.find(test_package::STEP_MARK)) + .unwrap_or(body.len()); + body[..end].trim().to_string() + }) + .collect() +} + +/// Each step's run from a sandbox script's codes and output: the failing +/// steps' outputs are printed in order. +pub fn file_runs(codes: &[Option], output: &str, kind: &str) -> Vec { + let mut failures = failing_outputs(output, kind).into_iter(); + codes + .iter() + .map(|c| FileRun { + code: *c, + output: match c { + Some(n) if *n != 0 => failures.next().unwrap_or_default(), + _ => String::new(), + }, + }) + .collect() +} + +// ── What the diff shows ──────────────────────────────────────────────────── + +/// The change as the check reads it: every changed path and its status. +pub type Diff = [(String, String, String)]; + +/// The new and changed test files (never a removed one, never a snapshot). +pub fn changed_tests(diff: &Diff) -> Vec { + diff.iter() + .filter(|(p, status, _)| { + status != "removed" && is_test_path(p) && !p.contains("__snapshots__/") + }) + .map(|(p, _, _)| p.clone()) + .collect() +} + +fn changes_code(diff: &Diff) -> bool { + diff.iter().any(|(p, _, _)| !is_test_path(p)) +} + +const OUTSIDE_LINE: &str = "outside the plan:"; + +/// The coder's reasons for files outside the plan, from its notes +/// (`Outside the plan: : `). +pub fn reasons(notes: &str) -> Vec<(String, String)> { + notes + .lines() + .filter_map(|l| { + let l = l.trim().trim_start_matches(['-', '*']).trim(); + let at = l.to_ascii_lowercase().find(OUTSIDE_LINE)?; + let rest = l[at + OUTSIDE_LINE.len()..].trim(); + let (path, why) = rest.split_once(": ")?; + let path = path.trim().trim_matches('`').trim(); + let why = why.trim(); + (!path.is_empty() && !why.is_empty()).then(|| (path.to_string(), why.to_string())) + }) + .collect() +} + +fn norm(p: &str) -> String { + super::generators::normalize_path(p) +} + +/// The changed files that are no part of the plan: not a task's file (or +/// under a task's directory), not a test, lockfile or settled generated +/// output, not a dependent the plan updates. Each carries the coder's +/// reason when its notes give one. +pub fn outside_plan( + changed: &[String], + plan: &PlanResult, + generated: &[String], + notes: &str, +) -> Vec { + let planned: Vec = super::feature::plan_files::planned_files(&plan.tasks) + .into_iter() + .map(|f| norm(&f.path)) + .collect(); + // A plan that names no files states no scope to hold the change to. + if planned.is_empty() { + return Vec::new(); + } + let updates: Vec = plan + .fix + .as_ref() + .map(|d| { + d.habits + .affected + .iter() + .filter(|a| a.updates()) + .map(|a| norm(a.path())) + .collect() + }) + .unwrap_or_default(); + let why = reasons(notes); + changed + .iter() + .filter(|c| { + let c = norm(c); + let in_plan = planned + .iter() + .any(|p| *p == c || (p.ends_with('/') && c.starts_with(p.as_str()))); + !(in_plan + || updates.contains(&c) + || is_test_path(&c) + || common::lockfile_sync::lock_manager(&c).is_some() + || generated + .iter() + .any(|g| super::generators::glob_match(g, &c))) + }) + .map(|c| OutsidePlan { + path: c.clone(), + why: why + .iter() + .find(|(p, _)| norm(p) == norm(c)) + .map(|(_, w)| w.clone()) + .unwrap_or_default(), + }) + .collect() +} + +/// The dependents of this repository the plan updates that the branch +/// doesn't touch. +pub fn not_updated(changed: &[String], plan: &PlanResult, own_repo: &str) -> Vec { + let Some(d) = plan.fix.as_ref() else { + return Vec::new(); + }; + d.habits + .affected + .iter() + .filter(|a| a.updates() && a.repo().is_none_or(|r| r.eq_ignore_ascii_case(own_repo))) + .map(|a| a.path().to_string()) + .filter(|p| !p.is_empty() && !changed.iter().any(|c| norm(c) == norm(p))) + .collect() +} + +/// Reads the change against the plan and runs the changed tests with and +/// without it. +pub async fn check_once( + bench: &dyn Bench, + diff: &Diff, + plan: &PlanResult, + own_repo: &str, + generated: &[String], + notes: &str, +) -> PrFacts { + let changed: Vec = diff.iter().map(|(p, _, _)| p.clone()).collect(); + let fix = plan.fix.as_ref(); + let mut facts = PrFacts { + bug: fix.is_some_and(|d| d.intent.is_bug()), + outside_plan: outside_plan(&changed, plan, generated, notes), + not_updated: not_updated(&changed, plan, own_repo), + ..Default::default() + }; + let tests = changed_tests(diff); + if tests.is_empty() { + facts.no_tests = "the change adds or changes no test file".to_string(); + return facts; + } + if !changes_code(diff) { + facts.no_tests = "the change is only tests, so there is no fix to take out".to_string(); + return facts; + } + let (run, extra) = tests.split_at(tests.len().min(MAX_TEST_FILES)); + match bench.run(run).await { + Ok(runs) => { + let none = FileRun::default(); + for (i, path) in run.iter().enumerate() { + let (verdict, detail) = verdict( + runs.with.get(i).unwrap_or(&none), + runs.without.get(i).unwrap_or(&none), + ); + facts.tests.push(TestResult { + path: path.clone(), + verdict, + detail, + }); + } + } + Err(why) => { + for path in run { + facts.tests.push(TestResult { + path: path.clone(), + verdict: Verdict::NotRun, + detail: why.clone(), + }); + } + } + } + for path in extra { + facts.tests.push(TestResult { + path: path.clone(), + verdict: Verdict::NotRun, + detail: format!("only the first {MAX_TEST_FILES} test files are run on their own"), + }); + } + facts +} + +/// Whether a bug's plan says no failing test can be written. +fn repro_waived(plan: &PlanResult) -> bool { + plan.fix + .as_ref() + .is_some_and(|d| !d.habits.repro.not_feasible.trim().is_empty()) +} + +/// What the coder must fix, one line each. Empty when the change holds. +pub fn blocking(f: &PrFacts, plan: &PlanResult) -> Vec { + let mut out = Vec::new(); + let repro = plan + .fix + .as_ref() + .map(|d| d.habits.repro.test.trim().to_string()) + .unwrap_or_default(); + for t in &f.tests { + match t.verdict { + Verdict::PassesEitherWay => out.push(format!( + "`{}` passes with the change taken out, so it doesn't test the change. Make it assert the behaviour the change adds or fixes (it must fail on the base code), through code that exists on the base.", + t.path + )), + Verdict::FailsWithChange => out.push(format!( + "`{}` fails with the change in place ({}). Fix the code or the test until it passes.", + t.path, t.detail + )), + Verdict::FailsBeforeAsserting if f.bug && (repro.is_empty() || norm(&repro) == norm(&t.path)) => out.push(format!( + "`{}` fails on the base code before any assertion runs ({}), so it doesn't show the reported failure. Test through an entry point that exists on the base, so the test builds there and fails on its assertion.", + t.path, t.detail + )), + _ => {} + } + } + if f.bug && f.tests.is_empty() && !repro_waived(plan) && f.no_tests.contains("no test file") { + out.push("This is a bug fix and the change has no test that fails without it. Add the test that reproduces the reported failure (it must fail on the base code and pass with the fix).".to_string()); + } + for o in f.outside_plan.iter().filter(|o| o.why.is_empty()) { + out.push(format!( + "`{}` was changed and is no task of the plan. Put it back with `restore_file` (omit `from_ref`), or, when the change truly needs it, say why in your Evidence on a line `Outside the plan: {}: `.", + o.path, o.path + )); + } + for p in &f.not_updated { + out.push(format!( + "The plan says `{p}` depends on this change and is updated with it, but the branch doesn't touch it. Update it." + )); + } + out +} + +/// The fix round's instructions. +pub fn fix_feedback(lines: &[String]) -> String { + format!( + "The check after the build ran each new or changed test with and without your change, and compared the changed files with the plan. Fix every item:\n{}\nDo not delete or skip a test to settle an item.", + lines + .iter() + .map(|l| format!("- {l}")) + .collect::>() + .join("\n") + ) +} + +/// What is still open after the fix rounds, for Open items. +pub fn open_findings(f: &PrFacts, plan: &PlanResult) -> Vec { + blocking(f, plan) + .into_iter() + .map(|l| { + let (point, settle) = if l.contains("no task of the plan") { + ( + "Changed outside the plan", + "CoderHelm restores it or records why the change needs it in its next round on this pull request.", + ) + } else if l.contains("depends on this change") { + ( + "Dependent not updated", + "CoderHelm updates it in its next round on this pull request.", + ) + } else { + ( + "Test doesn't prove the change", + "CoderHelm rewrites the test in its next round on this pull request; CI's result alone doesn't settle it.", + ) + }; + Finding { + point: point.to_string(), + detail: l.split(". ").next().unwrap_or(&l).trim_end_matches('.').to_string() + ".", + settle: settle.to_string(), + ..Default::default() + } + }) + .collect() +} + +fn test_line(t: &TestResult) -> String { + let detail = |d: &str| { + if d.is_empty() { + String::new() + } else { + format!(": `{d}`") + } + }; + match t.verdict { + Verdict::Proven => format!( + "- `{}`: fails without the change{}; passes with it.", + t.path, + detail(&t.detail) + ), + Verdict::FailsBeforeAsserting => format!( + "- `{}`: can't build or load without the change{}; passes with it. It covers the new code, it doesn't show a failure on the old.", + t.path, + detail(&t.detail) + ), + Verdict::PassesEitherWay => format!( + "- `{}`: passes with and without the change, so it doesn't test it yet.", + t.path + ), + Verdict::FailsWithChange => format!( + "- `{}`: fails with the change{}.", + t.path, + detail(&t.detail) + ), + Verdict::NotRun => format!("- `{}`: not run both ways here ({}).", t.path, t.detail), + } +} + +/// The pull request's section: the proof the tests give, what the files' +/// history showed, who the change affects, and what changed outside the +/// plan. Empty when there is nothing to say. +pub fn section(plan: &PlanResult, f: &PrFacts) -> String { + let mut out = String::new(); + let h = plan.fix.as_ref().map(|d| &d.habits); + let repro = h.map(|h| &h.repro); + if !f.tests.is_empty() { + out.push_str(if f.bug { + "**Reproduced, then fixed** (each new or changed test run on the base code with only the tests added, then on this branch)\n" + } else { + "**The tests fail without the change** (each new or changed test run on the base code with only the tests added, then on this branch)\n" + }); + for t in &f.tests { + out.push_str(&test_line(t)); + 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!( + "**No failing test for this fix:** {}. Proof instead: {}.\n\n", + r.not_feasible.trim().trim_end_matches('.'), + r.next_best.trim().trim_end_matches('.') + )); + } + if let Some(h) = h { + let hist: Vec<&habits::AreaHistory> = h + .area_history + .iter() + .filter(|a| !a.found.trim().is_empty()) + .collect(); + if !hist.is_empty() { + out.push_str("**History of the touched files**\n"); + for a in hist { + let refs = if a.refs.is_empty() { + String::new() + } else { + format!(" ({})", a.refs.join(", ")) + }; + out.push_str(&format!("- `{}`{refs}: {}", a.path.trim(), a.found.trim())); + if !a.bearing.trim().is_empty() { + out.push_str(&format!(" For this change: {}", a.bearing.trim())); + } + out.push('\n'); + } + out.push('\n'); + } + let affected: Vec<&habits::Affected> = h + .affected + .iter() + .filter(|a| !a.where_.trim().is_empty()) + .collect(); + if !affected.is_empty() { + out.push_str("**Who this affects**\n"); + for a in affected { + let uses = if a.uses.trim().is_empty() { + String::new() + } else { + format!(" (uses {})", a.uses.trim()) + }; + let state = if a.action.trim() == habits::UNCHECKED { + "found by a search of the team's repositories; the plan didn't settle whether it must change".to_string() + } else if !a.updates() { + format!("safe: {}", a.why.trim()) + } else if f.not_updated.iter().any(|p| norm(p) == norm(a.path())) { + "planned to change with this, not changed yet".to_string() + } else if a.repo().is_some() { + format!("changes in its own pull request: {}", a.why.trim()) + } else { + "updated in this pull request".to_string() + }; + out.push_str(&format!("- `{}`{uses}: {state}\n", a.where_.trim())); + } + out.push('\n'); + } else if !h.no_outside_use.trim().is_empty() { + out.push_str(&format!( + "**Who this affects:** nothing outside this repository ({}).\n\n", + h.no_outside_use.trim().trim_end_matches('.') + )); + } + } + if !f.outside_plan.is_empty() { + out.push_str("**Changed outside the plan's files**\n"); + for o in &f.outside_plan { + out.push_str(&format!( + "- `{}`: {}\n", + o.path, + if o.why.is_empty() { + "no reason recorded yet" + } else { + o.why.as_str() + } + )); + } + out.push('\n'); + } + if out.is_empty() { + return out; + } + format!( + "{START}\n### Before and after the code\n{}\n{END}", + out.trim_end() + ) +} + +/// The description with the section in place: replaced where it stands, +/// added at the end the first time, taken out when there is none. +pub fn shape_body(body: String, section: &str) -> String { + let stripped = match (body.find(START), body.find(END)) { + (Some(s), Some(e)) if e > s => { + format!("{}{}", &body[..s], &body[e + END.len()..]) + } + _ => body.clone(), + }; + if section.is_empty() { + return if stripped == body { + body + } else { + format!("{}\n", stripped.trim_end()) + }; + } + match (body.find(START), body.find(END)) { + (Some(s), Some(e)) if e > s => { + format!("{}{section}{}", &body[..s], &body[e + END.len()..]) + } + _ => format!("{}\n\n{section}\n", body.trim_end()), + } +} + +// ── The sandbox ──────────────────────────────────────────────────────────── + +/// Runs the test files in the sandbox on the branch and on a temporary +/// branch holding the base with only those files. +pub struct SandboxBench<'a> { + pub runner: super::test_bug::Runner<'a>, + pub base_branch: &'a str, + pub branch: &'a str, +} + +const KIND: &str = "unit"; + +#[async_trait::async_trait] +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 mut steps: Vec = Vec::new(); + let tree: Vec = r + .github + .get_tree(r.owner, r.repo, self.branch) + .await + .map_err(|e| e.to_string())? + .into_iter() + .map(|e| e.path) + .collect(); + let install: Vec = files + .first() + .and_then(|f| test_package::package_of(&tree, f, &|_| None)) + .and_then(|p| test_package::check_steps(&p)) + .map(|s| s.into_iter().filter(|s| s.kind == "install").collect()) + .unwrap_or_default(); + 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") + })?; + steps.push(Step { kind: KIND, cmd }); + } + let head = r + .github + .get_ref(r.owner, r.repo, self.branch) + .await + .map_err(|e| e.to_string())?; + let base_sha = r + .github + .get_ref(r.owner, r.repo, self.base_branch) + .await + .map_err(|e| e.to_string())?; + let temp = format!("{}-without-change", self.branch); + // One left by a step that was cut off is in the way of a new one. + let _ = r.github.delete_branch(r.owner, r.repo, &temp).await; + r.github + .create_branch(r.owner, r.repo, &temp, &base_sha) + .await + .map_err(|e| format!("a branch for the check couldn't be made ({e})"))?; + let both = async { + for f in files { + let content = r + .github + .read_file(r.owner, r.repo, f, self.branch) + .await + .map_err(|e| e.to_string())?; + let sha = r.github.get_file_sha(r.owner, r.repo, f, &temp).await.ok(); + r.github + .write_file( + r.owner, + r.repo, + f, + &content, + &temp, + "test: the changed tests on the code before the change", + sha.as_deref(), + ) + .await + .map_err(|e| e.to_string())?; + } + let before_sha = r + .github + .get_ref(r.owner, r.repo, &temp) + .await + .map_err(|e| e.to_string())?; + // Side by side: each waits on its own sandbox build. + let (with, without) = tokio::join!( + r.run_at(&head, &steps, None), + r.run_at(&before_sha, &steps, None) + ); + Ok::<_, String>((with?, without?)) + } + .await; + if let Err(e) = r.github.delete_branch(r.owner, r.repo, &temp).await { + warn!(error = %e, branch = %temp, "Could not delete the branch of the test check"); + } + let ((with_codes, with_out), (without_codes, without_out)) = both?; + let per_file = |codes: &[Option], out: &str| { + let failed_installs = codes.iter().take(installs).any(|c| *c != Some(0)); + let runs = file_runs(&codes[installs.min(codes.len())..], out, KIND); + (failed_installs, runs) + }; + let (with_broken, with) = per_file(&with_codes, &with_out); + let (without_broken, without) = per_file(&without_codes, &without_out); + if with_broken || without_broken { + return Err("the package's install failed in the sandbox".to_string()); + } + Ok(Runs { with, without }) + } +} + +/// The check on the open pull request. `Ok(None)` when the plan plans no +/// code. A problem gets a fix round; what is still open after the rounds is +/// in the facts ([`open_findings`]). +pub async fn gate( + w: &super::proof::Work<'_>, + evidence: &mut super::proof::RunEvidence, + usage: &mut crate::models::TokenUsage, + has_time: impl Fn() -> bool, + secs_left: impl Fn() -> u64, +) -> Result, GateStop> { + let head = w.head().await; + let standing = w.ledger.update(|l| { + if !l.habits.unchanged(&head) { + return None; + } + l.habits.reused(); + l.habits_outcome.clone() + }); + if let Some(standing) = standing { + return standing.map_err(GateStop::Why); + } + let outcome = check_and_fix(w, evidence, usage, has_time, secs_left).await; + if outcome == Err(GateStop::NeedsTime) { + return outcome; + } + let head = w.head().await; + let kept = outcome.clone().map_err(|e| match e { + GateStop::Why(why) => why, + GateStop::NeedsTime => String::new(), + }); + w.ledger.update(|l| { + l.habits.head = head; + l.habits_outcome = Some(kept); + }); + w.save_ledger().await; + outcome +} + +/// A bench for a step with no time for the sandbox: nothing runs, and each +/// test says so. +struct NoTime; + +#[async_trait::async_trait] +impl Bench for NoTime { + async fn run(&self, _files: &[String]) -> Result { + Err("no step of the run had the time for the two sandbox runs; the repository's CI runs the tests on this pull request".to_string()) + } +} + +async fn check_and_fix( + w: &super::proof::Work<'_>, + evidence: &mut super::proof::RunEvidence, + usage: &mut crate::models::TokenUsage, + has_time: impl Fn() -> bool, + secs_left: impl Fn() -> u64, +) -> Result, GateStop> { + let own_repo = format!("{}/{}", w.msg.repo_owner, w.msg.repo_name); + if super::feature::plan_files::planned_files(&w.plan.tasks).is_empty() { + return Ok(None); + } + loop { + let diff = w + .github + .compare_files_with_patches( + &w.msg.repo_owner, + &w.msg.repo_name, + &w.msg.base_branch, + w.branch, + ) + .await + .map_err(|e| GateStop::Why(format!("the diff couldn't be read ({e})")))?; + let paths: Vec = diff.iter().map(|(p, _, _)| p.clone()).collect(); + let work = super::run_end::work_files(&paths, &w.msg.ticket_id); + let diff: Vec<(String, String, String)> = diff + .into_iter() + .filter(|(p, _, _)| work.contains(p)) + .collect(); + let needs_sandbox = !changed_tests(&diff).is_empty() && changes_code(&diff); + let short = needs_sandbox && secs_left() < SANDBOX_STEP_SECS; + if short + && !w + .ledger + .update(|l| std::mem::replace(&mut l.habits_waited, true)) + { + w.save_ledger().await; + return Err(GateStop::NeedsTime); + } + let sandbox = SandboxBench { + runner: super::test_bug::Runner { + state: w.state, + github: w.github, + owner: &w.msg.repo_owner, + repo: &w.msg.repo_name, + team_id: &w.msg.team_id, + run_id: w.run_id, + provider: w.provider, + }, + base_branch: &w.msg.base_branch, + branch: w.branch, + }; + let bench: &dyn Bench = if short { &NoTime } else { &sandbox }; + let facts = check_once( + bench, + &diff, + w.plan, + &own_repo, + w.generated, + &evidence.notes, + ) + .await; + let blocking = blocking(&facts, w.plan); + info!( + run_id = w.run_id, + tests = facts.tests.len(), + outside_plan = facts.outside_plan.len(), + blocking = blocking.len(), + rounds = w.ledger.update(|l| l.habits.rounds), + "Check of the change against the plan's habits complete" + ); + let proven = facts + .tests + .iter() + .filter(|t| t.verdict == Verdict::Proven) + .count(); + if blocking.is_empty() { + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + &format!( + "Tests and scope check passed: {proven} of {} changed test file(s) fail without the change and pass with it; no file changed outside the plan without a reason", + facts.tests.len() + ), + ) + .await; + return Ok(Some(facts)); + } + w.report_findings("habits", blocking.len()).await; + let head = w.head().await; + w.ledger.update(|l| l.habits.checked(&head, blocking.len())); + let licence = if w.ledger.update(|l| l.habits.may_fix(MAX_FIX_ROUNDS)) && has_time() { + super::stop_judge::cycle_licence( + w.state, + w.msg, + w.run_id, + "habits_check", + w.ledger.update(|l| l.habits.rounds), + MAX_FIX_ROUNDS, + &super::stop_judge::evidence_lines("tests and scope check", &blocking), + ) + .await + } else { + None + }; + let Some(licence) = licence else { + w.save_ledger().await; + return Ok(Some(facts)); + }; + w.ledger.update(|l| l.habits.start_fix(licence)); + w.save_ledger().await; + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + &format!( + "Tests and scope check found {} item(s), fixing: {}", + blocking.len(), + common::truncate_str(&blocking.join(" "), 600) + ), + ) + .await; + let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "implement").await; + let fixed = super::implement::run( + w.state, + w.msg, + w.github, + w.plan, + w.branch, + w.rules, + w.repo_instructions, + Some(&fix_feedback(&blocking)), + "medium", + w.provider, + usage, + w.file_cache, + Some(w.run_id), + w.deadline, + true, + ) + .await; + w.ledger.update(|l| l.habits.end_fix()); + w.save_ledger().await; + let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, super::PASS_CHECKS).await; + match fixed { + Ok(r) => evidence.merge(r.evidence), + Err(e) => { + warn!(run_id = w.run_id, error = %e, "The fix round of the tests and scope check failed"); + return Ok(Some(facts)); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::passes::fix_location::FixDecision; + use crate::passes::habits::{Affected, AreaHistory, Habits, Repro}; + use crate::passes::triage::TicketIntent; + + fn run(code: i32, output: &str) -> FileRun { + FileRun { + code: Some(code), + output: output.into(), + } + } + + pub(crate) struct Fake(pub Result); + + #[async_trait::async_trait] + impl Bench for Fake { + async fn run(&self, _files: &[String]) -> Result { + self.0.clone() + } + } + + fn plan(tasks: &str, intent: TicketIntent, habits: Habits) -> PlanResult { + PlanResult { + proposal: String::new(), + design: String::new(), + tasks: tasks.into(), + spec: String::new(), + repo_tasks: Vec::new(), + fix: Some(FixDecision { + intent, + habits, + ..Default::default() + }), + } + } + + fn diff(paths: &[&str]) -> Vec<(String, String, String)> { + paths + .iter() + .map(|p| (p.to_string(), "modified".to_string(), String::new())) + .collect() + } + + const TASKS: &str = "- [ ] src/cart/total.test.ts: [modify] Three lines of 0.335\n- [ ] src/cart/total.ts: [modify] Round per line\n"; + + #[test] + fn two_runs_of_one_test_read_as_one_verdict() { + let pass = run(0, ""); + let assertion = run( + 1, + "FAIL src/cart/total.test.ts\nAssertionError: expected 1 to be 1.01", + ); + assert_eq!( + verdict(&pass, &assertion), + ( + Verdict::Proven, + "AssertionError: expected 1 to be 1.01".to_string() + ) + ); + assert_eq!(verdict(&pass, &pass).0, Verdict::PassesEitherWay); + let import = run( + 1, + "Error: Failed to resolve import \"./perLine\" from src/cart/total.test.ts", + ); + assert_eq!(verdict(&pass, &import).0, Verdict::FailsBeforeAsserting); + assert_eq!(verdict(&assertion, &assertion).0, Verdict::FailsWithChange); + // A filter that matched nothing is never a test that failed or passed. + let none = run(1, "No test files found, exiting with code 1"); + assert_eq!(verdict(&none, &none).0, Verdict::NotRun); + assert_eq!(verdict(&pass, &none).0, Verdict::NotRun); + assert_eq!(verdict(&FileRun::default(), &pass).0, Verdict::NotRun); + } + + #[test] + fn a_test_command_is_narrowed_to_one_file_and_never_passes_on_nothing() { + let c = scoped_cmd("pnpm exec vitest run", "src/cart/total.test.ts").unwrap(); + assert_eq!(c, "pnpm exec vitest run total.test.ts"); + assert!(!scoped_cmd("pnpm test", "src/a.test.ts") + .unwrap() + .contains("passWithNoTests")); + assert_eq!( + scoped_cmd("python -m pytest -q", "tests/test_total.py").as_deref(), + Some("python -m pytest -q tests/test_total.py") + ); + assert_eq!( + scoped_cmd("go test ./...", "pkg/cart/total_test.go").as_deref(), + Some("go test ./pkg/cart/") + ); + assert_eq!(scoped_cmd("cargo test", "src/total.rs"), None); + assert_eq!(scoped_cmd("pytest", "tests/$(id).py"), None); + assert_eq!(scoped_cmd("pytest", "../outside.py"), None); + } + + #[test] + fn each_failing_step_gets_its_own_output() { + let steps = vec![ + Step { + kind: KIND, + cmd: "a".into(), + }, + Step { + kind: KIND, + cmd: "b".into(), + }, + Step { + kind: KIND, + cmd: "c".into(), + }, + ]; + // The script's own shape: failing steps' tails, then one mark per step. + assert!(test_package::sandbox_script(&steps, None) + .contains("--- unit failed (exit $ch_t1) ---")); + let out = "--- unit failed (exit 1) ---\nexpected 1 to be 1.01\n\n--- unit failed (exit 2) ---\nNo test files found\n\nCODERHELM_TEST_STEP 1 1\nCODERHELM_TEST_STEP 2 0\nCODERHELM_TEST_STEP 3 2\n"; + let codes = test_package::step_codes(out, 3); + let runs = file_runs(&codes, out, KIND); + assert_eq!(runs[0], run(1, "expected 1 to be 1.01")); + assert_eq!(runs[1], run(0, "")); + assert_eq!(runs[2], run(2, "No test files found")); + } + + #[tokio::test] + async fn a_test_that_passes_either_way_goes_back_to_the_coder() { + let p = plan(TASKS, TicketIntent::Bug, Habits::default()); + let bench = Fake(Ok(Runs { + with: vec![run(0, "")], + without: vec![run(0, "")], + })); + let d = diff(&["src/cart/total.ts", "src/cart/total.test.ts"]); + let f = check_once(&bench, &d, &p, "acme/shop-api", &[], "").await; + assert_eq!(f.tests[0].verdict, Verdict::PassesEitherWay); + let b = blocking(&f, &p); + assert_eq!(b.len(), 1); + assert!(b[0].contains("passes with the change taken out")); + assert!(fix_feedback(&b).contains("Do not delete or skip a test")); + let open = open_findings(&f, &p); + assert_eq!(open[0].point, "Test doesn't prove the change"); + assert!(section(&p, &f).contains("passes with and without the change")); + } + + #[tokio::test] + async fn a_bug_fix_carries_the_failing_then_passing_result() { + let p = plan( + TASKS, + TicketIntent::Bug, + Habits { + repro: Repro { + test: "src/cart/total.test.ts".into(), + ..Default::default() + }, + ..Default::default() + }, + ); + let bench = Fake(Ok(Runs { + with: vec![run(0, "")], + without: vec![run(1, "AssertionError: expected 1 to be 1.01")], + })); + let d = diff(&["src/cart/total.ts", "src/cart/total.test.ts"]); + let f = check_once(&bench, &d, &p, "acme/shop-api", &[], "").await; + assert!(blocking(&f, &p).is_empty()); + let s = section(&p, &f); + assert!(s.starts_with(START) && s.ends_with(END)); + assert!(s.contains("**Reproduced, then fixed**")); + assert!(s.contains("- `src/cart/total.test.ts`: fails without the change: `AssertionError: expected 1 to be 1.01`; passes with it.")); + } + + #[tokio::test] + async fn a_bug_test_that_cannot_build_on_the_base_does_not_reproduce() { + let p = plan(TASKS, TicketIntent::Bug, Habits::default()); + let bench = Fake(Ok(Runs { + with: vec![run(0, "")], + without: vec![run(1, "Error: Cannot find module './perLine'")], + })); + let d = diff(&["src/cart/total.ts", "src/cart/total.test.ts"]); + let f = check_once(&bench, &d, &p, "acme/shop-api", &[], "").await; + assert!(blocking(&f, &p)[0].contains("before any assertion runs")); + // For new work the same result is a test of new code: noted, not blocking. + let feature = plan(TASKS, TicketIntent::Feature, Habits::default()); + let f = check_once(&bench, &d, &feature, "acme/shop-api", &[], "").await; + assert!(blocking(&f, &feature).is_empty()); + assert!(section(&feature, &f).contains("It covers the new code")); + } + + #[tokio::test] + async fn a_bug_without_a_test_needs_the_plans_reason_and_next_best_proof() { + let d = diff(&["config/limits.yml"]); + let tasks = "- [ ] config/limits.yml: [modify] Raise the limit\n"; + let bare = plan(tasks, TicketIntent::Bug, Habits::default()); + let f = check_once( + &Fake(Err("unused".into())), + &d, + &bare, + "acme/shop-api", + &[], + "", + ) + .await; + assert!(blocking(&f, &bare)[0].contains("no test that fails without it")); + let waived = plan( + tasks, + TicketIntent::Bug, + Habits { + repro: Repro { + not_feasible: "a value in a YAML file no test loads".into(), + next_best: "GET /limits returns 50 before and 100 after".into(), + ..Default::default() + }, + ..Default::default() + }, + ); + let f = check_once( + &Fake(Err("unused".into())), + &d, + &waived, + "acme/shop-api", + &[], + "", + ) + .await; + assert!(blocking(&f, &waived).is_empty()); + let s = section(&waived, &f); + assert!(s.contains("**No failing test for this fix:** a value in a YAML file no test loads. Proof instead: GET /limits returns 50 before and 100 after.")); + } + + #[tokio::test] + async fn tests_that_could_not_run_are_said_so_and_block_nothing() { + let p = plan(TASKS, TicketIntent::Feature, Habits::default()); + let d = diff(&["src/cart/total.ts", "src/cart/total.test.ts"]); + let f = check_once(&NoTime, &d, &p, "acme/shop-api", &[], "").await; + assert_eq!(f.tests[0].verdict, Verdict::NotRun); + assert!(blocking(&f, &p).is_empty()); + assert!(section(&p, &f).contains("not run both ways here (no step of the run had the time")); + // More files than are run on their own: the rest are named. + let many: Vec = (0..10).map(|i| format!("src/t{i}.test.ts")).collect(); + let mut paths: Vec<&str> = many.iter().map(String::as_str).collect(); + paths.push("src/cart/total.ts"); + let runs = Runs { + with: vec![run(0, ""); MAX_TEST_FILES], + without: vec![run(1, "expected"); MAX_TEST_FILES], + }; + let f = check_once(&Fake(Ok(runs)), &diff(&paths), &p, "acme/shop-api", &[], "").await; + assert_eq!(f.tests.len(), 10); + assert_eq!( + f.tests + .iter() + .filter(|t| t.verdict == Verdict::NotRun) + .count(), + 2 + ); + } + + #[test] + fn a_file_outside_the_plan_is_restored_or_carries_its_reason() { + let p = plan( + "- [ ] src/cart/total.ts: [modify] Round per line\n- [ ] docs/: [modify] The rounding note\n", + TicketIntent::Feature, + Habits { + affected: vec![Affected { where_: "src/invoice/pdf.ts".into(), action: "update".into(), ..Default::default() }], + ..Default::default() + }, + ); + let changed: Vec = [ + "src/cart/total.ts", + "src/cart/total.test.ts", + "docs/rounding.md", + "pnpm-lock.yaml", + "src/generated/schema.ts", + "src/invoice/pdf.ts", + "src/utils/format.ts", + "src/money.ts", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let notes = "Evidence: none needed\n- Outside the plan: `src/money.ts`: total.ts imports the new roundLine helper from it"; + let out = outside_plan(&changed, &p, &["src/generated/**".to_string()], notes); + assert_eq!( + out, + vec![ + OutsidePlan { + path: "src/utils/format.ts".into(), + why: String::new() + }, + OutsidePlan { + path: "src/money.ts".into(), + why: "total.ts imports the new roundLine helper from it".into() + }, + ] + ); + let f = PrFacts { + outside_plan: out, + ..Default::default() + }; + let b = blocking(&f, &p); + assert_eq!(b.len(), 1); + assert!(b[0].contains("`src/utils/format.ts` was changed and is no task of the plan")); + assert_eq!(open_findings(&f, &p)[0].point, "Changed outside the plan"); + let s = section(&p, &f); + assert!(s.contains("- `src/money.ts`: total.ts imports the new roundLine helper from it")); + assert!(s.contains("- `src/utils/format.ts`: no reason recorded yet")); + // A plan that names no files states no scope. + let open = plan("Do the thing", TicketIntent::Feature, Habits::default()); + assert!(outside_plan(&changed, &open, &[], "").is_empty()); + } + + #[test] + fn a_dependent_the_plan_updates_must_be_in_the_branch() { + let p = plan( + "- [ ] src/cart/total.ts: [modify] x\n- [ ] src/invoice/pdf.ts: [modify] y\n", + TicketIntent::Feature, + Habits { + affected: vec![ + Affected { + where_: "src/invoice/pdf.ts".into(), + uses: "cartTotal".into(), + action: "update".into(), + ..Default::default() + }, + Affected { + where_: "acme/storefront:src/checkout.ts".into(), + action: "update".into(), + why: "reads the per-line total".into(), + ..Default::default() + }, + Affected { + where_: "src/report.ts".into(), + action: "safe".into(), + why: "reads `amount`, unchanged".into(), + ..Default::default() + }, + ], + area_history: vec![AreaHistory { + path: "src/cart/total.ts".into(), + found: "Per-line rounding was reverted in #74.".into(), + refs: vec!["#74".into()], + bearing: "The export changes with it this time.".into(), + }], + ..Default::default() + }, + ); + let changed = vec!["src/cart/total.ts".to_string()]; + let missing = not_updated(&changed, &p, "acme/shop-api"); + assert_eq!(missing, vec!["src/invoice/pdf.ts"]); + let f = PrFacts { + not_updated: missing, + ..Default::default() + }; + assert!(blocking(&f, &p)[0].contains("the branch doesn't touch it")); + let s = section(&p, &f); + assert!(s.contains( + "- `src/invoice/pdf.ts` (uses cartTotal): planned to change with this, not changed yet" + )); + assert!(s.contains("- `acme/storefront:src/checkout.ts`: changes in its own pull request: reads the per-line total")); + assert!(s.contains("- `src/report.ts`: safe: reads `amount`, unchanged")); + assert!(s.contains("- `src/cart/total.ts` (#74): Per-line rounding was reverted in #74. For this change: The export changes with it this time.")); + let done = PrFacts::default(); + assert!(section(&p, &done) + .contains("- `src/invoice/pdf.ts` (uses cartTotal): updated in this pull request")); + } + + #[test] + fn the_section_is_replaced_in_place_and_removed_when_empty() { + let body = "## Summary\nx\n".to_string(); + let one = shape_body(body.clone(), &format!("{START}\none\n{END}")); + assert!(one.contains("one")); + let two = shape_body(one.clone(), &format!("{START}\ntwo\n{END}")); + assert!(two.contains("two") && !two.contains("one")); + assert_eq!(two.matches(START).count(), 1); + assert_eq!( + shape_body(two.clone(), &format!("{START}\ntwo\n{END}")), + two + ); + assert_eq!(shape_body(two, ""), body); + assert_eq!(shape_body(body.clone(), ""), body); + } +} diff --git a/services/worker/src/passes/incidents/ah_coder_habits.rs b/services/worker/src/passes/incidents/ah_coder_habits.rs new file mode 100644 index 000000000..3473639ab --- /dev/null +++ b/services/worker/src/passes/incidents/ah_coder_habits.rs @@ -0,0 +1,286 @@ +//! ah. A bug fix that was right on its face and wrong four ways. The ticket +//! said cart totals were a cent off. The plan named two files and nothing +//! about them. The run: +//! +//! - wrote the fix first and a test after it that passed with or without +//! the fix, so nothing showed the bug had existed or was gone; +//! - rounded per line, the approach a pull request had shipped and another +//! had reverted two months earlier, for a reason one commit list away; +//! - changed the shape of a response field another of the team's +//! repositories read, and said nothing about that repository; +//! - listed "half up or half even?" as an open doubt at the bottom of the +//! finished pull request, after building one of the two; +//! - reformatted a helper file no task named. +//! +//! Guarantee: before code, the plan of a bug names the test that fails on +//! the code as it is (or why none can, and the next best proof) and that +//! test is the first task; the worker reads the history of the files the +//! plan modifies and a revert must be answered by name; every use of a +//! changed name the worker finds in the team's other repositories is +//! updated by a task or called safe with the reason, and the pull request +//! names it either way; a doubt that changes what is built is asked at +//! planning time with the default being built. After the build each new or +//! changed test is run with and without the change: one that passes either +//! way goes back to the coder, and so does a changed file outside the plan +//! with no reason. The pull request carries the failing and the passing +//! result. + +use super::fixture::{fn_src, run_passes_src}; +use crate::passes::fix_location::{self, send_back}; +use crate::passes::habits::{self, Dependents, Facts}; +use crate::passes::habits_check::{self, Bench, FileRun, Runs, Verdict}; +use crate::passes::plan::PlanResult; +use crate::passes::triage::TicketIntent; +use serde_json::json; + +const OWN: &str = "acme/shop-api"; + +const TASKS: &str = "- [ ] src/cart/total.ts: [modify] Round each line before summing\n- [ ] src/cart/total.test.ts: [modify] A cart of three lines at 0.335\n"; + +fn plan(tasks: &str, block: &str) -> PlanResult { + let reply = format!("```fix_location.json\n{block}\n```"); + let mut fix = fix_location::parse_for(&reply, TicketIntent::Bug).expect("a decision"); + habits::fold_questions(&mut fix); + PlanResult { + proposal: String::new(), + design: "## Design\nRound each line in `cartTotal`.".into(), + tasks: tasks.into(), + spec: String::new(), + repo_tasks: Vec::new(), + fix: Some(fix), + } +} + +/// What the worker reads for the draft: the revert in the file's commits, +/// the storefront's use of the field, one caller in the repository. +fn facts() -> Facts { + let commits = [ + json!({"sha": "9f8e7d6c5b4a", "commit": {"message": "Revert \"Round cart totals per line (#212)\" (#219)\n\nThis reverts commit 1a2b3c4.", "committer": {"date": "2026-01-20T10:00:00Z"}}}), + json!({"sha": "1a2b3c4d5e6f", "commit": {"message": "Round cart totals per line (#212)", "committer": {"date": "2026-01-14T10:00:00Z"}}}), + ]; + Facts { + own_repo: OWN.into(), + history: vec![habits::file_history("src/cart/total.ts", &commits)], + dependents: Dependents { + in_repo: vec![("src/invoice/pdf.ts".into(), "references `cartTotal`".into())], + other_repos: vec![( + "acme/storefront".into(), + "lineTotals".into(), + vec!["src/checkout/summary.tsx:88: cart.lineTotals.map((t) => t.amount)".into()], + )], + has_other_repos: true, + }, + } +} + +/// The plan as it used to be written: the files and nothing about them. +const BARE: &str = r#"{"fix_location": "code", "cause": "Totals are rounded once per cart.", + "evidence": {"basis": "code", "producer": {"kind": "code", "where": "acme/shop-api:src/cart/total.ts cartTotal"}, "scope": "one function"}, + "habits": {"surfaces": ["lineTotals"]}, + "questions": ["Should rounding be half up or half even?"]}"#; + +/// The plan after the one send-back. +const CAREFUL: &str = r##"{"fix_location": "code", "cause": "Totals are rounded once per cart.", + "evidence": {"basis": "code", "producer": {"kind": "code", "where": "acme/shop-api:src/cart/total.ts cartTotal"}, "scope": "one function"}, + "habits": { + "repro": {"test": "src/cart/total.test.ts", "fails_with": "three lines at 0.335 total 1.00, expected 1.02"}, + "area_history": [{"path": "src/cart/total.ts", "found": "Per-line rounding shipped in #212 and was reverted in #219: the ledger export still summed unrounded lines, so invoices stopped matching it.", "refs": ["#212", "#219"], "bearing": "This plan changes the export's sum in the same pull request."}], + "surfaces": ["lineTotals"], + "affected": [ + {"where": "acme/storefront:src/checkout/summary.tsx", "uses": "lineTotals[].amount", "action": "safe", "why": "it reads `amount`, which keeps its name and type; only its value is rounded"}, + {"where": "src/invoice/pdf.ts", "uses": "cartTotal", "action": "update", "why": "prints the per-line amounts"} + ], + "ask_early": [{"question": "Should rounding be half up or half even?", "default": "half up, as the invoice module already rounds", "depends_on": ["src/cart/total.ts"]}] + }}"##; + +const CAREFUL_TASKS: &str = "- [ ] src/cart/total.ts: [modify] Round each line before summing\n- [ ] src/invoice/pdf.ts: [modify] Print the rounded line amounts\n- [ ] src/cart/total.test.ts: [modify] A cart of three lines at 0.335\n"; + +#[test] +fn a_plan_of_files_alone_is_sent_back_with_what_the_worker_read() { + let draft = plan(TASKS, BARE); + let gaps = habits::plan_gaps(&draft, &facts()); + let back = send_back(&gaps); + // The reproduction, the revert by commit and date, the other + // repository's use by file and line, the caller in this one. + assert!(back.contains("`habits.repro`"), "{back}"); + assert!(back.contains("REVERT 9f8e7d6 2026-01-20"), "{back}"); + assert!(back.contains("acme/storefront uses `lineTotals`"), "{back}"); + assert!(back.contains("src/checkout/summary.tsx:88"), "{back}"); + assert!( + back.contains("`src/invoice/pdf.ts` (references `cartTotal`)"), + "{back}" + ); + assert_eq!(gaps.len(), 4, "{gaps:?}"); + + // A draft that ignores the send-back keeps each gap on the decision, + // and the other repository's use is named among those it affects. + let mut ignored = plan(TASKS, BARE); + let d = ignored.fix.as_mut().unwrap(); + habits::keep_open(d, &facts(), &gaps); + assert_eq!(d.open_gaps.len(), 4); + assert_eq!( + d.habits.affected[0].where_, + "acme/storefront:src/checkout/summary.tsx" + ); + let section = habits_check::section(&ignored, &habits_check::PrFacts::default()); + assert!(section.contains("`acme/storefront:src/checkout/summary.tsx` (uses `lineTotals`): found by a search of the team's repositories"), "{section}"); +} + +#[test] +fn the_careful_plan_passes_and_the_test_comes_first() { + let mut p = plan(CAREFUL_TASKS, CAREFUL); + assert_eq!(habits::plan_gaps(&p, &facts()), Vec::::new()); + + // The doubt is asked now, with the default the run builds, once. + let d = p.fix.as_ref().unwrap(); + assert_eq!(d.questions.len(), 1); + assert!(d.questions[0] + .starts_with("Should rounding be half up or half even? Proposed default: half up")); + assert!(d.questions[0].contains("I am building the default now")); + + // The reproducing test is the first task, so it is the first commit. + let test = d.habits.repro.test.clone(); + p.tasks = habits::put_repro_first(&p.tasks, &test).expect("the test task moves up"); + assert!(p.tasks.starts_with("- [ ] src/cart/total.test.ts:")); + + // The coder reads all of it in the design. + let d = p.fix.as_ref().unwrap(); + let design = habits::with_design_section(&p.design, d, &p.tasks); + assert!(design.contains("Write `src/cart/total.test.ts` before any other task")); + assert!(design.contains("reverted in #219")); + assert!(design.contains("**Update with it:** `src/invoice/pdf.ts`")); + assert!(design.contains("Build: half up, as the invoice module already rounds")); +} + +struct Sandbox(Runs); + +#[async_trait::async_trait] +impl Bench for Sandbox { + async fn run(&self, _files: &[String]) -> Result { + Ok(self.0.clone()) + } +} + +fn ran(code: i32, output: &str) -> FileRun { + FileRun { + code: Some(code), + output: output.into(), + } +} + +fn diff(paths: &[&str]) -> Vec<(String, String, String)> { + paths + .iter() + .map(|p| (p.to_string(), "modified".to_string(), String::new())) + .collect() +} + +#[tokio::test] +async fn a_test_that_passes_without_the_fix_and_a_stray_file_go_back_to_the_coder() { + let p = plan(CAREFUL_TASKS, CAREFUL); + // The first build: the test asserts nothing the fix changes, the + // dependent wasn't touched, and a helper was reformatted. + let first = diff(&[ + "src/cart/total.ts", + "src/cart/total.test.ts", + "src/utils/format.ts", + ]); + let both_pass = Sandbox(Runs { + with: vec![ran(0, "")], + without: vec![ran(0, "")], + }); + let f = + habits_check::check_once(&both_pass, &first, &p, OWN, &[], "Evidence: none needed").await; + let blocking = habits_check::blocking(&f, &p); + assert_eq!(blocking.len(), 3, "{blocking:?}"); + let feedback = habits_check::fix_feedback(&blocking); + assert!(feedback.contains("`src/cart/total.test.ts` passes with the change taken out")); + assert!(feedback.contains("`src/utils/format.ts` was changed and is no task of the plan")); + assert!(feedback.contains("`src/invoice/pdf.ts` depends on this change")); + // It is the coder's to fix: never a line for a person. + for phrase in crate::passes::ownership::HAND_OFF_PHRASES { + assert!(!feedback.to_lowercase().contains(phrase), "{phrase}"); + } + + // After the fix round: the test fails on the base on its assertion, the + // dependent is updated, the helper is back. + let second = diff(&[ + "src/cart/total.ts", + "src/cart/total.test.ts", + "src/invoice/pdf.ts", + ]); + let proven = Sandbox(Runs { + with: vec![ran(0, "")], + without: vec![ran( + 1, + "FAIL src/cart/total.test.ts\nAssertionError: expected 1 to be 1.02", + )], + }); + let f = habits_check::check_once(&proven, &second, &p, OWN, &[], "").await; + assert_eq!(f.tests[0].verdict, Verdict::Proven); + assert!(habits_check::blocking(&f, &p).is_empty()); + assert!(habits_check::open_findings(&f, &p).is_empty()); + + // The pull request carries the failing and the passing result, the + // history and who it affects; a second check rewrites it in place. + let body = "## Summary\nRounds each cart line.\n".to_string(); + let section = habits_check::section(&p, &f); + let out = habits_check::shape_body(body, §ion); + assert!(out.contains("**Reproduced, then fixed**")); + assert!(out.contains( + "fails without the change: `AssertionError: expected 1 to be 1.02`; passes with it." + )); + assert!(out.contains("`src/cart/total.ts` (#212, #219): Per-line rounding shipped in #212 and was reverted in #219")); + assert!(out.contains("`acme/storefront:src/checkout/summary.tsx` (uses lineTotals[].amount): safe: it reads `amount`")); + assert!(out.contains("`src/invoice/pdf.ts` (uses cartTotal): updated in this pull request")); + assert_eq!(habits_check::shape_body(out.clone(), §ion), out); +} + +#[test] +fn the_pipeline_still_does_each_of_these_at_its_place() { + // Planning: the worker reads the facts for the draft and its gaps go in + // the one send-back; what is left is kept, the test moves first and the + // coder's design carries the section. + let plan_src = include_str!("../plan.rs"); + let facts_at = plan_src + .find("habit_reader.facts(&draft).await") + .expect("facts read"); + let send_at = plan_src + .find("super::fix_location::send_back(&back)") + .expect("send-back"); + assert!( + facts_at < send_at, + "the facts are read before the send-back" + ); + assert!(plan_src[facts_at..send_at].contains("back.extend(habit_gaps.iter().cloned())")); + for call in [ + "super::habits::keep_open(d, &facts, &left)", + "super::habits::put_repro_first(&files.tasks, &test)", + "super::habits::with_design_section(&files.design, d, &files.tasks)", + "super::habits::fold_questions(&mut d)", + ] { + assert!(plan_src.contains(call), "{call}"); + } + // The planner is told, for every kind of ticket. + for intent in [TicketIntent::Bug, TicketIntent::Feature] { + assert!(fix_location::planner_guidance(intent).contains("\"habits\"")); + } + + // After the build: the check runs on the open pull request, takes a + // step of its own when the sandbox runs need one, and its result goes + // into the description and the open items. + let rp = run_passes_src(); + let gate = rp.find("habits_check::gate(").expect("the check runs"); + let after = &rp[gate..gate + 1400]; + assert!(after.contains("habits_check::GateStop::NeedsTime")); + assert!(after.contains("steps::Gate::Checks")); + assert!(after.contains("habits_check::open_findings(h, &plan_result)")); + assert!(rp.contains("habits: habits_pr.as_ref()")); + let pr_src = include_str!("../pr.rs"); + let with_checks = fn_src(pr_src, "fn with_checks("); + assert!(with_checks.contains("super::habits_check::shape_body(")); + // It asks for a step once, and the sandbox wait fits a step. + let check_src = include_str!("../habits_check.rs"); + assert!(check_src.contains("std::mem::replace(&mut l.habits_waited, true)")); + const { assert!(habits_check::SANDBOX_STEP_SECS < 900) }; +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 518a27d05..d12d8203f 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -23,6 +23,7 @@ mod ad_hand_back_reply; mod ae_budget_rounds; mod af_lockfiles_out_of_sync; mod ag_red_ci_ships_what_passes; +mod ah_coder_habits; mod b_open_pr_retry; mod c_codegen_egress; mod d_echoed_markers; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 164257557..cf1745060 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -804,6 +804,7 @@ mod continuation_tests { "The link and redirect check needs more time", "The failing-test rules need more time", "The new-feature rules need more time", + "Running the changed tests with and without the change needs a step of its own", ] { assert!(rp.contains(why), "no hand-off for: {why}"); } @@ -1215,6 +1216,8 @@ pub mod fix_location; pub mod formatter; pub(crate) mod generators; pub mod github_history; +pub mod habits; +pub mod habits_check; pub mod health_check; pub mod hidden_suggest; /// Hosted side of hybrid: forward a held event to a self-hosted install again. @@ -6599,6 +6602,7 @@ async fn run_passes( links: "", test_fix: None, feature: None, + habits: None, keep_commits: stacked_on .as_ref() .is_some_and(|d| !d.unresolved.is_empty()), @@ -6821,6 +6825,38 @@ async fn run_passes( if let Some(f) = &feature_pr { gaps.extend(feature::open_findings(f)); } + // Each new or changed test run with and without the change, and the + // changed files held to the plan (see habits_check). Its sandbox runs + // take a step of their own when this one is short. + let habits_pr = match habits_check::gate(&work, &mut evidence, usage, has_time, || { + remaining_secs(start) + }) + .await + { + Ok(h) => h, + Err(habits_check::GateStop::NeedsTime) => { + close_memory(state, agent_memory.take()).await; + return hand_off_at( + state, + msg, + &github, + run_id, + &branch_name, + steps::Gate::Checks, + Some(&carry), + "Running the changed tests with and without the change needs a step of its own", + usage, + ) + .await; + } + Err(habits_check::GateStop::Why(why)) => { + gaps.push(proof::check_item("The tests and scope check", &why)); + None + } + }; + if let Some(h) = &habits_pr { + gaps.extend(habits_check::open_findings(h, &plan_result)); + } // What the stop judge assumed instead of asking: an Open item a person // corrects if it's wrong. gaps.extend(stop_judge::assumptions(state, &msg.team_id, run_id).await); @@ -6842,6 +6878,7 @@ async fn run_passes( links: &links, test_fix: test_pr.as_ref(), feature: feature_pr.as_ref(), + habits: habits_pr.as_ref(), keep_commits: false, }, ) @@ -7939,6 +7976,7 @@ async fn run_repo_pipeline( test_fix: None, // Multi-repo runs: the new-feature rules check single-repo runs. feature: None, + habits: None, keep_commits: false, }, provider, @@ -8039,6 +8077,28 @@ async fn run_repo_pipeline( None } }; + // This path has no step of its own to give: with too little time the + // tests are recorded as not run, with why. + ledger.update(|l| l.habits_waited = true); + let habits_pr = match habits_check::gate( + &work, + &mut evidence, + usage, + || has_time_for_remediation(start), + || remaining_secs(start), + ) + .await + { + Ok(h) => h, + Err(habits_check::GateStop::NeedsTime) => None, + Err(habits_check::GateStop::Why(why)) => { + gaps.push(proof::check_item("The tests and scope check", &why)); + None + } + }; + if let Some(h) = &habits_pr { + gaps.extend(habits_check::open_findings(h, &repo_plan)); + } gaps.extend(stop_judge::assumptions(state, &msg.team_id, run_id).await); pr::apply_checks( state, @@ -8058,6 +8118,7 @@ async fn run_repo_pipeline( links: &links, test_fix: test_pr.as_ref(), feature: None, + habits: habits_pr.as_ref(), keep_commits: false, }, ) diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index b4514c15d..530132b2b 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -13,7 +13,7 @@ use crate::WorkerState; /// any change to how plans are made or what a plan must carry, so a plan /// written by an older planner is never reused. pub const PLANNER_VERSION: &str = - "2026-11-06.intent-history-env-near-match-stop-rules-data-rules-cross-repo-asking-reproduce-decision-reask-series"; + "2026-11-13.intent-history-env-near-match-stop-rules-data-rules-cross-repo-asking-reproduce-decision-reask-series-habits"; /// The openspec file holding the plan's end-to-end checklist, readable. pub const END_TO_END_FILE: &str = "end_to_end.md"; @@ -829,6 +829,21 @@ Then the ```fix_location.json block described above."#, back.extend(feature_gaps.iter().cloned()); // A decision that stops without a fix names the one step a person takes. back.extend(super::fix_location::next_step_gaps(draft.fix.as_ref())); + // What a careful engineer settles before code (see habits): the worker + // reads the planned files' history and what depends on them itself, and + // the draft must answer what it found. + let habit_reader = super::habits::Reader { + state, + github, + graph: graphs.ready(), + search: &executor.read_only, + owner: &msg.repo_owner, + repo: &msg.repo_name, + team_repos: &team_repos, + }; + let habit_facts = habit_reader.facts(&draft).await; + let habit_gaps = super::habits::plan_gaps(&draft, &habit_facts); + back.extend(habit_gaps.iter().cloned()); // The outside steps: decided in order (the change, CoderHelm, a person // with a reason), looked up before claimed, ordered, valued, confirmable. let note_gaps = super::outside_work::plan_gaps(&draft, &abilities); @@ -1214,6 +1229,43 @@ Then the ```fix_location.json block described above."#, } } } + // The habits, read again on the plan as it now stands (a revision names + // new files and new names to search for). + { + let names = |p: &PlanResult| p.fix.as_ref().map(|d| d.habits.surfaces.clone()); + let facts = if draft.tasks == files.tasks && names(&draft) == names(&files) { + habit_facts + } else { + habit_reader.facts(&files).await + }; + let left = super::habits::plan_gaps(&files, &facts); + if !left.is_empty() { + warn!(ticket_id = %msg.ticket_id, gaps = left.len(), "Plan habits still open after one send-back"); + super::add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "Plan check (reproduction, history, dependents, early questions): {} left open", + left.len() + ), + ) + .await; + } + if let Some(d) = files.fix.as_mut() { + super::habits::keep_open(d, &facts, &left); + } + // The reproducing test is written before the fix. + let test = files + .fix + .as_ref() + .map(|d| d.habits.repro.test.clone()) + .unwrap_or_default(); + if let Some(tasks) = super::habits::put_repro_first(&files.tasks, &test) { + files.tasks = tasks; + files.repo_tasks = parse_repo_tasks(&files.tasks); + } + } // What the plan's own check still finds after the send-back stays on // the decision: the ticket, the PR and the reviewer see it. if !plan_findings.is_empty() { @@ -1381,6 +1433,9 @@ Then the ```fix_location.json block described above."#, // The questions only a person can answer are part of the plan people read. if let Some(d) = files.fix.as_ref() { files.proposal = with_questions(&files.proposal, d); + // What the coder holds to: the test first, the defaults being + // built, the dependents to update, the plan's own files. + files.design = super::habits::with_design_section(&files.design, d, &files.tasks); } // Write openspec to S3 @@ -1749,7 +1804,12 @@ fn parse_openspec_files(response: &str, intent: super::triage::TicketIntent) -> tasks: contents.remove(0), spec: contents.remove(0), repo_tasks, - fix: super::fix_location::parse_for(response, intent), + // A doubt asked early is one of the decision's questions from the + // start, so every check of them reads it (see habits). + fix: super::fix_location::parse_for(response, intent).map(|mut d| { + super::habits::fold_questions(&mut d); + d + }), } } diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index e7d20c639..aeab8ab07 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -49,6 +49,10 @@ pub struct Proof<'a> { /// content, the verification checklist and open product questions (see /// `feature`). pub feature: Option<&'a super::feature::PrFacts>, + /// The tests run with and without the change, the touched files' + /// history, who the change affects and what changed outside the plan + /// (see `habits_check`); `None` when that check didn't run. + pub habits: Option<&'a super::habits_check::PrFacts>, /// The branch's commits stay as they are (no squash): a stacked change /// was rebuilt with a labelled follow-up commit people should see (see /// `stack`). @@ -1650,6 +1654,10 @@ fn with_checks(body: &str, plan: &PlanResult, proof: &Proof<'_>, repo: &str) -> Some(f) => super::feature::shape_body(rest, f), None => rest, }; + let rest = match proof.habits { + Some(h) => super::habits_check::shape_body(rest, &super::habits_check::section(plan, h)), + None => rest, + }; let rest = if !proof.manual.trim().is_empty() && !rest.contains(MANUAL_HEADING) { format!( "{}\n\n{MANUAL_HEADING}\n{}", @@ -2179,6 +2187,7 @@ mod check_results_tests { links: "", test_fix: None, feature: None, + habits: None, keep_commits: false, } } @@ -2400,6 +2409,7 @@ mod refresh_tests { links: "", test_fix: None, feature: None, + habits: None, keep_commits: false, }; let owned = super::owned_sections(&plan, &proof, "acme/infra"); diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index df23c2193..61b0a9ad9 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -1021,6 +1021,16 @@ pub struct Ledger { pub links: CheckRecord, #[serde(default)] pub test_fix: CheckRecord, + /// The tests and scope check (`habits_check`). + #[serde(default)] + pub habits: CheckRecord, + /// What the tests and scope check last came to. + #[serde(default)] + pub habits_outcome: Option, String>>, + /// That check has asked once for a step of its own for its sandbox + /// runs: it never asks twice. + #[serde(default)] + pub habits_waited: bool, /// What the proof check last found (`None`: the judge couldn't answer). #[serde(default)] pub proof_findings: Option>, @@ -1068,6 +1078,7 @@ impl Ledger { &mut self.rules, &mut self.links, &mut self.test_fix, + &mut self.habits, ]; if records.iter().any(|r| r.fixing) { for r in records { @@ -1130,6 +1141,9 @@ impl Ledger { "they didn't finish", )), } + if let Some(Err(why)) = &self.habits_outcome { + open.push(proof::check_item("The tests and scope check", why)); + } open } @@ -1150,6 +1164,8 @@ impl Ledger { smaller.links.head = String::new(); smaller.test_outcome = None; smaller.test_fix.head = String::new(); + smaller.habits_outcome = None; + smaller.habits.head = String::new(); serde_json::to_string(&smaller).unwrap_or_default() } }