Apply a patch to modify one or more files using the enveloped patch format.

**RECOMMENDED: Use apply_patch for targeted file edits to avoid rewriting entire files and wasting tokens.**

Use `apply_patch` only when:
- You want to make targeted edits to specific lines (primary use case)
- You want to make multiple related changes across different files in a single operation
- You need to add/delete entire files along with modifications
- You have JUST read the file and are confident the content hasn't changed

**IMPORTANT: Patches require EXACT line matches. If the file content has changed since you last read it, the patch will fail.**

**Alternative: Use the `edit` tool if you need fuzzy matching or structured operations.**

## Patch Format

All patches must be wrapped in markers and use explicit file directives:

```
*** Begin Patch
*** Add File: path/to/file.txt
+line 1
+line 2
*** Update File: path/to/other.txt
-old line
+new line
*** Delete File: path/to/delete.txt
*** End Patch
```

## File Operations

### Add a new file:
```
*** Begin Patch
*** Add File: src/hello.ts
+export function hello() {
+  console.log("Hello!");
+}
*** End Patch
```

### Update an existing file (simple replacement):
```
*** Begin Patch
*** Update File: src/config.ts
-const PORT = 3000;
+const PORT = 8080;
*** End Patch
```

**CRITICAL**: The `-` lines must match EXACTLY what's in the file, character-for-character. If you're not 100% certain, use the `edit` tool instead.

### Update with context (recommended for precision):
```
*** Begin Patch
*** Update File: src/app.ts
@@ function main()
 function main() {
-  console.log("old");
+  console.log("new");
 }
*** End Patch
```

The `@@ context line` helps locate the exact position, but the `-` lines must still match exactly.

### Delete a file:
```
*** Begin Patch
*** Delete File: old/unused.ts
*** End Patch
```

### Multiple operations in one patch:
```
*** Begin Patch
*** Add File: new.txt
+New content
*** Update File: existing.txt
-old
+new
*** Delete File: obsolete.txt
*** End Patch
```

## Line Prefixes

- Lines starting with `+` are added
- Lines starting with `-` are removed  
- Lines starting with ` ` (space) are context (kept unchanged)
- Lines starting with `@@` provide context for finding the location

## Common Errors

**"Failed to find expected lines"**: The file content doesn't match your patch. The file may have changed, or you may have mistyped the lines. Solution: Use the `edit` tool instead.

## Important Notes

- **Patches are fragile**: Any mismatch in whitespace, indentation, or content will cause failure
- **Use `edit` for reliability**: The `edit` tool can make targeted changes without requiring exact matches
- All file paths are relative to the project root
- The patch format does NOT support standard unified diff format (no `---`/`+++` headers)
- Always wrap patches with `*** Begin Patch` and `*** End Patch`
