{"record":{"id":"d01b2030ec40cba2","repo":"datawhalechina/hello-agents","slug":"update-hunk-has-no-context-removals-refusing-to-a","errorCode":null,"errorMessage":"Update hunk has no context/removals; refusing to apply","messagePattern":"Update hunk has no context/removals; refusing to apply","errorType":"exception","errorClass":"PatchApplyError","httpStatus":null,"severity":"error","filePath":"Co-creation-projects/YYHDBL-HelloCodeAgentCli/code_agent/executors/apply_patch_executor.py","lineNumber":461,"sourceCode":"            PatchApplyError: 当 hunk 格式错误或找不到匹配的上下文时抛出\n        \"\"\"\n        before: List[str] = []\n        after: List[str] = []\n        for l in hunk_lines:\n            if not l:\n                continue\n            tag = l[0]\n            text = l[1:] + \"\\n\"\n            if tag == \" \":\n                before.append(text)\n                after.append(text)\n            elif tag == \"-\":\n                before.append(text)\n            elif tag == \"+\":\n                after.append(text)\n\n        if not before:\n            raise PatchApplyError(\"Update hunk has no context/removals; refusing to apply\")\n\n        idx = self._find_subsequence(current, before)\n        if idx is None:\n            context_line = next((b.strip() for b in before if b.strip()), \"\")\n            hint = f\"{rel_path}:search:'{context_line[:80]}'\"\n            raise PatchApplyError(\"Patch hunk context not found; file changed?\", recheck_targets=[hint])\n\n        return current[:idx] + after + current[idx + len(before) :]\n\n    def _find_subsequence(self, haystack: List[str], needle: List[str]) -> Optional[int]:\n        \"\"\"\n        在文件内容中查找代码块的起始位置。\n        使用简单的 O(N*M) 字符串匹配算法，在 haystack 中查找 needle 的精确匹配。\n        \n        参数:\n            haystack: 文件内容行列表\n            needle: 要查找的代码块行列表\n            ","sourceCodeStart":443,"sourceCodeEnd":479,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/Co-creation-projects/YYHDBL-HelloCodeAgentCli/code_agent/executors/apply_patch_executor.py#L443-L479","documentation":"Raised while applying an Update File hunk when the 'before' side is empty — the hunk contains only '+' additions and no context (' ') or removal ('-') lines. Pure-insertion hunks are rejected because _find_subsequence has no anchor to locate where the new lines belong, making the write position ambiguous.","triggerScenarios":"An Update File body whose every line starts with '+': e.g. trying to append to a file via Update with no surrounding context; models adding a new function but forgetting to include the surrounding context lines.","commonSituations":"LLM uses Update File where Add File was intended (new file, all-plus body); appending to the end of a file without quoting the last existing lines; patch-generation tools that emit zero-context diffs.","solutions":["For new files, use '*** Add File: ' with the full content instead of Update.","For insertions into an existing file, include at least one unchanged context line (prefixed with a single space) above or below the '+' lines.","For end-of-file appends, quote the final existing line(s) as context, then the '+' lines."],"exampleFix":"# before\n*** Update File: notes.py\n+def new_fn():\n+    pass\n*** End Patch\n\n# after\n*** Update File: notes.py\n def existing_fn():\n     pass\n+\n+def new_fn():\n+    pass","handlingStrategy":"validation","validationCode":"def hunk_has_anchor(body: str) -> bool:\n    lines = [l for l in body.splitlines() if l.strip()]\n    return any(not l.startswith('+') for l in lines)  # needs ' ' or '-' lines","typeGuard":null,"tryCatchPattern":"try:\n    executor.apply(patch_text)\nexcept PatchApplyError as e:\n    if 'no context/removals' in str(e):\n        # convert to Add File if new, else add surrounding context lines\n        patch_text = add_context_lines(patch_text, file_content)\n        executor.apply(patch_text)","preventionTips":["Always include at least one unchanged context line in Update hunks.","Use Add File for brand-new files, never Update.","Teach the model the hunk grammar with anchor requirements."],"tags":["patch","hunk","apply-patch","llm-output"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}