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 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 | 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 10x 10x 10x 10x 10x 8x 2x 2x 2x 2x 2x 2x 2x 10x 10x 10x 10x 10x 10x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 4x 4x 4x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 2x 2x 1x 1x 1x 1x 1x 1x | import {
BadRequestException,
Injectable,
Logger,
Optional,
} from '@nestjs/common';
import * as fs from 'fs/promises';
import { existsSync } from 'fs';
import * as path from 'path';
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 { PatchArgsDto } from './dto/patch.args.dto';
import { applySnippetPatch } from '../../../packages/tokenpatch';
import { generateToolCall, generateToolCallJson } from '../../utils';
import {
SPECIAL_PATCH_BEGIN_FILE_MARKER,
SPECIAL_PATCH_END_FILE_MARKER,
} from '../parser/parsing.constants';
import { SyntaxValidationService } from '../../syntax-validation/syntax-validation.service';
import { ApplicationStateService } from '../../application-state/application-state.service';
const ENABLE_TREE_SITTER = false;
// Mapping file extensions to their Tree-sitter grammar WASM files.
const grammarMap: Record<string, string> = {
'.js': 'tree-sitter-javascript.wasm',
'.jsx': 'tree-sitter-javascript.wasm',
'.ts': 'tree-sitter-typescript.wasm',
'.tsx': 'tree-sitter-tsx.wasm',
'.json': 'tree-sitter-json.wasm',
'.html': 'tree-sitter-html.wasm',
'.css': 'tree-sitter-css.wasm',
'.py': 'tree-sitter-python.wasm',
'.rs': 'tree-sitter-rust.wasm',
'.toml': 'tree-sitter-toml.wasm',
'.yaml': 'tree-sitter-yaml.wasm',
'.yml': 'tree-sitter-yaml.wasm',
'.sh': 'tree-sitter-bash.wasm',
};
@Injectable()
export class PatchHandler implements ActionHandler {
readonly toolName = 'patch';
private readonly logger = new Logger(PatchHandler.name);
private readonly projectRoot: string =
process.env.REPOBURG_PROJECT_PATH || process.cwd();
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 the file to be patched.',
required: true,
},
{
name: 'patch_code',
type: 'string',
description:
'A code snippet containing your changes, with enough surrounding context to serve as a unique anchor.',
required: true,
},
],
};
}
/**
* Generates a tool call example in 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 genericExample = `\`\`\`typescript
// ... 3-4 lines (or ~20+ tokens) of existing code (Unique Prefix Anchor) ...
// ... THE CODE YOU WANT TO CHANGE OR INSERT ...
// ... 3-4 lines (or ~20+ tokens) of existing code (Unique Suffix Anchor) ...
\`\`\``;
const goodAnchorExample = this.generateExample(
{
tool_name: this.toolName,
file_path: 'src/modules/auth/auth.service.ts',
patch_code: `\`\`\`typescript
async validateUser(username: string, pass: string): Promise<any> {
const user = await this.usersService.findOne(username);
if (user && user.password === pass) {
const { password, ...result } = user;
return result;
}
return null;
}
async login(user: any) {
// MODIFIED: Include roles in JWT payload
const payload = {
username: user.username,
sub: user.userId,
roles: user.roles || ['user']
};
return {
access_token: this.jwtService.sign(payload),
};
}
async register(user: CreateUserDto) {
return this.usersService.create(user);
}
\`\`\``,
},
useJsonFormat,
);
const badAnchorExample = this.generateExample(
{
tool_name: this.toolName,
file_path: 'src/utils/formatting.ts',
patch_code: `\`\`\`typescript
// MODIFIED: Handle non-string inputs gracefully
if (typeof str !== 'string') return String(str);
return str.charAt(0).toUpperCase() + str.slice(1);
\`\`\``,
},
useJsonFormat,
);
const appendExample = this.generateExample(
{
tool_name: this.toolName,
file_path: 'src/services/auth.service.ts',
patch_code: `\`\`\`typescript
async validateSession(token: string): Promise<boolean> {
return this.tokenService.verify(token);
}
}
// Helper for legacy clients
export function isLegacyToken(token: string): boolean {
return token.startsWith('leg_');
}
// ${SPECIAL_PATCH_END_FILE_MARKER}
\`\`\``,
},
useJsonFormat,
);
const prependExample = this.generateExample(
{
tool_name: this.toolName,
file_path: 'src/main.ts',
patch_code: `\`\`\`typescript
// ${SPECIAL_PATCH_BEGIN_FILE_MARKER}
import 'dotenv/config';
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';
// Global types
declare global {
namespace NodeJS {
interface ProcessEnv {
PORT?: string;
}
}
}
async function bootstrap() {
\`\`\``,
},
useJsonFormat,
);
const definition = `
-------------
### ${this.toolName}
Applies an intelligent, context-aware patch to a code file. This is the most robust and preferred method for modifying code.
The algorithm works by treating your 'patch_code' as a snippet of the file's **final desired state**. It finds a unique location in the original file that matches the prefix and suffix of your snippet and replaces the content between them.
#### Critical Rules
1. **The 'patch_code' is a literal replacement**: The entire content of your 'patch_code' will replace the section of the original file that it matches. It is not a diff or a partial change.
2. **Provide valid, parseable code**: The snippet in 'patch_code' must be syntactically correct. Do not provide incomplete lines or half-finished code blocks, as the parser will fail.
3. **Include unique anchors**: Your 'patch_code' MUST include enough surrounding, unchanged context (a few lines before and after your change) to serve as a unique anchor. If the context is not unique, the patch will fail.
4. **Small, atomic patches**: Prefer multiple small patches over one large patch. Large patches are harder to anchor uniquely. You can send multiple patch actions for the same file in a single turn.
#### Special Markers for Edge Cases
Standard anchoring requires unique context both above and below the change. This is impossible at the very start or end of a file, OR when the surrounding code is too short (e.g., only a closing brace \`}\` follows your change).
Use these markers to tell the patcher to skip the missing anchor:
- \`// ${SPECIAL_PATCH_BEGIN_FILE_MARKER}\`: Use this as the first line of 'patch_code' when adding imports or top-level definitions to the START of a file.
- \`// ${SPECIAL_PATCH_END_FILE_MARKER}\`: Use this as the last line of 'patch_code' when appending new functions or exports to the END of a file.
#### Absolutely Forbidden
- Unified diff style (lines starting with + or -). Providing this will cause the patch to fail.
- Ellipses (...) or comments like '// ... rest of code' in place of required syntax.
#### Parameters
- "file_path": (string) The relative path to the file to be patched.
- "patch_code": (string) A code snippet containing your changes, with enough surrounding context to serve as a unique anchor.
#### Conceptual Example
Explanation: Your patch code must follow this structure. The context anchors are crucial for locating the correct insertion point.
${genericExample}
#### Example: Good Anchoring
Explanation: Notice how the patch includes the constructor and 'validateUser' method above, and the start of the 'register' method below as anchors. This guarantees the patch location is unique.
Original File Content:
\`\`\`typescript
@Injectable()
export class AuthService {
constructor(
private readonly usersService: UsersService,
private readonly jwtService: JwtService,
) {}
async validateUser(username: string, pass: string): Promise<any> {
const user = await this.usersService.findOne(username);
if (user && user.password === pass) {
const { password, ...result } = user;
return result;
}
return null;
}
async login(user: any) {
const payload = { username: user.username, sub: user.userId };
return {
access_token: this.jwtService.sign(payload),
};
}
async register(user: CreateUserDto) {
return this.usersService.create(user);
}
async forgotPassword(user: CreateUserDto) {
return this.usersService.forgotPassword(user);
}
}
\`\`\`
${goodAnchorExample}
#### Example: Bad Anchoring
Explanation: This is a **bad example**. The 'patch_code' contains NO surrounding context. The patcher has no way of knowing *where* in the file this code belongs, or what it is replacing. This will result in an error.
Original File Content:
\`\`\`typescript
export function formatDate(date: Date): string {
return date.toISOString();
}
export function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
export function formatCurrency(amount: number): string {
return '$' + amount.toFixed(2);
}
\`\`\`
${badAnchorExample}
#### Example: Append
Explanation: Use the '// ${SPECIAL_PATCH_END_FILE_MARKER}' marker to add content to the end of a file.
Original File Content:
\`\`\`typescript
export class AuthService {
// ... other methods ...
async validateSession(token: string): Promise<boolean> {
return this.tokenService.verify(token);
}
}
\`\`\`
${appendExample}
#### Example: Prepend
Explanation: Use the '// ${SPECIAL_PATCH_BEGIN_FILE_MARKER}' marker to add content to the beginning of a file.
Original File Content:
\`\`\`typescript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
\`\`\`
${prependExample}
-------------
`;
return `\n${definition.trim()}\n`;
}
private readonly grammarDir = (() => {
// Path for production build (dist folder)
const prodPath = path.resolve(__dirname, '../../../bin/grammar/');
Iif (existsSync(prodPath)) {
return prodPath;
}
// Fallback path for development (src folder)
const devPath = path.resolve(__dirname, '../../bin/grammar/');
if (existsSync(devPath)) {
return devPath;
}
// If neither is found, log a warning and default to prod path.
// Logger is not available here, so using console.
console.warn(
`[PatchHandler] Grammar directory not found. Looked for ${prodPath} and ${devPath}. The patch tool may not function correctly.`,
);
return prodPath;
})();
private resolveAndValidatePath(unsafePath: string): string {
const normalizedPath = path.normalize(unsafePath);
Iif (path.isAbsolute(normalizedPath)) {
throw new BadRequestException(
`Absolute paths are not allowed: ${unsafePath}`,
);
}
const resolvedPath = path.resolve(this.projectRoot, normalizedPath);
Iif (!resolvedPath.startsWith(this.projectRoot)) {
throw new BadRequestException(
`Path traversal is not allowed: ${unsafePath}`,
);
}
return resolvedPath;
}
private shouldUseFullReplacementStrategy(patchCode: string): boolean {
const beginMarkerRegex = new RegExp(
`//\\s*${SPECIAL_PATCH_BEGIN_FILE_MARKER}.*`,
);
const endMarkerRegex = new RegExp(
`//\\s*${SPECIAL_PATCH_END_FILE_MARKER}.*`,
);
return beginMarkerRegex.test(patchCode) && endMarkerRegex.test(patchCode);
}
private async handleFullFileReplacement(
filePath: string,
safePath: string,
patchCode: string,
originalContent: string,
validatedArgs: PatchArgsDto,
): Promise<ActionExecutionResult> {
this.logger.log(
`Both begin/end markers detected for ${filePath}. Executing full file replacement strategy.`,
);
const beginMarkerRegex = new RegExp(
`//\\s*${SPECIAL_PATCH_BEGIN_FILE_MARKER}.*`,
);
const endMarkerRegex = new RegExp(
`//\\s*${SPECIAL_PATCH_END_FILE_MARKER}.*`,
);
const newFileContent = patchCode
.replace(beginMarkerRegex, '')
.replace(endMarkerRegex, '')
.trim();
await fs.writeFile(safePath, newFileContent, 'utf8');
return {
status: 'SUCCESS',
summary: `File "${filePath}" completely overwritten (detected both start/end markers).`,
persisted_args: { ...validatedArgs, content: newFileContent },
original_content_for_revert: originalContent,
execution_log: {
output: `${filePath} has been overwritten.`,
error_message: '',
},
};
}
async execute(
args: { [key: string]: any },
_context: PlanExecutionContext,
): Promise<ActionExecutionResult> {
const validatedArgs = plainToClass(PatchArgsDto, args);
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, patch_code } = validatedArgs;
const safePath = this.resolveAndValidatePath(file_path);
const fileExtension = path.extname(file_path);
const grammarFile = grammarMap[fileExtension];
let applyPatchOptions: any = {};
Iif (grammarFile && ENABLE_TREE_SITTER) {
const grammarPath = path.join(this.grammarDir, grammarFile);
applyPatchOptions = { grammarPath };
} else {
// No grammar found, defaulting to Tiktoken as alternative strategy.
this.logger.log(
`No Tree-sitter grammar found for ${fileExtension}, using Tiktoken strategy.`,
);
applyPatchOptions = { useTiktoken: true };
}
const originalContent = await fs
.readFile(safePath, 'utf8')
.catch((error) => {
Iif (error.code === 'ENOENT') {
return null;
}
throw error;
});
Iif (originalContent === null) {
const errorMessage = `File "${file_path}" not found.`;
return {
status: 'FAILURE',
summary: `Patch on "${file_path}" failed: File not found.`,
error_message: errorMessage,
persisted_args: validatedArgs,
execution_log: { output: '', error_message: errorMessage },
};
}
if (this.shouldUseFullReplacementStrategy(patch_code)) {
return this.handleFullFileReplacement(
file_path,
safePath,
patch_code,
originalContent,
validatedArgs,
);
}
try {
const newFileContent = await applySnippetPatch(
originalContent,
patch_code,
applyPatchOptions,
);
await fs.writeFile(safePath, newFileContent, 'utf8');
// Syntax validation after patch
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 patched file "${file_path}"`,
);
let errorMessage =
this.syntaxValidator.formatErrors(validationError);
errorMessage += `\n**CORRECTION:** Your \`patch\` introduced syntax errors. The original file has been restored. `;
errorMessage += `Your \`patch_code\` must be syntactically correct and properly formatted. `;
errorMessage += `Ensure you include sufficient context (unchanged lines before/after your changes) to anchor the patch uniquely. `;
errorMessage += `Use \`request_context\` to get the current file state and try again with corrected \`patch_code\`.`;
// Restore original content to prevent corruption
await fs.writeFile(safePath, originalContent, 'utf8');
return {
status: 'FAILURE',
summary: `File "${file_path}" contains syntax errors after patch 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 patch.`,
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 apply patch for ${file_path}: ${error.message}`,
);
const errorMessage = `Failed to apply patch for "${file_path}": ${error.message}\n\n**CORRECTION HINT:** The patch could not be applied. This is often because prefix or suffix anchors in patch code could not be uniquely located in the original file. Use \`request_context\` on \`'${file_path}'\` to get the latest version and try again with a more specific patch. If the patch continues to fail, consider using \`overwrite_file\` to replace the entire file content.`;
return {
status: 'FAILURE',
summary: `Patch on "${file_path}" failed: ${error.message}`,
error_message: errorMessage,
persisted_args: validatedArgs,
execution_log: { output: '', error_message: errorMessage },
};
}
}
}
|