{"record":{"id":"bf727701ff6a8ebb","repo":"FoundationAgents/MetaGPT","slug":"to-replace-must-not-be-empty","errorCode":null,"errorMessage":"`to_replace` must not be empty.","messagePattern":"`to_replace` must not be empty\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"metagpt/tools/libs/editor.py","lineNumber":888,"sourceCode":"            This tool is exclusive. If you use this tool, you cannot use any other commands in the current response.\n            If you need to use it multiple times, wait for the next turn.\n        \"\"\"\n        # FIXME: support replacing *all* occurrences\n\n        if to_replace == new_content:\n            raise ValueError(\"`to_replace` and `new_content` must be different.\")\n\n        # search for `to_replace` in the file\n        # if found, replace it with `new_content`\n        # if not found, perform a fuzzy search to find the closest match and replace it with `new_content`\n        file_name = self._try_fix_path(file_name)\n        with file_name.open(\"r\") as file:\n            file_content = file.read()\n\n        if to_replace.strip() == \"\":\n            if file_content.strip() == \"\":\n                raise ValueError(f\"The file '{file_name}' is empty. Please use the append method to add content.\")\n            raise ValueError(\"`to_replace` must not be empty.\")\n\n        if file_content.count(to_replace) > 1:\n            raise ValueError(\n                \"`to_replace` appears more than once, please include enough lines to make code in `to_replace` unique.\"\n            )\n        start = file_content.find(to_replace)\n        if start != -1:\n            # Convert start from index to line number\n            start_line_number = file_content[:start].count(\"\\n\") + 1\n            end_line_number = start_line_number + len(to_replace.splitlines()) - 1\n        else:\n\n            def _fuzzy_transform(s: str) -> str:\n                # remove all space except newline\n                return re.sub(r\"[^\\S\\n]+\", \"\", s)\n\n            # perform a fuzzy search (remove all spaces except newlines)\n            to_replace_fuzzy = _fuzzy_transform(to_replace)","sourceCodeStart":870,"sourceCodeEnd":906,"githubUrl":"https://github.com/FoundationAgents/MetaGPT/blob/11cdf466d042aece04fc6cfd13b28e1a70341b1f/metagpt/tools/libs/editor.py#L870-L906","documentation":"Raised by Editor._edit_file_by_replace when to_replace strips to an empty string but the file has non-whitespace content. An empty search pattern is meaningless for a targeted replace (and str.replace semantics would be dangerous), so the tool requires a concrete snippet to anchor on.","triggerScenarios":"editor.edit_file_by_replace(path, to_replace='', new_content=c) or to_replace='   \\n' against a file with real content; an LLM omitting the to_replace parameter or sending only whitespace.","commonSituations":"Tool-call schemas where to_replace is optional and gets defaulted to ''; whitespace-only snippets from bad extraction; prepend attempts mistakenly routed through replace.","solutions":["Provide the exact existing code snippet to anchor the replacement","To add content without removing anything, use insert (at a line) or append instead of replace","Validate to_replace.strip() is non-empty in your wrapper before calling"],"exampleFix":"// before\neditor.edit_file_by_replace(path, to_replace='', new_content='import os\\n')  # ValueError\n\n// after\neditor.insert_content_at('import os\\n', file=path, line_number=1)  # prepend via insert","handlingStrategy":"validation","validationCode":"if not to_replace.strip():\n    if Path(path).read_text().strip() == '':\n        editor.append_file(path, new_content)\n    else:\n        editor.insert_content_at(new_content, line_number=1)\nelse:\n    editor.edit_file_by_replace(path, to_replace, new_content)","typeGuard":"def has_anchor(to_replace: str) -> bool:\n    return to_replace.strip() != ''","tryCatchPattern":"try:\n    editor.edit_file_by_replace(path, to_replace, new_content)\nexcept ValueError as e:\n    if 'must not be empty' in str(e):\n        raise ValueError('to_replace missing — provide the exact snippet to replace')\n    raise","preventionTips":["Require to_replace in your tool schema (no default)","Use insert/append when adding rather than replacing","Validate snippet non-emptiness where LLM output is parsed"],"tags":["editor","replace","validation","metagpt"],"backgroundTag":null,"analyzedSha":"11cdf466d042aece04fc6cfd13b28e1a70341b1f","analyzedAt":"2026-08-14T23:20:02.994Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}