All files / src/llm-orchestration/action-handlers apply-diff.handler.ts

94.64% Statements 106/112
87.93% Branches 51/58
90.9% Functions 10/11
94.49% Lines 103/109

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 3367x 7x 7x 7x 7x               7x 7x                     7x 27x 27x 27x                                                                     2x           2x           2x                 2x                                         2x       19x 19x         19x 19x 1x       18x       17x 17x 17x   17x 17x 31x   31x 1x 1x   1x 1x     30x 30x 28x 28x 28x 28x   28x 28x   28x 17x 24x 24x       28x               2x 2x     17x       17x 17x   17x 28x 1x         27x   27x 7x           20x         1x           26x 2x 1x       1x           24x 24x               24x   24x       24x 2x               23x   6x 6x   8x 8x 8x   9x 9x 9x     12x             21x 21x 21x 2x 2x   2x                 19x 19x   18x     1x 1x         18x 1x 1x                 17x 17x 17x   12x   12x                     5x     5x 5x       2x   5x                    
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import * as fs from 'fs/promises';
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 { ApplyDiffArgsDto } from './dto/apply-diff.args.dto';
import { generateToolCall, generateToolCallJson } from '../../utils';
 
interface Change {
  startLine: number;
  endLine: number;
  operation: 'a' | 'c' | 'd';
  content: string[];
  anchor: string;
}
 
@Injectable()
export class ApplyDiffHandler implements ActionHandler {
  readonly toolName = 'apply_diff';
  private readonly logger = new Logger(ApplyDiffHandler.name);
  private readonly projectRoot: string =
    process.env.REPOBURG_PROJECT_PATH || process.cwd();
 
  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 modified.',
          required: true,
        },
        {
          name: 'patch',
          type: 'string',
          description:
            'A string containing one or more diff commands with anchors.',
          required: true,
        },
      ],
    };
  }
 
  /**
   * 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 examplePatch = `
@2,2c|ANCHOR=console.log('Hello, world!');
  console.log('Hello, Repoburg!');
@5,7d|ANCHOR=function farewell() {
`.trim();
 
    const example = this.generateExample(
      {
        tool_name: this.toolName,
        file_path: 'src/example.js',
        patch: examplePatch,
      },
      useJsonFormat,
    );
 
    const definition = `
::<${this.toolName}>
  Applies a patch to a file using a line-based diff format with anchor validation.
  NOTE: This is a legacy tool. Prefer using the more robust 'patch' tool for all modifications.
 
  The patch format uses commands starting with '@' to specify changes.
  Command syntax: \`@<start_line>,<end_line><operation>|ANCHOR=<substring>\`
  - <start_line>,<end_line>: 1-based line numbers.
  - <operation>: 'a' (add after), 'c' (change), 'd' (delete).
  - |ANCHOR=<substring>: A mandatory substring that must be present on the <start_line> to validate the change.
 
  Parameters:
  - "file_path": (string) The relative path to the file to be modified.
  - "patch": (string) A string containing one or more diff commands with anchors.
 
  <example>
    Explanation: This patch changes line 2 and deletes lines 5-7 from 'src/example.js'.
:${example}
  </example>
::</${this.toolName}>
`;
    return definition.trim();
  }
 
  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);
    if (!resolvedPath.startsWith(this.projectRoot)) {
      throw new BadRequestException(
        `Path traversal is not allowed: ${unsafePath}`,
      );
    }
    return resolvedPath;
  }
 
  private parsePatch(patch: string): Change[] {
    const changes: Change[] = [];
    const lines = patch.split('\n');
    const commandRegex = /^@(\d+),(\d+)([acd])\|ANCHOR=(.*)$/;
 
    let i = 0;
    while (i < lines.length) {
      const line = lines[i];
 
      if (!line.startsWith('@')) {
        if (line.trim()) {
          this.logger.warn(`Skipping invalid line in patch: "${line}"`);
        }
        i++;
        continue;
      }
 
      const match = line.match(commandRegex);
      if (match) {
        const startLine = parseInt(match[1], 10);
        const endLine = parseInt(match[2], 10);
        const operation = match[3] as 'a' | 'c' | 'd';
        const anchor = match[4];
 
        const contentLines: string[] = [];
        i++; // move past command line
 
        if (operation === 'a' || operation === 'c') {
          while (i < lines.length && !lines[i].startsWith('@')) {
            contentLines.push(lines[i]);
            i++;
          }
        }
 
        changes.push({
          startLine,
          endLine,
          operation,
          content: contentLines,
          anchor,
        });
      } else {
        this.logger.warn(`Skipping malformed command in patch: "${line}"`);
        i++;
      }
    }
    return changes;
  }
 
  private applyChanges(originalContent: string, changes: Change[]): string {
    const lines = originalContent ? originalContent.split('\n') : [];
    changes.sort((a, b) => b.startLine - a.startLine);
 
    for (const change of changes) {
      if (change.operation === 'a' && change.startLine !== change.endLine) {
        throw new BadRequestException(
          `For 'add' operations, start_line must equal end_line. Got ${change.startLine},${change.endLine}.`,
        );
      }
 
      const startIndex = change.startLine - 1;
 
      if (change.operation === 'a') {
        Iif (change.startLine < 0 || change.startLine > lines.length) {
          throw new BadRequestException(
            `Invalid line number ${change.startLine} in patch for file with ${lines.length} lines.`,
          );
        }
      } else {
        if (
          startIndex < 0 ||
          startIndex >= lines.length ||
          change.endLine > lines.length
        ) {
          throw new BadRequestException(
            `Invalid line number range ${change.startLine},${change.endLine} in patch for file with ${lines.length} lines.`,
          );
        }
      }
 
      if (change.operation === 'a' && change.startLine === 0) {
        if (lines.length > 0 && !(lines.length === 1 && lines[0] === '')) {
          throw new BadRequestException(
            `Invalid 'add at line 0' for a non-empty file.`,
          );
        }
        Iif (change.anchor !== '') {
          throw new BadRequestException(
            `Anchor for 'add at line 0' must be empty, but got '${change.anchor}'.`,
          );
        }
      } else {
        const anchorLineIndex = startIndex;
        Iif (anchorLineIndex < 0 || anchorLineIndex >= lines.length) {
          throw new BadRequestException(
            `Anchor validation failed: line number ${
              anchorLineIndex + 1
            } is out of bounds for anchor '${change.anchor}'.`,
          );
        }
 
        const anchorLine = lines[anchorLineIndex];
        const isValidAnchor =
          change.anchor === ''
            ? anchorLine === ''
            : anchorLine.includes(change.anchor);
 
        if (!isValidAnchor) {
          throw new BadRequestException(
            `Anchor validation failed at line ${
              anchorLineIndex + 1
            }: expected to find '${change.anchor}', but found '${anchorLine}'.`,
          );
        }
      }
 
      switch (change.operation) {
        case 'a':
          lines.splice(change.startLine, 0, ...change.content);
          break;
        case 'c':
          const deleteCountC = change.endLine - change.startLine + 1;
          lines.splice(startIndex, deleteCountC, ...change.content);
          break;
        case 'd':
          const deleteCountD = change.endLine - change.startLine + 1;
          lines.splice(startIndex, deleteCountD);
          break;
      }
    }
    return lines.join('\n');
  }
 
  async execute(
    args: { [key: string]: any },
    _context: PlanExecutionContext,
  ): Promise<ActionExecutionResult> {
    const validatedArgs = plainToClass(ApplyDiffArgsDto, 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 } = 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 = `File "${file_path}" not found.`;
      return {
        status: 'FAILURE',
        summary: `Apply diff on "${file_path}" failed: File not found.`,
        error_message: errorMessage,
        persisted_args: validatedArgs,
        execution_log: { output: '', error_message: errorMessage },
      };
    }
 
    try {
      const changes = this.parsePatch(patch);
      const newFileContent = this.applyChanges(originalContent, changes);
 
      await fs.writeFile(safePath, newFileContent, 'utf8');
 
      return {
        status: 'SUCCESS',
        summary: `File "${file_path}" successfully modified with apply_diff.`,
        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 diff for ${file_path}: ${error.message}`,
      );
      let errorMessage = `Failed to apply diff for "${file_path}": ${error.message}`;
      if (
        error instanceof BadRequestException &&
        error.message.startsWith('Anchor validation failed')
      ) {
        errorMessage += `\n\n**CORRECTION HINT:** The file content has changed. Use \`request_context\` on \`'${file_path}'\` to get the latest version.`;
      }
      return {
        status: 'FAILURE',
        summary: `Apply diff on "${file_path}" failed: ${error.message}`,
        error_message: errorMessage,
        persisted_args: validatedArgs,
        execution_log: { output: '', error_message: errorMessage },
      };
    }
  }
}