Overview
Asking an LLM to generate raw standard unified diffs (@@ -start,count +start,count @@) for large source files frequently breaks git apply or patch because LLMs struggle with exact line counting, hunk length math, and strict whitespace/prefix (+/-/�) alignment. In production coding agents and orchestration layers, the most reliable pattern is line-number-free SEARCH/REPLACE blocks (or context-anchored unified diff hunks where your harness ignores the LLM’s @@ line counts and resolves spans via fuzzy/context matching).
- Eliminate line-number arithmetic: Models excel at copying verbatim code spans from context but routinely miscount line offsets and hunk line totals in multi-hundred-line files. Removing line-number requirements—or treating
@@ ... @@strictly as a section separator rather than an exact offset—eliminates the #1 cause of corrupt patches. - Require unique surrounding context anchors (
oldCode->newCode): Having the model output exact contiguous blocks (search+replace) with 3–5 lines of unchanged surrounding context lets your applier locate the unique target span deterministically, verify uniqueness (rejecting ambiguous multi-matches), and generate a true unified diff locally for review orgit apply. - Layered fallback matching + structured retry feedback: Apply edits in tiers—(1) exact string match, (2) trailing-whitespace / CRLF-normalized match, (3) indentation-realigned match—and if a block still fails to match uniquely, return a structured error with nearby context lines so the model can self-correct on the next turn.
Steps
- Prompt or define a structured tool schema for
SEARCH/REPLACEedits: Ask the model to emit an ordered list of{ search, replace }blocks (or fenced<<<<<<< SEARCH/=======/>>>>>>> REPLACEblocks) containing enough unchanged surrounding lines to uniquely identify each edit site in the file. - Validate uniqueness and apply edits with tiered normalization: For each block, search the source file for
search; if it matches zero times, retry with normalized line endings/trailing spaces or indentation offset; if it matches more than once, fail fast with an ambiguity error requiring more surrounding context. - Apply edits atomically in memory before touching disk: Stage all hunks on an in-memory buffer first so a failure on hunk 3 never leaves a half-patched file on disk.
- Compute a valid unified diff locally if needed: Once the updated buffer passes syntax/lint checks, run a deterministic diff generator (
diff/git diff) between the original file and patched buffer whenever downstream tooling expects a strict RFC-compliant unified patch.
Example
export interface SearchReplaceEdit {
search: string;
replace: string;
}
export interface PatchApplyResult {
ok: boolean;
updatedContent?: string;
error?: string;
failedEditIndex?: number;
}
function normalizeLineEndings(text: string): string {
return text.replace(/\r\n/g, "\n");
}
function trimTrailingLineWhitespace(text: string): string {
return text
.split("\n")
.map((line) => line.replace(/[ \t]+$/g, ""))
.join("\n");
}
/**
* Finds a unique occurrence of `search` in `content` using exact matching first,
* then falling back to trailing-whitespace-normalized line matching.
*/
function locateUniqueSpan(
content: string,
search: string
): { start: number; end: number } | { error: string } {
if (!search.trim()) {
return { error: "Search block cannot be empty." };
}
// Tier 1: Exact substring match
const firstExact = content.indexOf(search);
if (firstExact !== -1) {
const secondExact = content.indexOf(search, firstExact + 1);
if (secondExact !== -1) {
return {
error:
"Ambiguous search block: matched multiple locations. Include more surrounding context lines.",
};
}
return { start: firstExact, end: firstExact + search.length };
}
// Tier 2: Line-by-line match ignoring trailing whitespace differences
const contentLines = content.split("\n");
const searchLines = search.split("\n");
const normContentLines = contentLines.map((l) => l.replace(/[ \t]+$/g, ""));
const normSearchLines = searchLines.map((l) => l.replace(/[ \t]+$/g, ""));
const matchedStartLines: number[] = [];
for (let i = 0; i <= normContentLines.length - normSearchLines.length; i++) {
let allMatch = true;
for (let j = 0; j < normSearchLines.length; j++) {
if (normContentLines[i + j] !== normSearchLines[j]) {
allMatch = false;
break;
}
}
if (allMatch) {
matchedStartLines.push(i);
}
}
if (matchedStartLines.length > 1) {
return {
error: `Ambiguous normalized match at lines \${matchedStartLines.map((l) => l + 1).join(", ")}. Add more context.`,
};
}
if (matchedStartLines.length === 1) {
const startLine = matchedStartLines[0];
const endLine = startLine + searchLines.length;
let startChar = 0;
for (let i = 0; i < startLine; i++) {
startChar += contentLines[i].length + 1;
}
let endChar = startChar;
for (let i = startLine; i < endLine; i++) {
endChar += contentLines[i].length + (i < endLine - 1 ? 1 : 0);
}
return { start: startChar, end: endChar };
}
return {
error:
"Search block not found in file. Ensure all lines, comments, and indentation match the source file verbatim.",
};
}
/**
* Applies a sequence of SEARCH/REPLACE edits atomically in memory.
*/
export function applySearchReplaceEdits(
originalContent: string,
edits: SearchReplaceEdit[]
): PatchApplyResult {
const usesCrlf = originalContent.includes("\r\n");
let working = normalizeLineEndings(originalContent);
for (let idx = 0; idx < edits.length; idx++) {
const edit = edits[idx];
const searchNorm = normalizeLineEndings(edit.search);
const replaceNorm = normalizeLineEndings(edit.replace);
const located = locateUniqueSpan(working, searchNorm);
if ("error" in located) {
return {
ok: false,
error: `Edit #${idx + 1} failed:${located.error}`,
failedEditIndex: idx,
};
}
working =
working.slice(0, located.start) + replaceNorm + working.slice(located.end);
}
const finalContent = usesCrlf ? working.replace(/\n/g, "\r\n") : working;
return {
ok: true,
updatedContent: finalContent,
};
}
Tips
- Include line numbers in the input prompt even when omitting them from the edit output: Passing the source file with
120 | const x = ...prefixes helps the LLM orient itself across large files without forcing the model to computeheaders on output. - Forbid placeholder comments like
// ... existing code ...insidesearchorreplace: Explicitly instruct the model that every character insidesearchandreplacemust be complete, literal code—any ellipsis shortcut will break exact matching or delete code. - Fall back to whole-file or function-level rewrites for small files or heavy refactors: If a file is under ~200 lines or more than ~40% of the file is changing, a full file/function rewrite avoids multi-hunk drift and merges faster than juggling dozens of small patches.
You must log in or register to comment.