All files / src/sessions sessions.service.ts

88.71% Statements 291/328
74.54% Branches 82/110
82.35% Functions 28/34
88.47% Lines 284/321

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 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 90519x 19x 19x 19x                 19x 19x 19x           19x 19x 19x     19x 51x     51x   51x   51x   51x 51x 51x 51x       19x 5x   5x         5x   5x 5x   5x 5x 5x         5x 2x     2x 1x       1x     4x 1x     1x 1x           3x     3x 1x       3x                     3x     3x 1x       3x                     3x     3x 1x       3x 3x 3x       19x                                                                               19x 95x                         95x 15x     95x                       95x 7x   88x                 19x 5x                     5x 3x   2x       19x   3x 3x 1x   2x     2x   1x   1x             19x             19x   3x 3x 1x   2x       19x       4x 4x 1x     3x       3x       3x 1x   3x 2x 2x             1x       3x       3x         3x         3x       3x       3x       3x 3x       19x 5x     4x       4x 3x     3x 3x         4x                     7x         7x   7x 3x   3x 3x     7x       19x                 19x             9x 8x     8x               8x   8x 8x 14x 12x 12x 12x                 8x   8x   12x           12x 12x     12x 12x 12x 12x 12x       12x     12x               8x       19x   7x   6x 6x 6x   6x   6x                                 6x     6x 6x 7x                                             7x     7x 7x 4x                                       4x     4x 4x 2x         2x               6x     6x         6x                 19x 15x 14x     14x               14x   14x 14x 23x       16x         14x 2x           12x   4x     12x 12x   12x 12x 1x     11x 11x   6x 3x     5x 5x 5x       8x 12x 12x     3x 3x                 19x                   21x     30x 20x 28x 2x             18x 28x       18x               18x   18x 24x 35x 31x 31x 31x                 18x   18x   27x   4x       27x 27x         27x 27x   27x               18x               19x       17x 16x     19x 16x 18x 2x             14x 17x       14x               14x   14x 14x 17x 15x 15x 15x         14x             14x 14x 14x 17x     14x 14x 3x 3x 3x           14x 13x 13x   2x     13x 13x   13x 13x 1x 1x 1x     12x   6x 4x         6x 6x 6x           10x 12x 12x     10x   2x 2x       14x               19x 9x   8x             8x 12x   8x 12x       8x                     8x 12x 12x 7x   5x 5x       8x      
import { Injectable, NotFoundException, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DataSource, Repository } from 'typeorm';
import {
  Session,
  Project,
  ContextTemplate,
  SystemPrompt,
  SessionInput,
  AIAction,
  ExecutionLog,
} from '../core-entities';
import * as fs from 'fs/promises';
import * as path from 'path';
import {
  CreateSessionDto,
  UpdateSessionDto,
  SessionStatus,
  RevertSessionResponseDto,
} from './dto/session.dto';
import { ApplicationStateService } from '../application-state/application-state.service';
import { Trace } from '../utils';
import { MessageBusService } from '../message-bus/message-bus.service';
 
@Injectable()
export class SessionsService {
  private readonly logger = new Logger(SessionsService.name);
  constructor(
    @InjectRepository(Session)
    private sessionsRepository: Repository<Session>,
    @InjectRepository(Project)
    private projectsRepository: Repository<Project>,
    @InjectRepository(ContextTemplate)
    private contextTemplatesRepository: Repository<ContextTemplate>,
    @InjectRepository(SystemPrompt)
    private systemPromptsRepository: Repository<SystemPrompt>,
    private readonly applicationStateService: ApplicationStateService,
    private readonly messageBusService: MessageBusService,
    private readonly dataSource: DataSource,
  ) {}
 
  @Trace()
  async create(createSessionDto: CreateSessionDto): Promise<Session> {
    this.messageBusService.clear();
 
    const session = this.sessionsRepository.create({
      ...createSessionDto,
      status: SessionStatus.ACTIVE,
    });
 
    if (!createSessionDto.model_id) {
      const manualModeEnabled =
        await this.applicationStateService.getManualLlmEnabled();
      if (!manualModeEnabled) {
        const recentModels =
          await this.applicationStateService.getRecentModels();
        if (recentModels.length > 0) {
          session.model_id = recentModels[0];
        }
      }
    }
 
    if (createSessionDto.project_id) {
      const project = await this.projectsRepository.findOneBy({
        id: createSessionDto.project_id,
      });
      if (!project) {
        throw new NotFoundException(
          `Project with ID "${createSessionDto.project_id}" not found`,
        );
      }
      session.project = project;
    }
 
    if (createSessionDto.system_prompt_id) {
      const systemPrompt = await this.systemPromptsRepository.findOneBy({
        id: createSessionDto.system_prompt_id,
      });
      if (!systemPrompt) {
        throw new NotFoundException(
          `SystemPrompt with ID "${createSessionDto.system_prompt_id}" not found`,
        );
      }
      session.systemPrompt = systemPrompt;
    } else {
      const defaultSystemPrompt = await this.systemPromptsRepository.findOneBy({
        is_default: true,
      });
      if (defaultSystemPrompt) {
        session.systemPrompt = defaultSystemPrompt;
      }
    }
 
    Iif (createSessionDto.default_initial_context_template_id) {
      const template = await this.contextTemplatesRepository.findOneBy({
        id: createSessionDto.default_initial_context_template_id,
      });
      Iif (!template) {
        throw new NotFoundException(
          `ContextTemplate with ID "${createSessionDto.default_initial_context_template_id}" not found`,
        );
      }
      session.defaultInitialContextTemplate = template;
    } else {
      const defaultInitial = await this.contextTemplatesRepository.findOneBy({
        is_default_initial: true,
      });
      if (defaultInitial) {
        session.defaultInitialContextTemplate = defaultInitial;
      }
    }
 
    Iif (createSessionDto.default_followup_context_template_id) {
      const template = await this.contextTemplatesRepository.findOneBy({
        id: createSessionDto.default_followup_context_template_id,
      });
      Iif (!template) {
        throw new NotFoundException(
          `ContextTemplate with ID "${createSessionDto.default_followup_context_template_id}" not found`,
        );
      }
      session.defaultFollowupContextTemplate = template;
    } else {
      const defaultFollowup = await this.contextTemplatesRepository.findOneBy({
        is_default_followup: true,
      });
      if (defaultFollowup) {
        session.defaultFollowupContextTemplate = defaultFollowup;
      }
    }
 
    const savedSession = await this.sessionsRepository.save(session);
    await this.applicationStateService.setActiveSessionId(savedSession.id);
    return this.findOne(savedSession.id);
  }
 
  @Trace()
  async findAll(filter?: string): Promise<Session[]> {
    const query = this.sessionsRepository
      .createQueryBuilder('session')
      .leftJoinAndSelect('session.project', 'project')
      .leftJoinAndSelect(
        'session.defaultInitialContextTemplate',
        'defaultInitialContextTemplate',
      )
      .leftJoinAndSelect(
        'session.defaultFollowupContextTemplate',
        'defaultFollowupContextTemplate',
      )
      .leftJoinAndSelect('session.systemPrompt', 'systemPrompt')
      .leftJoinAndSelect('session.subAgent', 'subAgent')
      .leftJoinAndSelect('session.parentSession', 'parentSession')
      .addSelect(
        (subQuery) =>
          subQuery
            .select('COUNT(si.id)')
            .from(SessionInput, 'si')
            .where('si.session_id = session.id'),
        'sessionInputCount',
      );
 
    Iif (filter === 'non-empty') {
      query.where(
        'EXISTS (SELECT 1 FROM session_inputs si WHERE si.session_id = session.id)',
      );
    }
 
    const result = await query.getRawAndEntities();
 
    return result.entities.map((session, index) => {
      const raw = result.raw[index];
      session.sessionInputCount = parseInt(raw.sessionInputCount, 10) || 0;
      return session;
    });
  }
 
  @Trace()
  async findOne(id: string, includeExecutionLogs = false): Promise<Session> {
    const relations: string[] = [
      'project',
      'defaultInitialContextTemplate',
      'defaultFollowupContextTemplate',
      'systemPrompt',
      'sessionInputs',
      'sessionInputs.contextTemplate',
      'sessionInputs.aiActions',
      'subAgent',
      'parentSession',
    ];
 
    // Only load executionLogs when explicitly requested (they can be large)
    if (includeExecutionLogs) {
      relations.push('sessionInputs.aiActions.executionLogs');
    }
 
    const session = await this.sessionsRepository.findOne({
      where: { id },
      relations,
      order: {
        sessionInputs: {
          sequence_number: 'ASC',
          aiActions: {
            order_of_execution: 'ASC',
          },
        },
      },
    });
    if (!session) {
      throw new NotFoundException(`Session with ID "${id}" not found`);
    }
    return session;
  }
 
  /**
   * Lightweight version of findOne() for boot/initial load.
   * Excludes heavy sessionInputs relation with nested aiActions and executionLogs.
   * Used by findActive() to speed up initial session loading.
   */
  @Trace()
  async findOneLight(id: string): Promise<Session> {
    const session = await this.sessionsRepository.findOne({
      where: { id },
      relations: [
        'project',
        'defaultInitialContextTemplate',
        'defaultFollowupContextTemplate',
        'systemPrompt',
        'subAgent',
        'parentSession',
      ],
    });
    if (!session) {
      throw new NotFoundException(`Session with ID "${id}" not found`);
    }
    return session;
  }
 
  @Trace()
  async findActive(): Promise<Session | null> {
    const activeSessionId =
      await this.applicationStateService.getActiveSessionId();
    if (!activeSessionId) {
      return null;
    }
    try {
      // Use lightweight findOneLight for boot performance
      // Frontend can call findOne() separately when full details needed
      return await this.findOneLight(activeSessionId);
    } catch (error) {
      if (error instanceof NotFoundException) {
        // The active session ID points to a session that no longer exists.
        return null;
      }
      throw error;
    }
  }
 
  @Trace()
  async findLatest(): Promise<Session | null> {
    return this.sessionsRepository.findOne({
      order: { created_at: 'DESC' },
    });
  }
 
  @Trace()
  async setActive(id: string): Promise<void> {
    // Use lightweight existence check instead of heavy findOne()
    const exists = await this.sessionsRepository.existsBy({ id });
    if (!exists) {
      throw new NotFoundException(`Session with ID "${id}" not found`);
    }
    await this.applicationStateService.setActiveSessionId(id);
  }
 
  @Trace()
  async update(
    id: string,
    updateSessionDto: UpdateSessionDto,
  ): Promise<Session> {
    const session = await this.sessionsRepository.findOneBy({ id });
    if (!session) {
      throw new NotFoundException(`Session with ID "${id}" not found`);
    }
 
    Iif (updateSessionDto.model_id !== undefined) {
      session.model_id = updateSessionDto.model_id;
    }
 
    Iif (updateSessionDto.reasoning_effort !== undefined) {
      session.reasoning_effort = updateSessionDto.reasoning_effort;
    }
 
    if (updateSessionDto.session_title !== undefined) {
      session.session_title = updateSessionDto.session_title;
    }
    if (updateSessionDto.status !== undefined) {
      session.status = updateSessionDto.status;
      if (
        [
          SessionStatus.COMPLETED,
          SessionStatus.ABORTED,
          SessionStatus.FAILED,
        ].includes(updateSessionDto.status)
      ) {
        session.end_time = new Date();
      }
    }
 
    Iif (updateSessionDto.system_prompt_id !== undefined) {
      session.system_prompt_id = updateSessionDto.system_prompt_id;
    }
 
    Iif (updateSessionDto.default_initial_context_template_id !== undefined) {
      session.default_initial_context_template_id =
        updateSessionDto.default_initial_context_template_id;
    }
 
    Iif (updateSessionDto.default_followup_context_template_id !== undefined) {
      session.default_followup_context_template_id =
        updateSessionDto.default_followup_context_template_id;
    }
 
    Iif (updateSessionDto.url !== undefined) {
      session.url = updateSessionDto.url;
    }
 
    Iif (updateSessionDto.sub_agent_id !== undefined) {
      session.sub_agent_id = updateSessionDto.sub_agent_id;
    }
 
    Iif (updateSessionDto.parent_session_id !== undefined) {
      session.parent_session_id = updateSessionDto.parent_session_id;
    }
 
    await this.sessionsRepository.save(session);
    return this.findOne(id);
  }
 
  @Trace()
  async remove(id: string): Promise<void> {
    const session = await this.findOne(id);
 
    // Get all descendant sessions recursively (children, grandchildren, etc.)
    const descendantIds = await this.findAllDescendantSessions(id);
 
    // Delete descendants first (bottom-up) to avoid FK violations
    // Process in reverse order (deepest first)
    for (const descendantId of descendantIds.reverse()) {
      const descendant = await this.sessionsRepository.findOneBy({
        id: descendantId,
      });
      if (descendant) {
        await this.sessionsRepository.remove(descendant);
      }
    }
 
    // Finally delete the target session
    await this.sessionsRepository.remove(session);
  }
 
  /**
   * Recursively finds all descendant session IDs in depth-first order.
   * Returns sessions in order from root to leaves (parent before children).
   * For deletion, reverse this order to delete children first.
   */
  private async findAllDescendantSessions(
    parentSessionId: string,
  ): Promise<string[]> {
    const children = await this.sessionsRepository.find({
      where: { parent_session_id: parentSessionId },
      select: ['id'],
    });
 
    const result: string[] = [];
 
    for (const child of children) {
      result.push(child.id);
      // Recursively find grandchildren
      const descendants = await this.findAllDescendantSessions(child.id);
      result.push(...descendants);
    }
 
    return result;
  }
 
  @Trace()
  async findChildSessions(parentSessionId: string): Promise<Session[]> {
    return this.sessionsRepository.find({
      where: { parent_session_id: parentSessionId },
      relations: ['subAgent', 'sessionInputs', 'sessionInputs.contextTemplate'],
      order: { created_at: 'DESC' },
    });
  }
 
  @Trace()
  async getFileChanges(sessionId: string): Promise<
    {
      file_path: string;
      initial_content: string | null;
      current_content: string | null;
    }[]
  > {
    const session = await this.findOne(sessionId);
    const projectRoot = process.env.REPOBURG_PROJECT_PATH || process.cwd();
 
    // Collect all file actions from all session inputs
    const fileActionTypes = [
      'create_file',
      'overwrite_file',
      'delete_file',
      'quick_edit',
      'patch',
      'apply_diff',
    ];
    const fileActionsMap = new Map<string, AIAction[]>();
 
    for (const input of session.sessionInputs || []) {
      for (const action of input.aiActions || []) {
        if (action.file_path && fileActionTypes.includes(action.action_type)) {
          const existing = fileActionsMap.get(action.file_path) || [];
          existing.push(action);
          fileActionsMap.set(action.file_path, existing);
        }
      }
    }
 
    const changes: {
      file_path: string;
      initial_content: string | null;
      current_content: string | null;
    }[] = [];
 
    for (const [filePath, actions] of fileActionsMap) {
      // Sort by creation time to find oldest
      const sortedActions = actions.sort(
        (a, b) =>
          new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
      );
 
      // Get initial content from oldest action's original_content_for_revert
      const oldestAction = sortedActions[0];
      const initialContent = oldestAction.original_content_for_revert;
 
      // Read current content from filesystem
      let currentContent: string | null = null;
      try {
        const safePath = path.resolve(projectRoot, filePath);
        if (safePath.startsWith(projectRoot)) {
          currentContent = await fs.readFile(safePath, 'utf8');
        }
      } catch {
        // File doesn't exist or can't be read
        currentContent = null;
      }
 
      changes.push({
        file_path: filePath,
        initial_content: initialContent,
        current_content: currentContent,
      });
    }
 
    // Sort by file path
    return changes.sort((a, b) => a.file_path.localeCompare(b.file_path));
  }
 
  @Trace()
  async cloneSession(sourceSessionId: string): Promise<Session> {
    // Load source session with all relations INCLUDING executionLogs for cloning
    const sourceSession = await this.findOne(sourceSessionId, true);
 
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();
 
    try {
      // Create new session
      const newSession = queryRunner.manager.create(Session, {
        project_id: sourceSession.project_id,
        session_title: sourceSession.session_title
          ? `${sourceSession.session_title} (Copy)`
          : 'Cloned Session',
        status: SessionStatus.ACTIVE,
        system_prompt_id: sourceSession.system_prompt_id,
        default_initial_context_template_id:
          sourceSession.default_initial_context_template_id,
        default_followup_context_template_id:
          sourceSession.default_followup_context_template_id,
        model_id: sourceSession.model_id,
        reasoning_effort: sourceSession.reasoning_effort,
        url: sourceSession.url,
        sub_agent_id: sourceSession.sub_agent_id,
        // parent_session_id is intentionally NULL - not linked to parent
      });
      await queryRunner.manager.save(newSession);
 
      // Clone session inputs with their actions and logs
      if (sourceSession.sessionInputs) {
        for (const sourceInput of sourceSession.sessionInputs) {
          const newInput = queryRunner.manager.create(SessionInput, {
            session_id: newSession.id,
            sequence_number: sourceInput.sequence_number,
            user_prompt: sourceInput.user_prompt,
            context_template_id: sourceInput.context_template_id,
            ad_hoc_context_definition: sourceInput.ad_hoc_context_definition,
            generated_context_string: sourceInput.generated_context_string,
            execution_strategy: sourceInput.execution_strategy,
            raw_llm_response: sourceInput.raw_llm_response,
            llm_response_explanation: sourceInput.llm_response_explanation,
            raw_studio_request_body: sourceInput.raw_studio_request_body,
            idempotency_key: sourceInput.idempotency_key,
            is_context_carrier: sourceInput.is_context_carrier,
            thoughts: sourceInput.thoughts,
            role: sourceInput.role,
            external_conversation_id: sourceInput.external_conversation_id,
            external_turn_id: sourceInput.external_turn_id,
            input_token_count: sourceInput.input_token_count,
            cached_token_count: sourceInput.cached_token_count,
            output_token_count: sourceInput.output_token_count,
            error_message: sourceInput.error_message,
            tool_calls: sourceInput.tool_calls,
          });
          await queryRunner.manager.save(newInput);
 
          // Clone AIActions for this input
          if (sourceInput.aiActions) {
            for (const sourceAction of sourceInput.aiActions) {
              const newAction = queryRunner.manager.create(AIAction, {
                input_id: newInput.id,
                action_type: sourceAction.action_type,
                file_path: sourceAction.file_path,
                content: sourceAction.content,
                original_content_for_revert:
                  sourceAction.original_content_for_revert,
                command_string: sourceAction.command_string,
                files: sourceAction.files,
                folders: sourceAction.folders,
                reason: sourceAction.reason,
                handover_string: sourceAction.handover_string,
                status: sourceAction.status,
                order_of_execution: sourceAction.order_of_execution,
                server_name: sourceAction.server_name,
                tool_name: sourceAction.tool_name,
                arguments: sourceAction.arguments,
                plain: sourceAction.plain,
                tool_call_id: sourceAction.tool_call_id,
              });
              await queryRunner.manager.save(newAction);
 
              // Clone ExecutionLogs for this action
              if (sourceAction.executionLogs) {
                for (const sourceLog of sourceAction.executionLogs) {
                  const newLog = queryRunner.manager.create(ExecutionLog, {
                    action_id: newAction.id,
                    output: sourceLog.output,
                    error_message: sourceLog.error_message,
                  });
                  await queryRunner.manager.save(newLog);
                }
              }
            }
          }
        }
      }
 
      await queryRunner.commitTransaction();
 
      // Return the cloned session with all relations including executionLogs
      return this.findOne(newSession.id, true);
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }
 
  /**
   * Revert a specific file to its state before the session started.
   * Finds the oldest action for this file and restores original_content_for_revert.
   */
  @Trace()
  async revertFile(sessionId: string, filePath: string): Promise<void> {
    const session = await this.findOne(sessionId);
    const projectRoot = process.env.REPOBURG_PROJECT_PATH || process.cwd();
 
    // Collect all file actions for this specific file path
    const fileActionTypes = [
      'create_file',
      'overwrite_file',
      'delete_file',
      'quick_edit',
      'patch',
      'apply_diff',
    ];
    const fileActions: AIAction[] = [];
 
    for (const input of session.sessionInputs || []) {
      for (const action of input.aiActions || []) {
        if (
          action.file_path === filePath &&
          fileActionTypes.includes(action.action_type)
        ) {
          fileActions.push(action);
        }
      }
    }
 
    if (fileActions.length === 0) {
      throw new NotFoundException(
        `No file actions found for path "${filePath}" in session ${sessionId}`,
      );
    }
 
    // Sort by creation time to find oldest
    const sortedActions = fileActions.sort(
      (a, b) =>
        new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
    );
 
    const oldestAction = sortedActions[0];
    const originalContent = oldestAction.original_content_for_revert;
 
    const safePath = path.resolve(projectRoot, filePath);
    if (!safePath.startsWith(projectRoot)) {
      throw new NotFoundException(`Path traversal detected: ${filePath}`);
    }
 
    try {
      if (originalContent === null) {
        // File was created by this session - delete it
        await fs.unlink(safePath);
        this.logger.log(`Reverted created file by deleting: ${filePath}`);
      } else {
        // File was modified - restore original content
        await fs.mkdir(path.dirname(safePath), { recursive: true });
        await fs.writeFile(safePath, originalContent, 'utf8');
        this.logger.log(`Reverted file to original content: ${filePath}`);
      }
 
      // Mark all actions for this file as confirmed_reverted
      for (const action of fileActions) {
        action.status = 'confirmed_reverted';
        await this.dataSource.manager.save(AIAction, action);
      }
    } catch (error) {
      this.logger.error(`Failed to revert file ${filePath}: ${error.message}`);
      throw error;
    }
  }
 
  /**
   * Get file changes for specific inputs within a session.
   * Used for section-level diff view.
   */
  @Trace()
  async getInputFileChanges(
    sessionId: string,
    inputIds: string[],
  ): Promise<
    {
      file_path: string;
      initial_content: string | null;
      current_content: string | null;
    }[]
  > {
    const session = await this.findOne(sessionId);
 
    // Validate inputIds belong to this session
    const sessionInputIds = (session.sessionInputs || []).map((i) => i.id);
    for (const inputId of inputIds) {
      if (!sessionInputIds.includes(inputId)) {
        throw new NotFoundException(
          `Input with ID "${inputId}" not found in session ${sessionId}`,
        );
      }
    }
 
    // Filter inputs to the specified IDs
    const targetInputs = (session.sessionInputs || []).filter((i) =>
      inputIds.includes(i.id),
    );
 
    // Collect file actions from target inputs
    const fileActionTypes = [
      'create_file',
      'overwrite_file',
      'delete_file',
      'quick_edit',
      'patch',
      'apply_diff',
    ];
    const fileActionsMap = new Map<string, AIAction[]>();
 
    for (const input of targetInputs) {
      for (const action of input.aiActions || []) {
        if (action.file_path && fileActionTypes.includes(action.action_type)) {
          const existing = fileActionsMap.get(action.file_path) || [];
          existing.push(action);
          fileActionsMap.set(action.file_path, existing);
        }
      }
    }
 
    const changes: {
      file_path: string;
      initial_content: string | null;
      current_content: string | null;
    }[] = [];
 
    for (const [filePath, actions] of fileActionsMap) {
      // Sort by creation time to find oldest and newest actions in this section
      const sortedActions = actions.sort(
        (a, b) =>
          new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
      );
 
      // Get initial content from oldest action's original_content_for_revert
      const oldestAction = sortedActions[0];
      const initialContent = oldestAction.original_content_for_revert;
 
      // Get current content from newest action's content (what this section produced)
      // This ensures section diff shows only changes made within this section,
      // not cumulative changes from later sections that exist on filesystem
      const newestAction = sortedActions[sortedActions.length - 1];
      const currentContent = newestAction.content;
 
      changes.push({
        file_path: filePath,
        initial_content: initialContent,
        current_content: currentContent,
      });
    }
 
    // Sort by file path
    return changes.sort((a, b) => a.file_path.localeCompare(b.file_path));
  }
 
  /**
   * Revert file changes for specific inputs within a session.
   * Used for section-level revert.
   */
  @Trace()
  async revertInputFileChanges(
    sessionId: string,
    inputIds: string[],
  ): Promise<RevertSessionResponseDto> {
    const session = await this.findOne(sessionId);
    const projectRoot = process.env.REPOBURG_PROJECT_PATH || process.cwd();
 
    // Validate inputIds belong to this session
    const sessionInputIds = (session.sessionInputs || []).map((i) => i.id);
    for (const inputId of inputIds) {
      if (!sessionInputIds.includes(inputId)) {
        throw new NotFoundException(
          `Input with ID "${inputId}" not found in session ${sessionId}`,
        );
      }
    }
 
    // Filter inputs to the specified IDs
    const targetInputs = (session.sessionInputs || []).filter((i) =>
      inputIds.includes(i.id),
    );
 
    // Collect file actions from target inputs
    const fileActionTypes = [
      'create_file',
      'overwrite_file',
      'delete_file',
      'quick_edit',
      'patch',
      'apply_diff',
    ];
    const fileActionsMap = new Map<string, AIAction[]>();
 
    for (const input of targetInputs) {
      for (const action of input.aiActions || []) {
        if (action.file_path && fileActionTypes.includes(action.action_type)) {
          const existing = fileActionsMap.get(action.file_path) || [];
          existing.push(action);
          fileActionsMap.set(action.file_path, existing);
        }
      }
    }
 
    const result: RevertSessionResponseDto = {
      reverted: [],
      failed: [],
      errors: [],
    };
 
    // Also check for conflicts - files modified in inputs after our target inputs
    const targetInputSequences = targetInputs.map((i) => i.sequence_number);
    const maxTargetSequence = Math.max(...targetInputSequences);
    const laterInputs = (session.sessionInputs || []).filter(
      (i) => i.sequence_number > maxTargetSequence,
    );
 
    const laterFilePaths = new Set<string>();
    for (const input of laterInputs) {
      for (const action of input.aiActions || []) {
        if (action.file_path && fileActionTypes.includes(action.action_type)) {
          laterFilePaths.add(action.file_path);
        }
      }
    }
 
    // Process each file
    for (const [filePath, actions] of fileActionsMap) {
      try {
        const sortedActions = actions.sort(
          (a, b) =>
            new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
        );
 
        const oldestAction = sortedActions[0];
        const originalContent = oldestAction.original_content_for_revert;
 
        const safePath = path.resolve(projectRoot, filePath);
        if (!safePath.startsWith(projectRoot)) {
          result.failed.push(filePath);
          result.errors.push(`Path traversal detected: ${filePath}`);
          continue;
        }
 
        if (originalContent === null) {
          // File was created - delete it
          await fs.unlink(safePath);
          this.logger.log(
            `Reverted section-created file by deleting: ${filePath}`,
          );
        } else {
          // File was modified - restore original content
          await fs.mkdir(path.dirname(safePath), { recursive: true });
          await fs.writeFile(safePath, originalContent, 'utf8');
          this.logger.log(
            `Reverted file to section-start content: ${filePath}`,
          );
        }
 
        // Mark these specific actions as confirmed_reverted
        for (const action of actions) {
          action.status = 'confirmed_reverted';
          await this.dataSource.manager.save(AIAction, action);
        }
 
        result.reverted.push(filePath);
      } catch (error) {
        result.failed.push(filePath);
        result.errors.push(error.message);
      }
    }
 
    return result;
  }
 
  /**
   * Revert all file changes made in this session.
   * Returns lists of reverted and failed files.
   */
  @Trace()
  async revertSession(sessionId: string): Promise<RevertSessionResponseDto> {
    const changes = await this.getFileChanges(sessionId);
 
    const result: RevertSessionResponseDto = {
      reverted: [],
      failed: [],
      errors: [],
    };
 
    // Process in order: first delete created files, then restore modified/deleted
    const createdFiles = changes.filter(
      (c) => c.initial_content === null && c.current_content !== null,
    );
    const otherFiles = changes.filter(
      (c) => c.initial_content !== null || c.current_content === null,
    );
 
    // Revert created files first (delete them)
    for (const change of createdFiles) {
      try {
        await this.revertFile(sessionId, change.file_path);
        result.reverted.push(change.file_path);
      } catch (error) {
        result.failed.push(change.file_path);
        result.errors.push(error.message);
      }
    }
 
    // Then revert modified/deleted files (restore them)
    for (const change of otherFiles) {
      try {
        await this.revertFile(sessionId, change.file_path);
        result.reverted.push(change.file_path);
      } catch (error) {
        result.failed.push(change.file_path);
        result.errors.push(error.message);
      }
    }
 
    return result;
  }
}