All files / src/ai-actions ai-actions.service.ts

71.36% Statements 152/213
60.31% Branches 38/63
75% Functions 12/16
71.09% Lines 150/211

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 48419x             19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x   19x     19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x       19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x                                       19x 27x 27x         27x   27x 27x 27x         2x 2x         2x   2x           2x                                     2x 2x   2x 2x 2x 2x                                                           19x 4x       4x 1x     3x 1x         2x 2x   1x 1x   1x       1x             19x                                   19x 32x       32x     32x       19x 7x   7x 2x         5x 5x       19x 4x   4x       2x         2x 2x       19x 3x   3x 2x         1x 1x     1x       19x 12x   12x 1x         11x 11x 11x   11x 11x     11x   2x     2x   1x       1x       1x 1x 1x         4x       4x 3x         3x     1x 1x   4x 4x   1x   1x   1x         1x                               1x 1x   2x   2x 2x 1x     1x     1x     1x 1x   2x 2x 2x           9x       2x       2x 2x 2x     11x       11x               11x 11x   11x       19x                         19x 2x   2x 1x         1x 1x                                                                                                              
import {
  Injectable,
  NotFoundException,
  BadRequestException,
  Logger,
  InternalServerErrorException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import * as fs from 'fs/promises';
import * as path from 'path';
import { AIAction, SessionInput, ExecutionLog } from '../core-entities';
import { ExecutionLogsService } from '../execution-logs/execution-logs.service';
import { Trace } from '../utils';
import { EventsGateway } from '../events/events.gateway';
import { exec } from 'child_process';
import { promisify } from 'util';
import * as crypto from 'crypto';
 
const execAsync = promisify(exec);
 
// Enum for AIAction statuses to avoid magic strings
export enum AIActionStatus {
  PROPOSED = 'proposed',
  AWAITING_CONTEXT = 'awaiting_context',
  AWAITING_HANDOVER = 'awaiting_handover',
  APPROVED_FOR_APPLY = 'approved_for_apply',
  REJECTED_BEFORE_APPLY = 'rejected_before_apply',
  APPLIED_PENDING_REVIEW = 'applied_pending_review',
  CONFIRMED_KEPT = 'confirmed_kept',
  CONFIRMED_REVERTED = 'confirmed_reverted',
  EXECUTION_FAILED = 'execution_failed',
  REVERT_FAILED = 'revert_failed',
}
 
// Re-introduced from the old parser module to fix test breakages
export enum AIActionType {
  CREATE_FILE = 'create_file',
  OVERWRITE_FILE = 'overwrite_file',
  DELETE_FILE = 'delete_file',
  RUN_COMMAND = 'run_command',
  REQUEST_CONTEXT = 'request_context',
  FINAL = 'final',
  QUICK_EDIT = 'quick_edit',
  APPLY_DIFF = 'apply_diff',
  PATCH = 'patch',
  NEW_SESSION = 'new_session',
  WRITE_TODO = 'write_todo',
  EXECUTE_CODE = 'execute_code',
}
 
export interface ActionResult {
  action_id: string;
  status: string;
  logs: ExecutionLog[];
}
 
export interface DiscardedActionInfo {
  action_id: string;
  status: string; // Should always be 'rejected_before_apply'
}
 
export interface ConfirmedActionInfo {
  action_id: string;
  status: string; // Should always be 'confirmed_kept'
}
 
@Injectable()
export class AIActionsService {
  private readonly logger = new Logger(AIActionsService.name);
  private readonly projectRoot: string =
    process.env.REPOBURG_PROJECT_PATH || process.cwd();
 
  constructor(
    @InjectRepository(AIAction)
    private aiActionsRepository: Repository<AIAction>,
    @InjectRepository(SessionInput) // To verify inputId existence
    private sessionInputsRepository: Repository<SessionInput>,
    private executionLogsService: ExecutionLogsService,
    private readonly eventsGateway: EventsGateway,
  ) {}
 
  // --- Start of Consolidated Logic from ActionExecutionService ---
  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)) {
      this.logger.warn(`Path traversal attempt detected: ${unsafePath}`);
      throw new BadRequestException(
        `Path traversal is not allowed. Access denied for path: ${unsafePath}`,
      );
    }
    return resolvedPath;
  }
 
  private async createFile(filePath: string, content: string): Promise<void> {
    const safePath = this.resolveAndValidatePath(filePath);
    const dir = path.dirname(safePath);
    try {
      await fs.mkdir(dir, { recursive: true });
      await fs.writeFile(safePath, content, 'utf8');
      this.logger.log(`Created file: ${safePath}`);
    } catch (error) {
      this.logger.error(`Error creating file ${safePath}: ${error.message}`);
      throw new InternalServerErrorException(
        `Failed to create file "${filePath}": ${error.message}`,
      );
    }
  }
 
  private async editFile(filePath: string, newContent: string): Promise<void> {
    const safePath = this.resolveAndValidatePath(filePath);
    try {
      // For edit, ensure directory exists, then write. This handles cases where edit implies creation.
      const dir = path.dirname(safePath);
      await fs.mkdir(dir, { recursive: true });
      await fs.writeFile(safePath, newContent, 'utf8');
      this.logger.log(`Edited file: ${safePath}`);
    } catch (error) {
      this.logger.error(`Error editing file ${safePath}: ${error.message}`);
      throw new InternalServerErrorException(
        `Failed to edit file "${filePath}": ${error.message}`,
      );
    }
  }
 
  private async deleteFile(filePath: string): Promise<void> {
    const safePath = this.resolveAndValidatePath(filePath);
    try {
      await fs.access(safePath); // Check if file exists
      await fs.unlink(safePath);
      this.logger.log(`Deleted file: ${safePath}`);
    } catch (error) {
      this.logger.error(`Error deleting file ${safePath}: ${error.message}`);
      Iif (error.code === 'ENOENT') {
        throw new NotFoundException(
          `File not found, cannot delete: "${filePath}"`,
        );
      }
      throw new InternalServerErrorException(
        `Failed to delete file "${filePath}": ${error.message}`,
      );
    }
  }
  // --- End of Consolidated Logic ---
 
  @Trace()
  async revertToStudioState(inputId: string): Promise<void> {
    const sessionInput = await this.sessionInputsRepository.findOneBy({
      id: inputId,
    });
 
    if (!sessionInput) {
      throw new NotFoundException(`SessionInput with ID ${inputId} not found.`);
    }
 
    if (!sessionInput.raw_studio_request_body) {
      throw new BadRequestException(
        'No raw studio state available to revert to for this turn.',
      );
    }
 
    try {
      const requestBody = JSON.parse(sessionInput.raw_studio_request_body);
 
      this.logger.log(`Broadcasting 'update-chat' event for input ${inputId}`);
      this.eventsGateway.sendToAll('update-chat', { requestBody });
    } catch (error) {
      this.logger.error(
        `Failed to parse and broadcast stored studio state for input ${inputId}`,
        error,
      );
      throw new InternalServerErrorException(
        'Failed to parse stored studio state.',
      );
    }
  }
 
  @Trace()
  async findAllByInputId(inputId: string): Promise<AIAction[]> {
    const sessionInput = await this.sessionInputsRepository.findOneBy({
      id: inputId,
    });
    Iif (!sessionInput) {
      throw new NotFoundException(
        `SessionInput with ID "${inputId}" not found. Cannot retrieve actions.`,
      );
    }
 
    return this.aiActionsRepository.find({
      where: { input_id: inputId },
      order: { order_of_execution: 'ASC', created_at: 'ASC' },
      relations: ['executionLogs'],
    });
  }
 
  @Trace()
  async findOne(actionId: string): Promise<AIAction> {
    const action = await this.aiActionsRepository.findOne({
      where: { id: actionId },
      relations: ['executionLogs'],
    });
    Iif (!action) {
      throw new NotFoundException(`AIAction with ID "${actionId}" not found`);
    }
    return action;
  }
 
  @Trace()
  async approveAction(actionId: string): Promise<AIAction> {
    const action = await this.findOne(actionId);
 
    if (action.status !== AIActionStatus.PROPOSED) {
      throw new BadRequestException(
        `Action with ID "${actionId}" cannot be approved. Status is "${action.status}", but must be "${AIActionStatus.PROPOSED}".`,
      );
    }
 
    action.status = AIActionStatus.APPROVED_FOR_APPLY;
    return this.aiActionsRepository.save(action);
  }
 
  @Trace()
  async discardAction(actionId: string): Promise<AIAction> {
    const action = await this.findOne(actionId);
 
    if (
      action.status !== AIActionStatus.PROPOSED &&
      action.status !== AIActionStatus.APPROVED_FOR_APPLY
    ) {
      throw new BadRequestException(
        `Action with ID "${actionId}" cannot be discarded. Status is "${action.status}", but must be "${AIActionStatus.PROPOSED}" or "${AIActionStatus.APPROVED_FOR_APPLY}".`,
      );
    }
 
    action.status = AIActionStatus.REJECTED_BEFORE_APPLY;
    return this.aiActionsRepository.save(action);
  }
 
  @Trace()
  async confirmKeepAction(actionId: string): Promise<AIAction> {
    const action = await this.findOne(actionId);
 
    if (action.status !== AIActionStatus.APPLIED_PENDING_REVIEW) {
      throw new BadRequestException(
        `Action with ID "${actionId}" cannot be confirmed. Status is "${action.status}", but must be "${AIActionStatus.APPLIED_PENDING_REVIEW}".`,
      );
    }
 
    action.status = AIActionStatus.CONFIRMED_KEPT;
    this.logger.log(
      `Action ID ${actionId} confirmed kept. Status: ${action.status}`,
    );
    return this.aiActionsRepository.save(action);
  }
 
  @Trace()
  async revertAction(actionId: string): Promise<AIAction> {
    const action = await this.findOne(actionId); // findOne already loads executionLogs
 
    if (action.status !== AIActionStatus.APPLIED_PENDING_REVIEW) {
      throw new BadRequestException(
        `Action with ID "${actionId}" cannot be reverted. Status is "${action.status}", but must be "${AIActionStatus.APPLIED_PENDING_REVIEW}".`,
      );
    }
 
    let revertSucceeded = false;
    let revertOutcomeMessage = `Reverting action type: ${action.action_type}`;
    let errorDetails: string | undefined = undefined;
 
    try {
      this.logger.log(
        `Attempting to revert action ID ${action.id}, type ${action.action_type}`,
      );
      switch (action.action_type) {
        case 'quick_edit':
          Iif (!action.file_path) {
            throw new Error('Missing file_path for quick_edit revert.');
          }
          if (action.original_content_for_revert === null) {
            // This is an invalid state for quick_edit, which always acts on existing files.
            throw new Error(
              'Invalid state: quick_edit action is missing original content for revert.',
            );
          }
          await this.editFile(
            action.file_path,
            action.original_content_for_revert,
          );
          revertOutcomeMessage = `File "${action.file_path}" content reverted from quick_edit.`;
          revertSucceeded = true;
          break;
        case 'overwrite_file':
        case 'apply_diff':
        case 'patch':
        case 'write_todo':
          Iif (!action.file_path)
            throw new Error(
              `Missing file_path for ${action.action_type} revert.`,
            );
          if (action.original_content_for_revert !== null) {
            await this.editFile(
              // Use editFile to restore; this will ensure directory exists
              action.file_path,
              action.original_content_for_revert,
            );
            revertOutcomeMessage = `File "${action.file_path}" content reverted to original.`;
          } else {
            // Original content was null, implies file was created by 'overwrite' or 'apply_diff'. Revert by deleting.
            await this.deleteFile(action.file_path);
            revertOutcomeMessage = `File "${action.file_path}" (created by ${action.action_type}) was deleted.`;
          }
          revertSucceeded = true;
          break;
        case 'delete_file':
          Iif (!action.file_path)
            throw new Error('Missing file_path for delete_file revert.');
          if (action.original_content_for_revert !== null) {
            // If there was original content, recreate file with it.
            await this.createFile(
              // Use createFile to restore; this will ensure directory exists
              action.file_path,
              action.original_content_for_revert,
            );
            revertOutcomeMessage = `Deleted file "${action.file_path}" restored with original content.`;
          } else E{
            // If original_content_for_revert is null, it implies an empty or non-existent file was deleted.
            // Reverting means ensuring it remains non-existent.
            // Attempt to delete (might fail if already gone, which is fine).
            try {
              await this.deleteFile(action.file_path);
              revertOutcomeMessage = `Ensured file "${action.file_path}" (originally non-existent or empty) remains deleted.`;
            } catch (e) {
              if (e instanceof NotFoundException) {
                revertOutcomeMessage = `File "${action.file_path}" was already non-existent as expected for revert.`;
              } else {
                throw e; // Re-throw other errors
              }
            }
          }
          revertSucceeded = true;
          break;
        case 'create_file':
          Iif (!action.file_path)
            throw new Error('Missing file_path for create_file revert.');
          try {
            await this.deleteFile(action.file_path);
            revertOutcomeMessage = `Created file "${action.file_path}" deleted.`;
          } catch (e) {
            // If file not found, it's already "reverted" in a sense
            Iif (e instanceof NotFoundException) {
              revertOutcomeMessage = `Created file "${action.file_path}" was already deleted/not found.`;
            } else {
              throw e; // Re-throw other errors
            }
          }
          revertSucceeded = true;
          break;
        case 'run_command':
          revertOutcomeMessage = `Command "${action.command_string}" cannot be automatically reverted.`;
          revertSucceeded = false; // Explicitly false as it's not truly reverted
          break;
        default:
          throw new Error(
            `Unsupported action_type for revert: "${action.action_type}"`,
          );
      }
      this.logger.log(
        `Revert attempt for action ID ${action.id} resulted in success: ${revertSucceeded}. Message: ${revertOutcomeMessage}`,
      );
    } catch (error) {
      this.logger.error(
        `Failed to revert action ID ${action.id}: ${error.message}`,
        error.stack,
      );
      revertOutcomeMessage = `Failed to revert action: ${error.message}`;
      errorDetails = error.message;
      revertSucceeded = false;
    }
 
    action.status = revertSucceeded
      ? AIActionStatus.CONFIRMED_REVERTED
      : AIActionStatus.REVERT_FAILED;
 
    const log = await this.executionLogsService.createLog({
      action_id: action.id,
      output: revertSucceeded ? revertOutcomeMessage : undefined,
      error_message: !revertSucceeded
        ? errorDetails || revertOutcomeMessage
        : undefined,
    });
 
    action.executionLogs = [...(action.executionLogs || []), log];
    await this.aiActionsRepository.save(action);
 
    return action;
  }
 
  @Trace()
  async deleteAllByInputId(inputId: string): Promise<void> {
    const actions = await this.aiActionsRepository.find({
      where: { input_id: inputId },
    });
    Iif (actions.length > 0) {
      this.logger.log(
        `Deleting ${actions.length} actions for input ID ${inputId}`,
      );
      await this.aiActionsRepository.remove(actions);
    }
  }
 
  @Trace()
  async reExecuteAction(actionId: string): Promise<AIAction> {
    const action = await this.findOne(actionId);
 
    if (action.action_type !== AIActionType.EXECUTE_CODE) {
      throw new BadRequestException(
        `Action with ID "${actionId}" is not of type EXECUTE_CODE. Only code execution actions can be re-run.`,
      );
    }
 
    if (!action.content) {
      throw new BadRequestException(
        `Action with ID "${actionId}" has no content (code) to execute.`,
      );
    }
 
    const tempDir = path.join(this.projectRoot, '.repoburg', 'temp');
    const randomId = crypto.randomBytes(8).toString('hex');
    const tempFilePath = path.join(tempDir, `exec-rerun-${randomId}.ts`);
 
    let unifiedOutput: string;
    // let executionStatus = 'SUCCESS'; // Unused
    let errorDetails: string | undefined;
 
    try {
      await fs.mkdir(tempDir, { recursive: true });
      await fs.writeFile(tempFilePath, action.content, 'utf-8');
 
      const { stdout, stderr } = await execAsync(`npx tsx "${tempFilePath}"`, {
        cwd: this.projectRoot,
        maxBuffer: 10 * 1024 * 1024,
        timeout: 30000, // 30 seconds timeout
      });
      unifiedOutput = stdout || stderr || '(Script produced no output)';
    } catch (error) {
      const execError = error as any;
      unifiedOutput = `EXECUTION FAILED: ${execError.message}\n\nSTDOUT:\n${
        execError.stdout || 'N/A'
      }\n\nSTDERR:\n${execError.stderr || 'N/A'}`;
      // executionStatus = 'FAILURE';
      errorDetails = execError.message;
      this.logger.error(
        `Error re-executing code action ${actionId}: ${unifiedOutput}`,
      );
    } finally {
      try {
        await fs.unlink(tempFilePath);
      } catch (cleanupErr) {
        this.logger.warn(
          `Failed to delete temp file ${tempFilePath}: ${cleanupErr}`,
        );
      }
    }
 
    const log = await this.executionLogsService.createLog({
      action_id: action.id,
      output: unifiedOutput,
      error_message: errorDetails,
    });
 
    // Refresh action with new logs
    action.executionLogs = [...(action.executionLogs || []), log];
 
    return action;
  }
}