Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 | 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 19x 19x 19x 19x 19x 19x 19x 6x 2x 2x 2x 2x 2x 9x 9x 1x 8x 8x 1x 7x 13x 13x 2x 13x 13x 65x 13x 1x 13x 13x 13x 13x 4x 4x 4x 9x 9x 7x 1x 1x 7x 1x 1x 6x 6x 6x 6x 3x 3x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x | import {
BadRequestException,
Injectable,
InternalServerErrorException,
Logger,
Optional,
} from '@nestjs/common';
import * as fs from 'fs/promises';
import * as fsSync from 'fs';
import * as path from 'path';
import * as os from 'os';
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';
import { ActionHandler } from './action-handler.interface';
import {
ActionExecutionResult,
PlanExecutionContext,
ToolMetadata,
} from '../llm-orchestration.interfaces';
import { QuickEditArgsDto } from './dto/quick-edit.args.dto';
import { generateToolCall, generateToolCallJson } from '../../utils';
import { HybridMatcher } from './matchers/hybrid.matcher';
import { SyntaxValidationService } from '../../syntax-validation/syntax-validation.service';
import { ApplicationStateService } from '../../application-state/application-state.service';
@Injectable()
export class QuickEditHandler implements ActionHandler {
readonly toolName = 'quick_edit';
private readonly logger = new Logger(QuickEditHandler.name);
private readonly projectRoot: string =
process.env.REPOBURG_PROJECT_PATH || process.cwd();
private readonly hybridMatcher = new HybridMatcher();
private readonly logDir: string =
process.env.QUICK_EDIT_LOG_DIR ||
path.join(os.homedir(), '.repoburg/quick-edit-logs');
constructor(
@Optional()
private readonly syntaxValidator?: SyntaxValidationService,
@Optional()
private readonly appStateService?: ApplicationStateService,
) {}
getMetadata(): ToolMetadata {
return {
name: this.toolName,
description: this.getDefinition(true),
arguments: [
{
name: 'file_path',
type: 'string',
description: 'The relative path to file to be modified.',
required: true,
},
{
name: 'action',
type: 'string',
description:
"The operation to perform. Allowed values: 'insert_after', 'insert_before', 'replace', 'delete_block'. Defaults to 'replace'.",
required: false,
},
{
name: 'search_block',
type: 'string',
description:
'A unique and exact block of code to locate the position for the edit.',
required: true,
},
{
name: 'new_content',
type: 'string',
description:
"The new code to be added. Required for 'insert_after', 'insert_before', and 'replace'.",
required: false,
},
],
};
}
/**
* Generates a tool call example in the specified format.
* @param toolCall - The tool call object to format
* @param useJson - If true, uses JSON format; otherwise uses XML-style format
* @returns Formatted tool call string
*/
private generateExample(
toolCall: Record<string, any>,
useJson: boolean = false,
): string {
return useJson
? generateToolCallJson(toolCall)
: generateToolCall(toolCall);
}
getDefinition(useJsonFormat: boolean = false): string {
const insertAfterExample = this.generateExample(
{
tool_name: this.toolName,
file_path: 'src/components/Header.tsx',
action: 'insert_after',
search_block: `import React from 'react';`,
new_content: `import { useTheme } from '@emotion/react';`,
},
useJsonFormat,
);
const replaceExample = this.generateExample(
{
tool_name: this.toolName,
file_path: 'src/config.ts',
action: 'replace',
search_block: `export const API_TIMEOUT = 5000;`,
new_content: `export const API_TIMEOUT = 10000; // Increased timeout`,
},
useJsonFormat,
);
const deleteExample = this.generateExample(
{
tool_name: this.toolName,
file_path: 'src/utils/legacy.js',
action: 'delete_block',
search_block: `
function oldUnusedFunction() {
return 'hello';
}
`.trim(),
},
useJsonFormat,
);
const definition = `
-------------
### ${this.toolName}
Makes small, targeted changes to a file by finding a unique block of text and inserting, replacing, or deleting it.
**Best Practices:**
- Include 3-5 lines surrounding code you want to edit
- Use unique identifiers (variable names, function names) in your search block
- Avoid selecting large blocks (>10 lines) - smaller is more reliable
- Verify your search block matches the file exactly character-for-character
- When code appears multiple times, include more surrounding context to disambiguate
**Common Pitfalls:**
- Search block with trailing characters the LLM added (e.g., "value;xyz")
- Extra whitespace or indentation not present in file
- Selecting only common patterns (imports, exports) that appear multiple times
- Including code that was already edited in a previous action
**When to use quick_edit vs overwrite_file:**
- Use quick_edit for small, targeted changes (1-10 lines)
- Use overwrite_file for large replacements, complete file rewrites, or when search block cannot be unique
#### Parameters
- "file_path": (string) The relative path to file to be modified.
- "action": (enum, optional) The operation to perform. Allowed values: 'insert_after', 'insert_before', 'replace', 'delete_block'. Defaults to 'replace'.
- "search_block": (string) A unique and exact block of code to locate the position for the edit.
- "new_content": (string, optional) The new code to be added. Required for 'insert_after', 'insert_before', and 'replace'.
#### Example: Insert After
Explanation: Add an import statement after the React import.
${insertAfterExample}
#### Example: Replace
Explanation: Change the API timeout constant value.
${replaceExample}
#### Example: Delete
Explanation: Remove the old unused function.
${deleteExample}
-------------
`;
return `\n${definition.trim()}\n`;
}
private resolveAndValidatePath(unsafePath: string): string {
const normalizedPath = path.normalize(unsafePath);
if (path.isAbsolute(normalizedPath)) {
throw new BadRequestException(
`Absolute paths are not allowed: ${unsafePath}`,
);
}
const resolvedPath = path.resolve(this.projectRoot, normalizedPath);
if (!resolvedPath.startsWith(this.projectRoot)) {
throw new BadRequestException(
`Path traversal is not allowed: ${unsafePath}`,
);
}
return resolvedPath;
}
/**
* Normalizes common parameter name mistakes before validation.
* Maps intuitive but incorrect names to the expected schema.
* @param args - The raw arguments from the LLM
* @returns Normalized arguments with correct parameter names
*/
private normalizeArgs(args: Record<string, any>): Record<string, any> {
const normalized = { ...args };
// Apply default value for action if missing or undefined
if (normalized.action === undefined || normalized.action === null) {
normalized.action = 'replace';
}
// Map common parameter name mistakes to correct ones
const mappings: Record<string, string> = {
old_content: 'search_block',
search: 'search_block',
target: 'search_block',
replacement: 'new_content',
content: 'new_content',
};
for (const [incorrect, correct] of Object.entries(mappings)) {
Iif (incorrect in normalized && !(correct in normalized)) {
normalized[correct] = normalized[incorrect];
delete normalized[incorrect];
this.logger.debug(
`Auto-corrected parameter name: "${incorrect}" → "${correct}"`,
);
}
}
return normalized;
}
/**
* Format error message when file is not found.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
private formatNotFoundMessage(filePath: string, searchBlock: string): string {
return `File \`${filePath}\` not found. Use \`request_context\` to verify the file path and content.`;
}
/**
* Format error message with candidate matches.
* Provides concise information to help the LLM choose the correct block.
*/
private formatErrorWithCandidates(
filePath: string,
searchBlock: string,
matchResult: any,
): string {
// No candidates at all
Iif (!matchResult.candidates || matchResult.candidates.length === 0) {
return `Search block not found in \`${filePath}\`. Use \`request_context\` to read the file and verify content.`;
}
// Multiple candidates found - short message
const count = matchResult.candidates.length;
return `Found **${count} possible matches** for your search block in \`${filePath}\`. Include more surrounding lines or use \`request_context\` to uniquely identify the correct location.`;
}
/**
* Writes a detailed log file when search block matching fails.
* Creates a separate log file for each failure with a timestamp-based filename.
* @param action - The action being performed
* @param searchBlock - The search block that failed to match
* @param filePath - The relative path to the file
* @param fileContent - The full content of the file before modification
*/
private async writeMatchFailureLog(
action: string,
searchBlock: string,
filePath: string,
fileContent: string,
): Promise<void> {
try {
// Use fsSync.promises to avoid test mocks interfering with logging
await fsSync.promises.mkdir(this.logDir, { recursive: true });
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const logFileName = `quick-edit-failure-${timestamp}.txt`;
const logFilePath = path.join(this.logDir, logFileName);
const logContent = `Timestamp: ${new Date().toISOString()}
Action: ${action}
FilePath: ${filePath}
Search Block:
${searchBlock}
File Content Before Modification:
${fileContent}`;
await fsSync.promises.writeFile(logFilePath, logContent, 'utf8');
this.logger.debug(`Match failure log written to: ${logFilePath}`);
} catch (error) {
this.logger.error(`Failed to write match failure log: ${error.message}`);
}
}
async execute(
args: { [key: string]: any },
_context: PlanExecutionContext,
): Promise<ActionExecutionResult> {
// Auto-correct common parameter name mistakes before validation
const normalizedArgs = this.normalizeArgs(args);
const validatedArgs = plainToClass(QuickEditArgsDto, normalizedArgs);
const errors = await validate(validatedArgs);
if (errors.length > 0) {
const errorMessages = errors
.map((err) => Object.values(err.constraints || {}).join(', '))
.join('; ');
return {
status: 'FAILURE',
summary: `Invalid arguments for ${this.toolName}.`,
error_message: errorMessages,
persisted_args: args,
execution_log: { output: '', error_message: errorMessages },
};
}
const { file_path, action, search_block, new_content } = validatedArgs;
const safePath = this.resolveAndValidatePath(file_path);
const originalContent = await fs
.readFile(safePath, 'utf8')
.catch((error) => {
if (error.code === 'ENOENT') {
return null;
}
throw error;
});
if (originalContent === null) {
const errorMessage = this.formatNotFoundMessage(file_path, search_block);
return {
status: 'FAILURE',
summary: `Quick edit on "${file_path}" failed: File not found.`,
error_message: errorMessage,
persisted_args: validatedArgs,
execution_log: { output: '', error_message: errorMessage },
};
}
// Use hybrid matching algorithm
const matchResult = this.hybridMatcher.findBestMatch(
search_block,
originalContent,
);
Iif (!matchResult.found || !matchResult.unique) {
await this.writeMatchFailureLog(
action,
search_block,
file_path,
originalContent,
);
const errorMessage = this.formatErrorWithCandidates(
file_path,
search_block,
matchResult,
);
return {
status: 'FAILURE',
summary: `Quick edit on "${file_path}" failed: Match issue.`,
error_message: errorMessage,
persisted_args: validatedArgs,
execution_log: { output: '', error_message: errorMessage },
};
}
let newFileContent: string;
const { before, after } = matchResult;
switch (action) {
case 'replace':
newFileContent = `${before}${new_content}${after}`;
break;
case 'insert_after':
newFileContent = `${before}${search_block}\n${new_content}${after}`;
break;
case 'insert_before':
newFileContent = `${before}${new_content}\n${search_block}${after}`;
break;
case 'delete_block':
newFileContent = `${before}${after}`;
break;
}
// Check if content is identical after edit
Iif (newFileContent === originalContent) {
const noChangeMessage = `The quick_edit operation on "${file_path}" resulted in no changes. The new content is identical to the original content. This typically means your edit didn't change anything (e.g., replacing with the same content, or inserting duplicate content). Please review your edit and ensure you're making the intended changes.`;
return {
status: 'FAILURE',
summary: `Quick edit on "${file_path}" produced no changes.`,
error_message: noChangeMessage,
persisted_args: validatedArgs,
execution_log: { output: '', error_message: noChangeMessage },
};
}
try {
await fs.writeFile(safePath, newFileContent, 'utf8');
// Syntax validation after quick edit
Iif (this.syntaxValidator && this.appStateService) {
const isValidationEnabled =
await this.appStateService.getSyntaxValidationEnabled();
Iif (isValidationEnabled) {
const validationError = await this.syntaxValidator.validate(
file_path,
newFileContent,
);
Iif (validationError) {
this.logger.warn(
`Syntax validation failed for quick edit on "${file_path}"`,
);
let errorMessage =
this.syntaxValidator.formatErrors(validationError);
errorMessage += `\n**CORRECTION:** Your \`quick_edit\` introduced syntax errors. The original file content has been restored. `;
errorMessage += `Please ensure your edit maintains syntactically valid code. `;
errorMessage += `Common issues: missing closing braces in inserted code, mismatched quotes, or broken imports. `;
errorMessage += `Use \`request_context\` to verify the file state and try again with a corrected \`search_block\` or \`new_content\`.`;
// Restore original content to prevent corruption
if (originalContent !== null) {
await fs.writeFile(safePath, originalContent, 'utf8');
} else {
await fs.unlink(safePath).catch(() => {});
}
return {
status: 'FAILURE',
summary: `File "${file_path}" contains syntax errors after quick_edit and was reverted.`,
error_message: errorMessage,
persisted_args: validatedArgs,
execution_log: { output: '', error_message: errorMessage },
};
}
}
}
return {
status: 'SUCCESS',
summary: `File "${file_path}" successfully modified with quick_edit.`,
persisted_args: { ...validatedArgs, content: newFileContent },
original_content_for_revert: originalContent,
execution_log: {
output: `${file_path} has been modified.`,
error_message: '',
},
};
} catch (error) {
this.logger.error(
`Failed to write file for quick edit at ${file_path}: ${error.message}`,
);
throw new InternalServerErrorException(
`Failed to quick_edit file "${file_path}": ${error.message}`,
);
}
}
}
|