Overview
Thepatch tool enables agents to create, modify, and delete files using a specialized patch grammar format. It supports context-based hunk matching for updates, directory creation for new files, and FileTime-based conflict detection to prevent editing stale files.
Tool Definition
The patch to apply, using the patch grammar format. Supports three operation types: Add File, Delete File, and Update File.
Patch Grammar Format
Add File
Create a new file with specified content:Delete File
Remove an existing file:Update File
Modify an existing file using hunks with context:- Starts with
@@ ... @@marker - Contains context lines (unchanged, for matching)
- Lines prefixed with
-are removed - Lines prefixed with
+are added - Context lines help locate the hunk even if line numbers changed
Return Value
Returns a context string with results for each operation:Added /path/to/filefor successful additionsDeleted /path/to/filefor successful deletionsUpdated /path/to/filefor successful updates- Error message if any operation fails
Behavior
Add File Operations
- Checks if file already exists (fails if it does)
- Creates parent directories recursively if needed
- Writes content to new file
- Records read timestamp via
fileTime.read()
Delete File Operations
- Asserts file hasn’t been modified since last read via
fileTime.assert() - Deletes the file
- Fails if file was modified externally
Update File Operations
- Asserts file hasn’t been modified via
fileTime.assert() - Acquires write lock via
fileTime.withLock() - Reads current file content
- Applies hunks using context-based matching
- Writes updated content
- Records new read timestamp
- Releases lock
Permission Derivation
For “always allow” feature, the tool:- Extracts all file paths from the patch
- Finds the longest common directory prefix
- Returns a glob pattern like
/common/dir/**
- Single file
/src/foo.ts→/src/** - Multiple files
/src/a.ts,/src/b.ts→/src/** - Different directories
/src/a.ts,/lib/b.ts→/**
Hunk Matching Algorithm
TheapplyHunks function from ./lib/patch-apply.ts:
- Scans file content for matching context lines
- Verifies old lines match expected values
- Replaces old lines with new lines
- Maintains line positions across multiple hunks
- Fails if context doesn’t match (indicates file changed)
Error Handling
The tool fails fast on the first error and returns descriptive messages:- Parse errors:
Patch parse error: <message> - File exists:
File already exists: /path - File modified:
Patch failed on /path: <FileTime assertion error> - Hunk mismatch:
Patch failed on /path: <context matching error>
Usage Examples
Creating a New File
Deleting a File
Updating a File with Single Hunk
Updating with Multiple Hunks
Multiple Operations in One Patch
Handling Conflicts
Implementation Details
The tool is defined inpackages/ai/tools/patch.ts and uses supporting libraries:
./lib/patch-parser.ts- Parses patch grammar into PatchOp structures./lib/patch-apply.ts- Applies hunks with context-based matching./lib/filetime.ts- Tracks read/write timestamps for conflict detection
Schema Definition
PatchOp Types
Execute Function Flow
- Parse patch text into PatchOp array using
parsePatch() - If parse fails, return error immediately
- For each operation:
- Add: Check existence, create dirs, write file, track timestamp
- Delete: Assert unchanged, delete file
- Update: Assert unchanged, lock file, read content, apply hunks, write, track timestamp
- If any operation fails, return error (no partial application)
- Return success message for all operations
FileTime Integration
Related Tools
- read - Read files before patching (required for FileTime tracking)
- bash - Alternative for simple file operations
- agent - Delegate complex refactoring to subagents
Related Documentation
- Types Reference - ToolExecutionResult and FileTime types
- Custom Tool Guide - How to build custom tools with patch-like functionality
