FoundationAgents/MetaGPT · error · ValueError
`to_replace` appears more than once, please include enough l
Error message
`to_replace` appears more than once, please include enough lines to make code in `to_replace` unique.
What it means
Raised by Editor._edit_file_by_replace when the to_replace snippet occurs more than once in the file. Because the tool performs a single targeted replacement (a FIXME notes all-occurrences support is absent), an ambiguous match is rejected rather than replacing an arbitrary instance.
Source
Thrown at metagpt/tools/libs/editor.py:891
# FIXME: support replacing *all* occurrences
if to_replace == new_content:
raise ValueError("`to_replace` and `new_content` must be different.")
# search for `to_replace` in the file
# if found, replace it with `new_content`
# if not found, perform a fuzzy search to find the closest match and replace it with `new_content`
file_name = self._try_fix_path(file_name)
with file_name.open("r") as file:
file_content = file.read()
if to_replace.strip() == "":
if file_content.strip() == "":
raise ValueError(f"The file '{file_name}' is empty. Please use the append method to add content.")
raise ValueError("`to_replace` must not be empty.")
if file_content.count(to_replace) > 1:
raise ValueError(
"`to_replace` appears more than once, please include enough lines to make code in `to_replace` unique."
)
start = file_content.find(to_replace)
if start != -1:
# Convert start from index to line number
start_line_number = file_content[:start].count("\n") + 1
end_line_number = start_line_number + len(to_replace.splitlines()) - 1
else:
def _fuzzy_transform(s: str) -> str:
# remove all space except newline
return re.sub(r"[^\S\n]+", "", s)
# perform a fuzzy search (remove all spaces except newlines)
to_replace_fuzzy = _fuzzy_transform(to_replace)
file_content_fuzzy = _fuzzy_transform(file_content)
# find the closest match
start = file_content_fuzzy.find(to_replace_fuzzy)View on GitHub (pinned to 11cdf466d0)
Solutions
- Widen to_replace with surrounding context lines until it is unique in the file
- Include distinctive lines (function def, decorators, comments) in the snippet
- For truly repeated instances, replace one-by-one with distinguishing context, or handle it outside this API
Example fix
// before
editor.edit_file_by_replace(path, to_replace='return None\n', new_content='return 0\n')
# 'return None' appears 3 times -> ValueError
// after
editor.edit_file_by_replace(path,
to_replace='def count():\n return None\n',
new_content='def count():\n return 0\n') Defensive patterns
Strategy: validation
Validate before calling
file_content = Path(path).read_text()
if file_content.count(to_replace) > 1:
# widen context until unique
idx = file_content.find(to_replace)
# include neighboring lines around idx into to_replace before calling
raise ValueError('ambiguous replace — add context lines')
editor.edit_file_by_replace(path, to_replace, new_content) Type guard
def snippet_is_unique(path: str, snippet: str) -> bool:
return Path(path).read_text().count(snippet) == 1 Try / catch
try:
editor.edit_file_by_replace(path, to_replace, new_content)
except ValueError as e:
if 'more than once' in str(e):
# expand to_replace with surrounding lines and retry once
raise Prevention
- Always include a few context lines around the code being replaced
- Avoid replacing ultra-common lines ('pass', blank lines, imports) without context
- Pre-check uniqueness with file_content.count(snippet) == 1 in your wrapper
When it happens
Trigger: Replacing a common snippet such as a blank line, 'pass', an import, or a repeated log statement that appears multiple times; short one-line replacements of boilerplate code.
Common situations: Agents replacing small/common lines; refactoring duplicated code where the target itself is the duplication; replacing a function signature that appears in both definition and calls.
Related errors
- `to_replace` and `new_content` must be different.
- The file '{file_name}' is empty. Please use the append metho
- `to_replace` must not be empty.
- No file open. Use the open_file function first.
- File {path} not found
AI-assisted analysis of FoundationAgents/MetaGPT@11cdf466d0 (2026-08-14).
Data as JSON: /api/errors/187a02b9edc70340.
Report an issue: GitHub.