Aider-AI/aider · error · DiffError

Unknown or misplaced line while parsing patch: {line}

Error message

Unknown or misplaced line while parsing patch: {line}

What it means

Catch-all parse error: a line inside the patch body matched none of the recognized action headers (Update/Delete/Add/Move, end-of-file marker, etc.) and was not blank. The parser only skips blank lines between actions; anything else is unexpected at top level.

Source

Thrown at aider/coders/patch_coder.py:402

                if path in patch.actions:
                    raise DiffError(f"Duplicate action for file: {path}")
                # Check if file exists in the context provided (should not for Add).
                # Note: We only have needed files, a full check requires FS access.
                # if path in current_files:
                #     raise DiffError(f"Add File Error - file already exists: {path}")

                action, index = self._parse_add_file_content(lines, index)
                action.path = path  # Ensure path is set
                patch.actions[path] = action
                continue

            # If we are here, the line is unexpected
            # Allow blank lines between actions
            if not norm_line.strip():
                index += 1
                continue

            raise DiffError(f"Unknown or misplaced line while parsing patch: {line}")

        # Check if we consumed the whole input or stopped early
        # Tolerate missing "*** End Patch" if we processed actions
        # if index < len(lines) and _norm(lines[index-1]) != "*** End Patch":
        #    raise DiffError("Patch parsing finished unexpectedly before end of input.")

        patch.fuzz = fuzz_accumulator
        return patch

    def _parse_update_file_sections(
        self, lines: List[str], index: int, file_content: str
    ) -> Tuple[PatchAction, int, int]:
        """Parses all sections (@@, context, -, +) for a single Update File action."""
        action = PatchAction(type=ActionType.UPDATE, path="")  # Path set by caller
        orig_lines = file_content.splitlines()  # Use splitlines for consistency
        current_file_index = 0  # Track position in original file content
        total_fuzz = 0

View on GitHub (pinned to 5dc9490bb3)

Solutions

  1. Check the reported line and ensure every non-blank line belongs to a file section started by a valid '*** Update File:'/'*** Add File:'/'*** Delete File:' header
  2. Verify marker spelling and case exactly ('*** Update File:', '*** End Patch')
  3. Move any commentary outside the fence and regenerate the patch

Example fix

// before
+import os
*** Update File: a.py
*** End Patch

// after
*** Update File: a.py
+import os
*** End Patch
Defensive patterns

Strategy: try-catch

Validate before calling

KNOWN = ("*** Begin Patch", "*** Update File: ", "*** Delete File: ", "*** Add File: ", "*** Move to: ", "*** End of File", "*** End Patch")

def top_level_lines_ok(patch_lines: list[str]) -> bool:
    in_section = False
    for line in patch_lines:
        if line.startswith("*** "):
            in_section = not line.startswith("*** End Patch")
            continue
        if not in_section and line.strip():
            return False
    return True

Try / catch

try:
    edits = coder.get_edits(reply)
except DiffError as e:
    if "Unknown or misplaced line" in str(e):
        bad = str(e).split("parsing patch: ", 1)[-1]
        reply = regenerate_with_note(reply, f"Fix this stray line: {bad}")
        edits = coder.get_edits(reply)
    else:
        raise

Prevention

When it happens

Trigger: A context/change line ('+ foo' or ' foo') appearing before any '*** Update File:' header; stray prose from the model inside the patch fence; wrong fence or marker spelling (e.g. '*** update file:'); trailing junk after '*** End Patch'.

Common situations: Model chats inside the code block; patch body lines leaked outside their file section; localized marker text or case mismatches; hand-edited patches with typos in the '***' headers.

Related errors


AI-assisted analysis of Aider-AI/aider@5dc9490bb3 (2026-08-15). Data as JSON: /api/errors/1e05f9b59d45acb3. Report an issue: GitHub.