> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_10_snapshot_and_file_system/10.3_patch_system.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 10.3 Patch System

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Date Generated**: 2026-02-17

***

In addition to line-by-line editing (the Edit tool) and full-file overwriting (the Write tool), OpenCode also provides a patch-based file modification approach -- the `apply_patch` tool. It allows the LLM to describe creation, deletion, and modification operations on multiple files in a single, standardized patch format. This section analyzes the implementation of `patch/index.ts`.

## 10.3.1 patch/index.ts: Diff Patch Generation and Application

The `Patch` module (681 lines) implements a complete patch parsing and application system. Its patch format is not the standard unified diff, but rather a custom format designed specifically for LLMs.

### Patch Format

OpenCode's patch format uses `***` markers to distinguish between different operations:

```
*** Begin Patch
*** Add File: path/to/new-file.ts
+line 1 of new file
+line 2 of new file

*** Delete File: path/to/old-file.ts

*** Update File: path/to/existing.ts
@@ context line
-old line to remove
+new line to add
 unchanged line

*** End Patch
```

### Hunk Types

A patch is parsed into a set of `Hunk`s (operation units), each corresponding to an operation on a single file:

```typescript
export type Hunk =
  | { type: "add"; path: string; contents: string }       // Add new file
  | { type: "delete"; path: string }                       // Delete file
  | { type: "update"; path: string; move_path?: string;    // Modify file
      chunks: UpdateFileChunk[] }

export interface UpdateFileChunk {
  old_lines: string[]          // Old lines to be replaced
  new_lines: string[]          // New lines after replacement
  change_context?: string      // Context identifier (for positioning)
  is_end_of_file?: boolean     // Whether operating at the end of file
}
```

The `update` type Hunk is the most complex -- it contains multiple `UpdateFileChunk`s, each describing a localized replacement operation within the file.

### Patch Parsing

The `parsePatch()` function parses patch text and extracts a structured list of Hunks:

```typescript
export function parsePatch(patchText: string): { hunks: Hunk[] } {
  const cleaned = stripHeredoc(patchText.trim())  // Remove heredoc wrapper
  const lines = cleaned.split("\n")
  const hunks: Hunk[] = []

  // Find Begin/End markers
  const beginIdx = lines.findIndex(line => line.trim() === "*** Begin Patch")
  const endIdx = lines.findIndex(line => line.trim() === "*** End Patch")

  // Iterate through content between markers
  while (i < endIdx) {
    if (lines[i].startsWith("*** Add File:")) {
      // Parse new file contents (lines starting with "+")
      hunks.push({ type: "add", path, contents })
    } else if (lines[i].startsWith("*** Delete File:")) {
      hunks.push({ type: "delete", path })
    } else if (lines[i].startsWith("*** Update File:")) {
      // Parse update chunks
      hunks.push({ type: "update", path, move_path, chunks })
    }
  }
  return { hunks }
}
```

### Fuzzy Matching Application

A standout feature of `apply_patch` is its **multi-level fuzzy matching**. When searching for old lines to replace in a file, it does not require strict character-level exact matching, but instead provides a four-level progressive matching strategy:

```typescript
function seekSequence(
  lines: string[],
  pattern: string[],
  startIndex: number,
  eof = false
): number {
  // Pass 1: Exact match
  const exact = tryMatch(lines, pattern, startIndex, (a, b) => a === b, eof)
  if (exact !== -1) return exact

  // Pass 2: Match after trimming trailing whitespace
  const rstrip = tryMatch(lines, pattern, startIndex,
    (a, b) => a.trimEnd() === b.trimEnd(), eof)
  if (rstrip !== -1) return rstrip

  // Pass 3: Match after trimming leading and trailing whitespace
  const trim = tryMatch(lines, pattern, startIndex,
    (a, b) => a.trim() === b.trim(), eof)
  if (trim !== -1) return trim

  // Pass 4: Match after Unicode normalization
  const normalized = tryMatch(lines, pattern, startIndex,
    (a, b) => normalizeUnicode(a.trim()) === normalizeUnicode(b.trim()), eof)
  return normalized
}
```

Why is multi-level matching needed? Because context lines in LLM-generated patches may contain subtle differences:

* **Whitespace differences**: The LLM may have added or removed extra spaces/indentation.
* **Unicode differences**: The LLM may have converted regular quotes `'` into smart quotes `'`, or hyphens `-` into em dashes `--`.

The `normalizeUnicode()` function handles these common Unicode substitutions:

```typescript
function normalizeUnicode(str: string): string {
  return str
    .replace(/[\u2018\u2019\u201A\u201B]/g, "'")  // Smart single quotes -> regular single quotes
    .replace(/[\u201C\u201D\u201E\u201F]/g, '"')   // Smart double quotes -> regular double quotes
    .replace(/[\u2010-\u2015]/g, "-")               // Various dashes -> hyphen
    .replace(/\u2026/g, "...")                       // Ellipsis -> three dots
    .replace(/\u00A0/g, " ")                         // Non-breaking space -> regular space
}
```

### Replacement Application

After finding the match position, `applyReplacements()` applies all replacements in reverse order to avoid index offset issues:

```typescript
function applyReplacements(
  lines: string[],
  replacements: Array<[number, number, string[]]>
): string[] {
  const result = [...lines]
  // Apply from back to front to avoid index offset
  for (let i = replacements.length - 1; i >= 0; i--) {
    const [startIdx, oldLen, newSegment] = replacements[i]
    result.splice(startIdx, oldLen)
    for (let j = 0; j < newSegment.length; j++) {
      result.splice(startIdx + j, 0, newSegment[j])
    }
  }
  return result
}
```

## 10.3.2 Implementation Details of the apply\_patch Tool

The `apply_patch` tool is actually a "shadow feature" of the Bash tool -- when a Bash command is detected as an `apply_patch` invocation, it is intercepted and handled using the Patch module rather than being executed as an actual shell command:

```typescript
// Detection logic in tool/bash.ts
const result = Patch.maybeParseApplyPatch(argv)
if (result.type === "Body") {
  // Intercept! Don't execute the shell command; use the Patch module to apply the patch
  const action = await Patch.maybeParseApplyPatchVerified(argv, cwd)
  // ... apply patch and return result
}
```

`maybeParseApplyPatchVerified()` not only parses the patch but also **pre-validates** the correctness of each operation -- it checks whether all replacements can find matches before actually writing to any files. If any chunk cannot find matching old lines in the target file, it returns a `CorrectnessError` instead of partially applying the patch, ensuring atomicity of the operation.

***

> **Section Summary**
>
> OpenCode's Patch system implements a patch format optimized for LLMs, supporting file addition, deletion, and modification operations. The core highlight is the four-level progressive fuzzy matching strategy (exact -> trim trailing whitespace -> trim leading and trailing whitespace -> Unicode normalization), which tolerates common whitespace and character differences in LLM-generated patches. Replacements are applied in reverse order to avoid index offsets, and the entire operation ensures atomicity through pre-validation.
