Skip to content

< all problems106 · Level 05, Agents

Apply the Model's Edit Without Mangling the File

medium · implement · Agents

A coding agent edits a file by having the model return the block to replace and the block to put in its place. Implement apply_edit(text, old, new), which applies one such edit to the file's text and returns the new text.

  1. An exact match of old that occurs once in text is replaced by new.
  2. A loose match. With no exact match, compare line by line ignoring each line's leading whitespace. The model often loses the indentation. Where that finds one block, replace it, and shift every line of new by the difference between the file's indentation of the matched block's first line and the indentation of old's first line. A blank line stays blank.
  3. No match raises EditError, and the message quotes the line of the file closest to the first line of old (difflib finds it).
  4. More than one match, exact or loose, raises EditError, and the message says how many places matched.
  5. Line endings are kept. A file with \r\n endings comes back with \r\n endings, even when old and new use \n. A file that ended with a newline still does, and one that did not still does not.
  6. An empty old (nothing but whitespace) raises EditError: that is an insert, not an edit.

The catch. Rule 2 is not strip() on both sides. old's first line can carry indentation of its own, and new can carry nesting of its own: a line indented four spaces deeper than new's first line must still be four spaces deeper after the shift.