Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 1 addition & 11 deletions docs/features/experimental/experimental-features.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,6 @@ To enable or disable experimental features:

The following experimental features are currently available:

### Unified Diff Editing Strategy

This is an alternate diff editing strategy to the standard search-and-replace algorithm. It evaluates multiple different approaches to applying a unified diff to a file, and selects the best approach for the given file.

**Note:** You must have "Enable editing through diffs" checked to use this feature.

### Multi-block Diff Editing Strategy

Multi-block diff strategy allows updating multiple code blocks in a file in one request.

### Search and Replace

Adds a new tool for searching and replacing text in a file.
Expand All @@ -44,4 +34,4 @@ When enabled, Roo will remind the model about the details of its current mode de

If you encounter any issues with experimental features, or if you have suggestions for improvements, please report them on the [Roo Code GitHub Issues page](https://github.com/RooVetGit/Roo-Code/issues).

Your feedback is valuable and helps us improve Roo Code!
Your feedback is valuable and helps us improve Roo Code!
11 changes: 1 addition & 10 deletions docs/features/fast-edits.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,4 @@ This slider controls how closely the code sections identified by the AI must mat

**Use values below 100% with extreme caution.** Lower precision might be necessary occasionally, but always review the proposed changes carefully.

Internally, this setting adjusts a `fuzzyMatchThreshold` used with algorithms like Levenshtein distance to compare code similarity.


## Experimental Features

Under the "Experimental Features" section, you will find this option:

<img src="/img/fast-edits/fast-edits-2.png" alt="Roo Code settings showing the Experimental Features section with the experimental unified diff strategy checkbox" width="500" />

* **Use experimental unified diff strategy**: This checkbox might appear to enable specific variations or optimizations of the `UnifiedDiffStrategy`. Enabling this could potentially reduce retries caused by model errors but might also introduce unexpected behavior or incorrect edits. Enable only if you understand the risks and are prepared to carefully review all changes.
Internally, this setting adjusts a `fuzzyMatchThreshold` used with algorithms like Levenshtein distance to compare code similarity.
185 changes: 10 additions & 175 deletions docs/features/tools/apply-diff.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ This tool applies targeted changes to existing files using sophisticated strateg

## Key Features

- Implements two primary diff strategies: `MultiSearchReplaceDiffStrategy` and `UnifiedDiffStrategy`.
- Uses intelligent fuzzy matching with configurable confidence thresholds (typically 0.8-1.0).
- Provides context around matches using `BUFFER_LINES` (default 40).
- Employs an overlapping window approach for searching large files.
Expand All @@ -49,21 +48,20 @@ When the `apply_diff` tool is invoked, it follows this process:

1. **Parameter Validation**: Validates required `path` and `diff` parameters.
2. **RooIgnore Check**: Validates if the target file path is allowed by `.rooignore` rules.
3. **Strategy Selection**: Determines the appropriate diff strategy (`MultiSearchReplaceDiffStrategy` or `UnifiedDiffStrategy`) based on the `diff` format and configuration.
4. **File Analysis**: Loads the target file content.
5. **Match Finding**: Uses the selected strategy's algorithms (exact, fuzzy, overlapping windows) to locate the target content, considering confidence thresholds and context (`BUFFER_LINES`).
6. **Change Preparation**: Generates the proposed changes, preserving indentation.
7. **User Interaction**:
3. **File Analysis**: Loads the target file content.
4. **Match Finding**: Uses the selected strategy's algorithms (exact, fuzzy, overlapping windows) to locate the target content, considering confidence thresholds and context (`BUFFER_LINES`).
5. **Change Preparation**: Generates the proposed changes, preserving indentation.
6. **User Interaction**:
* Displays the changes in a diff view.
* Allows the user to review and potentially edit the proposed changes.
* Waits for user approval or rejection.
8. **Change Application**: If approved, applies the changes (potentially including user edits) to the file.
9. **Error Handling**: If errors occur (e.g., match failure, partial application), increments the `consecutiveMistakeCountForApplyDiff` for the file and reports the failure type.
10. **Feedback**: Returns the result, including any user feedback or error details.
7. **Change Application**: If approved, applies the changes (potentially including user edits) to the file.
8. **Error Handling**: If errors occur (e.g., match failure, partial application), increments the `consecutiveMistakeCountForApplyDiff` for the file and reports the failure type.
9. **Feedback**: Returns the result, including any user feedback or error details.

## Diff Strategies
## Diff Strategy

Roo Code uses these primary strategies for applying diffs:
Roo Code uses this strategy for applying diffs:

### MultiSearchReplaceDiffStrategy

Expand Down Expand Up @@ -97,167 +95,4 @@ Example format for the `<diff>` block:
=======
const defaultTimeout = 10000; // Increased timeout
>>>>>>> REPLACE
```

### UnifiedDiffStrategy

Uses the standard unified diff format but incorporates advanced matching algorithms. It supports fuzzy matching with confidence scoring, overlapping windows for large files, and a git-based fallback mechanism for complex changes. This strategy is often used by default when "Enable editing through diffs" is turned on in settings.

* **Best for**: Applying standard patches, handling complex changes, situations where line numbers might be inaccurate, or when fuzzy matching is beneficial.
* **Requires**: Standard unified diff format.

Example format for the `<diff>` block:

```diff
--- a/src/utils.ts
+++ b/src/utils.ts
@@ -1,5 +1,5 @@
import { Logger } from '../logger';

function calculateTotal(items: number[]): number {
- return items.reduce((sum, item) => sum + item, 0);
+ // Add 10% markup and round
+ const total = items.reduce((sum, item) => sum + item * 1.1, 0);
+ return Math.round(total * 100) / 100;
}
```

## Technical Details

### Confidence Thresholds
- Fuzzy matching relies on confidence scores (typically 0.8 to 1.0).
- A score of 1.0 requires a near-exact match, while lower values (e.g., 0.8) allow more flexibility but increase the risk of incorrect matches.
- The threshold can be adjusted in Roo Code settings ("Match precision" slider).

<img src="/img/fast-edits/fast-edits-1.png" alt="Match precision slider in Roo Code settings" width="600" />
*Description: Settings screen showing the 'Match precision' slider for diffs.*

### Context Buffer (`BUFFER_LINES`)
- When searching, the strategies often use surrounding lines (`BUFFER_LINES`, default 40) to help confirm the correct match location, especially for fuzzy matching.

### Overlapping Window Search
- For large files (`LARGE_FILE_THRESHOLD`, default 1000 lines), search is performed in overlapping windows (`MAX_WINDOW_SIZE`, default 500 lines) to manage memory and improve performance.

### Indentation Preservation
- The tool automatically detects and preserves the indentation of the surrounding code when applying changes.

### Overlapping Matches
- The `UnifiedDiffStrategy` can combine multiple potential matches that overlap, improving confidence in the final selected location.

## User Interaction

### Diff View
- Before applying any changes, Roo presents them in a standard diff view within VS Code.
- This allows you to visually inspect the exact changes proposed.

### Editing Changes
- You can directly edit the proposed changes within the diff view before applying them. Roo will use your modified version.

### User Feedback
- After applying (or attempting to apply) the diff, Roo reports success or failure, often including details about the process or specific errors encountered.

## Error Handling

### Consecutive Error Tracking
- Roo tracks `consecutiveMistakeCountForApplyDiff` for each file. If `apply_diff` fails repeatedly on the same file, Roo might switch strategies or suggest alternative approaches.

### Failure Types
- The system distinguishes between partial failures (some changes applied, others failed) and complete failures.

### Common Error Messages
- **Marker Sequencing:** Errors if `<<<<<<< SEARCH`, `=======`, `>>>>>>> REPLACE` markers are missing, misplaced, or duplicated in `MultiSearchReplaceDiffStrategy`.
- **Match Not Found:** The specified `SEARCH` content couldn't be located with sufficient confidence.
- **File Access Denied:** The file path is blocked by a `.rooignore` rule.

Example Marker Sequencing Error:
```
ERROR: Special marker '=======' found in your diff content at line X:
[...]
```

## Marker Handling (MultiSearchReplaceDiffStrategy)

### Validation
- The `MultiSearchReplaceDiffStrategy` strictly validates the sequence and presence of markers (`<<<<<<< SEARCH`, `:start_line:`, `:end_line:`, `-------`, `=======`, `>>>>>>> REPLACE`).

### Escaping Markers
- If your actual code *contains* text that looks like a diff marker (e.g., `<<<<<<< SEARCH`), you **must** escape it in the `diff` block by adding a backslash (`\`) at the beginning of the line when using `apply_diff`.

Example Escaping in `<diff>` block:
```diff
<<<<<<< SEARCH
:start_line:5
:end_line:7
-------
Code before marker
\<<<<<<< SEARCH // Escaped marker in original code
Code after marker
=======
Replacement content
>>>>>>> REPLACE
```
- Escape `\<<<<<<< SEARCH`, `\=======`, and `\>>>>>>> REPLACE` as needed within both `SEARCH` and `REPLACE` blocks if they appear as literal text in your code.

## Integration

### RooIgnore
- The tool respects `.rooignore` files. If a file path matches a pattern in `.rooignore`, `apply_diff` will be blocked. See [Advanced Usage -> Large Projects](/advanced-usage/large-projects) for more on `.rooignore`.

### Cline Integration
- `apply_diff` is integrated into the core `Cline` class, ensuring it respects overall tool permissions and settings like "Enable editing through diffs".

## Best Practices

- **Multiple Changes:** Use the `MultiSearchReplaceDiffStrategy` to apply multiple, independent changes to a file in a single `apply_diff` request for efficiency.
- **Escaping (for `apply_diff`):** When using `apply_diff` with `MultiSearchReplaceDiffStrategy`, always escape literal diff markers (`<<<<<<< SEARCH`, `=======`, `>>>>>>> REPLACE`) within your code snippets using a preceding backslash (`\`).
- **Clarity:** Provide clear and unique `SEARCH` blocks. If the content is highly repetitive, include more surrounding lines for context.
- **Review:** Always review the changes presented in the diff view carefully before approving, especially when fuzzy matching might be involved.
- **Large/Complex Changes:** For very complex refactoring across multiple files, consider breaking down the task or guiding Roo step-by-step. The `UnifiedDiffStrategy` offers the best chance for complex single-file edits due to its advanced matching capabilities.

## Examples When Used

- Fixing a bug: Roo identifies the buggy function and uses `apply_diff` to modify only that function, potentially using `UnifiedDiffStrategy` if the code has slightly changed since it was last read (leveraging fuzzy matching).
- Refactoring: Roo applies targeted improvements using `MultiSearchReplaceDiffStrategy` for several small changes or `UnifiedDiffStrategy` for a standard patch.
- Feature Enhancement: Roo adds new logic within an existing function using a precise diff, relying on indentation preservation.

## Usage Examples

Using `MultiSearchReplaceDiffStrategy` (Requires line numbers):
```xml
<apply_diff>
<path>src/calculation.py</path>
<diff>
<<<<<<< SEARCH
:start_line:1
:end_line:5
-------
def calculate_total(items):
total = 0
for item in items:
total += item
return total
=======
def calculate_total(items):
"""Calculate total with 10% markup"""
return sum(item * 1.1 for item in items)
>>>>>>> REPLACE
</diff>
</apply_diff>
```

Using `UnifiedDiffStrategy`:
```xml
<apply_diff>
<path>src/utils.ts</path>
<diff>
--- a/src/utils.ts
+++ b/src/utils.ts
@@ -24,7 +24,7 @@
function formatUsername(name: string): string {
return name
.toLowerCase()
- .replace(/[^a-z0-9]/g, '');
+ .replace(/[^a-z0-9_-]/g, ''); // Allow underscores and hyphens
}
</diff>
</apply_diff>
```
Binary file removed static/img/fast-edits/fast-edits-2.png
Binary file not shown.