All files / src/llm-orchestration/action-handlers overwrite-file.handler.ts

83.33% Statements 55/66
68.42% Branches 13/19
77.77% Functions 7/9
82.81% Lines 53/64

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 2527x             7x 7x 7x 7x             7x 7x 7x 7x     7x 13x 13x 13x         13x   13x                                                                   4x           2x                                   2x                 2x         2x                 2x                                     2x       6x 6x 1x       5x 5x 1x       4x       4x 4x   1x 1x                   8x 8x 8x 2x 2x   2x                 6x 6x   4x   4x 4x 4x     3x   1x   1x 1x         1x                                                         3x                     1x     1x            
import {
  BadRequestException,
  Injectable,
  InternalServerErrorException,
  Logger,
  Optional,
} 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 { OverwriteFileArgsDto } from './dto/overwrite-file.args.dto';
import { generateToolCall, generateToolCallJson } from '../../utils';
import { SyntaxValidationService } from '../../syntax-validation/syntax-validation.service';
import { ApplicationStateService } from '../../application-state/application-state.service';
 
@Injectable()
export class OverwriteFileHandler implements ActionHandler {
  readonly toolName = 'overwrite_file';
  private readonly logger = new Logger(OverwriteFileHandler.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 overwritten.',
          required: true,
        },
        {
          name: 'content',
          type: 'string',
          description: 'The new, complete content for the file.',
          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 exampleContent = `\`\`\`typescript
/**
 * Global application configuration.
 */
export const AppConfig = Object.freeze({
  // Feature flags
  ENABLE_ANALYTICS: process.env.NODE_ENV === 'production',
  ENABLE_FEATURE_X: true,
 
  // API endpoints
  API_BASE_URL: process.env.API_URL || 'https://api.example.com',
  API_TIMEOUT: parseInt(process.env.API_TIMEOUT || '5000', 10),
 
  // Third-party service keys
  SENTRY_DSN: process.env.SENTRY_DSN,
});
\`\`\``.trim();
 
    const example = this.generateExample(
      {
        tool_name: this.toolName,
        file_path: 'src/config/app.config.ts',
        content: exampleContent,
      },
      useJsonFormat,
    );
 
    const badExampleContent = `\`\`\`typescript
  // This is wrong! Only a partial snippet is provided.
  NEW_API_KEY: 'ABC-123',
\`\`\``.trim();
 
    const badExample = this.generateExample(
      {
        tool_name: this.toolName,
        file_path: 'src/config/app.config.ts',
        content: badExampleContent,
      },
      useJsonFormat,
    );
 
    const definition = `
-------------
### ${this.toolName}
  Overwrites an existing file with new content. This is a destructive operation that replaces the **entire file**.
  You MUST provide the full, final content of the file. NEVER EVER provide only a snippet or partial content, as that will result in loss of data.
 
  #### Parameters
  - "file_path": (string) The relative path to the file to be overwritten.
  - "content": (string) The new, complete content for the file.
 
  #### Example
    Explanation: Refactor the entire 'app.config.ts' to a new, more structured format.
:${example}
 
  #### Bad Example
    Explanation: This is an incorrect use case. The 'content' field only contains a small snippet, not the entire file. This tool would wipe the original file and replace it with only the new lines, which is not the intended outcome.
:${badExample}
-------------
`;
    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;
  }
 
  private async readFileContent(filePath: string): Promise<string | null> {
    try {
      return await fs.readFile(filePath, 'utf8');
    } catch (error) {
      if (error.code === 'ENOENT') {
        return null; // File doesn't exist, which is valid for overwrite.
      }
      throw error;
    }
  }
 
  async execute(
    args: { [key: string]: any },
    _context: PlanExecutionContext,
  ): Promise<ActionExecutionResult> {
    const validatedArgs = plainToClass(OverwriteFileArgsDto, 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, content } = validatedArgs;
    const safePath = this.resolveAndValidatePath(file_path);
 
    const originalContent = await this.readFileContent(safePath);
 
    try {
      await fs.mkdir(path.dirname(safePath), { recursive: true });
      await fs.writeFile(safePath, content, 'utf8');
 
      // Syntax validation after file overwrite
      if (this.syntaxValidator && this.appStateService) {
        const isValidationEnabled =
          await this.appStateService.getSyntaxValidationEnabled();
 
        if (isValidationEnabled) {
          const validationError = await this.syntaxValidator.validate(
            file_path,
            content,
          );
 
          Iif (validationError) {
            this.logger.warn(
              `Syntax validation failed for overwritten file "${file_path}"`,
            );
            let errorMessage =
              this.syntaxValidator.formatErrors(validationError);
            errorMessage += `\n**CORRECTION:** Your overwrite introduced syntax errors. The original file content has been restored. `;
            errorMessage += `Use \`overwrite_file\` again with the complete, corrected content. `;
            errorMessage += `Remember: \`overwrite_file\` replaces the ENTIRE file - provide the full final content, not just the changed portion.`;
 
            // Restore original content to prevent corruption
            if (originalContent !== null) {
              await fs.writeFile(safePath, originalContent, 'utf8');
            } else {
              // If no original content existed, delete the corrupted file
              await fs.unlink(safePath).catch(() => {});
            }
 
            return {
              status: 'FAILURE',
              summary: `File "${file_path}" contains syntax errors and was reverted.`,
              error_message: errorMessage,
              persisted_args: validatedArgs,
              execution_log: { output: '', error_message: errorMessage },
            };
          }
        }
      }
 
      return {
        status: 'SUCCESS',
        summary: `File "${file_path}" overwritten.`,
        persisted_args: { file_path, content },
        original_content_for_revert: originalContent,
        execution_log: {
          output: `${file_path} has been overwritten.`,
          error_message: '',
        },
      };
    } catch (error) {
      this.logger.error(
        `Failed to overwrite file at ${file_path}: ${error.message}`,
      );
      throw new InternalServerErrorException(
        `Failed to overwrite file "${file_path}": ${error.message}`,
      );
    }
  }
}