diff --git a/docs/incidents/bx_person_lines_kept.md b/docs/incidents/bx_person_lines_kept.md new file mode 100644 index 000000000..9c3ceddf1 --- /dev/null +++ b/docs/incidents/bx_person_lines_kept.md @@ -0,0 +1,5 @@ +# bx. `bx_person_lines_kept` + +**What happened:** A person pushed a fixed end-to-end spec to a CoderHelm pull request: they took out assertions that failed and fixed a selector, and the suite passed on staging. CoderHelm's next rounds wrote the removed assertions back in from older versions of the spec, in two commits, and most of the tests broke. The branch guards stopped only resets and force pushes, and the snapshot check stopped only writes over commits the pass had never read. + +**The guarantee:** Every write CoderHelm commits (`write_file`, `batch_write`, so every edit, restore, revert and fix round, WIP branches included) is held against every commit a person made on the branch since its base. A line a person removed is never put back and a line they added is never taken out; the rest of the write goes through. The pull request gets one note, edited in place, that names what was kept and asks; a write with nothing left is refused with why. A round a person asked for is their answer. The revert after red checks puts back only CoderHelm's own changes. diff --git a/docs/incidents/by_scope_churn_folded.md b/docs/incidents/by_scope_churn_folded.md new file mode 100644 index 000000000..375d878c4 --- /dev/null +++ b/docs/incidents/by_scope_churn_folded.md @@ -0,0 +1,5 @@ +# by. `by_scope_churn_folded` + +**What happened:** A web pull request ended with "restore ... to base" commits for files it never meant to touch. After red checks, the revert went back to the last green head and put back every file that differed from it, including files a merge of the base had brought in; the scope check then saw them changed and a round restored each to the base, a commit apiece. Other rounds restored a file the plan changes and rebuilt it from scratch, up to fourteen times in one run. + +**The guarantee:** The revert puts back only files CoderHelm's own commits changed after the green head. The build of the plan is bounded by the plan's files: any other existing file is refused until the call says why, and the pull request lists it. In planned-work, proof and fix rounds a planned file is never restored, and any other file only to the pull request's base. CoderHelm's own newest commits that change a file and put it back are folded into one commit (or dropped) after every coder round, after a review-fix round and before ready; a person's commits are never rewritten. diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 07ce9a481..810041ea2 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -224,6 +224,9 @@ pub mod model_provider; /// Files a run keeps as its outputs (reports, tables, snapshots). pub mod outputs; pub mod person_gate; +/// A person's lines on a CoderHelm branch stay theirs: writes that would undo them are +/// kept out. +pub mod person_lines; /// Plugins: packages of skills, agents, tools, triggers and outputs a team installs. pub mod plugins; /// One shape for "something is wrong": set by a check, cleared by the same diff --git a/services/common/src/person_lines.rs b/services/common/src/person_lines.rs new file mode 100644 index 000000000..8ae143198 --- /dev/null +++ b/services/common/src/person_lines.rs @@ -0,0 +1,520 @@ +//! A person's lines on a CoderHelm branch stay theirs. +//! +//! The failure this was written for: a person pushed a fixed end-to-end +//! spec to CoderHelm's pull request (30 of 30 passing on staging). The next +//! fix round read the spec, looked at an older version of it, and wrote the +//! assertions the person had taken out back in, in two commits. Nine of ten +//! tests broke. Nothing stopped it: the branch guards stop resets and force +//! pushes, and the snapshot check stops writes over commits the pass never +//! read, but this pass had read the person's commit. It simply disagreed +//! with it and wrote over it. +//! +//! Now every write CoderHelm commits to a branch is held against the +//! commits people made on it ([`PersonEdit`], read from each commit's +//! patch). A change that takes out a line a person added, or puts back a +//! line a person removed, is not committed ([`guard`]): that part of the +//! file keeps the person's version, the rest of the write goes through, +//! and the pull request gets one short note that says what CoderHelm +//! disagrees with and asks the person ([`note`]). The person's work wins +//! until they answer; a round a person asked for is their answer. +//! +//! Lines that carry no meaning on their own (`}`, `});`, blank lines) are +//! never counted: they appear everywhere and would block every edit. + +use std::collections::HashSet; + +/// The marker of the one note on a pull request about a person's lines +/// CoderHelm left alone; the note is edited in place. +pub const NOTE_MARKER: &str = ""; + +/// What one commit a person made did to one file. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PersonEdit { + /// The commit. + pub sha: String, + /// Who made it (their login, else their name). + pub author: String, + pub path: String, + /// The lines the commit added (without the `+`). + pub added: Vec, + /// The lines the commit removed (without the `-`). + pub removed: Vec, +} + +impl PersonEdit { + /// The edit a commit's file entry describes, from its unified `patch`. + pub fn from_patch(sha: &str, author: &str, path: &str, patch: &str) -> PersonEdit { + let (added, removed) = patch_lines(patch); + PersonEdit { + sha: sha.to_string(), + author: author.to_string(), + path: path.to_string(), + added, + removed, + } + } +} + +/// The added and removed lines of a unified diff hunk list (GitHub's +/// `files[].patch`): no file headers, no "no newline" markers. +pub fn patch_lines(patch: &str) -> (Vec, Vec) { + let mut added = Vec::new(); + let mut removed = Vec::new(); + for line in patch.lines() { + if line.starts_with("+++") || line.starts_with("---") { + continue; + } + if let Some(l) = line.strip_prefix('+') { + added.push(l.to_string()); + } else if let Some(l) = line.strip_prefix('-') { + removed.push(l.to_string()); + } + } + (added, removed) +} + +/// Whether a line means something on its own: at least three letters or +/// digits once trimmed. Braces, blank lines and lone punctuation are in +/// every file and never mark whose a change is. +pub fn significant(line: &str) -> bool { + line.trim().chars().filter(|c| c.is_alphanumeric()).count() >= 3 +} + +fn key(line: &str) -> String { + line.trim().to_string() +} + +/// What a write would have done to a person's line. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Undo { + /// Taken out a line the person added. + RemovesTheirLine, + /// Put back a line the person removed. + RestoresWhatTheyRemoved, + /// Deleted a file the person changed. + DeletesTheirFile, +} + +/// One part of a write that was not committed because it would undo a +/// person's change. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Kept { + pub path: String, + pub sha: String, + pub author: String, + pub undo: Undo, + /// The person's line in question (trimmed). + pub line: String, +} + +impl Kept { + /// One line on what was kept and why. + pub fn sentence(&self) -> String { + let short: String = self.sha.chars().take(7).collect(); + let line = crate::truncate_str(&self.line, 90); + match self.undo { + Undo::RemovesTheirLine => format!( + "`{}`: CoderHelm's change would take out `{line}`, which {} added in {short}", + self.path, self.author + ), + Undo::RestoresWhatTheyRemoved => format!( + "`{}`: CoderHelm's change would put back `{line}`, which {} removed in {short}", + self.path, self.author + ), + Undo::DeletesTheirFile => format!( + "`{}`: CoderHelm's change would delete the file {} changed in {short}", + self.path, self.author + ), + } + } +} + +/// A write held against the people's edits of its file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Guarded { + /// What may be committed: the proposed content with every part that + /// would undo a person's change put back as it is now. + pub content: String, + /// What was kept as the person had it. + pub kept: Vec, +} + +/// One step of a line diff from `a` to `b`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Op { + Same(usize), + Del(usize), + Ins(usize), +} + +/// Cells of the longest-common-subsequence table above which the middle of +/// a file is treated as one replaced block (a whole-file rewrite). +const MAX_CELLS: usize = 4_000_000; + +/// The line diff from `a` to `b`: a shared start and end, and the longest +/// common subsequence of what lies between. +fn diff(a: &[&str], b: &[&str]) -> Vec { + let mut pre = 0; + while pre < a.len() && pre < b.len() && a[pre] == b[pre] { + pre += 1; + } + let mut suf = 0; + while suf < a.len() - pre && suf < b.len() - pre && a[a.len() - 1 - suf] == b[b.len() - 1 - suf] + { + suf += 1; + } + let (am, bm) = (&a[pre..a.len() - suf], &b[pre..b.len() - suf]); + let mut ops: Vec = (0..pre).map(Op::Same).collect(); + let (n, m) = (am.len(), bm.len()); + if n.saturating_mul(m) > MAX_CELLS { + ops.extend((0..n).map(|i| Op::Del(pre + i))); + ops.extend((0..m).map(|j| Op::Ins(pre + j))); + } else { + // lcs[i][j]: the longest common subsequence of am[i..] and bm[j..]. + let w = m + 1; + let mut lcs = vec![0u32; (n + 1) * w]; + for i in (0..n).rev() { + for j in (0..m).rev() { + lcs[i * w + j] = if am[i] == bm[j] { + lcs[(i + 1) * w + j + 1] + 1 + } else { + lcs[(i + 1) * w + j].max(lcs[i * w + j + 1]) + }; + } + } + let (mut i, mut j) = (0, 0); + while i < n && j < m { + if am[i] == bm[j] { + ops.push(Op::Same(pre + i)); + i += 1; + j += 1; + } else if lcs[(i + 1) * w + j] >= lcs[i * w + j + 1] { + ops.push(Op::Del(pre + i)); + i += 1; + } else { + ops.push(Op::Ins(pre + j)); + j += 1; + } + } + ops.extend((i..n).map(|i| Op::Del(pre + i))); + ops.extend((j..m).map(|j| Op::Ins(pre + j))); + } + ops.extend((0..suf).map(|k| Op::Same(a.len() - suf + k))); + ops +} + +/// The person's lines of `path`: what they added that is still meant to be +/// there, and what they removed. +struct Theirs<'a> { + added: Vec<(String, &'a PersonEdit)>, + removed: Vec<(String, &'a PersonEdit)>, +} + +fn theirs<'a>(path: &str, edits: &'a [PersonEdit]) -> Theirs<'a> { + let mut t = Theirs { + added: Vec::new(), + removed: Vec::new(), + }; + for e in edits.iter().filter(|e| e.path == path) { + let added: HashSet = e.added.iter().map(|l| key(l)).collect(); + let removed: HashSet = e.removed.iter().map(|l| key(l)).collect(); + for l in e.added.iter().filter(|l| significant(l)) { + // A line moved within the commit is neither added nor removed. + if !removed.contains(&key(l)) { + t.added.push((key(l), e)); + } + } + for l in e.removed.iter().filter(|l| significant(l)) { + if !added.contains(&key(l)) { + t.removed.push((key(l), e)); + } + } + } + t +} + +/// Holds a write of `proposed` over `current` (what the branch has now; +/// `None` when the file doesn't exist) against the people's `edits`. +/// A line a person added that the change would take out stays, and a line +/// a person removed that the change would put back stays out; every other +/// line is the proposed content. A write over a file no person touched is unchanged. +pub fn guard(path: &str, current: Option<&str>, proposed: &str, edits: &[PersonEdit]) -> Guarded { + let t = theirs(path, edits); + if t.added.is_empty() && t.removed.is_empty() { + return Guarded { + content: proposed.to_string(), + kept: Vec::new(), + }; + } + let cur = current.unwrap_or(""); + let a: Vec<&str> = cur.split_inclusive('\n').collect(); + let b: Vec<&str> = proposed.split_inclusive('\n').collect(); + // Compared without line endings and indentation, so a re-indent or a + // missing final newline is not a different line. + let ak: Vec = a.iter().map(|l| key(l)).collect(); + let bk: Vec = b.iter().map(|l| key(l)).collect(); + let ar: Vec<&str> = ak.iter().map(String::as_str).collect(); + let br: Vec<&str> = bk.iter().map(String::as_str).collect(); + let ops = diff(&ar, &br); + + let mut out = String::with_capacity(proposed.len()); + let mut kept: Vec = Vec::new(); + let mut k = 0; + while k < ops.len() { + if let Op::Same(i) = ops[k] { + // Same once trimmed: the proposed line keeps its new indentation + // only when nothing around it was kept back; taking the + // current one is always safe and changes no meaning. + out.push_str(a[i]); + k += 1; + continue; + } + // One block of changes: every delete and insert up to the next + // shared line, decided line by line in their order. + let start = k; + while k < ops.len() && !matches!(ops[k], Op::Same(_)) { + k += 1; + } + let block = &ops[start..k]; + let inserted: HashSet<&str> = block + .iter() + .filter_map(|o| match o { + Op::Ins(j) => Some(br[*j]), + _ => None, + }) + .collect(); + let deleted: HashSet<&str> = block + .iter() + .filter_map(|o| match o { + Op::Del(i) => Some(ar[*i]), + _ => None, + }) + .collect(); + for op in block { + match *op { + Op::Del(i) => { + let line = ar[i]; + let theirs = (!inserted.contains(line)) + .then(|| t.added.iter().find(|(l, _)| l == line)) + .flatten(); + // Their line stays where it is. + if let Some((_, e)) = theirs { + out.push_str(a[i]); + kept.push(Kept { + path: path.to_string(), + sha: e.sha.clone(), + author: e.author.clone(), + undo: Undo::RemovesTheirLine, + line: line.to_string(), + }); + } + } + Op::Ins(j) => { + let line = br[j]; + let theirs = (!deleted.contains(line)) + .then(|| t.removed.iter().find(|(l, _)| l == line)) + .flatten(); + match theirs { + // What they removed stays out. + Some((_, e)) => kept.push(Kept { + path: path.to_string(), + sha: e.sha.clone(), + author: e.author.clone(), + undo: Undo::RestoresWhatTheyRemoved, + line: line.to_string(), + }), + None => out.push_str(b[j]), + } + } + Op::Same(_) => {} + } + } + } + if kept.is_empty() { + // Nothing kept back: the write is exactly what was proposed + // (indentation and line endings included). + return Guarded { + content: proposed.to_string(), + kept, + }; + } + Guarded { content: out, kept } +} + +/// Holds deleting `path` (content `current`) against the people's edits: +/// the file stays when a line a person added is still in it. +pub fn guard_delete(path: &str, current: &str, edits: &[PersonEdit]) -> Option { + let t = theirs(path, edits); + let now: HashSet = current.lines().map(key).collect(); + t.added + .iter() + .find(|(l, _)| now.contains(l)) + .map(|(_, e)| Kept { + path: path.to_string(), + sha: e.sha.clone(), + author: e.author.clone(), + undo: Undo::DeletesTheirFile, + line: String::new(), + }) +} + +/// The most kept parts a note or refusal lists. +const MAX_LISTED: usize = 4; + +fn listed(kept: &[Kept]) -> Vec { + let mut seen = HashSet::new(); + kept.iter() + .filter(|k| seen.insert((k.path.clone(), k.sha.clone(), k.undo))) + .take(MAX_LISTED) + .map(Kept::sentence) + .collect() +} + +/// The pull request's note about the parts CoderHelm left as a person had +/// them: short, says what it disagrees with, and asks. +pub fn note(kept: &[Kept]) -> String { + let mut who: Vec<&str> = kept.iter().map(|k| k.author.as_str()).collect(); + who.sort(); + who.dedup(); + let mut out = format!( + "{NOTE_MARKER}\nCoderHelm kept {}'s version and committed none of these:\n", + who.join(", ") + ); + for l in listed(kept) { + out.push_str(&format!("- {l}\n")); + } + out.push_str( + "Reply here if CoderHelm's version should replace yours; until then your lines stay.", + ); + out +} + +/// What the coder reads when every part of its write was kept back: what +/// it would have undone, and what to do instead. +pub fn refusal(kept: &[Kept]) -> String { + format!( + "Not committed: this change would undo a person's commit on this branch. {}. \ + Their version stays. Make your change around their lines; if you think their change \ + is wrong, say why in your Evidence, and the pull request asks them.", + listed(kept).join("; ") + ) +} + +/// The parts of `kept` of one note, merged with what an earlier note +/// listed (`earlier`), newest last, without repeats. +pub fn merge(earlier: &[Kept], new: &[Kept]) -> Vec { + let mut out: Vec = earlier.to_vec(); + for k in new { + if !out.contains(k) { + out.push(k.clone()); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn edit(path: &str, patch: &str) -> PersonEdit { + PersonEdit::from_patch("abc1234def", "dana", path, patch) + } + + #[test] + fn patch_lines_skip_headers() { + let (a, r) = patch_lines("--- a/x\n+++ b/x\n@@ -1,2 +1,2 @@\n ctx\n-old line\n+new line\n"); + assert_eq!(a, vec!["new line"]); + assert_eq!(r, vec!["old line"]); + } + + #[test] + fn a_file_no_person_touched_is_written_as_proposed() { + let g = guard("a.ts", Some("one\ntwo\n"), "one\nthree\n", &[]); + assert_eq!(g.content, "one\nthree\n"); + assert!(g.kept.is_empty()); + } + + #[test] + fn putting_back_a_removed_assertion_is_kept_out_and_the_rest_goes_through() { + // The person took a failing assertion out and fixed a selector. + let person = edit( + "e2e/tests/signup.spec.ts", + "@@ -3,4 +3,3 @@\n await page.goto('/signup');\n- await expect(page.getByRole('heading', { name: 'Price' })).toBeVisible();\n- await page.getByText('Old label').click();\n+ await page.getByText('New label').click();\n", + ); + let current = "test('signup', async ({ page }) => {\n await page.goto('/signup');\n await page.getByText('New label').click();\n});\n\nconst timeout = 1000;\n"; + // CoderHelm's round writes the assertion back and also changes an + // unrelated constant. + let proposed = "test('signup', async ({ page }) => {\n await page.goto('/signup');\n await expect(page.getByRole('heading', { name: 'Price' })).toBeVisible();\n await page.getByText('New label').click();\n});\n\nconst timeout = 5000;\n"; + let g = guard( + "e2e/tests/signup.spec.ts", + Some(current), + proposed, + &[person], + ); + assert!(!g.content.contains("name: 'Price'"), "{}", g.content); + assert!(g.content.contains("const timeout = 5000;")); + assert_eq!(g.kept.len(), 1); + assert_eq!(g.kept[0].undo, Undo::RestoresWhatTheyRemoved); + } + + #[test] + fn taking_out_a_line_the_person_added_is_kept_out() { + let person = edit( + "src/a.ts", + "@@ -1 +1,2 @@\n export const a = 1;\n+export const fixedByPerson = true;\n", + ); + let current = "export const a = 1;\nexport const fixedByPerson = true;\n"; + let proposed = "export const a = 2;\n"; + let g = guard("src/a.ts", Some(current), proposed, &[person]); + assert!(g.content.contains("fixedByPerson")); + assert_eq!(g.kept[0].undo, Undo::RemovesTheirLine); + } + + #[test] + fn braces_and_blank_lines_never_count() { + let person = edit("src/a.ts", "@@ -1 +1,3 @@\n+}\n+\n+});\n"); + let g = guard("src/a.ts", Some("x\n}\n\n});\n"), "x\n", &[person]); + assert!(g.kept.is_empty()); + assert_eq!(g.content, "x\n"); + } + + #[test] + fn a_reindent_of_their_line_is_not_an_undo() { + let person = edit("src/a.ts", "@@ -1 +1 @@\n+ callThePersonsFix();\n"); + let g = guard( + "src/a.ts", + Some(" callThePersonsFix();\n"), + " callThePersonsFix();\n", + &[person], + ); + assert!(g.kept.is_empty()); + } + + #[test] + fn deleting_a_file_with_their_lines_is_kept_out() { + let person = edit("src/a.ts", "@@ -0,0 +1 @@\n+export const keepMe = 1;\n"); + assert!(guard_delete( + "src/a.ts", + "export const keepMe = 1;\n", + std::slice::from_ref(&person) + ) + .is_some()); + assert!(guard_delete("src/a.ts", "something else\n", &[person]).is_none()); + } + + #[test] + fn the_note_is_short_and_asks() { + let k = Kept { + path: "e2e/x.spec.ts".into(), + sha: "abcdef1234".into(), + author: "dana".into(), + undo: Undo::RestoresWhatTheyRemoved, + line: "await expect(a).toBeVisible();".into(), + }; + let n = note(&[k.clone(), k]); + assert!(n.starts_with(NOTE_MARKER)); + assert_eq!(n.lines().count(), 4, "{n}"); + assert!(n.contains("abcdef1")); + assert!(n.contains("Reply here")); + } +} diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index ade11d8e2..b2e6053c2 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -736,6 +736,143 @@ pub struct GitHubClient { /// While a caller records ([`Self::record_validators`]): the URL and /// `ETag` of each read it made, to ask later whether any changed. validators: Mutex>>, + /// The commits people made on each branch CoderHelm writes to, keyed by + /// "owner/repo:branch" and read again only when the branch gains a + /// commit that isn't CoderHelm's (`common::person_lines`). + person_edits: tokio::sync::Mutex>, + /// A person asked for the round now writing: their ask is their answer, + /// so their own lines may change ([`Self::set_person_asked`]). + person_asked: std::sync::atomic::AtomicBool, + /// What writes left as a person had it, per pull request + /// ("owner/repo#n"): the one note on it lists them all. + person_kept: Mutex>>, +} + +/// The most of CoderHelm's newest commits [`GitHubClient::fold_own_churn`] +/// reads one by one. +const MAX_FOLD_COMMITS: usize = 40; + +/// Where CoderHelm's newest run of its own commits starts among a +/// compare's `commits` (oldest first): after the last commit that is a +/// person's or a merge. `commits.len()` when the newest isn't its own. +pub fn own_tail_start(commits: &[serde_json::Value]) -> usize { + commits + .iter() + .rposition(|c| !is_bot_commit(c) || c["parents"].as_array().is_some_and(|p| p.len() > 1)) + .map_or(0, |i| i + 1) +} + +/// How a run of CoderHelm's own commits folds. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Fold { + /// Files the commits changed and then put back. + pub churn: Vec, + /// The one commit's message; `None` when the commits change nothing + /// together and are dropped. + pub message: Option, +} + +impl Fold { + /// The progress note for folding `n` commits. + pub fn note(&self, n: usize) -> String { + let files: Vec = self + .churn + .iter() + .take(5) + .map(|f| format!("`{f}`")) + .collect(); + let more = self.churn.len().saturating_sub(5); + let files = if more > 0 { + format!("{} and {more} more", files.join(", ")) + } else { + files.join(", ") + }; + match self.message { + None => format!( + "Dropped CoderHelm's last {n} commits: together they changed nothing ({files} \ + changed and put back)" + ), + Some(_) => format!( + "Folded CoderHelm's last {n} commits into one: {files} changed and put back, so \ + no commit carries them" + ), + } + } +} + +/// The fold of a run of CoderHelm's own commits (`touched`: each commit's +/// message and files, oldest first) whose changes together are `net`: +/// `None` when no file was changed and put back. The one commit keeps the +/// message of the first commit that changed a file that stays changed. +pub fn fold_plan(touched: &[(String, Vec)], net: &[String]) -> Option { + let mut churn: Vec = Vec::new(); + for (_, files) in touched { + for f in files { + if !net.contains(f) && !churn.contains(f) { + churn.push(f.clone()); + } + } + } + if churn.is_empty() { + return None; + } + let message = if net.is_empty() { + None + } else { + touched + .iter() + .find(|(_, files)| files.iter().any(|f| net.contains(f))) + .map(|(m, _)| m.clone()) + .or_else(|| Some("Apply changes".to_string())) + }; + Some(Fold { churn, message }) +} + +/// A round a person may or may not have asked for: see +/// [`GitHubClient::person_asked_round`]. +pub struct PersonAskedRound<'a>(&'a GitHubClient); + +impl Drop for PersonAskedRound<'_> { + fn drop(&mut self) { + self.0.set_person_asked(false); + } +} + +/// The people's commits on a branch, as of its tip `tip`. +#[derive(Clone, Default)] +struct PersonCache { + tip: String, + /// The branch's open pull request. + pr: Option, + edits: Vec, +} + +/// The most of a branch's people's commits whose patches are read: the +/// newest, which are the ones a round is likely to write over. +const MAX_PERSON_COMMITS: usize = 30; + +/// The people's commits among a compare's `commits` (oldest first): not +/// CoderHelm's ([`is_bot_commit`]) and not a merge of another branch (its +/// lines are that branch's, not this person's work), newest +/// [`MAX_PERSON_COMMITS`] kept. +pub fn person_commits(commits: &[serde_json::Value]) -> Vec<(String, String)> { + let mut out: Vec<(String, String)> = commits + .iter() + .filter(|c| !is_bot_commit(c)) + .filter(|c| c["parents"].as_array().map_or(0, |p| p.len()) <= 1) + .filter_map(|c| { + let sha = c["sha"].as_str()?.to_string(); + let who = c["author"]["login"] + .as_str() + .or_else(|| c["commit"]["author"]["name"].as_str()) + .unwrap_or("a person") + .to_string(); + Some((sha, who)) + }) + .collect(); + let skip = out.len().saturating_sub(MAX_PERSON_COMMITS); + out.drain(..skip); + out } #[derive(Serialize)] @@ -787,9 +924,232 @@ impl GitHubClient { token_cache: Mutex::new(None), snapshots: tokio::sync::RwLock::new(HashMap::new()), validators: Mutex::new(None), + person_edits: tokio::sync::Mutex::new(HashMap::new()), + person_asked: std::sync::atomic::AtomicBool::new(false), + person_kept: Mutex::new(HashMap::new()), }) } + /// Whether a person asked for the round now writing (a review or a + /// comment of theirs): their ask is their answer, so a write may change + /// lines they wrote. Set at the start of such a round, cleared after. + pub fn set_person_asked(&self, asked: bool) { + self.person_asked + .store(asked, std::sync::atomic::Ordering::SeqCst); + } + + /// [`Self::set_person_asked`] for one round: cleared when the returned + /// value drops, however the round ends. + pub fn person_asked_round(&self, asked: bool) -> PersonAskedRound<'_> { + self.set_person_asked(asked); + PersonAskedRound(self) + } + + /// The edits people made on `branch` past its pull request's base, and + /// the pull request. `None` when they couldn't be read (the write goes + /// on: an API hiccup never bricks a round). + async fn people_on( + &self, + owner: &str, + repo: &str, + branch: &str, + ) -> Option<(Option, Vec)> { + let key = format!("{owner}/{repo}:{branch}"); + let tip = self.get_ref(owner, repo, branch).await.ok()?; + let cached = self.person_edits.lock().await.get(&key).cloned(); + if let Some(c) = &cached { + if c.tip == tip { + return Some((c.pr, c.edits.clone())); + } + // Only CoderHelm's own commits since: the people's are as read. + if let Ok(new) = self.compare_commits(owner, repo, &c.tip, &tip, 100).await { + if !new.is_empty() && new.len() < 100 && new.iter().all(is_bot_commit) { + let mut c = c.clone(); + c.tip = tip.clone(); + self.person_edits.lock().await.insert(key, c.clone()); + return Some((c.pr, c.edits)); + } + } + } + // A round's WIP branch starts at its pull request's head: the + // people's commits are the pull request's. + let wip = common::run_round::wip_branch(""); + let pr_branch = branch.strip_prefix(wip.as_str()).unwrap_or(branch); + let prs = self + .get(&format!( + "{API_BASE}/repos/{owner}/{repo}/pulls?head={owner}:{pr_branch}&state=open&per_page=1" + )) + .await + .ok()?; + let Some(pr) = prs.as_array().and_then(|a| a.first()) else { + // No pull request: nobody reviews the branch yet, and a + // person's commits on it keep it from being restarted + // (`start_branch`). + let c = PersonCache { + tip, + ..Default::default() + }; + self.person_edits.lock().await.insert(key, c); + return Some((None, Vec::new())); + }; + let number = pr["number"].as_u64(); + let base = pr["base"]["ref"].as_str()?.to_string(); + let commits = self + .compare_commits(owner, repo, &base, branch, 250) + .await + .ok()?; + let mut edits = Vec::new(); + for (sha, who) in person_commits(&commits) { + let c = self + .get(&format!("{API_BASE}/repos/{owner}/{repo}/commits/{sha}")) + .await + .ok()?; + for f in c["files"].as_array().into_iter().flatten() { + let (Some(path), Some(patch)) = (f["filename"].as_str(), f["patch"].as_str()) + else { + continue; + }; + edits.push(common::person_lines::PersonEdit::from_patch( + &sha, &who, path, patch, + )); + } + } + let c = PersonCache { + tip, + pr: number, + edits, + }; + self.person_edits.lock().await.insert(key, c.clone()); + Some((c.pr, c.edits)) + } + + /// `ops` held against the commits people made on `branch` + /// (`common::person_lines`): a part of a write that takes out a line a + /// person added, or puts back one they removed, is not committed, and + /// the pull request's one note says what CoderHelm disagrees with and + /// asks them. `Err` (the refusal the coder reads) when nothing of the + /// write is left. + pub async fn hold_for_people( + &self, + owner: &str, + repo: &str, + branch: &str, + ops: Vec, + ) -> Result, String> { + use common::person_lines as pl; + if self.person_asked.load(std::sync::atomic::Ordering::SeqCst) { + return Ok(ops); + } + let Some((pr, edits)) = self.people_on(owner, repo, branch).await else { + tracing::warn!( + branch, + "could not read the people's commits on the branch; the write goes on unheld" + ); + return Ok(ops); + }; + if edits.is_empty() { + return Ok(ops); + } + let mut kept: Vec = Vec::new(); + let mut out = Vec::with_capacity(ops.len()); + for op in ops { + let path = match &op { + FileOp::Write { path, .. } | FileOp::Delete { path } => path.clone(), + }; + if !edits.iter().any(|e| e.path == path) { + out.push(op); + continue; + } + let current = match self.read_file_live(owner, repo, &path, branch).await { + Ok(c) => Some(c), + Err(e) if is_not_found(&*e) => None, + Err(_) => { + out.push(op); + continue; + } + }; + match op { + FileOp::Write { path, content } => { + let g = pl::guard(&path, current.as_deref(), &content, &edits); + if g.kept.is_empty() { + out.push(FileOp::Write { path, content }); + continue; + } + kept.extend(g.kept); + if current.as_deref() != Some(g.content.as_str()) { + out.push(FileOp::Write { + path, + content: g.content, + }); + } + } + FileOp::Delete { path } => { + match current + .as_deref() + .and_then(|c| pl::guard_delete(&path, c, &edits)) + { + Some(k) => kept.push(k), + None => out.push(FileOp::Delete { path }), + } + } + } + } + if kept.is_empty() { + return Ok(out); + } + tracing::warn!( + branch, + kept = kept.len(), + "a write would undo a person's commit on the branch: their version kept" + ); + if let Some(n) = pr { + self.note_people_kept(owner, repo, n, &kept).await; + } + if out.is_empty() { + return Err(pl::refusal(&kept)); + } + Ok(out) + } + + /// Writes the pull request's one note on what CoderHelm left as a person + /// had it: edited in place, never a second comment. + async fn note_people_kept( + &self, + owner: &str, + repo: &str, + pr: u64, + kept: &[common::person_lines::Kept], + ) { + use common::person_lines as pl; + let key = format!("{owner}/{repo}#{pr}"); + let all = { + let mut m = self.person_kept.lock().unwrap(); + let all = pl::merge(m.get(&key).map(Vec::as_slice).unwrap_or(&[]), kept); + m.insert(key, all.clone()); + all + }; + let body = pl::note(&all); + let existing = self + .list_issue_comments(owner, repo, pr) + .await + .unwrap_or_default() + .into_iter() + .find(|c| { + c["body"] + .as_str() + .is_some_and(|b| b.contains(pl::NOTE_MARKER)) + && c["user"]["type"].as_str() == Some("Bot") + }) + .and_then(|c| c["id"].as_u64()); + let res = match existing { + Some(id) => self.edit_issue_comment(owner, repo, id, &body).await, + None => self.create_issue_comment(owner, repo, pr, &body).await, + }; + if let Err(e) = res { + tracing::warn!(pr, error = %e, "could not write the note on a person's lines kept"); + } + } + /// Starts recording the validator (`ETag`) of every read made from now /// until [`Self::take_validators`]. pub fn record_validators(&self) { @@ -2160,6 +2520,81 @@ impl GitHubClient { Ok(()) } + /// Folds away churn in the newest of CoderHelm's commits on `branch`: + /// when its own commits since the last commit that isn't its own (a + /// person's, or a merge) change a file and then put it back, those + /// commits become one commit that carries only what changed (or none, + /// when nothing did), so the pull request never shows an edit and its + /// "restore" as commits of their own. A person's commits and every + /// commit before them are never rewritten; the branch moves only if no + /// one pushed since it was read. `Ok(Some(note))` when it folded. + pub async fn fold_own_churn( + &self, + owner: &str, + repo: &str, + branch: &str, + ) -> Result, Box> { + let prs = self + .get(&format!( + "{API_BASE}/repos/{owner}/{repo}/pulls?head={owner}:{branch}&state=open&per_page=1" + )) + .await?; + let Some(base) = prs + .as_array() + .and_then(|a| a.first()) + .and_then(|p| p["base"]["ref"].as_str()) + else { + return Ok(None); + }; + let commits = self.compare_commits(owner, repo, base, branch, 250).await?; + if commits.len() >= 250 { + return Ok(None); + } + let start = own_tail_start(&commits); + let tail = &commits[start..]; + if tail.len() < 2 || tail.len() > MAX_FOLD_COMMITS { + return Ok(None); + } + let (Some(tip), Some(parent)) = ( + tail.last().and_then(|c| c["sha"].as_str()), + tail[0]["parents"][0]["sha"].as_str(), + ) else { + return Ok(None); + }; + let mut touched: Vec<(String, Vec)> = Vec::new(); + for c in tail { + let sha = c["sha"].as_str().unwrap_or_default(); + let (_, files) = self.commit_stats(owner, repo, sha).await?; + touched.push(( + c["commit"]["message"].as_str().unwrap_or("").to_string(), + files, + )); + } + let net = self.changed_files_between(owner, repo, parent, tip).await?; + let Some(fold) = fold_plan(&touched, &net) else { + return Ok(None); + }; + let to = match &fold.message { + None => parent.to_string(), + Some(message) => { + let tree = self.git_commit(owner, repo, tip).await?["tree"]["sha"] + .as_str() + .ok_or("Missing tree sha in tip commit")? + .to_string(); + self.new_commit( + owner, + repo, + serde_json::json!({ "message": message, "tree": tree, "parents": [parent] }), + ) + .await? + } + }; + if !self.move_with_lease(owner, repo, branch, tip, &to).await? { + return Ok(None); + } + Ok(Some(fold.note(tail.len()))) + } + /// Create a new branch from an existing ref. pub async fn create_branch( &self, @@ -2860,6 +3295,23 @@ impl GitHubClient { message: &str, sha: Option<&str>, ) -> Result> { + // A person's lines on the branch stay theirs: what of this write + // would undo one is not committed (`hold_for_people`). + let held = self + .hold_for_people( + owner, + repo, + branch, + vec![FileOp::Write { + path: path.to_string(), + content: content.to_string(), + }], + ) + .await?; + let content: &str = match held.first() { + Some(FileOp::Write { content, .. }) => content, + _ => return Err(format!("nothing of the write to '{path}' is left to commit").into()), + }; self.guard_empty_overwrite(owner, repo, path, branch, content) .await?; let url = format!("{API_BASE}/repos/{owner}/{repo}/contents/{path}"); @@ -2970,6 +3422,12 @@ impl GitHubClient { message: &str, files: &[FileOp], ) -> Result> { + // A person's lines on the branch stay theirs: what of this write + // would undo one is not committed (`hold_for_people`). + let held = self + .hold_for_people(owner, repo, branch, files.to_vec()) + .await?; + let files = held.as_slice(); // An empty Write over a file with bytes is refused before anything is // created; a removal must come as FileOp::Delete. for f in files { @@ -5202,6 +5660,7 @@ pub struct CommitFile { } /// File operation for batch_write. +#[derive(Debug, Clone, PartialEq, Eq)] pub enum FileOp { Write { path: String, content: String }, Delete { path: String }, diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 2b6dbea85..8bbb61a36 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -754,6 +754,10 @@ Rules: // Correct a stale stored base so the rest of the system stays consistent. heal_run_base_branch(state, &msg, &base).await; let ci_only = comments.is_empty() && msg.review_body.trim().is_empty(); + // A person's lines on the branch stay theirs (`GitHubClient:: + // hold_for_people`) in a round CoderHelm started; a person's comment or + // review is their answer, so their round may change them. + let _person_asked = github.person_asked_round(!ci_only); // The PR's changed files: the scope of a CI-only cycle, and what the // team's always-applied skills scoped to paths are matched against. let pr_files = github @@ -1341,6 +1345,7 @@ Rules: .await; } let head = if fix_pushed { + super::round::fold_churn(&github, &msg.repo_owner, &msg.repo_name, &branch).await; super::round::branch_head(&github, &msg.repo_owner, &msg.repo_name, &branch).await } else { String::new() @@ -3176,6 +3181,21 @@ impl<'a> ToolExecutor for FeedbackToolExecutor<'a> { "Cannot modify {path}: CI/CD workflow files are protected." ))); } + // A round on the pull request never restores a planned file, + // and restores others only to the base (`ScopeGuard::restore`). + let asked_ref = input + .get("from_ref") + .and_then(|v| v.as_str()) + .filter(|s| !s.trim().is_empty()) + .unwrap_or(self.base_branch); + if let Err(refusal) = self.scope_guard.restore(path, asked_ref, self.base_branch) { + crate::agent::tool_outcome::note( + crate::agent::tool_outcome::ToolOutcome::soft_fail(format!( + "not restored: {path}" + )), + ); + return Ok(json!(refusal)); + } if let Some(refusal) = self .scope_refusal(path, super::write_guard::reason_input(input)) .await diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 1beced54c..ad57e9434 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -203,6 +203,11 @@ pub async fn run( if let Some(run_id) = run_id { super::run_guard::check(state, &msg.team_id, run_id).await?; } + // A person's lines on the branch stay theirs (`GitHubClient:: + // hold_for_people`) unless a person asked for this round: their ask is + // their answer. + let _person_asked = + github.person_asked_round(round_for == super::write_guard::RoundFor::PersonAsk); let rules_block = super::format_rules_block(rules); // Trim repo instructions for simple issues to reduce per-turn token cost let trimmed_instructions = if complexity == "simple" && repo_instructions.len() > 2000 { @@ -1286,6 +1291,9 @@ pub async fn run( lines if lines.is_empty() => closing.trim().to_string(), lines => format!("{}\n{lines}", closing.trim()), }; + // A file this round (or the rounds before it) changed and then put + // back leaves no commit of its own on the pull request. + super::round::fold_churn(github, &msg.repo_owner, &msg.repo_name, branch).await; Ok(ImplementResult { files_modified: files, timed_out, @@ -2801,6 +2809,17 @@ impl<'a> WriteToolExecutor<'a> { "Cannot modify {path}: CI/CD workflow files are protected." ))); } + // A round on the pull request never restores a planned file, + // and restores others only to the base (`ScopeGuard::restore`). + let asked_ref = input + .get("from_ref") + .and_then(|v| v.as_str()) + .filter(|s| !s.trim().is_empty()) + .unwrap_or(&self.base_branch); + if let Err(refusal) = self.scope_guard.restore(path, asked_ref, &self.base_branch) { + note(LogOutcome::soft_fail(format!("not restored: {path}"))); + return Ok(json!(refusal)); + } // A file outside the round's files is identical to base in // this PR — a "restore" of it is a no-op commit or churn. if let Err(refusal) = self diff --git a/services/worker/src/passes/incidents/bx_person_lines_kept.rs b/services/worker/src/passes/incidents/bx_person_lines_kept.rs new file mode 100644 index 000000000..00281e898 --- /dev/null +++ b/services/worker/src/passes/incidents/bx_person_lines_kept.rs @@ -0,0 +1,175 @@ +//! bx. A person pushed a fixed end-to-end spec to CoderHelm's pull request: +//! they took out assertions that failed and fixed a selector, and the suite +//! passed 30 of 30 on staging. CoderHelm's next round looked at an older +//! version of the spec and wrote the removed assertions back in; a second +//! commit did it again from another old version. Nine of ten tests broke. +//! The branch guards stopped only resets and force pushes, and the +//! snapshot check only writes over commits the pass had never read. This +//! pass had read the person's commit and wrote over it anyway. +//! +//! Guarantee: every write CoderHelm commits (`write_file`, `batch_write`, +//! so every edit, restore, revert and fix round) is held against every +//! commit a person made on the branch since its base, not only the ones +//! since CoderHelm's last commit. A part that puts back a line a person +//! removed, or takes out one they added, is not committed; the rest is. +//! The pull request gets one note, edited in place, that names what was +//! kept and asks. A round a person asked for is their answer. The revert +//! after red checks puts back only CoderHelm's own changes. + +use crate::clients::github::{person_commits, FileOp}; +use crate::passes::supervisor::{own_revert_paths, AfterGreen}; +use common::person_lines::{guard, note, refusal, PersonEdit, Undo, NOTE_MARKER}; +use serde_json::json; + +const SPEC: &str = "e2e/tests/browse/camp-registration.spec.ts"; + +/// The spec as the person left it: two failing assertions out, the +/// register button found by its new name. +const PERSONS_SPEC: &str = "\ +import { test, expect } from '@playwright/test'; + +test('register page embeds the portal', async ({ page }) => { + await page.goto('/venue-a/summer-camps/register'); + await expect(page.frameLocator('iframe').first()).toBeTruthy(); + await page.getByRole('button', { name: 'Register now' }).click(); +}); +"; + +/// The person's commit, as GitHub's patch shows it. +const PERSONS_PATCH: &str = "\ +@@ -3,8 +3,6 @@ import { test, expect } from '@playwright/test'; + test('register page embeds the portal', async ({ page }) => { + await page.goto('/venue-a/summer-camps/register'); +- await expect(page.getByRole('heading', { name: 'Summer Camp Registration' })).toBeVisible(); +- await expect(page.getByRole('dialog', { name: 'Register' }).getByRole('heading', { name: 'Price Per Week' })).toBeVisible(); + await expect(page.frameLocator('iframe').first()).toBeTruthy(); +- await page.getByRole('button', { name: 'Register' }).click(); ++ await page.getByRole('button', { name: 'Register now' }).click(); + }); +"; + +/// What the round wrote: an older version of the spec, which puts the +/// assertions and the old selector back, plus one change of its own. +const ROUNDS_SPEC: &str = "\ +import { test, expect } from '@playwright/test'; + +test('register page embeds the portal', async ({ page }) => { + await page.goto('/venue-a/summer-camps/register'); + await expect(page.getByRole('heading', { name: 'Summer Camp Registration' })).toBeVisible(); + await expect(page.getByRole('dialog', { name: 'Register' }).getByRole('heading', { name: 'Price Per Week' })).toBeVisible(); + await expect(page.frameLocator('iframe').first()).toBeTruthy(); + await page.getByRole('button', { name: 'Register' }).click(); +}); + +test('register page has a title', async ({ page }) => { + await page.goto('/venue-a/summer-camps/register'); + await expect(page).toHaveTitle(/Register/); +}); +"; + +fn persons_edit() -> PersonEdit { + PersonEdit::from_patch("9f3c2a1b7e", "a-person", SPEC, PERSONS_PATCH) +} + +#[test] +fn a_round_that_writes_back_what_a_person_removed_commits_only_its_own_change() { + let g = guard(SPEC, Some(PERSONS_SPEC), ROUNDS_SPEC, &[persons_edit()]); + // The person's fix stands. + assert!(!g.content.contains("Price Per Week"), "{}", g.content); + assert!(!g.content.contains("'Summer Camp Registration'")); + assert!(g.content.contains("name: 'Register now'")); + assert!(!g.content.contains("{ name: 'Register' }).click()")); + // The round's own new test goes through. + assert!(g.content.contains("register page has a title")); + assert!(g + .kept + .iter() + .all(|k| k.undo == Undo::RestoresWhatTheyRemoved || k.undo == Undo::RemovesTheirLine)); + assert!(g.kept.iter().any(|k| k.line.contains("Price Per Week"))); +} + +#[test] +fn a_write_that_only_reverts_the_person_is_refused_with_why() { + // The second commit: the spec restored from an older commit, nothing + // else. + let older = ROUNDS_SPEC + .split("\ntest('register page has a title'") + .next() + .unwrap(); + let g = guard(SPEC, Some(PERSONS_SPEC), older, &[persons_edit()]); + assert_eq!(g.content, PERSONS_SPEC, "nothing of it is left to commit"); + let why = refusal(&g.kept); + assert!(why.starts_with("Not committed"), "{why}"); + assert!(why.contains("a-person") && why.contains("9f3c2a1"), "{why}"); + let n = note(&g.kept); + assert!(n.starts_with(NOTE_MARKER)); + assert!(n.lines().count() <= 6, "{n}"); + assert!(n.contains("Reply here"), "{n}"); +} + +#[test] +fn the_persons_commit_counts_after_coderhelm_commits_on_top_of_it() { + // Base, the person's fix, then CoderHelm's first revert: the second + // revert must still see the person's commit. + let commits = vec![ + json!({"sha": "1111111", "author": {"login": "coderhelm[bot]", "type": "Bot"}, "parents": [{}]}), + json!({"sha": "9f3c2a1b7e", "author": {"login": "a-person", "type": "User"}, "parents": [{}]}), + json!({"sha": "0f5d6c6", "author": {"login": "coderhelm[bot]", "type": "Bot"}, "parents": [{}]}), + // A merge of the base is not the person's work. + json!({"sha": "3333333", "author": {"login": "a-person", "type": "User"}, "parents": [{}, {}]}), + ]; + assert_eq!( + person_commits(&commits), + vec![("9f3c2a1b7e".to_string(), "a-person".to_string())] + ); +} + +#[test] +fn the_revert_after_red_checks_puts_back_only_coderhelms_own_files() { + let changed: Vec = [SPEC, "src/blocks/portal.tsx", "src/lib/base-only.ts"] + .iter() + .map(|s| s.to_string()) + .collect(); + let after = vec![ + AfterGreen { + own: false, + merge: false, + files: vec![SPEC.into()], + }, + AfterGreen { + own: true, + merge: false, + files: vec!["src/blocks/portal.tsx".into()], + }, + AfterGreen { + own: true, + merge: true, + files: vec!["src/lib/base-only.ts".into()], + }, + ]; + assert_eq!( + own_revert_paths(&changed, &after), + vec!["src/blocks/portal.tsx".to_string()] + ); +} + +/// Every commit path goes through the hold, and a person's round lifts it. +#[test] +fn every_write_is_held_and_a_persons_round_is_their_answer() { + let gh = include_str!("../../clients/github.rs"); + for f in ["pub async fn write_file(", "pub async fn batch_write("] { + let at = gh.find(f).unwrap(); + let body = &gh[at..at + 1200]; + assert!(body.contains(".hold_for_people("), "{f}"); + } + // A round's WIP branch is held against its pull request's people too. + assert!(gh.contains("let wip = common::run_round::wip_branch(\"\");")); + let implement = include_str!("../implement.rs"); + assert!(implement + .contains("person_asked_round(round_for == super::write_guard::RoundFor::PersonAsk)")); + let feedback = include_str!("../feedback.rs"); + assert!(feedback.contains("github.person_asked_round(!ci_only)")); + // FileOp is cloned into the hold. + let op = FileOp::Delete { path: SPEC.into() }; + assert_eq!(op.clone(), op); +} diff --git a/services/worker/src/passes/incidents/by_scope_churn_folded.rs b/services/worker/src/passes/incidents/by_scope_churn_folded.rs new file mode 100644 index 000000000..0abb127d6 --- /dev/null +++ b/services/worker/src/passes/incidents/by_scope_churn_folded.rs @@ -0,0 +1,223 @@ +//! by. A web pull request ended with "restore ... to base" commits for +//! files it never meant to touch: a signup form hook, a membership flow +//! service, birthday validation, sign-in observability and their tests. +//! After red checks, the revert went back to the last green head and put +//! back every file that differed from it, including twelve files a merge +//! of the base had brought in, so old base code landed in the pull +//! request. The scope check then saw twelve changed files no task named, +//! and a round put each one back to the base, one commit apiece. The +//! build itself had no file boundary either: it could edit any file. +//! +//! Guarantee: the revert puts back only files CoderHelm's own commits +//! changed after the green head (`supervisor::own_revert_paths`). The +//! build of the plan is bounded by the plan's files: any other existing +//! file is refused until the call says why, and that reason is added to +//! what the plan changes. A run of CoderHelm's own commits that changes a +//! file and puts it back is folded into one commit that carries only what +//! stayed changed (or dropped), at the end of every coder round, after a +//! review-fix round, and before the pull request is marked ready; a +//! person's commits and everything before them are never rewritten. + +use crate::clients::github::{fold_plan, own_tail_start}; +use crate::passes::supervisor::{own_revert_paths, AfterGreen}; +use crate::passes::write_guard::{RoundFor, ScopeGuard}; +use serde_json::json; + +const PLANNED: &[&str] = &[ + "apps/web/src/components/blocks/portal-embed.tsx", + "apps/web/src/lib/routing/routing-service.ts", + "e2e/tests/browse/camp-registration.spec.ts", +]; + +/// Files a merge of the base changed: never the pull request's. +const BASE_FILES: &[&str] = &[ + "apps/web/src/components/signup/use-signup-form.ts", + "apps/web/src/features/online-join/services/membershipFlowService.ts", + "apps/web/src/lib/validation-utils.ts", + "apps/web/src/test/lib/validation-utils-birthday.test.ts", +]; + +fn s(v: &[&str]) -> Vec { + v.iter().map(|p| p.to_string()).collect() +} + +fn plan() -> crate::passes::plan::PlanResult { + crate::passes::plan::PlanResult { + tasks: PLANNED + .iter() + .map(|p| format!("- [ ] {p}: [modify] The camp registration change\n")) + .collect(), + ..Default::default() + } +} + +#[test] +fn the_revert_after_red_checks_never_puts_back_files_a_base_merge_brought() { + let mut changed = s(PLANNED); + changed.extend(s(BASE_FILES)); + let after = vec![ + AfterGreen { + own: true, + merge: true, + files: s(BASE_FILES), + }, + AfterGreen { + own: true, + merge: false, + files: s(PLANNED), + }, + ]; + let back = own_revert_paths(&changed, &after); + assert_eq!(back, s(PLANNED)); + assert!(BASE_FILES.iter().all(|f| !back.contains(&f.to_string()))); +} + +#[test] +fn the_build_of_the_plan_refuses_an_unplanned_file_until_it_says_why() { + // A fresh branch: the pull request changes nothing yet. + let g = ScopeGuard::for_round(RoundFor::PlanTasks, &[], Some(&plan()), "acme/site", ""); + assert!(g.bounded(), "the plan's files anchor the build"); + for p in PLANNED { + assert!(g.check(p, None).is_ok(), "{p}"); + } + let stray = BASE_FILES[1]; + let refused = g.check(stray, None).unwrap_err(); + assert!(refused.contains("the plan's tasks"), "{refused}"); + // With a stated reason the plan gains the file and the pull request + // says why. + let why = "the registration route reads its membership flag from this service"; + assert!(g.check(stray, Some(why)).is_ok()); + assert!(g.outside().iter().any(|(p, w)| p == stray && w == why)); + // A plan that names no file leaves the build unbounded, and the + // dependency and generator runs stay unbounded. + let empty = crate::passes::plan::PlanResult::default(); + assert!( + !ScopeGuard::for_round(RoundFor::PlanTasks, &[], Some(&empty), "acme/site", "").bounded() + ); + assert!( + !ScopeGuard::for_round(RoundFor::Build, &s(PLANNED), Some(&plan()), "acme/site", "") + .bounded() + ); +} + +fn commit(sha: &str, login: &str, parents: usize) -> serde_json::Value { + let ty = if login.ends_with("[bot]") { + "Bot" + } else { + "User" + }; + json!({ + "sha": sha, + "author": {"login": login, "type": ty}, + "parents": (0..parents).map(|i| json!({"sha": format!("p{i}")})).collect::>(), + }) +} + +#[test] +fn an_edit_and_its_restore_fold_away_and_a_persons_commit_is_never_rewritten() { + let commits = vec![ + commit("a1", "coderhelm[bot]", 1), + commit("b2", "a-person", 1), + // CoderHelm's newest run: the revert that touched the base files, + // the restores that put each one back. + commit("c3", "coderhelm[bot]", 1), + commit("d4", "coderhelm[bot]", 1), + commit("e5", "coderhelm[bot]", 1), + ]; + // Only what follows the person's commit is CoderHelm's to fold. + assert_eq!(own_tail_start(&commits), 2); + // A merge ends the run too. + let mut merged = commits.clone(); + merged.push(commit("f6", "coderhelm[bot]", 2)); + assert_eq!(own_tail_start(&merged), merged.len()); + + let mut revert_files = s(PLANNED); + revert_files.extend(s(BASE_FILES)); + let touched = vec![ + ( + "Revert the change that broke CI; it is deferred on the pull request".to_string(), + revert_files, + ), + ( + format!("Restore {} from main", BASE_FILES[0]), + s(&BASE_FILES[..2]), + ), + ( + format!("Restore {} from main", BASE_FILES[2]), + s(&BASE_FILES[2..]), + ), + ]; + // Together they change only the planned files. + let fold = fold_plan(&touched, &s(PLANNED)).expect("churn to fold"); + assert_eq!(fold.churn, s(BASE_FILES)); + assert!(fold + .message + .as_deref() + .is_some_and(|m| m.starts_with("Revert the change"))); + assert!(fold.note(3).contains("changed and put back")); + // Edits that all came back out: the commits are dropped. + let drop = fold_plan(&touched[1..], &[]).unwrap(); + assert_eq!(drop.message, None); + // Nothing put back: nothing to fold. + assert!(fold_plan(&touched[..1], &touched[0].1).is_none()); +} + +#[test] +fn churn_is_folded_after_every_round_and_before_ready() { + let implement = include_str!("../implement.rs"); + assert!(implement + .contains("super::round::fold_churn(github, &msg.repo_owner, &msg.repo_name, branch)")); + let feedback = include_str!("../feedback.rs"); + assert!(feedback.contains("super::round::fold_churn(&github,")); + let ready = include_str!("../ready.rs"); + let fold = ready + .find("super::round::fold_churn(gh,") + .expect("ready folds"); + let squash = ready.find(".squash_branch(").unwrap(); + assert!(fold < squash, "the fold runs before the final squash"); + // The build of the plan is the bounded round. + let passes = include_str!("../mod.rs"); + assert!(!passes.contains("write_guard::RoundFor::Build,")); + assert!(passes.matches("write_guard::RoundFor::PlanTasks,").count() >= 4); +} + +/// Audited runs: a planned-work round restored the shared file the plan +/// changes and rebuilt it four times; a web run restored fourteen times and +/// edited its page object ten. In planned-work, proof and fix rounds a +/// planned file is never restored; any other file only to the base. +#[test] +fn a_round_on_the_pull_request_never_restores_a_planned_file() { + let pr = s(PLANNED); + for round in [ + RoundFor::PlannedWork, + RoundFor::ProofGap, + RoundFor::OwnReview, + RoundFor::CiFix, + RoundFor::TestFix, + RoundFor::Habits, + ] { + let g = ScopeGuard::for_round(round, &pr, Some(&plan()), "acme/site", ""); + let page = PLANNED[2]; + let no = g.restore(page, "main", "main").unwrap_err(); + assert!(no.contains("a file the plan changes"), "{round:?}: {no}"); + // Not from an older commit either. + assert!(g.restore(page, "3e4679a", "main").is_err(), "{round:?}"); + // A file outside the plan goes back to the base, and only there. + assert!( + g.restore(BASE_FILES[0], "main", "main").is_ok(), + "{round:?}" + ); + let old = g.restore(BASE_FILES[0], "9a32d16", "main").unwrap_err(); + assert!(old.contains("only to the pull request's base"), "{old}"); + } + // The build of the plan and a person's ask are not held by it. + let build = ScopeGuard::for_round(RoundFor::PlanTasks, &pr, Some(&plan()), "acme/site", ""); + assert!(build.restore(PLANNED[2], "main", "main").is_ok()); + let person = ScopeGuard::for_round(RoundFor::PersonAsk, &pr, Some(&plan()), "acme/site", ""); + assert!(person.restore(PLANNED[2], "main", "main").is_ok()); + // Both restore tools ask it before anything else is done. + assert!( + include_str!("../implement.rs").contains(".restore(path, asked_ref, &self.base_branch)") + ); + assert!(include_str!("../feedback.rs").contains(".restore(path, asked_ref, self.base_branch)")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index f2268db93..fb7deac72 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -5439,7 +5439,7 @@ async fn run_passes( &file_cache, Some(run_id), implement_deadline, - write_guard::RoundFor::Build, + write_guard::RoundFor::PlanTasks, ) .await? }; @@ -5507,7 +5507,7 @@ async fn run_passes( &file_cache, Some(run_id), implement_deadline, - write_guard::RoundFor::Build, + write_guard::RoundFor::PlanTasks, ) .await?; } @@ -5717,7 +5717,7 @@ async fn run_passes( &file_cache, Some(run_id), implement_deadline, - write_guard::RoundFor::Build, + write_guard::RoundFor::PlanTasks, ) .await?; if again.files_modified.is_empty() { @@ -7782,7 +7782,7 @@ async fn run_repo_pipeline( file_cache, Some(run_id), implement_deadline, - write_guard::RoundFor::Build, + write_guard::RoundFor::PlanTasks, ) .await?; write_pass_trace( diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index 69ef6ce2a..9fa054804 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -1546,6 +1546,11 @@ async fn make_ready(ctx: &Ctx<'_>, f: &Facts) -> Result<(), Refused> { if let Some(clean) = f.title.strip_prefix("⚠️ Partial: ") { let _ = gh.update_pr_title(ctx.owner, ctx.repo, ctx.pr, clean).await; } + // A file changed and put back never leaves commits of its own, even + // when a person's commit keeps the whole history from being squashed. + if let Some(head) = pr["head"]["ref"].as_str() { + super::round::fold_churn(gh, ctx.owner, ctx.repo, head).await; + } // Final squash: the run's whole history (the implementation and every // fix round) as one clean commit, best-effort. if let (Some(keep_first), Some(head), Some(base)) = ( diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 3a3438b6f..913770c8f 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -7262,6 +7262,26 @@ async fn revert_to_green( .compare_changed_files(pr.owner, pr.repo, &sha, pr.branch) .await .ok()?; + // Only what CoderHelm's own commits after the green head changed + // goes back (`supervisor::own_revert_paths`): never a file a + // merge of the base brought in, never one only a person changed. + let at = shas.iter().position(|s| *s == sha)?; + let mut after = Vec::new(); + for c in commits.iter().skip(at + 1) { + let Some(c_sha) = c["sha"].as_str() else { + continue; + }; + let (_, files) = github.commit_stats(pr.owner, pr.repo, c_sha).await.ok()?; + after.push(sup::AfterGreen { + own: crate::clients::github::is_bot_commit(c), + merge: c["parents"].as_array().is_some_and(|p| p.len() > 1), + files, + }); + } + let changed = sup::own_revert_paths(&changed, &after); + if changed.is_empty() { + return None; + } let mut files = Vec::new(); for path in &changed { let was = github diff --git a/services/worker/src/passes/round.rs b/services/worker/src/passes/round.rs index 731b87c13..e37bb72e9 100644 --- a/services/worker/src/passes/round.rs +++ b/services/worker/src/passes/round.rs @@ -46,6 +46,17 @@ pub(crate) async fn branch_head( .unwrap_or_default() } +/// Folds away CoderHelm's own commits on `branch` that changed a file and +/// put it back (`GitHubClient::fold_own_churn`), best effort: a failure +/// leaves the history as it is. +pub(crate) async fn fold_churn(github: &GitHubClient, owner: &str, repo: &str, branch: &str) { + match github.fold_own_churn(owner, repo, branch).await { + Ok(Some(note)) => info!(branch, note = %note, "folded churn commits"), + Ok(None) => {} + Err(e) => warn!(branch, error = %e, "could not fold churn commits; history left as it is"), + } +} + /// Writes the round on the run record. A new round also clears an earlier /// round's "didn't finish": it is being worked again. pub(crate) async fn record(state: &WorkerState, team_id: &str, run_id: &str, round: &Round) { diff --git a/services/worker/src/passes/supervisor.rs b/services/worker/src/passes/supervisor.rs index 52d876bd9..17862cc82 100644 --- a/services/worker/src/passes/supervisor.rs +++ b/services/worker/src/passes/supervisor.rs @@ -437,6 +437,44 @@ pub fn revert_for(heads: &[(String, bool)], done: &[(String, String)], reverts: } } +/// One commit of a pull request after the green head a revert goes back +/// to. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct AfterGreen { + /// CoderHelm made it. + pub own: bool, + /// It merges another branch (the base brought up to date). + pub merge: bool, + pub files: Vec, +} + +/// The files a revert to the last green head may put back: the ones +/// CoderHelm's own commits after it changed. A file a merge of the base +/// brought in is the base's: putting it back to the green head's version +/// writes old base code into the pull request (a revert once did that to +/// twelve unrelated files, and the scope check then spent a round putting +/// each one back to the base, a commit apiece). A file only a person +/// changed is theirs. A file both CoderHelm and a merge changed can't be +/// taken apart file by file, so it stays. +pub fn own_revert_paths(changed: &[String], after: &[AfterGreen]) -> Vec { + use std::collections::HashSet; + let own: HashSet<&str> = after + .iter() + .filter(|c| c.own && !c.merge) + .flat_map(|c| c.files.iter().map(String::as_str)) + .collect(); + let merged: HashSet<&str> = after + .iter() + .filter(|c| c.merge) + .flat_map(|c| c.files.iter().map(String::as_str)) + .collect(); + changed + .iter() + .filter(|p| own.contains(p.as_str()) && !merged.contains(p.as_str())) + .cloned() + .collect() +} + // ── The ending ────────────────────────────────────────────────────────────── /// What a run's ending is decided from. diff --git a/services/worker/src/passes/write_guard.rs b/services/worker/src/passes/write_guard.rs index f223999f0..7c7ab3968 100644 --- a/services/worker/src/passes/write_guard.rs +++ b/services/worker/src/passes/write_guard.rs @@ -60,9 +60,17 @@ pub const REASON_INPUT: &str = "outside_plan"; /// round may edit and how the files its instructions name are read. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RoundFor { - /// The build of the plan (the first pass, a continuation, a dependency - /// or generator run): any file. + /// A dependency or generator run: the files it touches are the + /// tool's, not a plan's, so any file. Build, + /// The build of the plan (the first pass, a continuation, the tasks a + /// build left): the files its tasks name, their tests and module + /// files. Any other existing file is refused until the call says why + /// the change needs it, and that reason is added to what the plan + /// changes (the pull request lists it). A plan that names no file has + /// no boundary. The build once rewrote twelve files no task named; + /// a round later put each one back, a commit apiece. + PlanTasks, /// A person asked (a review, a comment): their ask is the /// authorization, any file. PersonAsk, @@ -125,7 +133,8 @@ impl RoundFor { /// What the round was started for, in the refusal's words. pub fn what(self) -> &'static str { match self { - RoundFor::Build => "the plan", + RoundFor::Build => "the dependency or generator run", + RoundFor::PlanTasks => "the plan's tasks", RoundFor::PersonAsk => "a person's request", RoundFor::AppBug => "the bug the tests showed", RoundFor::FeatureRules => "the new-feature rules", @@ -261,6 +270,18 @@ impl Scope { s } + /// Whether a task of the plan names `path` (or its folder), whatever + /// else names it. + pub fn in_plan(&self, path: &str) -> bool { + let p = normalize(path); + self.plan.contains(p) || self.plan_dirs.iter().any(|d| p.starts_with(d.as_str())) + } + + /// Whether the plan names any file or folder of this repository. + pub fn has_plan(&self) -> bool { + !self.plan.is_empty() || !self.plan_dirs.is_empty() + } + /// Every file the scope names (not its directories). fn files(&self) -> impl Iterator { self.pr @@ -623,15 +644,61 @@ impl ScopeGuard { own_repo: &str, reason: &str, ) -> Self { - if !round.bounded() || pr_files.is_empty() || pr_files.len() >= MAX_TRUSTED_SCOPE_FILES { + if !round.bounded() || pr_files.len() >= MAX_TRUSTED_SCOPE_FILES { + return Self::unscoped(); + } + let scope = Scope::of(round, pr_files, plan, own_repo, reason); + // The build of the plan is anchored by the plan's files, even + // before the branch changes any; every other round by the pull + // request's. + let anchored = if round == RoundFor::PlanTasks { + scope.has_plan() + } else { + !pr_files.is_empty() + }; + if !anchored { return Self::unscoped(); } Self { - scope: Some((round, Scope::of(round, pr_files, plan, own_repo, reason))), + scope: Some((round, scope)), ..Self::unscoped() } } + /// Whether this round may `restore_file` `path` from `from_ref`. In a + /// round on the pull request (planned work, a proof gap, a fix of any + /// kind), a file the plan changes is never restored: the round edits + /// what is on the branch. Audited runs restored such a file and wrote + /// it again from scratch, up to fourteen times in one run. A file + /// outside the plan is restored only to the pull request's base, never + /// from an older commit. The build of the plan and rounds with no + /// boundary are not held here. + pub fn restore(&self, path: &str, from_ref: &str, base: &str) -> Result<(), String> { + let Some((round, scope)) = &self.scope else { + return Ok(()); + }; + if *round == RoundFor::PlanTasks { + return Ok(()); + } + if scope.in_plan(path) { + return Err(format!( + "Not restored: `{}` is a file the plan changes. This round ({}) edits what is on \ + the branch: read the file and change only what the round is for, with edit_file. \ + Never restore a planned file and rebuild it.", + normalize(path), + round.what() + )); + } + if from_ref.trim() != base.trim() { + return Err(format!( + "Not restored: a file outside the plan is put back only to the pull request's \ + base (`{base}`), never from `{}`. Leave from_ref out.", + from_ref.trim() + )); + } + Ok(()) + } + /// Whether the round has a file boundary. pub fn bounded(&self) -> bool { self.scope.is_some() @@ -815,8 +882,9 @@ mod scope_guard_tests { const TASKS: &str = "- [x] apps/web/src/routes/gift.tsx: [create] The gift route\n\ - [ ] apps/web/src/lib/metadata.ts: [modify] Page metadata for the gift route\n"; - const ROUNDS: [RoundFor; 13] = [ + const ROUNDS: [RoundFor; 14] = [ RoundFor::Build, + RoundFor::PlanTasks, RoundFor::PersonAsk, RoundFor::AppBug, RoundFor::FeatureRules,