Skip to content

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

apply-edit-block

Apply search/replace edit blocks from coding agents to source text, with a fallback ladder for near-exact matches.

The problem

Coding agents (and the humans steering them) emit edits as a block of "find this text, replace it with this text." The search text is almost never byte-exact: the model drops trailing whitespace, reindents a block, paraphrases a comment, or gets one word wrong in an otherwise correct match. Aider, Cline, Roo, Continue, and a pile of homegrown tools each reimplement their own ladder of fallback matching strategies to cope with this, usually as a tangle of regexes buried inside a larger apply-patch function. There are a handful of small competing npm packages for this and no clear winner, and none of them report which strategy actually matched so callers can log and tune it.

This package is that ladder, pulled out on its own. It matches search text against source text using five strategies of decreasing strictness, applies the replacement, and reports which strategy it used and how confident the match was. It does the matching only: no filesystem access, no git, no diff generation.

Install

npm i apply-edit-block

Usage

import { applyEdit, applyEdits, parseBlocks, similarity } from 'apply-edit-block';

const source = `function greet(name) {
  console.log('hi ' + name);
}
`;

// The model reindented the block and dropped a trailing space, but the
// exact strategy still finds it via the fallback ladder.
const edit = {
  search: '  console.log(\'hi \' + name); ',
  replace: '  console.log(`hi ${name}`);',
};

const result = applyEdit(source, edit);
console.log(result.strategy);   // 'trailing-ws'
console.log(result.text);
// function greet(name) {
//   console.log(`hi ${name}`);
// }

// Parse the conventional fenced format agents emit and apply every block.
const patch = `
<<<<<<< SEARCH
  console.log('hi ' + name);
=======
  console.log(\`hi \${name}\`);
>>>>>>> REPLACE
`;
const edits = parseBlocks(patch);
const multi = applyEdits(source, edits);
console.log(multi.ok, multi.applied); // true 1

// similarity() is the same scoring function 'fuzzy' uses internally.
console.log(similarity('a\nb\nc', 'a\nb\nz')); // 0.666...

API

applyEdit(source, edit, options?) -> EditResult

  • source: string - the full file contents.
  • edit: { search: string, replace: string }.
  • options.anchorSlack: number (default 2) - for the 'anchor' strategy, how far the source's line gap between the first/last non-empty search lines may differ from the search's.
  • options.threshold: number (default 0.85) - for the 'fuzzy' strategy, the minimum similarity score required to accept a window.
  • Returns:
    {
      ok: boolean,
      text: string,          // edited source on success, ORIGINAL source on failure
      strategy: string|null, // 'exact' | 'trailing-ws' | 'indent' | 'anchor' | 'fuzzy' | 'empty-search' | null
      similarity: number,    // 1 on exact match; best similarity found otherwise (0..1)
      start: number,         // char offset of match start in the original source, -1 on failure
      end: number,           // char offset of match end (exclusive) in the original source, -1 on failure
    }
    
  • Throws TypeError only if source or edit.search is not a string. A failed match never throws; it returns ok: false.
  • An empty search string means "prepend replace to the file": ok: true, strategy: 'empty-search', start: 0, end: 0.

The strategies are tried in this order, stopping at the first success:

  1. exact - plain indexOf.
  2. trailing-ws - line-by-line comparison with trailing whitespace stripped from every line on both sides.
  3. indent - line-by-line comparison with each line's leading whitespace stripped. On success, the indent delta (the matched source line's indentation minus the search's first line's indentation) is applied to every line of the replacement: add spaces for a positive delta, strip up to that many leading spaces for a negative one. Blank replacement lines are left blank.
  4. anchor - matches only on the first and last non-empty lines of search, and requires the line gap between them in the source to be within anchorSlack of the search's gap. Useful when an interior line was paraphrased.
  5. fuzzy - slides a window the size of search's line count over the source and scores each window with similarity(); the best-scoring window is accepted if its score is at least threshold.

On failure, similarity reports the best score fuzzy saw while sliding, so callers can tune threshold.

applyEdits(source, edits, options?) -> MultiResult

Applies an array of edits in order, each to the output of the previous one.

{ ok: boolean, text: string, results: EditResult[], applied: number }

ok is true only if every edit applied. On the first failure it stops immediately: text is the source as of the last successful edit, results holds one EditResult per edit attempted (including the failing one), and applied is the count that succeeded.

parseBlocks(text) -> Edit[]

Parses the conventional fenced format:

<<<<<<< SEARCH
old code
=======
new code
>>>>>>> REPLACE

Marker lines are matched by prefix (<{3,}, ={3,}, >{3,}), so 3 or more marker characters and trailing text on the marker line (<<<<<<< SEARCH, ======= divider) are both tolerated. Text outside a block is ignored. Returns [] when there are no blocks. A block that opens but never closes (no matching >>>>>>> line before the text ends, or before a new <<<<<<< line starts another block) is skipped, not treated as an error.

similarity(a, b) -> number

Normalized line-level similarity between two strings, 0..1. This is the exact function the 'fuzzy' strategy uses internally, exported so callers can score candidate matches themselves or tune threshold against real data.

How it works

similarity() splits both strings on \n and computes the longest common subsequence (LCS) of the two line arrays, using exact string equality per line, then divides by the length of the longer array. This is a classic O(n*m) dynamic-programming LCS, not a character-level edit distance. That tradeoff is deliberate: it is cheap to reason about and it is what makes the 'fuzzy' strategy tolerate one bad line out of ten (LCS of 9, divided by 10, is 0.9) without needing a fuzzy string-distance library.

The tradeoff has a real limit: a line that differs by even one character (extra indentation, a changed variable name, a dropped semicolon) counts as a total non-match for that line in the LCS, since comparison is exact-string, not per-character. That is why 'indent' and 'trailing-ws' exist as their own strategies rather than being folded into 'fuzzy': they normalize a specific, common kind of per-line noise before comparing, so a whole block that only differs in leading or trailing whitespace still counts as fully matched rather than scoring low on similarity.

The 'anchor' strategy is the loosest exact-match strategy: it trusts only the first and last non-empty lines of search and a line-count budget for what's in between, so it can survive a paraphrased comment or a rewritten line in the middle of an otherwise-recognizable block. It does not use similarity at all.

All offsets (start, end) are character indices into the original source string that was passed in, and end is exclusive, so source.slice(start, end) is always the exact text that was replaced.

Related

Small, single-purpose packages for the same problem space. Each one has zero dependencies and does one thing.

  • prompt-cache-fit - Reorder prompt blocks least-variable-first for prefix cache reuse, and measure the hit rate.
  • cmd-risk - Classify how destructive a shell command is, so an agent knows when to ask a human.
  • ctx-compact - Trim a conversation to a token budget without ever orphaning a tool result.
  • cassette-fn - Record and replay LLM calls at the function boundary, so your tools still run on replay.

License

MIT

About

Apply LLM search/replace edit blocks that do not match exactly, with a five-strategy fallback ladder

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages