All files / src/api/prReview orchestrationMethods.js

100% Statements 1028/1028
100% Branches 240/240
100% Functions 7/7
100% Lines 1028/1028

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 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 10291x 1x 1x 1x 1x 1x 1x 1x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 1x 1x 1x 1x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 3x 3x 3x 3x 41x 38x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 3x 1x 1x 1x 1x 3x 38x 19x 34x 1x 15x 1x 1x 1x 14x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 12x 12x 13x 13x 13x 13x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 5x 5x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 4x 10x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 10x 1x 1x 1x 1x 1x 10x 10x 10x 11x 1x 1x 1x 1x 13x 1x 1x 13x 1x 1x 1x 1x 1x 13x 38x 38x 5x 5x 5x 5x 5x 5x 5x 5x 5x 38x 41x 41x 41x 41x 40x 40x 40x 40x 7x 7x 41x 1x 1x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 28x 41x 3x 1x 1x 1x 1x 3x 2x 2x 2x 2x 2x 2x 1x 1x 2x 41x 13x 13x 13x 13x 41x 41x 28x 1x 1x 1x 28x 27x 27x 6x 6x 27x 28x 41x 41x 41x 41x 41x 28x 28x 2x 28x 28x 28x 2x 2x 2x 2x 28x 26x 26x 26x 26x 26x 26x 26x 26x 5x 5x 26x 26x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 26x 2x 2x 2x 2x 5x 5x 5x 5x 5x 26x 21x 21x 21x 21x 26x 41x 13x 13x 13x 13x 41x 41x 41x 41x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 41x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 1x 1x 3x 40x 41x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 40x 40x 40x 40x 40x 40x 40x 40x 40x 41x 41x 6x 41x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 6x 6x 6x 6x 6x 6x 4x 4x 4x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 6x 4x 4x 6x 1x 1x 1x 1x 6x 6x 40x 41x 1x 1x 1x 1x 1x 1x 40x 40x 40x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 4x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 4x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 4x 40x 41x 3x 3x 3x 3x 3x 40x 40x 41x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 20x 20x 20x 20x 26x 26x 26x 26x 14x 14x 26x 12x 12x 26x 20x 20x 11x 11x 20x 20x 20x 20x 20x 20x 25x 25x 25x 20x 20x 20x 25x 25x 25x 25x 25x 25x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 14x 14x 14x 14x 14x 14x 14x 14x 14x 20x 20x 13x 20x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 14x 14x 14x 14x 20x 13x 13x 14x 14x 20x 20x 20x 6x 6x 6x 6x 5x 6x 6x 6x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 4x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 2x 2x 2x 2x 2x 16x 16x 16x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 4x 4x 4x 4x 4x 4x 3x 4x 4x 4x 4x 4x 4x 4x 2x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 17x 2x 2x 15x 15x 48x 48x 48x 15x 15x 15x 15x 15x 17x 21x 21x 21x 21x 21x 21x 19x 19x 19x 21x 17x 17x 21x 15x 15x 15x 15x 15x 15x 15x 15x 15x 27x 27x 26x 27x 5x 5x 21x 27x 28x 13x 13x 28x 8x 8x 27x 15x 15x 15x 8x 8x 8x 5x 5x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 15x 15x 15x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 1x 1x 17x 17x 17x 18x 2x 2x 15x 15x 15x 15x 15x 18x 1x 1x 14x 14x 18x 5x 5x 9x 18x 1x 1x 8x 8x 15x 1x 1x 1x 1x  
const fs = require("fs").promises;
const path = require("path");
 
const orchestrationMethods = {
  /**
   * Analiza un Pull Request y genera recomendaciones.
   */
  async analyzePR(options) {
    const {
      prDetails,
      commits,
      changes,
      globalFiles,
      reviewType,
      reviewDetail,
      includeSuggestions,
      aiModel,
      standardsPaths,
      azureDevOpsService,
      preloadedThreads,
      reviewContextCache,
    } = options;
 
    try {
      if (typeof this._loadIgnoredFilePatterns === "function") {
        try {
          this._loadIgnoredFilePatterns();
        } catch (reloadError) {
          this.logger?.warn(
            `   ⚠️ No se pudieron recargar patrones ignorados: ${reloadError.message}`,
          );
        }
      }
 
      this._logSectionHeader("ANÁLISIS DE PULL REQUEST", "🤖");
      this._logDataGroup("Configuración", "⚙️", {
        Tipo: reviewType,
        Detalle: reviewDetail,
        Sugerencias: includeSuggestions ? "Sí" : "No",
        "Modelo IA": aiModel || "gpt-4o",
      });
 
      let existingThreads = [];
      let reviewMode = "full";
      let previousIssues = [];
      let developerIssueResponses = {};
      const cache =
        reviewContextCache && typeof reviewContextCache === "object"
          ? reviewContextCache
          : null;
 
      this._logStep(1, 5, "Verificando comentarios previos del PR");
 
      const cachedThreadContext = cache?.threadContext;
      if (cachedThreadContext) {
        const resolvedThreadContext = this._loadThreadContextFromCache(
          cachedThreadContext,
        );
        existingThreads = resolvedThreadContext.existingThreads;
        reviewMode = resolvedThreadContext.reviewMode;
        previousIssues = resolvedThreadContext.previousIssues;
        developerIssueResponses = resolvedThreadContext.developerIssueResponses;
 
        if (cachedThreadContext.commitsAfterReview) {
          prDetails.commitsAfterReview = cachedThreadContext.commitsAfterReview;
          prDetails.lastReviewDate = cachedThreadContext.lastReviewDate;
        }
 
        this.logger.info(
          `   ♻️ Reutilizando contexto de seguimiento (${existingThreads.length} thread(s), modo=${reviewMode})`,
        );
      } else {
        if (Array.isArray(preloadedThreads)) {
          existingThreads = preloadedThreads;
          this.logger.info(
            `   ♻️ Reutilizando ${existingThreads.length} thread(s) precargados`,
          );
 
          if (existingThreads.length > 0) {
            previousIssues = this._extractPreviousIssues(existingThreads);
            developerIssueResponses =
              this._extractDeveloperIssueResponses(existingThreads);
 
            this._logDataGroup("Threads precargados", "📊", {
              "Total de threads": existingThreads.length,
              "Issues previos": previousIssues.length,
              "Respuestas desarrollador": Object.keys(
                developerIssueResponses,
              ).length,
            });
 
            if (previousIssues.length > 0) {
              reviewMode = "follow-up";
              this.logger.info(
                `   🔄 MODO SEGUIMIENTO: Detectados ${previousIssues.length} issues previos`,
              );
              this.logger.info(
                `   ℹ️ Esta revisión SOLO verificará si se resolvieron los issues reportados`,
              );
 
              const lastReviewDate = this._getLastReviewDate(existingThreads);
              const commitsAfterReview = Array.isArray(commits)
                ? commits.filter((c) => {
                    const commitDate = new Date(c?.author?.date);
                    return (
                      !Number.isNaN(commitDate.getTime()) &&
                      commitDate > lastReviewDate
                    );
                  })
                : [];
 
              this.logger.info(
                `   📊 ${commitsAfterReview.length} commit(s) realizados después de la revisión`,
              );
 
              prDetails.commitsAfterReview = commitsAfterReview;
              prDetails.lastReviewDate = lastReviewDate;
            } else {
              this.logger.info(
                `   ℹ️ No se detectaron issues previos en los threads precargados`,
              );
            }
          }
        } else if (!azureDevOpsService) {
          this.logger.warn(`   ⚠️ No hay servicio de Azure DevOps disponible`);
        } else if (!prDetails.projectName) {
          this.logger.warn(`   ⚠️ No hay nombre de proyecto en prDetails`);
        } else if (!prDetails.repository) {
          this.logger.warn(
            `   ⚠️ No hay información de repositorio en prDetails`,
          );
        } else {
          try {
            const repoId = prDetails.repository.id || prDetails.repository.name;
            this.logger.info(
              `   📡 Obteniendo threads: proyecto=${prDetails.projectName}, repo=${repoId}, PR=${prDetails.pullRequestId}`,
            );
 
            existingThreads = await azureDevOpsService.getPullRequestThreads(
              prDetails.projectName,
              prDetails.repository.id || prDetails.repository.name,
              prDetails.pullRequestId,
            );
 
            this.logger.info(
              `   ✅ Se obtuvieron ${existingThreads?.length || 0} thread(s)`,
            );
 
            if (existingThreads && existingThreads.length > 0) {
              previousIssues = this._extractPreviousIssues(existingThreads);
              developerIssueResponses =
                this._extractDeveloperIssueResponses(existingThreads);
 
              this._logDataGroup("Threads encontrados", "📊", {
                "Total de threads": existingThreads.length,
                "Issues previos": previousIssues.length,
                "Respuestas desarrollador": Object.keys(developerIssueResponses)
                  .length,
              });
 
              if (previousIssues.length > 0) {
                reviewMode = "follow-up";
                this.logger.info(
                  `   🔄 MODO SEGUIMIENTO: Detectados ${previousIssues.length} issues previos`,
                );
                this.logger.info(
                  `   ℹ️ Esta revisión SOLO verificará si se resolvieron los issues reportados`,
                );
 
                const lastReviewDate = this._getLastReviewDate(existingThreads);
                const commitsAfterReview = commits.filter((c) => {
                  const commitDate = new Date(c.author.date);
                  return commitDate > lastReviewDate;
                });
 
                this.logger.info(
                  `   📊 ${commitsAfterReview.length} commit(s) realizados después de la revisión`,
                );
 
                let commitsWithDiffs = [];
                if (
                  commitsAfterReview.length > 0 &&
                  azureDevOpsService &&
                  typeof azureDevOpsService.getCommitDiffs === "function"
                ) {
                  this.logger.info(
                    `   📦 Obteniendo cambios completos de commits de ajuste...`,
                  );
 
                  const commitIds = commitsAfterReview.map((c) => c.commitId);
                  const sourceBranch =
                    prDetails.sourceRefName || prDetails.sourceBranch;
 
                  try {
                    const commitChanges = await azureDevOpsService.getCommitDiffs(
                      prDetails.projectName,
                      prDetails.repository.id || prDetails.repository.name,
                      commitIds,
                      sourceBranch,
                    );
 
                    commitsWithDiffs = commitsAfterReview.map((commit) => ({
                      ...commit,
                      changes: commitChanges.filter(
                        (c) => c.commitId === commit.commitId.substring(0, 8),
                      ),
                    }));
 
                    this.logger.info(
                      `   ✅ Cambios completos obtenidos: ${commitChanges.length} archivo(s)`,
                    );
                  } catch (diffError) {
                    this.logger.warn(
                      `   ⚠️ Error obteniendo diffs de commits: ${diffError.message}`,
                    );
                    commitsWithDiffs = commitsAfterReview;
                  }
                } else if (commitsAfterReview.length > 0) {
                  this.logger.warn(
                    "   ⚠️ Servicio de Azure DevOps no disponible para obtener diffs de seguimiento",
                  );
                  commitsWithDiffs = commitsAfterReview;
                }
 
                prDetails.commitsAfterReview = commitsWithDiffs;
                prDetails.lastReviewDate = lastReviewDate;
              } else {
                this.logger.info(
                  `   ℹ️ No se detectaron issues previos en los threads`,
                );
              }
            } else {
              this.logger.info(`   ℹ️ No hay threads/comentarios en este PR`);
            }
          } catch (error) {
            this.logger.warn(
              `   ⚠️ Error obteniendo comentarios previos: ${error.message}`,
            );
            this.logger.warn(`   Stack: ${error.stack?.substring(0, 200)}`);
          }
        }
 
        if (cache) {
          cache.threadContext = {
            existingThreads,
            reviewMode,
            previousIssues,
            developerIssueResponses,
            commitsAfterReview: prDetails.commitsAfterReview,
            lastReviewDate: prDetails.lastReviewDate,
          };
        }
      }
 
      this._logStep(2, 5, "Detectando tecnologías utilizadas");
      let technologies = cache?.technologies;
      if (!Array.isArray(technologies)) {
        technologies = this._normalizeTechnologies(
          this._detectTechnologies(commits, reviewType),
        );
        if (cache) {
          cache.technologies = technologies;
        }
      } else {
        this.logger.info("   ♻️ Reutilizando tecnologías detectadas previamente");
      }
 
      if (technologies.length > 0) {
        this.logger.info(`   ✅ Tecnologías: ${technologies.join(", ")}`);
      }
 
      await this._loadSkillDefinitions();
 
      let standardsContent = {};
      if (
        reviewMode !== "follow-up" &&
        standardsPaths &&
        Object.values(standardsPaths).some((p) => p)
      ) {
        if (cache?.standardsContent) {
          standardsContent = cache.standardsContent;
          this.logger.info(
            "   ♻️ Reutilizando estándares del equipo desde caché de ejecución",
          );
        } else {
          this._logStep(3, 5, "Cargando estándares del equipo");
          standardsContent = await this._readStandardsFiles(
            standardsPaths,
            technologies,
          );
          if (cache) {
            cache.standardsContent = standardsContent;
          }
        }
      } else if (reviewMode === "follow-up") {
        this.logger.info(
          "   ℹ️ Modo seguimiento: se omite carga de estándares para reducir contexto",
        );
      }
 
      if (reviewMode !== "follow-up") {
        if (cache?.copilotInstructionsPrepared) {
          this.logger.info(
            "   ♻️ Reutilizando instrucciones de Copilot preparadas previamente",
          );
        } else {
          await this.ensureCopilotInstructions(standardsContent);
          if (cache) {
            cache.copilotInstructionsPrepared = true;
          }
        }
      }
 
      this._detectModelAndSetLimits(aiModel || "gpt-4o");
 
      let instructionsContent = null;
      if (reviewMode !== "follow-up") {
        const instructionsCacheKey = aiModel || "gpt-4o";
        const cachedInstructions = cache?.instructionsByModel?.[
          instructionsCacheKey
        ];
 
        if (typeof cachedInstructions === "string") {
          instructionsContent = cachedInstructions;
          this.logger.info(
            "   ♻️ Reutilizando instrucciones de archivo desde caché de ejecución",
          );
        } else {
          try {
            const globalStoragePath = this.context?.globalStorageUri?.fsPath;
            if (globalStoragePath) {
              const instructionsPath = path.join(
                globalStoragePath,
                "pr-review-instructions.md",
              );
              instructionsContent = await fs.readFile(instructionsPath, "utf-8");
 
              const maxInstructions =
                this.currentModelLimits?.maxInstructions || 100000;
              if (instructionsContent.length > maxInstructions) {
                const originalLength = instructionsContent.length;
                instructionsContent = instructionsContent.substring(
                  0,
                  maxInstructions,
                );
                this.logger.warn(
                  `   ⚠️ Instrucciones truncadas: ${originalLength} → ${maxInstructions} chars (límite del modelo)`,
                );
              }
 
              if (cache) {
                cache.instructionsByModel = cache.instructionsByModel || {};
                cache.instructionsByModel[instructionsCacheKey] =
                  instructionsContent;
              }
 
              this.logger.info(
                "   ✓ Usando instrucciones de archivo como contexto",
              );
            }
          } catch (error) {
            this.logger.info(
              "   ⚠️ No se pudo leer archivo de instrucciones, usando prompt completo",
            );
          }
        }
      } else {
        this.logger.info(
          "   ✓ Modo seguimiento: instrucciones globales desactivadas para ahorrar contexto",
        );
      }
 
      this._logStep(4, 5, "Preparando contexto para análisis con IA");
      const prompt = instructionsContent
        ? this._buildLightweightPrompt(
            prDetails,
            commits,
            changes,
            globalFiles,
            technologies,
            reviewDetail,
            includeSuggestions,
            existingThreads,
            reviewMode,
            previousIssues,
            developerIssueResponses,
          )
        : this._buildPrompt(
            prDetails,
            commits,
            changes,
            globalFiles,
            technologies,
            reviewDetail,
            includeSuggestions,
            standardsContent,
            existingThreads,
            reviewMode,
            previousIssues,
            developerIssueResponses,
          );
 
      this._logStep(5, 5, "Ejecutando análisis con GitHub Copilot");
 
      let copilotResponse;
      const requestedModel = aiModel || "gpt-4o";
 
      try {
        copilotResponse = await this._callCopilot(
          prompt,
          requestedModel,
          instructionsContent,
        );
      } catch (error) {
        const isClaudeModel =
          requestedModel.toLowerCase().includes("claude") ||
          requestedModel.toLowerCase().includes("sonnet");
        const isHttp403 =
          error.message?.includes("403") || error.message?.includes("HTTP 403");
 
        if (isClaudeModel && isHttp403) {
          this.logger.warn(`\n⚠️ Claude Sonnet falló con error 403`);
          this.logger.info(
            `🔄 Intentando automáticamente con GPT-4o (fallback)...`,
          );
          this.logger.info(
            `   💡 GPT-4o tiene límites más generosos para PRs grandes\n`,
          );
 
          this._detectModelAndSetLimits("gpt-4o");
 
          const newPrompt = instructionsContent
            ? this._buildLightweightPrompt(
                prDetails,
                commits,
                changes,
                globalFiles,
                technologies,
                reviewDetail,
                includeSuggestions,
                existingThreads,
                reviewMode,
                previousIssues,
                developerIssueResponses,
              )
            : this._buildPrompt(
                prDetails,
                commits,
                changes,
                globalFiles,
                technologies,
                reviewDetail,
                includeSuggestions,
                standardsContent,
                existingThreads,
                reviewMode,
                previousIssues,
                developerIssueResponses,
              );
 
          copilotResponse = await this._callCopilot(
            newPrompt,
            "gpt-4o",
            instructionsContent,
          );
 
          this.logger.info(`✅ Análisis exitoso con GPT-4o (fallback)`);
        } else {
          throw error;
        }
      }
 
      if (this._isDebugEnabled()) {
        this.logger.info(`   📄 DEBUG: Respuesta de IA (primeros 1000 chars):`);
        this.logger.info(
          `   ${copilotResponse.substring(0, 1000).replace(/\n/g, " ")}...`,
        );
        this.logger.info(
          `   📏 Longitud total de respuesta: ${copilotResponse.length} caracteres`,
        );
 
        const hasJsonStart = copilotResponse.includes("{");
        const hasJsonEnd = copilotResponse.includes("}");
        this.logger.info(
          `   🔍 Contiene JSON: inicio=${hasJsonStart}, fin=${hasJsonEnd}`,
        );
      }
 
      let analysis = this._parseAnalysis(
        copilotResponse,
        includeSuggestions,
        reviewMode,
        previousIssues,
      );
 
      if (
        reviewMode === "follow-up" &&
        Array.isArray(analysis.followUpMissingIssueNumbers) &&
        analysis.followUpMissingIssueNumbers.length > 0
      ) {
        let pendingMissingIssueNumbers = [...analysis.followUpMissingIssueNumbers];
        let mergedResolution = Array.isArray(analysis.issuesResolution)
          ? analysis.issuesResolution
          : this._normalizeIssuesResolution([], previousIssues);
        const maxFollowUpRetries = 1;
 
        for (
          let attempt = 1;
          attempt <= maxFollowUpRetries && pendingMissingIssueNumbers.length > 0;
          attempt++
        ) {
          this.logger.warn(
            `   ⚠️ Respuesta incompleta (intento ${attempt}/${maxFollowUpRetries}): ` +
              `faltan ${pendingMissingIssueNumbers.length} issue(s) ` +
              `(${pendingMissingIssueNumbers.join(", ")}). Reintentando...`,
          );
 
          try {
            const missingPrompt = this._buildFollowUpMissingIssuesPrompt(
              prDetails,
              changes,
              previousIssues,
              pendingMissingIssueNumbers,
              developerIssueResponses,
              globalFiles,
            );
 
            const missingResponse = await this._callCopilot(
              missingPrompt,
              requestedModel,
              instructionsContent,
            );
 
            const missingAnalysis = this._parseAnalysis(
              missingResponse,
              false,
              "follow-up",
              previousIssues,
            );
 
            const retryResolution = Array.isArray(
              missingAnalysis.issuesResolution,
            )
              ? missingAnalysis.issuesResolution
              : [];
 
            const pendingSet = new Set(pendingMissingIssueNumbers);
            const retryByNumber = new Map();
            retryResolution.forEach((item) => {
              if (pendingSet.has(item.issueNumber)) {
                retryByNumber.set(item.issueNumber, item);
              }
            });
 
            mergedResolution = mergedResolution.map(
              (item) => retryByNumber.get(item.issueNumber) || item,
            );
 
            analysis = this._parseAnalysis(
              JSON.stringify({
                reviewMode: "follow-up",
                issuesResolution: mergedResolution,
              }),
              includeSuggestions,
              "follow-up",
              previousIssues,
            );
 
            const retryMissing = Array.isArray(
              missingAnalysis.followUpMissingIssueNumbers,
            )
              ? missingAnalysis.followUpMissingIssueNumbers
              : [];
 
            if (retryMissing.length > 0) {
              this.logger.warn(
                `   ⚠️ Aun faltan respuestas para issue(s): ${retryMissing.join(
                  ", ",
                )}.`,
              );
              pendingMissingIssueNumbers = retryMissing;
            } else {
              pendingMissingIssueNumbers = [];
            }
          } catch (retryError) {
            this.logger.warn(
              `   ⚠️ Reintento follow-up falló (intento ${attempt}/${maxFollowUpRetries}): ${retryError.message}`,
            );
          }
        }
      }
 
      if (reviewMode !== "follow-up" && analysis.issues?.length > 0) {
        analysis.issues = this._filterIssuesToDiff(
          analysis.issues,
          this._lastDiffByFile,
          this._lastDiffIncludeDeleted,
        );
      }
 
      this._logSubsectionHeader("✅ ANÁLISIS COMPLETADO");
      this._logDataGroup("Resultados", "📊", {
        "Issues encontrados": analysis.issues?.length || 0,
        Sugerencias: analysis.suggestions?.length || 0,
        Tecnologías: technologies.length,
        "Archivos ignorados": this.lastIgnoredFiles?.length || 0,
      });
 
      analysis.technologies = technologies;
      analysis.ignoredFiles = this.lastIgnoredFiles || [];
 
      if (this._pendingLargeFiles && this._pendingLargeFiles.length > 0) {
        this.logger.info(`\n${"=".repeat(60)}`);
        this.logger.info(`📦 PROCESANDO ARCHIVOS GRANDES`);
        this.logger.info(`${"=".repeat(60)}`);
        this.logger.info(
          `   Se encontraron ${this._pendingLargeFiles.length} archivo(s) grande(s) que no cabían en el bloque anterior`,
        );
        this.logger.info(
          `   ✅ Estos archivos se procesarán SIN TRUNCAR usando GPT-4o\n`,
        );
 
        try {
          const largeFileAnalysis = await this._analyzeLargeFiles(
            this._pendingLargeFiles,
            prDetails,
            commits,
            technologies,
            reviewDetail,
            includeSuggestions,
            instructionsContent,
            developerIssueResponses,
            reviewMode,
            previousIssues,
          );
 
          if (largeFileAnalysis.issues && largeFileAnalysis.issues.length > 0) {
            analysis.issues = (analysis.issues || []).concat(
              largeFileAnalysis.issues,
            );
            this.logger.info(
              `   ✅ ${largeFileAnalysis.issues.length} issue(s) adicionales de archivos grandes`,
            );
          }
          if (
            largeFileAnalysis.suggestions &&
            largeFileAnalysis.suggestions.length > 0
          ) {
            analysis.suggestions = (analysis.suggestions || []).concat(
              largeFileAnalysis.suggestions,
            );
            this.logger.info(
              `   ✅ ${largeFileAnalysis.suggestions.length} sugerencia(s) adicionales de archivos grandes`,
            );
          }
 
          this.logger.info(`\n📊 RESULTADO FINAL COMBINADO:`);
          this.logger.info(
            `   • Total issues: ${analysis.issues?.length || 0}`,
          );
          this.logger.info(
            `   • Total sugerencias: ${analysis.suggestions?.length || 0}`,
          );
        } catch (error) {
          this.logger.error(
            `   ⚠️ Error procesando archivos grandes: ${error.message}`,
          );
          this.logger.warn(
            `   Los archivos grandes no serán revisados en esta iteración`,
          );
        }
      }
 
      if (analysis.issues && analysis.issues.length > 0) {
        analysis.issues = this._sortIssuesBySeverity(analysis.issues);
        this.logger.info(
          `   🔢 Issues ordenados por severidad (CRITICAL → HIGH → MEDIUM → LOW)`,
        );
      }
 
      return analysis;
    } catch (error) {
      this.logger.error(`❌ Error en análisis de PR: ${error.message}`);
      throw error;
    }
  },
 
  /**
   * Analiza archivos grandes que no cupieron en el bloque principal.
   */
  async _analyzeLargeFiles(
    largeFiles,
    prDetails,
    commits,
    technologies,
    reviewDetail,
    includeSuggestions,
    instructionsContent,
    developerIssueResponses = {},
    reviewMode = "full",
    previousIssues = [],
  ) {
    const allIssues = [];
    const allSuggestions = [];
 
    const modelToUse = "gpt-4o";
    this._detectModelAndSetLimits(modelToUse);
    let effectiveMaxTotalDiff = Math.max(
      25000,
      Math.floor((this.currentModelLimits.maxTotalDiff || 120000) * 0.85),
    );
    let effectiveSingleFileLimit = Math.max(
      6000,
      Math.floor((this.currentModelLimits.maxSingleFile || 30000) * 0.9),
    );
 
    this.logger.info(
      `   🤖 Usando ${modelToUse} para archivos grandes (límites: ${(this.currentModelLimits.maxSingleFile / 1000).toFixed(0)}k por archivo)`,
    );
 
    let fileIndex = 0;
    while (fileIndex < largeFiles.length) {
      let currentBatchSize = 0;
      const filesInBatch = [];
 
      for (let i = fileIndex; i < largeFiles.length; i++) {
        const file = largeFiles[i];
        if (
          currentBatchSize + file.size <= effectiveMaxTotalDiff
        ) {
          filesInBatch.push(file);
          currentBatchSize += file.size;
        } else {
          break;
        }
      }
 
      if (filesInBatch.length === 0) {
        filesInBatch.push(largeFiles[fileIndex]);
      }
 
      const batchNumber = Math.floor(fileIndex / filesInBatch.length) + 1;
      this.logger.info(
        `\n   📦 Batch ${batchNumber}: Analizando ${filesInBatch.length} archivo(s) grande(s)...`,
      );
      filesInBatch.forEach((f) => {
        this.logger.info(
          `      • ${f.path} (${(f.size / 1000).toFixed(0)}k chars)`,
        );
      });
 
      const batchChanges = filesInBatch.map((f) => ({
        path: f.path,
        changeType: f.changeType,
        diff:
          typeof f.diff === "string"
            ? this._truncateContent(f.diff, effectiveSingleFileLimit)
            : f.diff,
      }));
 
      const prompt = this._buildLightweightPrompt(
        prDetails,
        commits,
        batchChanges,
        largeFiles,
        technologies,
        reviewDetail,
        includeSuggestions,
        [],
        reviewMode,
        previousIssues,
        developerIssueResponses,
      );
 
      try {
        const response = await this._callCopilot(
          prompt,
          modelToUse,
          instructionsContent,
          false,
          { preferNonMini: true },
        );
 
        const batchAnalysis = this._parseAnalysis(
          response,
          includeSuggestions,
          reviewMode,
          previousIssues,
        );
 
        if (
          reviewMode !== "follow-up" &&
          batchAnalysis.issues &&
          batchAnalysis.issues.length > 0
        ) {
          const batchDiffByFile = {};
          batchChanges.forEach((change) => {
            batchDiffByFile[change.path] = change.diff || "";
          });
          batchAnalysis.issues = this._filterIssuesToDiff(
            batchAnalysis.issues,
            batchDiffByFile,
            true,
          );
        }
 
        if (batchAnalysis.issues) {
          allIssues.push(...batchAnalysis.issues);
        }
        if (batchAnalysis.suggestions) {
          allSuggestions.push(...batchAnalysis.suggestions);
        }
 
        this.logger.info(
          `      ✅ Batch ${batchNumber} completado: ${batchAnalysis.issues?.length || 0} issues, ${batchAnalysis.suggestions?.length || 0} sugerencias`,
        );
      } catch (error) {
        const contextLimitError =
          typeof this._isContextLimitError === "function"
            ? this._isContextLimitError(error?.message)
            : /(context|message limit|token limit|too many tokens|max(?:imum)? context)/i.test(
                String(error?.message || ""),
              );
 
        if (contextLimitError) {
          if (filesInBatch.length > 1 && effectiveMaxTotalDiff > 30000) {
            const previous = effectiveMaxTotalDiff;
            effectiveMaxTotalDiff = Math.max(
              30000,
              Math.floor(effectiveMaxTotalDiff * 0.6),
            );
            this.logger.warn(
              `      ⚠️ Límite de contexto alcanzado. Reduciendo tamaño de batch: ${previous.toLocaleString()} -> ${effectiveMaxTotalDiff.toLocaleString()} chars y reintentando.`,
            );
            continue;
          }
 
          if (instructionsContent) {
            this.logger.warn(
              "      ⚠️ Límite de contexto alcanzado. Reintentando sin instrucciones globales para archivos grandes.",
            );
            instructionsContent = null;
            continue;
          }
 
          if (effectiveSingleFileLimit > 6000) {
            const previous = effectiveSingleFileLimit;
            effectiveSingleFileLimit = Math.max(
              6000,
              Math.floor(effectiveSingleFileLimit * 0.7),
            );
            this.logger.warn(
              `      ⚠️ Límite de contexto persistente. Reduciendo diff por archivo: ${previous.toLocaleString()} -> ${effectiveSingleFileLimit.toLocaleString()} chars y reintentando.`,
            );
            continue;
          }
        }
 
        this.logger.error(
          `      ❌ Error en batch ${batchNumber}: ${error.message}`,
        );
      }
 
      fileIndex += filesInBatch.length;
    }
 
    const sortedIssues = this._sortIssuesBySeverity(allIssues);
 
    return {
      issues: sortedIssues,
      suggestions: allSuggestions,
    };
  },
 
  _loadThreadContextFromCache(threadContext = {}) {
    return {
      existingThreads: Array.isArray(threadContext?.existingThreads)
        ? threadContext.existingThreads
        : [],
      reviewMode:
        typeof threadContext?.reviewMode === "string" &&
        threadContext.reviewMode.trim().length > 0
          ? threadContext.reviewMode
          : "full",
      previousIssues: Array.isArray(threadContext?.previousIssues)
        ? threadContext.previousIssues
        : [],
      developerIssueResponses:
        threadContext?.developerIssueResponses &&
        typeof threadContext.developerIssueResponses === "object"
          ? threadContext.developerIssueResponses
          : {},
    };
  },
 
  /**
   * Elimina falsos positivos típicos de análisis en bloques cuando un issue
   * indica que "falta" un archivo/script que sí está presente en otro bloque.
   *
   * @param {Array} issues - Issues detectados por IA.
   * @param {Array} allFiles - Archivos del PR (changeEntries de Azure DevOps).
   * @returns {Array} Issues validados.
   */
  filterCrossBlockMissingFileFalsePositives(issues = [], allFiles = []) {
    if (!Array.isArray(issues) || issues.length === 0) {
      return [];
    }
 
    const normalizePath = (value) =>
      String(value || "")
        .replace(/\\/g, "/")
        .replace(/^\/+/, "")
        .toLowerCase();
 
    const prPaths = new Set();
    const prBasenames = new Set();
 
    for (const entry of allFiles || []) {
      const rawPath =
        typeof entry === "string"
          ? entry
          : entry?.item?.path || entry?.path || "";
      const normalized = normalizePath(rawPath);
      if (!normalized) continue;
 
      prPaths.add(normalized);
      const basename = normalized.split("/").pop();
      if (basename) {
        prBasenames.add(basename);
      }
    }
 
    const fileRefRegex =
      /([a-z0-9_./\\-]+\.(?:cs|sql|ts|js|json|xml|config|csproj|sln|xaml|aspx|cshtml|razor))/gi;
    const missingIntentRegex =
      /(missing|not\s+found|no\s+se\s+encuentra|no\s+encontrad[oa]|falta(?:n)?|ausent[ea]|no\s+existe)/i;
    const fileContextRegex =
      /(archivo|file|script|clase|class|m[oó]dulo|module|referencia|referenced?)/i;
 
    const issueHasKnownReference = (reference) => {
      const ref = normalizePath(reference);
      if (!ref) return false;
 
      if (prPaths.has(ref)) {
        return true;
      }
 
      for (const candidate of prPaths) {
        if (candidate.endsWith(`/${ref}`) || candidate.endsWith(ref)) {
          return true;
        }
      }
 
      const basename = ref.split("/").pop();
      return !!basename && prBasenames.has(basename);
    };
 
    const normalizeReclassifiedResolvedIssue = (issue, references = []) => {
      const location =
        typeof issue?.location === "string"
          ? issue.location
              .replace(/NO\s+RESUELTO/gi, "RESUELTO")
              .replace(/PARCIALMENTE\s+RESUELTO/gi, "RESUELTO")
          : issue?.location;
 
      const rawDescription =
        typeof issue?.description === "string" ? issue.description : "";
      const hasContradictoryDescription =
        /(NO\s+fue\s+corregido|Correccion\s+incompleta|NO\s+RESUELTO)/i.test(
          rawDescription,
        );
 
      const normalizedDescription = hasContradictoryDescription
        ? `✅ Issue reclasificado como resuelto: las referencias reportadas (${references.slice(0, 2).join(", ")}) existen en los archivos del PR analizados.`
        : issue?.description;
 
      return {
        ...issue,
        category: "resolved",
        isResolved: true,
        location,
        description: normalizedDescription,
      };
    };
 
    return issues.map((issue) => {
      const combinedText = [
        issue?.description,
        issue?.recommendation,
        issue?.location,
        issue?.code,
      ]
        .filter(Boolean)
        .join(" ");
 
      if (!combinedText) {
        return issue;
      }
 
      const hasMissingIntent = missingIntentRegex.test(combinedText);
      const hasFileContext = fileContextRegex.test(combinedText);
      if (!hasMissingIntent || !hasFileContext) {
        return issue;
      }
 
      const references = Array.from(combinedText.matchAll(fileRefRegex)).map(
        (match) => match[1],
      );
 
      if (references.length === 0) {
        return issue;
      }
 
      const allReferencesExistInPR = references.every(issueHasKnownReference);
      if (!allReferencesExistInPR) {
        return issue;
      }
 
      if (issue?.category === "resolved") {
        return issue;
      }
 
      return normalizeReclassifiedResolvedIssue(issue, references);
    });
  },
};
 
module.exports = orchestrationMethods;