From fd7febc9efb25660e149cbfe29a1eddb580b4b96 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 16:01:17 -0500 Subject: [PATCH] Merge conflicts mechanically first and never commit an unchecked merge A conflicted merge of the base handed every file both sides changed to the model whole, cut at a size limit, and committed the reply after weak checks. A reply of prose followed by a rewritten file passed them. Each file is now merged three ways: changes only one side made apply mechanically, the model sees only a hunk both sides changed differently, and its reply must be that hunk's code. The merged file is checked before commit (no prose or markers, size within both sides' changes, both sides' added identifiers kept, it parses). A failed merge retries with smaller hunks, then pushes nothing and is recorded as CoderHelm's own problem. Incident case xy pins the invariant. --- .../xy_merge_keeps_both_sides_and_parses.md | 14 + services/worker/src/passes/await_merge.rs | 10 +- services/worker/src/passes/branch_update.rs | 9 +- .../xy_merge_keeps_both_sides_and_parses.rs | 348 +++++ services/worker/src/passes/merge3.rs | 1185 +++++++++++++++++ services/worker/src/passes/mod.rs | 1 + services/worker/src/passes/pr.rs | 264 ++-- 7 files changed, 1709 insertions(+), 122 deletions(-) create mode 100644 docs/incidents/xy_merge_keeps_both_sides_and_parses.md create mode 100644 services/worker/src/passes/incidents/xy_merge_keeps_both_sides_and_parses.rs create mode 100644 services/worker/src/passes/merge3.rs diff --git a/docs/incidents/xy_merge_keeps_both_sides_and_parses.md b/docs/incidents/xy_merge_keeps_both_sides_and_parses.md new file mode 100644 index 000000000..fea37af65 --- /dev/null +++ b/docs/incidents/xy_merge_keeps_both_sides_and_parses.md @@ -0,0 +1,14 @@ +# xy. `xy_merge_keeps_both_sides_and_parses` + +**What happened:** CoderHelm merged the base into a pull request's branch, and one file both sides had changed, a dashboard component, conflicted. The base had changed many of its lines; the branch had added two. CoderHelm sent all three versions of the whole file to the model, cut at a size limit, and committed what came back: a few lines of prose ("I'll analyze the differences between the three versions: ...") and then a different file, with most of the base's changes gone. It failed to compile at its first line, and it was pushed. The right result was the base's file with the branch's two lines. + +**Why:** the conflicted merge (`pr::resolve_conflicts`) handed every file both sides changed to the model whole, even where the two sides' changes didn't touch. The reply was checked only for being empty, for losing most of the smaller side, and with a bracket scan compared with the branch's version. A prose lead-in and a rewritten file passed all three. + +**The guarantee:** CoderHelm never commits a merge result that adds prose, drops either side's changes, or fails to parse. + +- Each file is merged three ways (`merge3::merge_text`). Every change only one side made, or both made the same way, is applied mechanically, with no model. +- Only a hunk both sides changed differently goes to the model, alone with its ancestor, ours and theirs and a few unchanged lines around it. Its reply must be that hunk's lines: prose, markdown fences and conflict markers are stripped where they wrap it and refused inside it, it can't be longer than both sides together, and every identifier either side added must still be there. +- The merged file is checked before anything is committed (`merge3::check_merged`): no conflict markers or prose, a line count within both sides' changes together, both sides' added identifiers present, and it parses for its language as well as the sides do (TypeScript, TSX, JavaScript, Python and Rust by their parsers; JSON, YAML and TOML must parse; other code by the bracket scan). +- A merge that fails is tried once more with smaller hunks. Failing again, nothing is pushed and the branch stays as it was. The failure is CoderHelm's own problem: an internal alert, a line on the run page, and the reason as the stop reason. + +The case replays it with invented content: a TSX file where the base changed many lines and the branch added two merges mechanically without asking the model, the result that was pushed fails every check, and a model reply of prose plus a rewritten file for a real overlapping hunk pushes nothing. diff --git a/services/worker/src/passes/await_merge.rs b/services/worker/src/passes/await_merge.rs index 19c31b892..c957fc59e 100644 --- a/services/worker/src/passes/await_merge.rs +++ b/services/worker/src/passes/await_merge.rs @@ -2252,7 +2252,15 @@ async fn bring_base_in( ); let ticket = gate_ticket(msg)?; let mut usage = crate::models::TokenUsage::default(); - super::pr::resolve_conflicts(state, &ticket, github, branch, &provider, &mut usage).await?; + // A merge that failed its checks pushed nothing: the head is unchanged + // and the conflict stands (said below). + match super::pr::resolve_conflicts(state, &ticket, github, branch, &provider, &mut usage).await + { + Err(e) if e.is::() => {} + other => { + other?; + } + } let head = github.get_ref(owner, repo, branch).await?; if head == msg.head_sha { let files = changed_on_both_sides(github, owner, repo, base, branch).await; diff --git a/services/worker/src/passes/branch_update.rs b/services/worker/src/passes/branch_update.rs index 623aae65f..44d718b49 100644 --- a/services/worker/src/passes/branch_update.rs +++ b/services/worker/src/passes/branch_update.rs @@ -454,7 +454,14 @@ impl Branches for OnGithub<'_> { ) .await; self.usage.lock().unwrap().merge(&usage); - resolved?; + match resolved { + // A merge that failed its checks pushed nothing: the conflict + // stands. + Err(e) if e.is::() => return Ok(None), + other => { + other?; + } + } // Merged when the branch now has all of the base. if self.behind(base, branch).await? == 0 { Ok(Some(self.head(branch).await?)) diff --git a/services/worker/src/passes/incidents/xy_merge_keeps_both_sides_and_parses.rs b/services/worker/src/passes/incidents/xy_merge_keeps_both_sides_and_parses.rs new file mode 100644 index 000000000..7e1ddf15e --- /dev/null +++ b/services/worker/src/passes/incidents/xy_merge_keeps_both_sides_and_parses.rs @@ -0,0 +1,348 @@ +//! xy. CoderHelm merged the base into a pull request's branch. One file +//! both sides changed, a dashboard component, conflicted. The base had +//! changed many of its lines and the branch had added two. CoderHelm sent +//! all three versions of the whole file to the model, cut at a size limit, +//! and committed what came back: eight lines of prose ("I'll analyze the +//! differences between the three versions: ...") and then a different +//! file, with most of the base's changes gone. It didn't compile at its +//! first line, and it was pushed. +//! +//! Why: the conflicted merge (`pr::resolve_conflicts`) gave every file both +//! sides changed to the model whole, even where the two sides' changes +//! didn't touch. The reply was checked only for being empty, for losing +//! most of the smaller side, and with a bracket scan compared with the +//! branch's version; a prose lead-in and a rewritten file passed all three. +//! +//! Guarantee: CoderHelm never commits a merge result that adds prose, drops +//! either side's changes, or fails to parse. Each file is merged three ways +//! (`merge3::merge_text`): every change only one side made is applied +//! mechanically, with no model. Only a hunk both sides changed differently +//! goes to the model, alone with its ancestor, ours and theirs, and its +//! reply must be the hunk's lines (prose, fences and markers refused, no +//! longer than both sides together, every identifier either side added +//! kept). The merged file is checked before anything is committed +//! (`merge3::check_merged`): no prose or markers, a size within both sides' +//! changes, both sides' added identifiers there, and it parses for its +//! language as well as the sides do. A failed merge is tried once more with +//! smaller hunks; failing again, nothing is pushed, the branch stays as it +//! was, and the failure is CoderHelm's own problem (an internal alert) with +//! the reason as the stop reason. + +use crate::passes::merge3::{self, HunkAsk, HunkModel}; + +const PATH: &str = "web/src/components/app-frame.tsx"; + +/// The common ancestor. +const BASE: &str = r#"import { useState } from "react"; +import { NavLink } from "./nav-link"; +import { useAccount } from "../hooks/use-account"; + +export function AppFrame({ children }: { children: React.ReactNode }) { + const account = useAccount(); + const [open, setOpen] = useState(false); + + if (!account) { + return
Loading
; + } + + return ( +
+ +
+
+ +
+ {children} +
+
+ ); +} +"#; + +/// The base branch: many lines changed (a verification step, a paused +/// workspace screen, a tools group, a help menu). +const MAIN: &str = r#"import { useState } from "react"; +import { NavLink } from "./nav-link"; +import { useAccount } from "../hooks/use-account"; +import { VerifyStep } from "./verify-step"; +import { PausedScreen } from "./paused-screen"; +import { HelpLinks } from "./help-links"; + +export function AppFrame({ children }: { children: React.ReactNode }) { + const account = useAccount(); + const [open, setOpen] = useState(false); + const [helpOpen, setHelpOpen] = useState(false); + + if (!account) { + return
Loading
; + } + + if (account.needsVerifyStep) { + return ; + } + + if (account.workspacePaused) { + return ; + } + + return ( +
+ +
+
+ + + {helpOpen && setHelpOpen(false)} />} +
+ {children} +
+
+ ); +} +"#; + +/// The pull request's branch: two lines added. +const BRANCH: &str = r#"import { useState } from "react"; +import { NavLink } from "./nav-link"; +import { ReviewCount } from "./review-count"; +import { useAccount } from "../hooks/use-account"; + +export function AppFrame({ children }: { children: React.ReactNode }) { + const account = useAccount(); + const [open, setOpen] = useState(false); + + if (!account) { + return
Loading
; + } + + return ( +
+ +
+
+ +
+ {children} +
+
+ ); +} +"#; + +/// The model's reply as it came: prose, then a file of its own that keeps +/// the branch's two lines and loses the base's changes. +const PROSE_AND_REWRITE: &str = r#"I'll analyze the differences between the three versions: + +1. **main branch changes**: added a verification step, a paused screen, a tools group and a help menu. +2. **feature branch changes**: added a Reviews link with a count. + +The merged file keeps both: + +import { useState } from "react"; +import { NavLink } from "./nav-link"; +import { ReviewCount } from "./review-count"; + +export function AppFrame({ children }: { children: React.ReactNode }) { + return ( +
+ Reviews + {children} +
+ ); +} +"#; + +/// What the merge must be: the base branch's file with the branch's two +/// lines. +fn expected() -> String { + MAIN.replace( + "import { NavLink } from \"./nav-link\";\n", + "import { NavLink } from \"./nav-link\";\nimport { ReviewCount } from \"./review-count\";\n", + ) + .replace( + " Runs\n", + " Runs\n Reviews \n", + ) +} + +/// A model that always answers with `reply`, counting what it is asked. +struct Stub { + reply: Vec, + asked: Vec, +} + +impl Stub { + fn new(replies: &[&str]) -> Self { + Stub { + reply: replies.iter().map(|s| s.to_string()).collect(), + asked: Vec::new(), + } + } +} + +#[async_trait::async_trait] +impl HunkModel for Stub { + async fn resolve(&mut self, ask: &HunkAsk) -> Result { + self.asked.push(ask.clone()); + let n = self.asked.len() - 1; + Ok(self.reply[n.min(self.reply.len() - 1)].clone()) + } +} + +fn run(f: F) -> F::Output { + tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(f) +} + +#[test] +fn the_sides_apart_merge_mechanically_and_the_model_is_never_asked() { + let mut model = Stub::new(&[PROSE_AND_REWRITE]); + let merged = run(merge3::merge_text( + PATH, + Some(BASE), + MAIN, + BRANCH, + "main branch", + &mut model, + )) + .expect("the mechanical merge"); + assert_eq!(merged.text, expected()); + assert_eq!(merged.by_model, 0); + assert!( + model.asked.is_empty(), + "no model for changes that don't overlap" + ); + assert_eq!(merge3::parse_errors(PATH, &merged.text), Some(0)); +} + +#[test] +fn the_result_that_was_pushed_fails_every_check() { + let err = merge3::check_merged(PATH, BASE, BRANCH, MAIN, PROSE_AND_REWRITE).unwrap_err(); + assert!(err.contains("starts with prose"), "{err}"); + + // Without its prose, the rewritten file still drops the base's work. + let code = &PROSE_AND_REWRITE[PROSE_AND_REWRITE.find("import").unwrap()..]; + let err = merge3::check_merged(PATH, BASE, BRANCH, MAIN, code).unwrap_err(); + assert!(err.contains("lines") || err.contains("drops"), "{err}"); + let err = merge3::check_merged( + PATH, + BASE, + BRANCH, + MAIN, + &expected().replace(" \n", ""), + ) + .unwrap_err(); + assert!(err.contains("parse"), "{err}"); + + // The prose alone fails the parser too. + assert!(merge3::parse_errors(PATH, PROSE_AND_REWRITE).unwrap() > 0); + // And the right merge passes. + assert!(merge3::check_merged(PATH, BASE, BRANCH, MAIN, &expected()).is_ok()); +} + +/// The branch's link next to a line the base changed: one real hunk. +fn touching() -> (String, String) { + let main = MAIN.replace( + " Settings\n", + " Workspace settings\n", + ); + (main, BRANCH.to_string()) +} + +#[test] +fn an_overlapping_hunk_reaches_the_model_alone_and_a_prose_reply_pushes_nothing() { + let (main, branch) = touching(); + let mut model = Stub::new(&[PROSE_AND_REWRITE]); + let err = run(merge3::merge_text( + PATH, + Some(BASE), + &main, + &branch, + "main branch", + &mut model, + )) + .unwrap_err(); + assert!(err.0.contains("merging each conflicting hunk"), "{err}"); + assert!(err.0.contains("smaller pieces"), "{err}"); + // It saw the hunk, never the whole file. + assert!(!model.asked.is_empty()); + for ask in &model.asked { + assert!(!ask.ours.contains("export function AppFrame"), "{ask:?}"); + assert!(ask.ours.lines().count() <= 2, "{ask:?}"); + assert!(ask.theirs.lines().count() <= 6, "{ask:?}"); + } + + // A reply that is the hunk's lines lands in place; the rest stays + // mechanical. + let hunk = concat!( + " Reviews \n", + " Workspace settings\n", + "
\n", + "

Tools

\n", + " Keys\n", + " Usage\n", + "
\n", + ); + let mut model = Stub::new(&[&format!("\n{hunk}")]); + let merged = run(merge3::merge_text( + PATH, + Some(BASE), + &main, + &branch, + "main branch", + &mut model, + )) + .expect("the hunk merged"); + assert_eq!(model.asked.len(), 1); + assert_eq!( + merged.text, + expected().replace(">Settings", ">Workspace settings") + ); +} + +/// The wiring: the conflicted merge of the base goes through the three way +/// merge, a refused merge pushes nothing and is CoderHelm's own problem, +/// and no prompt asks the model for a whole merged file. +#[test] +fn the_conflicted_merge_goes_through_the_three_way_merge() { + let pr = include_str!("../pr.rs"); + let resolve = super::fixture::fn_src(pr, "pub async fn resolve_conflicts("); + assert!(resolve.contains("merge_file_or_why(")); + assert!(resolve.contains("Err(why) => return Err(refuse_merge(")); + assert!(!resolve.contains("return Ok(false);\n };")); + let refuse = super::fixture::fn_src(pr, "async fn refuse_merge("); + assert!(refuse.contains("own_problems::record(") && refuse.contains("own_problems::alert(")); + assert!(refuse.contains("OwnSubject::Tooling")); + let file = super::fixture::fn_src(pr, "pub async fn merge_file_or_why("); + assert!(file.contains("merge3::merge_text(")); + assert!(!pr.contains("Produce the correctly merged file")); + // The rebuilt stack merges through the same path. + assert!(include_str!("../restack.rs").contains("super::pr::merge_file(")); + // A refused merge leaves the conflict standing where it was reported. + for src in [ + include_str!("../await_merge.rs"), + include_str!("../branch_update.rs"), + ] { + assert!(src.contains("e.is::()")); + } +} diff --git a/services/worker/src/passes/merge3.rs b/services/worker/src/passes/merge3.rs new file mode 100644 index 000000000..165b555d9 --- /dev/null +++ b/services/worker/src/passes/merge3.rs @@ -0,0 +1,1185 @@ +//! The three way merge of one text file, for a conflicted merge of the base +//! into a branch (`pr::resolve_conflicts`) and a rebuilt stack (`restack`). +//! +//! The merge is mechanical first: each side's changes against the common +//! ancestor are found line by line, and every change only one side made, or +//! both made the same way, is applied as it is, with no model involved. +//! Only a hunk both sides changed differently goes to the model, alone: it +//! sees that hunk's ancestor, ours and theirs (and a few unchanged lines +//! around it), never the whole file, and its reply must be the lines that +//! replace the hunk. Prose, markdown fences and conflict markers are +//! stripped where they wrap the reply and refused inside it. +//! +//! The merged file is checked before anything is committed +//! ([`check_merged`]): no conflict markers or prose, a size within both +//! sides' changes together, every identifier either side added still there, +//! and the file parsing for its language as well as the two sides did. A +//! merge that fails is tried once more with smaller hunks; failing again, +//! it is refused with the reason, and nothing is pushed. + +use std::collections::{HashMap, HashSet}; +use std::sync::OnceLock; + +use super::syntax_check; + +/// Lines of unchanged context shown around a hunk on the first try. +const CONTEXT: usize = 6; +/// The largest region the exact line matcher compares (lines times lines); +/// past it the region is one change, which is never wrong, only coarser. +const DP_CELLS: usize = 4_000_000; + +/// A merge CoderHelm refused to commit, with why. The branch is left as it +/// was. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Refused(pub String); + +impl std::fmt::Display for Refused { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +impl std::error::Error for Refused {} + +/// One stretch of the merged file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Piece<'a> { + /// Lines the merge settled without a model. + Clean(Vec<&'a str>), + /// Lines both sides changed differently. + Conflict(Hunk<'a>), +} + +/// A conflicting hunk: the ancestor's lines and each side's. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Hunk<'a> { + pub base: Vec<&'a str>, + pub ours: Vec<&'a str>, + pub theirs: Vec<&'a str>, +} + +/// What the model is asked about one hunk. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HunkAsk { + pub path: String, + /// What the other side is ("main branch"). + pub their_label: String, + pub base: String, + pub ours: String, + pub theirs: String, + /// Unchanged lines just before and after the hunk (empty on a retry). + pub before: String, + pub after: String, +} + +/// Resolves one conflicting hunk: the model's raw reply, or why there is +/// none. +#[async_trait::async_trait] +pub trait HunkModel: Send { + async fn resolve(&mut self, ask: &HunkAsk) -> Result; +} + +/// A merged file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Merged { + pub text: String, + /// Hunks the model resolved (0: the merge was mechanical). + pub by_model: usize, +} + +/// How much of the file one model call sees. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Scope { + /// Each conflicting hunk with a few lines around it. + Hunk, + /// Each hunk cut where both sides agree, each piece alone. + Split, +} + +impl Scope { + fn words(self) -> &'static str { + match self { + Scope::Hunk => "merging each conflicting hunk", + Scope::Split => "merging the hunks in smaller pieces", + } + } +} + +/// The lines of `s`, each with its line ending. +pub fn lines(s: &str) -> Vec<&str> { + s.split_inclusive('\n').collect() +} + +// ─── Line matching ────────────────────────────────────────────────── + +/// Pairs of equal lines `(i in a, j in b)`, both increasing: a common +/// subsequence of the two (patience anchors, then exact matching between +/// them). +fn matches(a: &[&str], b: &[&str]) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + match_range(a, b, (0, a.len()), (0, b.len()), &mut out); + out +} + +fn match_range( + a: &[&str], + b: &[&str], + (mut a0, mut a1): (usize, usize), + (mut b0, mut b1): (usize, usize), + out: &mut Vec<(usize, usize)>, +) { + while a0 < a1 && b0 < b1 && a[a0] == b[b0] { + out.push((a0, b0)); + a0 += 1; + b0 += 1; + } + let mut tail = Vec::new(); + while a1 > a0 && b1 > b0 && a[a1 - 1] == b[b1 - 1] { + a1 -= 1; + b1 -= 1; + tail.push((a1, b1)); + } + if a0 < a1 && b0 < b1 { + let anchors = unique_anchors(a, b, (a0, a1), (b0, b1)); + if anchors.is_empty() { + exact(a, b, (a0, a1), (b0, b1), out); + } else { + let (mut pa, mut pb) = (a0, b0); + for (i, j) in anchors { + match_range(a, b, (pa, i), (pb, j), out); + out.push((i, j)); + pa = i + 1; + pb = j + 1; + } + match_range(a, b, (pa, a1), (pb, b1), out); + } + } + out.extend(tail.into_iter().rev()); +} + +/// Lines found exactly once on each side of the region, the longest run of +/// them in the same order on both. +fn unique_anchors( + a: &[&str], + b: &[&str], + (a0, a1): (usize, usize), + (b0, b1): (usize, usize), +) -> Vec<(usize, usize)> { + let mut seen: HashMap<&str, (u32, u32, usize, usize)> = HashMap::new(); + for (i, l) in a.iter().enumerate().take(a1).skip(a0) { + let e = seen.entry(*l).or_insert((0, 0, 0, 0)); + e.0 += 1; + e.2 = i; + } + for (j, l) in b.iter().enumerate().take(b1).skip(b0) { + if let Some(e) = seen.get_mut(*l) { + e.1 += 1; + e.3 = j; + } + } + let mut pairs: Vec<(usize, usize)> = seen + .values() + .filter(|e| e.0 == 1 && e.1 == 1) + .map(|e| (e.2, e.3)) + .collect(); + pairs.sort_unstable(); + // Longest increasing run by `j` (patience sorting). + let mut tops: Vec = Vec::new(); + let mut back: Vec> = vec![None; pairs.len()]; + for k in 0..pairs.len() { + let j = pairs[k].1; + let pos = tops.partition_point(|&t| pairs[t].1 < j); + if pos > 0 { + back[k] = Some(tops[pos - 1]); + } + if pos == tops.len() { + tops.push(k); + } else { + tops[pos] = k; + } + } + let mut run = Vec::new(); + let mut at = tops.last().copied(); + while let Some(k) = at { + run.push(pairs[k]); + at = back[k]; + } + run.reverse(); + run +} + +/// The longest common subsequence of a small region; a region too large is +/// left as one change. +fn exact( + a: &[&str], + b: &[&str], + (a0, a1): (usize, usize), + (b0, b1): (usize, usize), + out: &mut Vec<(usize, usize)>, +) { + let (n, m) = (a1 - a0, b1 - b0); + if n.saturating_mul(m) > DP_CELLS { + return; + } + let w = m + 1; + let mut t = vec![0u32; (n + 1) * w]; + for i in (0..n).rev() { + for j in (0..m).rev() { + t[i * w + j] = if a[a0 + i] == b[b0 + j] { + t[(i + 1) * w + j + 1] + 1 + } else { + t[(i + 1) * w + j].max(t[i * w + j + 1]) + }; + } + } + let (mut i, mut j) = (0, 0); + while i < n && j < m { + if a[a0 + i] == b[b0 + j] { + out.push((a0 + i, b0 + j)); + i += 1; + j += 1; + } else if t[(i + 1) * w + j] >= t[i * w + j + 1] { + i += 1; + } else { + j += 1; + } + } +} + +/// A side's change: base lines `b0..b1` became side lines `s0..s1`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Change { + b0: usize, + b1: usize, + s0: usize, + s1: usize, +} + +fn changes(base: &[&str], side: &[&str]) -> Vec { + let mut out = Vec::new(); + let (mut pb, mut ps) = (0, 0); + for (i, j) in matches(base, side) + .into_iter() + .chain(std::iter::once((base.len(), side.len()))) + { + if i > pb || j > ps { + out.push(Change { + b0: pb, + b1: i, + s0: ps, + s1: j, + }); + } + pb = i + 1; + ps = j + 1; + } + out +} + +/// Lines added and removed by a side against the base. +fn added_removed(base: &[&str], side: &[&str]) -> (usize, usize) { + changes(base, side) + .iter() + .fold((0, 0), |(a, r), c| (a + (c.s1 - c.s0), r + (c.b1 - c.b0))) +} + +/// The lines both versions share, in order: the ancestor of two versions +/// that have none (both added the path). +pub fn shared_lines(ours: &str, theirs: &str) -> String { + let (o, t) = (lines(ours), lines(theirs)); + matches(&o, &t).into_iter().map(|(i, _)| o[i]).collect() +} + +// ─── The mechanical merge ─────────────────────────────────────────── + +/// The three way merge of line lists: every change one side made applied, +/// the same change on both sides applied once, and a hunk both sides +/// changed differently left as a [`Piece::Conflict`] (with the lines both +/// sides agree on at its edges taken out of it). +pub fn merge3<'a>(base: &[&'a str], ours: &[&'a str], theirs: &[&'a str]) -> Vec> { + #[derive(Clone, Copy, PartialEq, Eq)] + enum Side { + Ours, + Theirs, + } + let mut all: Vec<(Side, Change)> = changes(base, ours) + .into_iter() + .map(|c| (Side::Ours, c)) + .chain(changes(base, theirs).into_iter().map(|c| (Side::Theirs, c))) + .collect(); + all.sort_by_key(|(s, c)| (c.b0, *s == Side::Theirs)); + + let mut out: Vec> = Vec::new(); + let (mut at, mut off_o, mut off_t) = (0usize, 0isize, 0isize); + let mut i = 0; + while i < all.len() { + let rs = all[i].1.b0; + let mut re = all[i].1.b1; + let mut j = i + 1; + while j < all.len() && all[j].1.b0 <= re { + re = re.max(all[j].1.b1); + j += 1; + } + push_clean(&mut out, &base[at..rs]); + let region = &all[i..j]; + // A side's lines for base lines rs..re: equal to the base, shifted + // by what its earlier changes added, outside its own changes. + let span = |side: Side, off: isize| -> (usize, usize, isize, bool) { + let last = region.iter().rev().find(|(s, _)| *s == side); + let start = (rs as isize + off) as usize; + match last { + Some((_, c)) => { + let noff = c.s1 as isize - c.b1 as isize; + (start, (re as isize + noff) as usize, noff, true) + } + None => (start, (re as isize + off) as usize, off, false), + } + }; + let (o0, o1, noff_o, has_o) = span(Side::Ours, off_o); + let (t0, t1, noff_t, has_t) = span(Side::Theirs, off_t); + let (os, ts) = (&ours[o0..o1], &theirs[t0..t1]); + if !has_t || os == ts { + push_clean(&mut out, os); + } else if !has_o { + push_clean(&mut out, ts); + } else { + let p = os.iter().zip(ts).take_while(|(x, y)| x == y).count(); + let room = os.len().min(ts.len()) - p; + let s = os + .iter() + .rev() + .zip(ts.iter().rev()) + .take(room) + .take_while(|(x, y)| x == y) + .count(); + push_clean(&mut out, &os[..p]); + out.push(Piece::Conflict(Hunk { + base: base[rs..re].to_vec(), + ours: os[p..os.len() - s].to_vec(), + theirs: ts[p..ts.len() - s].to_vec(), + })); + push_clean(&mut out, &os[os.len() - s..]); + } + off_o = noff_o; + off_t = noff_t; + at = re; + i = j; + } + push_clean(&mut out, &base[at..]); + out +} + +/// Appends clean lines, joined to the clean stretch before them. +fn push_clean<'a>(out: &mut Vec>, ls: &[&'a str]) { + if ls.is_empty() { + return; + } + if let Some(Piece::Clean(prev)) = out.last_mut() { + prev.extend_from_slice(ls); + } else { + out.push(Piece::Clean(ls.to_vec())); + } +} + +/// A hunk cut where its two sides agree: the agreed lines clean, each +/// stretch between them its own smaller conflict (the whole hunk's +/// ancestor kept for reference). +fn split<'a>(h: &Hunk<'a>) -> Vec> { + let mut out = Vec::new(); + let (mut po, mut pt) = (0, 0); + let ms = matches(&h.ours, &h.theirs); + let mut agreed: Vec<&'a str> = Vec::new(); + for (i, j) in ms + .into_iter() + .chain(std::iter::once((h.ours.len(), h.theirs.len()))) + { + if i > po || j > pt { + if !agreed.is_empty() { + out.push(Piece::Clean(std::mem::take(&mut agreed))); + } + out.push(Piece::Conflict(Hunk { + base: h.base.clone(), + ours: h.ours[po..i].to_vec(), + theirs: h.theirs[pt..j].to_vec(), + })); + } + if i < h.ours.len() { + agreed.push(h.ours[i]); + } + po = i + 1; + pt = j + 1; + } + if !agreed.is_empty() { + out.push(Piece::Clean(agreed)); + } + out +} + +// ─── The model's reply for one hunk ───────────────────────────────── + +/// The system prompt for one hunk. +pub fn hunk_system(path: &str, their_label: &str) -> String { + format!( + "You resolve one merge conflict in `{path}`. You get only the lines both sides \ + changed: the common ancestor's lines, the {their_label}'s lines and the feature \ + branch's lines, with a few unchanged lines around them for orientation. Write the \ + lines that replace the conflict so the file keeps both sides' changes; where both \ + changed the same thing differently, keep the feature branch's intent and fold the \ + other side's change into it. Your reply is pasted into the file in place of the \ + conflict, so put exactly those lines between and : no \ + explanation, no markdown fences, no conflict markers, and never the surrounding \ + lines." + ) +} + +/// The user message for one hunk. +pub fn hunk_prompt(ask: &HunkAsk) -> String { + let block = |tag: &str, body: &str| format!("<{tag}>\n{body}\n\n"); + let mut p = String::new(); + if !ask.before.is_empty() { + p.push_str(&block("unchanged_before", &ask.before)); + } + p.push_str(&block("ancestor", &ask.base)); + p.push_str(&block("theirs", &ask.theirs)); + p.push_str(&block("ours", &ask.ours)); + if !ask.after.is_empty() { + p.push_str(&block("unchanged_after", &ask.after)); + } + p.push_str(&format!( + "`theirs` is the {}; `ours` is the feature branch. Reply with the merged lines \ + between and .", + ask.their_label + )); + p +} + +/// The reply's code: what is between `` tags when they are there +/// (prose around them dropped), without a wrapping markdown fence. +fn reply_body(raw: &str) -> String { + let mut body = raw; + if let Some(start) = raw.find("") { + let rest = &raw[start + "".len()..]; + if let Some(end) = rest.rfind("") { + body = &rest[..end]; + } + body = body.strip_prefix("\r\n").unwrap_or(body); + body = body.strip_prefix('\n').unwrap_or(body); + } + let t = body.trim(); + if let Some(rest) = t.strip_prefix("```") { + if let Some(inner) = rest.strip_suffix("```") { + let after_lang = inner.find('\n').map(|i| i + 1).unwrap_or(inner.len()); + return inner[after_lang..].to_string(); + } + } + body.to_string() +} + +/// The model's reply for `h`, checked: the lines that replace the hunk, or +/// why the reply can't be used. +pub fn hunk_reply(path: &str, raw: &str, h: &Hunk<'_>) -> Result { + let mut out = reply_body(raw); + let ends_nl = h + .ours + .last() + .or(h.theirs.last()) + .is_none_or(|l| l.ends_with('\n')); + if !out.is_empty() && ends_nl && !out.ends_with('\n') { + out.push('\n'); + } + if out.trim().is_empty() { + if !h.ours.is_empty() && !h.theirs.is_empty() { + return Err("the reply was empty, dropping both sides' lines".into()); + } + out.clear(); + } + let got = lines(&out); + let cap = h.ours.len() + h.theirs.len(); + if got.len() > cap { + return Err(format!( + "the reply has {} lines where both sides together have {cap}: it rewrote more \ + than the conflict", + got.len() + )); + } + let inputs: Vec<&[&str]> = vec![&h.base, &h.ours, &h.theirs]; + foreign_lines(path, &got, &inputs, "the reply")?; + for (side, ls) in [("feature branch", &h.ours), ("other side", &h.theirs)] { + let missing = lost_symbols(&join(&h.base), &join(ls), &out); + if !missing.is_empty() { + return Err(format!( + "the reply drops what the {side} added: {}", + missing.join(", ") + )); + } + } + Ok(out) +} + +// ─── Checks of the merged file ────────────────────────────────────── + +fn join(ls: &[&str]) -> String { + ls.concat() +} + +const MARKERS: [&str; 4] = ["<<<<<<< ", "||||||| ", "=======", ">>>>>>> "]; + +fn marker_kind(line: &str) -> Option { + let t = line.trim_end_matches(['\n', '\r']); + MARKERS.iter().position(|m| { + if *m == "=======" { + t == *m + } else { + t.starts_with(m) || t == m.trim_end() + } + }) +} + +fn marker_counts(ls: &[&str]) -> [usize; 4] { + let mut c = [0; 4]; + for l in ls { + if let Some(k) = marker_kind(l) { + c[k] += 1; + } + } + c +} + +/// Words a model uses about the merge itself, never code. +const MODEL_TALK: &[&str] = &[ + "i'll ", + "i will ", + "i've ", + "let me ", + "here is the", + "here's the", + "here are the", + "the merged", + "merged file", + "merged version", + "merged result", + "resolved version", + "resolved file", + "three versions", + "both versions", + "both sides", + "main branch changes", + "feature branch changes", + "conflict resolution", +]; + +/// Files whose lines are text people read (prose there is content). +fn prose_file(path: &str) -> bool { + let ext = path.rsplit('.').next().unwrap_or("").to_ascii_lowercase(); + matches!( + ext.as_str(), + "md" | "mdx" + | "markdown" + | "txt" + | "rst" + | "adoc" + | "html" + | "htm" + | "vue" + | "svelte" + | "tsx" + | "jsx" + | "po" + | "csv" + ) || !path.contains('.') +} + +/// A line that reads as the model talking: its words about the merge, a +/// markdown list of bold labels, and in a code file a plain sentence. +fn model_prose(path: &str, line: &str) -> bool { + let t = line.trim(); + if t.is_empty() { + return false; + } + let l = t.to_ascii_lowercase(); + if MODEL_TALK.iter().any(|w| l.starts_with(w)) { + return true; + } + let unlisted = t.trim_start_matches(|c: char| { + c.is_ascii_digit() || matches!(c, '.' | '-' | '*' | ')' | ' ') + }); + if t.starts_with("**") || (unlisted.len() < t.len() && unlisted.starts_with("**")) { + return true; + } + if prose_file(path) { + return false; + } + let code = t.chars().any(|c| { + matches!( + c, + ';' | '{' + | '}' + | '(' + | ')' + | '=' + | '<' + | '>' + | '[' + | ']' + | '"' + | '`' + | '/' + | '#' + | '\'' + ) + }); + !code && t.split_whitespace().count() >= 6 && (t.ends_with('.') || t.ends_with(':')) +} + +/// Refuses lines none of `inputs` has that are prose, a markdown fence or a +/// conflict marker. +fn foreign_lines(path: &str, got: &[&str], inputs: &[&[&str]], what: &str) -> Result<(), String> { + let known: HashSet<&str> = inputs + .iter() + .flat_map(|ls| ls.iter().map(|l| l.trim())) + .collect(); + let most = inputs + .iter() + .map(|ls| marker_counts(ls)) + .fold([0; 4], |a, c| std::array::from_fn(|k| a[k] + c[k])); + let have = marker_counts(got); + if (0..4).any(|k| have[k] > most[k]) { + return Err(format!("{what} has conflict markers")); + } + let first = got.iter().position(|l| !l.trim().is_empty()); + for (n, l) in got.iter().enumerate() { + let t = l.trim(); + if t.is_empty() || known.contains(t) { + continue; + } + if t.starts_with("```") { + return Err(format!("{what} has a markdown fence")); + } + if model_prose(path, l) { + let lead = if Some(n) == first { + "starts with" + } else { + "has" + }; + return Err(format!( + "{what} {lead} prose, not code: \"{}\"", + common::truncate_str(t, 80) + )); + } + } + Ok(()) +} + +fn ident_re() -> &'static regex::Regex { + static RE: OnceLock = OnceLock::new(); + RE.get_or_init(|| regex::Regex::new(r"[A-Za-z_$][A-Za-z0-9_$]+").expect("identifier pattern")) +} + +fn idents(s: &str) -> HashSet<&str> { + ident_re().find_iter(s).map(|m| m.as_str()).collect() +} + +/// Identifiers `side` added against `base` that `merged` no longer has. +fn lost_symbols(base: &str, side: &str, merged: &str) -> Vec { + let (b, m) = (idents(base), idents(merged)); + let mut lost: Vec = idents(side) + .into_iter() + .filter(|w| !b.contains(w) && !m.contains(w)) + .map(String::from) + .collect(); + lost.sort(); + lost.truncate(8); + lost +} + +/// The grammar that parses `path`, when CoderHelm carries one. +fn grammar(path: &str) -> Option { + let ext = path.rsplit('.').next().unwrap_or("").to_ascii_lowercase(); + match ext.as_str() { + "ts" | "mts" | "cts" => Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()), + "tsx" => Some(tree_sitter_typescript::LANGUAGE_TSX.into()), + "js" | "mjs" | "cjs" | "jsx" => Some(tree_sitter_javascript::LANGUAGE.into()), + "py" => Some(tree_sitter_python::LANGUAGE.into()), + "rs" => Some(tree_sitter_rust::LANGUAGE.into()), + _ => None, + } +} + +/// Syntax errors the language's parser finds in `text` (`None`: no parser +/// for it). +pub fn parse_errors(path: &str, text: &str) -> Option { + let lang = grammar(path)?; + let mut parser = tree_sitter::Parser::new(); + parser.set_language(&lang).ok()?; + let tree = parser.parse(text, None)?; + let mut cursor = tree.walk(); + let mut errors = 0; + loop { + let node = cursor.node(); + let bad = node.is_error() || node.is_missing(); + if bad { + errors += 1; + } + if !bad && node.has_error() && cursor.goto_first_child() { + continue; + } + loop { + if cursor.goto_next_sibling() { + break; + } + if !cursor.goto_parent() { + return Some(errors); + } + } + } +} + +/// Does `merged` parse for its language at least as well as one of the +/// sides does? Data files must parse; code is read by its parser, or by the +/// bracket scan where CoderHelm has none. +fn parses(path: &str, ours: &str, theirs: &str, merged: &str) -> Result<(), String> { + if let Some(errors) = parse_errors(path, merged) { + let sides = parse_errors(path, ours) + .unwrap_or(0) + .max(parse_errors(path, theirs).unwrap_or(0)); + if errors > sides { + return Err(format!( + "the merged file doesn't parse ({errors} syntax errors where the sides have {sides})" + )); + } + return Ok(()); + } + match ( + syntax_check::validate_change(path, Some(ours), merged), + syntax_check::validate_change(path, Some(theirs), merged), + ) { + (Err(e), Err(_)) => Err(format!("the merged file doesn't parse ({e})")), + _ => Ok(()), + } +} + +/// The checks a merged file passes before it is committed: no conflict +/// markers, prose or markdown fences either side didn't have; a line count +/// within the base's plus both sides' changes; every identifier either side +/// added still there; and it parses for its language as well as a side +/// does. +pub fn check_merged( + path: &str, + base: &str, + ours: &str, + theirs: &str, + merged: &str, +) -> Result<(), String> { + let (b, o, t, m) = (lines(base), lines(ours), lines(theirs), lines(merged)); + foreign_lines(path, &m, &[&b[..], &o[..], &t[..]], "the merged file")?; + let (add_o, del_o) = added_removed(&b, &o); + let (add_t, del_t) = added_removed(&b, &t); + let low = b.len().saturating_sub(del_o + del_t); + let high = b.len() + add_o + add_t; + if m.len() < low || m.len() > high { + return Err(format!( + "the merged file has {} lines; both sides' changes together allow {low} to {high}", + m.len() + )); + } + for (side, text) in [("feature branch", ours), ("other side", theirs)] { + let lost = lost_symbols(base, text, merged); + if !lost.is_empty() { + return Err(format!( + "the merged file drops what the {side} added: {}", + lost.join(", ") + )); + } + } + parses(path, ours, theirs, merged) +} + +// ─── The merge ────────────────────────────────────────────────────── + +fn context_before(pieces: &[Piece<'_>], k: usize) -> String { + match k.checked_sub(1).map(|p| &pieces[p]) { + Some(Piece::Clean(ls)) => join(&ls[ls.len().saturating_sub(CONTEXT)..]), + _ => String::new(), + } +} + +fn context_after(pieces: &[Piece<'_>], k: usize) -> String { + match pieces.get(k + 1) { + Some(Piece::Clean(ls)) => join(&ls[..ls.len().min(CONTEXT)]), + _ => String::new(), + } +} + +/// Every conflict of `pieces` resolved by the model at `scope`. +async fn resolve_all( + path: &str, + their_label: &str, + pieces: &[Piece<'_>], + scope: Scope, + model: &mut M, +) -> Result<(String, usize), String> { + let mut text = String::new(); + let mut asked = 0; + for (k, piece) in pieces.iter().enumerate() { + let h = match piece { + Piece::Clean(ls) => { + text.push_str(&join(ls)); + continue; + } + Piece::Conflict(h) => h, + }; + let parts = match scope { + Scope::Hunk => vec![Piece::Conflict(h.clone())], + Scope::Split => split(h), + }; + for part in &parts { + let small = match part { + Piece::Clean(ls) => { + text.push_str(&join(ls)); + continue; + } + Piece::Conflict(s) => s, + }; + let (before, after) = match scope { + Scope::Hunk => (context_before(pieces, k), context_after(pieces, k)), + Scope::Split => (String::new(), String::new()), + }; + let ask = HunkAsk { + path: path.to_string(), + their_label: their_label.to_string(), + base: join(&small.base), + ours: join(&small.ours), + theirs: join(&small.theirs), + before: before.clone(), + after: after.clone(), + }; + asked += 1; + let raw = model + .resolve(&ask) + .await + .map_err(|e| format!("the model couldn't merge a hunk ({e})"))?; + let out = hunk_reply(path, &raw, small)?; + echoed(&out, &before, &after, small)?; + text.push_str(&out); + } + } + Ok((text, asked)) +} + +/// Refuses a reply that repeats the unchanged line just before or after +/// the hunk (it would be in the file twice). +fn echoed(out: &str, before: &str, after: &str, h: &Hunk<'_>) -> Result<(), String> { + let got = lines(out); + let side_has = |l: &str| h.ours.iter().chain(&h.theirs).any(|x| x.trim() == l.trim()); + let (first, last) = (got.first(), got.last()); + if let (Some(f), Some(b)) = (first, lines(before).last()) { + if !b.trim().is_empty() && f.trim() == b.trim() && !side_has(f) { + return Err("the reply repeats the line before the conflict".into()); + } + } + if let (Some(l), Some(a)) = (last, lines(after).first()) { + if !a.trim().is_empty() && l.trim() == a.trim() && !side_has(l) { + return Err("the reply repeats the line after the conflict".into()); + } + } + Ok(()) +} + +/// Merges `ours` (the branch's version of `path`) with `theirs` (the +/// `their_label` version) from their common `ancestor` (`None` when both +/// added the path: the lines they share stand in for it). Mechanical where +/// the sides don't overlap; the model resolves only overlapping hunks, and +/// the result passes [`check_merged`] or the merge is refused. +pub async fn merge_text( + path: &str, + ancestor: Option<&str>, + theirs: &str, + ours: &str, + their_label: &str, + model: &mut M, +) -> Result { + let base = match ancestor { + Some(a) => a.to_string(), + None => shared_lines(ours, theirs), + }; + let (b, o, t) = (lines(&base), lines(ours), lines(theirs)); + let pieces = merge3(&b, &o, &t); + if !pieces.iter().any(|p| matches!(p, Piece::Conflict(_))) { + let text: String = pieces + .iter() + .map(|p| match p { + Piece::Clean(ls) => join(ls), + Piece::Conflict(_) => String::new(), + }) + .collect(); + return check_merged(path, &base, ours, theirs, &text) + .map(|()| Merged { text, by_model: 0 }) + .map_err(|e| Refused(format!("the mechanical merge failed its checks: {e}"))); + } + let mut why = Vec::new(); + for scope in [Scope::Hunk, Scope::Split] { + let tried = match resolve_all(path, their_label, &pieces, scope, model).await { + Ok((text, by_model)) => { + check_merged(path, &base, ours, theirs, &text).map(|()| Merged { text, by_model }) + } + Err(e) => Err(e), + }; + match tried { + Ok(m) => return Ok(m), + Err(e) => why.push(format!("{}: {e}", scope.words())), + } + } + Err(Refused(why.join("; then "))) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A model that answers from a list and counts what it was asked. + pub(crate) struct Scripted { + pub replies: Vec, + pub asked: Vec, + } + + #[async_trait::async_trait] + impl HunkModel for Scripted { + async fn resolve(&mut self, ask: &HunkAsk) -> Result { + self.asked.push(ask.clone()); + if self.replies.is_empty() { + return Err("no reply left".into()); + } + Ok(self.replies.remove(0)) + } + } + + fn scripted(replies: &[&str]) -> Scripted { + Scripted { + replies: replies.iter().map(|s| s.to_string()).collect(), + asked: Vec::new(), + } + } + + fn run(f: F) -> F::Output { + tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(f) + } + + #[test] + fn changes_on_both_sides_apart_merge_without_a_model() { + let base = "a\nb\nc\nd\ne\nf\n"; + let ours = "a\nB\nc\nd\ne\nf\n"; + let theirs = "a\nb\nc\nd\nE\nf\ng\n"; + let mut m = scripted(&[]); + let got = run(merge_text( + "x.txt", + Some(base), + theirs, + ours, + "main branch", + &mut m, + )) + .unwrap(); + assert_eq!(got.text, "a\nB\nc\nd\nE\nf\ng\n"); + assert_eq!(got.by_model, 0); + assert!(m.asked.is_empty()); + } + + #[test] + fn the_same_change_on_both_sides_is_applied_once() { + let pieces = merge3(&lines("a\nb\n"), &lines("a\nX\n"), &lines("a\nX\n")); + assert_eq!(pieces, vec![Piece::Clean(vec!["a\n", "X\n"])]); + } + + #[test] + fn an_overlap_is_one_small_hunk_with_agreed_edges_taken_out() { + let base = lines("a\nb\nc\nd\n"); + let ours = lines("a\nk\nb1\nm\nd\n"); + let theirs = lines("a\nk\nb2\nm\nd\n"); + let p = merge3(&base, &ours, &theirs); + assert_eq!( + p, + vec![ + Piece::Clean(vec!["a\n", "k\n"]), + Piece::Conflict(Hunk { + base: vec!["b\n", "c\n"], + ours: vec!["b1\n"], + theirs: vec!["b2\n"], + }), + Piece::Clean(vec!["m\n", "d\n"]), + ] + ); + } + + #[test] + fn only_the_hunk_reaches_the_model_and_its_reply_lands_in_place() { + let base = "fn a() {}\nlet x = 1;\nfn z() {}\n"; + let ours = "fn a() {}\nlet x = one();\nfn z() {}\n"; + let theirs = "fn a() {}\nlet x = 2;\nfn z() {}\n"; + let mut m = scripted(&["Sure.\n\nlet x = one() + 2;\n\nDone."]); + let got = run(merge_text( + "x.rs", + Some(base), + theirs, + ours, + "main branch", + &mut m, + )) + .unwrap(); + assert_eq!(got.text, "fn a() {}\nlet x = one() + 2;\nfn z() {}\n"); + assert_eq!(m.asked.len(), 1); + assert_eq!(m.asked[0].ours, "let x = one();\n"); + assert_eq!(m.asked[0].theirs, "let x = 2;\n"); + assert_eq!(m.asked[0].base, "let x = 1;\n"); + } + + #[test] + fn a_reply_with_prose_markers_or_lost_lines_is_refused() { + let h = Hunk { + base: vec!["let x = 1;\n"], + ours: vec!["let x = alpha;\n"], + theirs: vec!["let x = beta;\n"], + }; + let path = "x.ts"; + assert!( + hunk_reply(path, "I'll merge these.\nlet x = alpha + beta;\n", &h) + .unwrap_err() + .contains("prose") + ); + assert!(hunk_reply( + path, + "<<<<<<< ours\nlet x = alpha;\n=======\nlet x = beta;\n>>>>>>> theirs\n", + &h + ) + .unwrap_err() + .contains("rewrote more")); + assert!(hunk_reply(path, "let x = alpha;\n", &h) + .unwrap_err() + .contains("beta")); + assert!(hunk_reply(path, "```ts\nlet x = alpha ?? beta;\n```", &h).is_ok()); + let two = Hunk { + base: vec![], + ours: vec!["let a = 1;\n", "let b = 2;\n"], + theirs: vec!["let c = 3;\n", "let d = 4;\n"], + }; + assert!( + hunk_reply(path, "<<<<<<< a\nlet a = 1;\nlet c = 3;\n", &two) + .unwrap_err() + .contains("markers") + ); + } + + #[test] + fn a_failed_hunk_is_tried_again_in_smaller_pieces_then_refused() { + let base = "a\nb\nc\n"; + let ours = "a\nb1\nkeep\nc1\n"; + let theirs = "a\nb2\nkeep\nc2\n"; + // First try: prose. Retry in pieces: two clean answers. + let mut m = scripted(&["Here is the merged file:\nb1b2\n", "b1\nb2\n", "c1\nc2\n"]); + let got = run(merge_text( + "x.txt", + Some(base), + theirs, + ours, + "main branch", + &mut m, + )) + .unwrap(); + assert_eq!(got.text, "a\nb1\nb2\nkeep\nc1\nc2\n"); + assert_eq!(m.asked.len(), 3); + assert!(m.asked[1].before.is_empty()); + // Every try failing: refused, with both reasons. + let mut m = scripted(&["I'll merge it.\n", "I'll merge it.\n"]); + let err = run(merge_text( + "x.txt", + Some(base), + theirs, + ours, + "main branch", + &mut m, + )) + .unwrap_err(); + assert!(err.0.contains("merging each conflicting hunk")); + assert!(err.0.contains("smaller pieces")); + } + + #[test] + fn two_added_files_merge_from_the_lines_they_share() { + let ours = "one\ntwo\nmine\nthree\n"; + let theirs = "one\ntwo\nthree\nyours\n"; + let mut m = scripted(&[]); + let got = run(merge_text( + "x.txt", + None, + theirs, + ours, + "main branch", + &mut m, + )) + .unwrap(); + assert_eq!(got.text, "one\ntwo\nmine\nthree\nyours\n"); + } + + #[test] + fn the_parser_reads_code_and_compares_with_the_sides() { + assert_eq!( + parse_errors("a.tsx", "export const A = () =>
hi
;\n"), + Some(0) + ); + assert!( + parse_errors( + "a.tsx", + "I'll analyze the differences:\nexport const A = 1;\n" + ) + .unwrap() + > 0 + ); + assert!(parse_errors("a.py", "def f(:\n pass\n").unwrap() > 0); + assert_eq!(parse_errors("a.rs", "fn main() {}\n"), Some(0)); + assert_eq!(parse_errors("a.go", "package x"), None); + assert!(parses("a.json", "{}", "{}", "{").is_err()); + assert!(parses("a.rs", "fn a() {}\n", "fn b() {}\n", "fn a() {\n").is_err()); + } + + #[test] + fn the_size_must_stay_within_both_sides_changes() { + let base = "a\nb\nc\nd\n"; + let ours = "a\nb\nc\nd\ne\n"; + let theirs = "A\nb\nc\nd\n"; + assert!(check_merged("x.txt", base, ours, theirs, "A\nb\nc\nd\ne\n").is_ok()); + let err = check_merged("x.txt", base, ours, theirs, "A\ne\n").unwrap_err(); + assert!(err.contains("allow"), "{err}"); + } + + #[test] + fn markers_already_in_a_side_are_not_conflict_markers() { + // A markdown underline both sides already have. + let base = "Title\n=======\nbody\n"; + let ours = "Title\n=======\nbody\nmore\n"; + let theirs = "Title\n=======\nBody\n"; + // The changed line and the line added after it touch: one hunk. + let mut m = scripted(&["Body\nmore\n"]); + let got = run(merge_text( + "x.md", + Some(base), + theirs, + ours, + "main branch", + &mut m, + )) + .unwrap(); + assert_eq!(got.text, "Title\n=======\nBody\nmore\n"); + assert_eq!(m.asked.len(), 1); + assert!(check_merged("x.md", base, ours, theirs, "Title\n=======\nBody\nmore\n").is_ok()); + assert!(check_merged( + "x.md", + base, + ours, + theirs, + "Title\n=======\n<<<<<<< ours\nbody\n" + ) + .is_err()); + } +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index efb87db81..d07b063ad 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1370,6 +1370,7 @@ mod log_fix_checks; #[cfg(test)] mod log_fix_eval; pub mod log_look; +pub mod merge3; pub mod minimal_change; pub mod mode_repair; pub mod model_check; diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 5a643b43c..7e04f1c55 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -9,8 +9,8 @@ use crate::clients::git_mode; use crate::clients::github::{GitEntry, GitHubClient}; use crate::models::{TicketMessage, TicketSource, TokenUsage}; use crate::passes::checks::CiCommand; +use crate::passes::merge3; use crate::passes::plan::PlanResult; -use crate::passes::syntax_check; use crate::WorkerState; #[allow(dead_code)] @@ -1154,8 +1154,14 @@ async fn reopen_prior_pr( } /// Attempt to merge main into the feature branch before creating the PR. -/// If there are conflicts, resolve them with the LLM and commit the resolution. -/// Returns Ok(true) if conflicts were found and resolved, Ok(false) if no conflicts. +/// If there are conflicts, each file both sides changed is merged three +/// ways (`merge_file_or_why`): mechanically where the changes don't +/// overlap, the model only for an overlapping hunk, and the merged file +/// checked before anything is committed. Returns Ok(true) if conflicts were +/// found and resolved, Ok(false) if no conflicts. A merge that fails its +/// checks pushes nothing: the branch stays as it was, the failure is +/// CoderHelm's own problem (an internal alert), and the error is a +/// [`merge3::Refused`] with the reason. pub async fn resolve_conflicts( state: &WorkerState, msg: &TicketMessage, @@ -1188,7 +1194,10 @@ pub async fn resolve_conflicts( return Ok(false); } - info!(branch, "Merge conflicts detected, resolving with LLM"); + info!( + branch, + "Merge conflicts detected, merging the files both sides changed" + ); // Get SHAs for the merge commit parents let branch_sha = github @@ -1298,6 +1307,7 @@ pub async fn resolve_conflicts( ); } let mut resolved = planned.take; + let mut by_model = 0; for m in planned.to_merge { let (path, o, t, mode) = (m.path.as_str(), &m.ours, &m.theirs, m.mode); // Read all three versions: merge base, base branch (main), feature @@ -1318,24 +1328,24 @@ pub async fn resolve_conflicts( None => None, }; - let Some(merged_content) = merge_file( + let merged = match merge_file_or_why( state, provider, usage, path, ancestor.as_deref(), - "main branch", + &format!("{} branch", msg.base_branch), &main_content, &branch_content, ) - .await? - else { - return Ok(false); + .await + { + Ok(m) => m, + Err(why) => return Err(refuse_merge(state, msg, branch, path, &why).await.into()), }; + by_model += merged.by_model; - let sha = github - .put_blob(owner, repo, merged_content.as_bytes()) - .await?; + let sha = github.put_blob(owner, repo, merged.text.as_bytes()).await?; resolved.push(( path.to_string(), Some(GitEntry { @@ -1367,8 +1377,7 @@ pub async fn resolve_conflicts( info!( branch, resolved = resolved.len(), - llm_resolved = conflicting.len(), - auto_resolved = resolved.len().saturating_sub(conflicting.len()), + hunks_by_model = by_model, "Creating merge commit" ); @@ -1391,8 +1400,38 @@ pub async fn resolve_conflicts( Ok(true) } -/// A path both sides changed whose two versions are text files: the model -/// merges them, and the result is committed with `mode`. +/// A merge of the base that failed its checks: nothing is pushed, the +/// branch stays as it was, and the failure is CoderHelm's own problem (an +/// internal alert, and a line on the run page when the run is known). The +/// error says why, for the caller's stop reason. +async fn refuse_merge( + state: &WorkerState, + msg: &TicketMessage, + branch: &str, + path: &str, + why: &merge3::Refused, +) -> merge3::Refused { + let text = format!( + "CoderHelm did not push its merge of `{}` into `{branch}`: `{path}` failed the merge \ + checks ({why}). The branch is unchanged.", + msg.base_branch + ); + let own = common::person_only::OwnProblem { + subject: common::person_only::OwnSubject::Tooling, + text: text.clone(), + }; + match msg.continuation_run_id.as_deref().filter(|r| !r.is_empty()) { + Some(run_id) => super::own_problems::record(state, &msg.team_id, run_id, &own).await, + None => { + super::own_problems::alert(state, &msg.team_id, "", own.subject.code(), &own.text).await + } + } + merge3::Refused(text) +} + +/// A path both sides changed whose two versions are text files: merged +/// three ways (`merge_file_or_why`), and the result is committed with +/// `mode`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ToMerge { pub path: String, @@ -1405,12 +1444,12 @@ pub struct ToMerge { } /// What resolving a conflicted merge of the base lays over the branch's -/// tree, before the model merges anything. +/// tree, before any file both sides changed is merged. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct MergePlan { /// Whole entries, mode and all (`None` removes the path). pub take: Vec<(String, Option)>, - /// Paths for the model. + /// Paths for the three way merge. pub to_merge: Vec, /// Paths where the branch's entry stands though both changed it: a /// symbolic link or a submodule on one side is never merged as text. @@ -1474,12 +1513,10 @@ pub fn merge_plan( out } -/// Merges two versions of `path` with the model, keeping both sides' work: -/// `main_content` (the `their_label` version) and `branch_content` (the -/// change's, preferred only where both changed the same lines), read from -/// `ancestor` when known. `None` when the model's file fails the checks -/// (empty, most of the file dropped, broken syntax): an unresolved conflict -/// is safer than a corrupted file. +/// Merges two versions of `path`, keeping both sides' work: `main_content` +/// (the `their_label` version) and `branch_content` (the change's), from +/// `ancestor` when known. `None` when the merge can't be made safely +/// ([`merge_file_or_why`] says why). #[allow(clippy::too_many_arguments)] pub async fn merge_file( state: &WorkerState, @@ -1491,109 +1528,96 @@ pub async fn merge_file( main_content: &str, branch_content: &str, ) -> Result, Box> { - let cap = |s: &str, limit: usize| -> String { - if s.len() > limit { - let head = common::truncate_str(s, limit); - let cut = head.rfind('\n').unwrap_or(head.len()); - format!("{}... (truncated, {} bytes total)", &head[..cut], s.len()) - } else { - s.to_string() - } - }; - - // Build a 3-way merge prompt - let system = format!("You are a precise merge conflict resolver. You will be given three versions of a file: the common ancestor, the {their_label} version, and the feature branch version. Produce the correctly merged file that incorporates changes from BOTH sides. When changes conflict directly, prefer the feature branch version. Return ONLY the file content — no explanations, no markdown fences, no commentary."); - - let mut prompt = format!("Merge these versions of `{path}`.\n\n"); - - if let Some(anc) = ancestor { - prompt.push_str(&format!( - "## Common ancestor\n```\n{}\n```\n\n", - cap(anc, 12_000) - )); - } - - prompt.push_str(&format!( - "## {their_label} version (their changes)\n```\n{}\n```\n\n", - cap(main_content, 16_000) - )); - prompt.push_str(&format!( - "## feature branch version (our changes — prefer when conflicting)\n```\n{}\n```\n\n", - cap(branch_content, 16_000) - )); - - if ancestor.is_some() { - prompt.push_str( - "Use the common ancestor to understand what each side changed. \ - Include changes from BOTH sides. Only prefer the feature branch \ - when both sides modified the exact same lines.", - ); - } else { - prompt.push_str( - "Include changes from BOTH sides. Only prefer the feature branch \ - when both sides modified the exact same lines.", - ); - } - - let mut messages = vec![( - "user".to_string(), - vec![serde_json::json!({"type": "text", "text": prompt})], - )]; - - let model_id = provider.primary_model_id(); - let merged_content = provider::converse( + Ok(merge_file_or_why( state, provider, - common::agent_policy::Agent::Coder, - model_id, - &system, - &mut messages, - &[], - &super::triage::NoOpExecutor, usage, - llm::ConverseOptions { - max_turns: 40, - max_tokens: 16384, - deadline: None, - effort: None, - }, - None, - None, + path, + ancestor, + their_label, + main_content, + branch_content, ) - .await?; + .await + .ok() + .map(|m| m.text)) +} - // Validate the model's merge before it becomes a commit — the output - // used to be committed verbatim (dropped hunks, stray fences, - // truncation all landed as file corruption). Any invalid file aborts - // the whole resolution: an unresolved conflict GitHub can display is - // strictly safer than a silently corrupted merge. - let merged_content = strip_code_fences(&merged_content); - let min_side = branch_content.len().min(main_content.len()); - if merged_content.trim().is_empty() && min_side > 0 { - warn!( - path, - "LLM merge produced empty output — aborting conflict resolution" - ); - return Ok(None); - } - if min_side > 200 && merged_content.len() < min_side * 3 / 10 { - warn!( - path, - merged = merged_content.len(), - min_side, - "LLM merge dropped most of the file — aborting conflict resolution" - ); - return Ok(None); +/// The three way merge of `path` (`merge3::merge_text`): every change only +/// one side made applied mechanically, the model asked only about a hunk +/// both changed differently (that hunk alone), and the merged file checked +/// (no prose or markers, both sides' changes kept, it parses) before it is +/// returned. A merge that fails its checks is refused with the reason; +/// nothing of it is committed. +#[allow(clippy::too_many_arguments)] +pub async fn merge_file_or_why( + state: &WorkerState, + provider: &ModelProvider, + usage: &mut TokenUsage, + path: &str, + ancestor: Option<&str>, + their_label: &str, + main_content: &str, + branch_content: &str, +) -> Result { + let mut model = HunkByModel { + state, + provider, + usage, + }; + let merged = merge3::merge_text( + path, + ancestor, + main_content, + branch_content, + their_label, + &mut model, + ) + .await; + match &merged { + Ok(m) => info!(path, by_model = m.by_model, "Merged both sides' changes"), + Err(why) => warn!(path, %why, "The merge failed its checks; nothing is committed"), } - if let Err(problem) = syntax_check::validate_change(path, Some(branch_content), &merged_content) - { - warn!( - path, - problem, "LLM merge is syntactically broken — aborting conflict resolution" - ); - return Ok(None); + merged +} + +/// The model, asked about one conflicting hunk (`merge3::hunk_prompt`). +struct HunkByModel<'a> { + state: &'a WorkerState, + provider: &'a ModelProvider, + usage: &'a mut TokenUsage, +} + +#[async_trait::async_trait] +impl merge3::HunkModel for HunkByModel<'_> { + async fn resolve(&mut self, ask: &merge3::HunkAsk) -> Result { + let system = merge3::hunk_system(&ask.path, &ask.their_label); + let mut messages = vec![( + "user".to_string(), + vec![serde_json::json!({"type": "text", "text": merge3::hunk_prompt(ask)})], + )]; + provider::converse( + self.state, + self.provider, + common::agent_policy::Agent::Coder, + self.provider.primary_model_id(), + &system, + &mut messages, + &[], + &super::triage::NoOpExecutor, + self.usage, + llm::ConverseOptions { + max_turns: 2, + max_tokens: 8192, + deadline: None, + effort: None, + }, + None, + None, + ) + .await + .map_err(|e| e.to_string()) } - Ok(Some(merged_content)) } /// Strip a wrapping markdown code fence the model may have added despite