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 | 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 102x 102x 102x 99x 99x 3x 3x 102x 6x 68x 68x 68x 6x 34x 34x 34x 34x 34x 6x 6x 6x 6x 6x 67x 67x 5x 5x 62x 62x 67x 67x 67x 67x 3x 67x 67x 6x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 4x 4x 4x 4x 4x 31x 31x 1x 1x 1x 1x 31x 31x 31x 31x 31x 31x 31x 31x 6x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 6x 34x 34x 31x 31x 31x 25x 25x 6x 31x 31x 31x 34x 34x 6x 54x 54x 54x 14x 14x 40x 40x 54x 6x 14x 14x 14x 14x 1x 1x 14x 6x 47x 47x 47x 35x 35x 12x 12x 12x 12x 47x 47x 47x 47x 47x 47x 47x 1x 1x 11x 11x 11x 11x 37x 1x 1x 10x 10x 10x 10x 37x 6x 6x 6x 5x 6x 1x 1x 5x 5x 6x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 37x 3x 3x 3x 2x 3x 1x 1x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 47x 6x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 141x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 3x 3x 3x 3x 44x 47x 9x 9x 9x 9x 35x 35x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 315x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 34x 34x 47x 1x 1x 47x 47x 47x 47x 102x 47x 47x 47x 47x 47x 47x 47x 47x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 47x 47x 47x 47x 47x 47x 3x 3x 3x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 34x 34x 34x 34x 34x 68x 34x 34x 47x 3x 3x 3x 3x 34x 47x 1x 1x 1x 1x 34x 34x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 32x 47x 2x 2x 32x 47x 1x 1x 32x 32x 47x 47x 47x 33x 47x 47x 2x 2x 2x 2x 2x 2x 2x 34x 34x 34x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 47x 47x 47x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 2x 2x 34x 34x 34x 34x 34x 5x 34x 29x 29x 34x 34x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 27x 31x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 31x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 47x 1x 1x 34x 34x 34x 34x 34x 47x 1x 1x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 44x 16x 16x 34x 34x 49x 34x 34x 34x 47x 47x 5x 47x 1x 3x 1x 1x 34x 47x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 6x 6x 6x 6x 7x 7x 7x 7x 3x 7x 7x 7x 7x 6x 7x 7x 7x 7x 14x 14x 9x 9x 9x 9x 14x 14x 28x 14x 7x 7x 7x 7x 7x 14x 14x 14x 14x 14x 14x 14x 9x 9x 9x 9x 14x 6x 6x 5x 5x 1x 1x 1x 1x 6x 6x 6x 6x 6x 47x 27x 27x 27x 27x 27x 27x 33x 33x 99x 33x 47x 6x 6x 6x 6x | const {
deduplicateFollowUpIssues,
applyAzureCommentLimit,
buildDeduplicationLogMessage,
buildCrossBlockValidationLogMessage,
buildIssuesLogEntries,
buildSuggestionsLogEntries,
buildReviewCommentText,
buildCommentLimitWarningEntries,
buildCommentDebugLogEntries,
buildReviewRequestLogEntries,
buildPRReviewStatusPayload,
buildBlockPlanningLogMessage,
resolveAutoLiteModeDecision,
buildAutoLiteModeActivationLogEntries,
buildPRDetailsLogEntries,
buildPRChangesSummaryLogEntries,
buildFollowUpDetectionLogEntries,
buildThreadFetchWarningLogEntry,
buildPRReviewStartLogEntries,
buildAutoCommentDisabledLogEntry,
buildPRReviewCompletionLogEntries,
buildBlockAnalysisSummaryLogMessage,
buildDetectedTechnologiesLogMessage,
buildPRReviewResultPayload,
} = require("./sidebarProviderHelpers");
const DEFAULT_MAX_FILES_TO_REVIEW = 100;
const DEFAULT_ADAPTIVE_WARNING_SECONDS = 180;
const DEFAULT_ADAPTIVE_CRITICAL_SECONDS = 300;
function normalizeConfigNumber(rawValue, fallback, { min = 1 } = {}) {
const parsed = Number(rawValue);
if (Number.isFinite(parsed) && parsed >= min) {
return Math.floor(parsed);
}
return fallback;
}
function normalizePositiveNumber(rawValue, fallback) {
return normalizeConfigNumber(rawValue, fallback, { min: 1 });
}
function normalizeMaxFilesToReview(rawValue) {
return normalizeConfigNumber(rawValue, DEFAULT_MAX_FILES_TO_REVIEW, {
min: 0,
});
}
/**
* Extrae la ruta de un change entry de Azure DevOps.
* Soporta formatos path/serverItem/filePath/item.path.
*/
function getChangeEntryPath(entry) {
if (!entry || typeof entry !== "object") {
return "";
}
return (
entry.path ||
entry.serverItem ||
entry.filePath ||
entry?.item?.path ||
""
);
}
function calculateAdaptiveSettings({
elapsedSeconds,
currentDetail,
currentSuggestions,
warningThreshold,
criticalThreshold,
warningApplied,
criticalApplied,
}) {
let nextDetail = currentDetail;
let nextSuggestions = currentSuggestions;
let nextWarningApplied = warningApplied;
let nextCriticalApplied = criticalApplied;
if (!nextWarningApplied && elapsedSeconds >= warningThreshold) {
nextWarningApplied = true;
if (nextDetail === "detailed") {
nextDetail = "standard";
}
}
if (!nextCriticalApplied && elapsedSeconds >= criticalThreshold) {
nextCriticalApplied = true;
nextDetail = "light";
nextSuggestions = false;
}
return {
detail: nextDetail,
suggestions: nextSuggestions,
warningApplied: nextWarningApplied,
criticalApplied: nextCriticalApplied,
};
}
function resolveReviewRuntimeConfig(config) {
const maxFilesToReview = normalizeMaxFilesToReview(
config.get("prReview.maxFilesToReview", DEFAULT_MAX_FILES_TO_REVIEW),
);
const adaptiveModeEnabled = config.get("prReview.adaptiveMode.enabled", true);
const adaptiveWarningSeconds = normalizePositiveNumber(
config.get(
"prReview.adaptiveMode.warningSeconds",
DEFAULT_ADAPTIVE_WARNING_SECONDS,
),
DEFAULT_ADAPTIVE_WARNING_SECONDS,
);
const adaptiveCriticalSeconds = Math.max(
adaptiveWarningSeconds,
normalizePositiveNumber(
config.get(
"prReview.adaptiveMode.criticalSeconds",
DEFAULT_ADAPTIVE_CRITICAL_SECONDS,
),
DEFAULT_ADAPTIVE_CRITICAL_SECONDS,
),
);
return {
maxFilesToReview,
adaptiveModeEnabled,
adaptiveWarningSeconds,
adaptiveCriticalSeconds,
};
}
function sortFilesDeterministically(files = []) {
return [...files].sort((a, b) => {
const pathA = getChangeEntryPath(a).toLowerCase();
const pathB = getChangeEntryPath(b).toLowerCase();
if (pathA !== pathB) {
return pathA.localeCompare(pathB);
}
const typeA = (a?.changeType || a?.change?.changeType || "").toLowerCase();
const typeB = (b?.changeType || b?.change?.changeType || "").toLowerCase();
return typeA.localeCompare(typeB);
});
}
function parsePositiveInteger(rawValue) {
const parsed = Number.parseInt(String(rawValue ?? ""), 10);
if (!Number.isInteger(parsed) || parsed <= 0) {
return null;
}
return parsed;
}
function safeDecodePathSegment(segment) {
try {
return decodeURIComponent(segment);
} catch (_error) {
return segment;
}
}
function parseReviewPullRequestUrl(prUrl) {
const rawInput = typeof prUrl === "string" ? prUrl.trim() : "";
if (!rawInput) {
return null;
}
const markdownLinkMatch = rawInput.match(
/^\s*\[[^\]]+\]\((https?:\/\/[^\s)]+)\)\s*$/i,
);
const urlCandidate = markdownLinkMatch ? markdownLinkMatch[1] : rawInput;
const rawUrl =
urlCandidate.startsWith("<") && urlCandidate.endsWith(">")
? urlCandidate.slice(1, -1).trim()
: urlCandidate;
if (!rawUrl) {
return null;
}
let parsedUrl;
try {
parsedUrl = new URL(rawUrl);
} catch (_error) {
return null;
}
const hostname = parsedUrl.hostname.toLowerCase();
const segments = parsedUrl.pathname.split("/").filter(Boolean);
if (hostname === "dev.azure.com") {
if (
segments.length < 6 ||
segments[2].toLowerCase() !== "_git" ||
segments[4].toLowerCase() !== "pullrequest"
) {
return null;
}
const prId = parsePositiveInteger(segments[5]);
if (!prId) {
return null;
}
return {
organization: safeDecodePathSegment(segments[0]),
project: safeDecodePathSegment(segments[1]),
repository: safeDecodePathSegment(segments[3]),
prId,
};
}
if (hostname.endsWith(".visualstudio.com")) {
if (
segments.length < 5 ||
segments[1].toLowerCase() !== "_git" ||
segments[3].toLowerCase() !== "pullrequest"
) {
return null;
}
const organization = hostname.slice(0, -".visualstudio.com".length);
const prId = parsePositiveInteger(segments[4]);
if (!organization || !prId) {
return null;
}
return {
organization,
project: safeDecodePathSegment(segments[0]),
repository: safeDecodePathSegment(segments[2]),
prId,
};
}
return null;
}
async function executeSidebarPrReview({
data,
config,
context,
logger,
sendMessage,
commentMaxLength = 150000,
autoLiteDefaults = {},
dependencies = {},
} = {}) {
const {
autoLiteModeEnabled = true,
filesThreshold = 180,
blocksThreshold = 24,
} = autoLiteDefaults;
buildPRReviewStartLogEntries().forEach((line) => {
logger.info(line);
});
const parsedPrFromUrl = parseReviewPullRequestUrl(data?.prUrl);
const resolvedPrId =
parsePositiveInteger(data?.prId) || parsedPrFromUrl?.prId;
const devopsOrg =
data.organization ||
parsedPrFromUrl?.organization ||
config.get("devops.organization");
const devopsPat = config.get("devops.pat");
const project = data.project || parsedPrFromUrl?.project;
const repository = data.repository || parsedPrFromUrl?.repository;
const normalizedPat = typeof devopsPat === "string" ? devopsPat.trim() : "";
const hasValidPat =
/^[A-Za-z0-9]{20,128}$/.test(normalizedPat) && !/^\*+$/.test(normalizedPat);
if (!devopsOrg || !hasValidPat) {
throw new Error(
"❌ Configuración de Azure DevOps incompleta. Verifica organización y un PAT válido (20-128 caracteres alfanuméricos, no enmascarado).",
);
}
if (!project || !repository || !resolvedPrId) {
throw new Error(
"❌ Error extrayendo datos de la URL del PR. Verifica el formato.",
);
}
const AzureDevOpsServiceImpl = dependencies.AzureDevOpsService
? dependencies.AzureDevOpsService
: require("../api/azureDevOps").AzureDevOpsService;
const PRReviewServiceImpl = dependencies.PRReviewService
? dependencies.PRReviewService
: require("../api/prReview").PRReviewService;
buildReviewRequestLogEntries({
prId: resolvedPrId,
devopsOrg,
project,
repository,
reviewType: data.reviewType,
reviewDetail: data.reviewDetail,
aiModel: data.aiModel,
autoComment: data.autoComment,
includeSuggestions: data.includeSuggestions,
}).forEach((line) => {
logger.info(line);
});
sendMessage(
"prReviewStatus",
buildPRReviewStatusPayload("fetching-pr-details", {
prId: resolvedPrId,
}),
);
const azureService = new AzureDevOpsServiceImpl(
devopsOrg,
devopsPat,
logger.info.bind(logger),
);
const prDetails = await azureService.getPullRequestDetails(
project,
repository,
resolvedPrId,
);
prDetails.projectName = project;
prDetails.repository = prDetails.repository || {
id: repository,
name: repository,
};
prDetails.pullRequestId = resolvedPrId;
buildPRDetailsLogEntries(prDetails).forEach((line) => {
logger.info(line);
});
sendMessage("prReviewStatus", buildPRReviewStatusPayload("fetching-commits"));
const commits = await azureService.getPullRequestCommits(
project,
repository,
resolvedPrId,
);
sendMessage("prReviewStatus", buildPRReviewStatusPayload("fetching-changes"));
const changesMetadata = await azureService.getPullRequestChanges(
project,
repository,
resolvedPrId,
);
const runtimeConfig = resolveReviewRuntimeConfig(config);
const maxFilesToReview = runtimeConfig.maxFilesToReview;
const sortedAllPrFiles = sortFilesDeterministically(changesMetadata.allFiles);
const limitApplies =
maxFilesToReview > 0 && sortedAllPrFiles.length > maxFilesToReview;
const filesToReview = limitApplies
? sortedAllPrFiles.slice(0, maxFilesToReview)
: sortedAllPrFiles;
const notReviewedFiles = limitApplies
? sortedAllPrFiles
.slice(maxFilesToReview)
.map((file) => getChangeEntryPath(file))
.filter(Boolean)
: [];
const reviewChangesMetadata = {
...changesMetadata,
allFiles: filesToReview,
totalFiles: filesToReview.length,
totalFilesInPR: sortedAllPrFiles.length,
maxFilesToReview,
notReviewedFiles,
};
if (limitApplies) {
logger.warn(
`⚠️ Límite de revisión activo: ${maxFilesToReview} archivo(s) de ${sortedAllPrFiles.length} en el PR.`,
);
logger.warn(
` ${notReviewedFiles.length} archivo(s) quedaron fuera del análisis en esta ejecución.`,
);
sendMessage("prReviewStatus", {
message:
`⚠️ Se aplicó límite de archivos (${maxFilesToReview}). ` +
`${notReviewedFiles.length} archivo(s) no se revisaron.`,
type: "warning",
});
}
buildPRChangesSummaryLogEntries({
commitsCount: commits.length,
totalFiles: reviewChangesMetadata.totalFilesInPR,
}).forEach((line) => {
logger.info(line);
});
if (reviewChangesMetadata.totalFilesInPR !== reviewChangesMetadata.totalFiles) {
logger.info(
`ℹ️ Archivos a revisar en esta ejecución: ${reviewChangesMetadata.totalFiles}`,
);
}
if (maxFilesToReview === 0) {
logger.info(
`ℹ️ Configuración maxFilesToReview=0: se revisarán todos los archivos (${reviewChangesMetadata.totalFiles}).`,
);
}
const standardsPaths = {
sql: config.get("standards.sqlPath") || "",
angular: config.get("standards.angularPath") || "",
dotnet: config.get("standards.dotnetPath") || "",
ssis: config.get("standards.ssisPath") || "",
};
sendMessage(
"prReviewStatus",
buildPRReviewStatusPayload("checking-previous-reviews"),
);
let isFollowUpMode = false;
let previousIssues = [];
let existingThreads = [];
const reviewService = new PRReviewServiceImpl(logger, context);
try {
existingThreads = await azureService.getPullRequestThreads(
project,
repository,
resolvedPrId,
);
if (existingThreads && existingThreads.length > 0) {
previousIssues = reviewService._extractPreviousIssues(existingThreads);
}
if (previousIssues.length > 0) {
isFollowUpMode = true;
}
buildFollowUpDetectionLogEntries({
threadsCount: existingThreads?.length || 0,
previousIssuesCount: previousIssues.length,
}).forEach((line) => {
logger.info(line);
});
} catch (threadError) {
logger.warn(buildThreadFetchWarningLogEntry(threadError?.message));
sendMessage("prReviewStatus", {
message:
"⚠️ No se pudieron recuperar threads previos. Se continuará con revisión inicial y podría omitirse la verificación de issues históricos.",
type: "warning",
});
}
const blocks = reviewService.calculateDynamicBlocks(
reviewChangesMetadata.allFiles,
data.aiModel || "gpt-4o",
);
const totalBlocks = blocks.length;
logger.info(
buildBlockPlanningLogMessage({
isFollowUpMode,
totalBlocks,
aiModel: data.aiModel,
}),
);
const autoLiteDecision = resolveAutoLiteModeDecision({
isFollowUpMode,
totalFiles: reviewChangesMetadata.totalFiles,
totalBlocks,
requestedReviewDetail: data.reviewDetail,
requestedIncludeSuggestions: data.includeSuggestions,
autoLiteModeEnabled: config.get(
"prReview.autoLiteMode.enabled",
autoLiteModeEnabled,
),
filesThreshold: config.get(
"prReview.autoLiteMode.filesThreshold",
filesThreshold,
),
blocksThreshold: config.get(
"prReview.autoLiteMode.blocksThreshold",
blocksThreshold,
),
});
const effectiveReviewDetail = autoLiteDecision.effectiveReviewDetail;
const effectiveIncludeSuggestions =
autoLiteDecision.effectiveIncludeSuggestions;
const blockPrefetchEnabled = config.get("prReview.blockPrefetch.enabled", true);
const adaptiveModeEnabled = runtimeConfig.adaptiveModeEnabled;
const adaptiveWarningSeconds = runtimeConfig.adaptiveWarningSeconds;
const adaptiveCriticalSeconds = runtimeConfig.adaptiveCriticalSeconds;
if (autoLiteDecision.shouldAutoApply) {
buildAutoLiteModeActivationLogEntries({
totalFiles: reviewChangesMetadata.totalFiles,
totalBlocks,
filesThreshold: autoLiteDecision.normalizedFilesThreshold,
blocksThreshold: autoLiteDecision.normalizedBlocksThreshold,
previousDetail: data.reviewDetail,
effectiveReviewDetail,
previousSuggestions: data.includeSuggestions,
effectiveIncludeSuggestions,
}).forEach((line) => {
logger.warn(line);
});
sendMessage("prReviewStatus", {
message:
"⚠️ PR grande detectado: se activó modo liviano automático para estabilidad",
type: "info",
});
}
const allIssues = [];
const allSuggestions = [];
const allTechnologies = new Set();
const sharedReviewContext = {};
const reviewStartedAt = Date.now();
let runtimeReviewDetail = effectiveReviewDetail;
let runtimeIncludeSuggestions = effectiveIncludeSuggestions;
let adaptiveWarningApplied = false;
let adaptiveCriticalApplied = false;
const fetchBlockFiles = async (blockIndex) => {
return azureService.getFilesBlock(
project,
repository,
reviewChangesMetadata.prDetails,
reviewChangesMetadata.iteration,
blocks[blockIndex],
blockIndex + 1,
);
};
let currentBlockFilesPromise =
totalBlocks > 0 ? fetchBlockFiles(0) : null;
for (let i = 0; i < totalBlocks; i++) {
const blockNumber = i + 1;
sendMessage(
"prReviewStatus",
buildPRReviewStatusPayload("processing-block", {
blockNumber,
totalBlocks,
}),
);
if (!currentBlockFilesPromise) {
currentBlockFilesPromise = fetchBlockFiles(i);
}
const blockFiles = await currentBlockFilesPromise;
const nextBlockIndex = i + 1;
if (blockPrefetchEnabled && nextBlockIndex < totalBlocks) {
currentBlockFilesPromise = fetchBlockFiles(nextBlockIndex);
} else {
currentBlockFilesPromise = null;
}
if (adaptiveModeEnabled && !isFollowUpMode) {
const elapsedSeconds = Math.floor((Date.now() - reviewStartedAt) / 1000);
const previousDetail = runtimeReviewDetail;
const previousSuggestions = runtimeIncludeSuggestions;
const adaptiveState = calculateAdaptiveSettings({
enabled: adaptiveModeEnabled,
isFollowUpMode,
elapsedSeconds,
currentDetail: runtimeReviewDetail,
currentSuggestions: runtimeIncludeSuggestions,
warningThreshold: adaptiveWarningSeconds,
criticalThreshold: adaptiveCriticalSeconds,
warningApplied: adaptiveWarningApplied,
criticalApplied: adaptiveCriticalApplied,
});
runtimeReviewDetail = adaptiveState.detail;
runtimeIncludeSuggestions = adaptiveState.suggestions;
adaptiveWarningApplied = adaptiveState.warningApplied;
adaptiveCriticalApplied = adaptiveState.criticalApplied;
if (
previousDetail !== runtimeReviewDetail ||
previousSuggestions !== runtimeIncludeSuggestions
) {
logger.warn(
`⚠️ Modo adaptativo aplicado en bloque ${blockNumber}/${totalBlocks}: ` +
`detalle ${previousDetail} -> ${runtimeReviewDetail}, ` +
`sugerencias ${previousSuggestions ? "on" : "off"} -> ${
runtimeIncludeSuggestions ? "on" : "off"
} (elapsed ${elapsedSeconds}s).`,
);
sendMessage("prReviewStatus", {
message:
`⚠️ Modo adaptativo activo (${elapsedSeconds}s): ` +
`${runtimeReviewDetail}/${runtimeIncludeSuggestions ? "con" : "sin"} sugerencias`,
type: "info",
});
}
}
sendMessage(
"prReviewStatus",
buildPRReviewStatusPayload("analyzing-block", {
blockNumber,
totalBlocks,
aiModel: data.aiModel,
}),
);
let blockResult;
try {
blockResult = await reviewService.analyzePR({
prDetails,
commits,
changes: blockFiles,
globalFiles: sortedAllPrFiles,
reviewType: data.reviewType,
reviewDetail: runtimeReviewDetail,
includeSuggestions: runtimeIncludeSuggestions,
aiModel: data.aiModel || "gpt-4o",
standardsPaths,
azureDevOpsService: azureService,
preloadedThreads: existingThreads,
reviewContextCache: sharedReviewContext,
});
} catch (error) {
logger.error(
`❌ Error analizando bloque ${blockNumber}/${totalBlocks}: ${error.message}`,
);
sendMessage("prReviewStatus", {
message:
`⚠️ Error analizando bloque ${blockNumber}/${totalBlocks}. ` +
`Se continuará con el siguiente bloque.`,
type: "warning",
});
const errorCode = error?.code || error?.response?.status;
const networkCodes = new Set([
"ECONNRESET",
"ETIMEDOUT",
"ECONNREFUSED",
"ENOTFOUND",
]);
const transientStatuses = new Set([408, 429, 502, 503, 504]);
const isTransientError =
networkCodes.has(error?.code) ||
transientStatuses.has(error?.response?.status);
const severity = isTransientError ? "MEDIUM" : "HIGH";
const recommendation =
error?.code === "ETIMEDOUT" || error?.response?.status === 408
? "Reduce el tamaño del bloque o aumenta el timeout."
: "Reintenta la revisión o prueba con GPT-4o si el PR es grande.";
blockResult = {
issues: [
{
severity,
category: "review-error",
location: `Bloque ${blockNumber}/${totalBlocks}`,
description:
`Error en análisis con IA (${errorCode || "unknown"}): ${
error.message
}. ` + `Se omitió este bloque para continuar el proceso.`,
recommendation,
},
],
suggestions: [],
technologies: [],
};
}
if (blockResult.issues) {
allIssues.push(...blockResult.issues);
}
if (blockResult.suggestions) {
allSuggestions.push(...blockResult.suggestions);
}
if (blockResult.technologies) {
blockResult.technologies.forEach((tech) => allTechnologies.add(tech));
}
logger.info(
buildBlockAnalysisSummaryLogMessage({
blockNumber,
totalBlocks,
issuesCount: blockResult.issues?.length || 0,
suggestionsCount: blockResult.suggestions?.length || 0,
}),
);
}
const { deduplicatedIssues, resolvedCount, partialCount, unresolvedCount } =
deduplicateFollowUpIssues(allIssues, {
autoResolveOmittedByModel: isFollowUpMode,
});
const validatedIssues =
reviewService.filterCrossBlockMissingFileFalsePositives(
deduplicatedIssues,
sortedAllPrFiles,
);
const dedupLogMessage = buildDeduplicationLogMessage({
originalCount: allIssues.length,
deduplicatedCount: deduplicatedIssues.length,
resolvedCount,
partialCount,
unresolvedCount,
});
if (dedupLogMessage) {
logger.info(dedupLogMessage);
}
const crossBlockLogMessage = buildCrossBlockValidationLogMessage({
deduplicatedCount: deduplicatedIssues.length,
validatedCount: validatedIssues.length,
});
if (crossBlockLogMessage) {
logger.info(crossBlockLogMessage);
}
const reviewResult = buildPRReviewResultPayload({
totalFiles: reviewChangesMetadata.totalFiles,
totalBlocks,
issues: validatedIssues,
suggestions: allSuggestions,
technologies: Array.from(allTechnologies),
});
const technologiesLogMessage = buildDetectedTechnologiesLogMessage(
reviewResult.technologies,
);
if (technologiesLogMessage) {
logger.info(technologiesLogMessage);
}
buildIssuesLogEntries(reviewResult.issues).forEach((line) => {
logger.info(line);
});
if (
runtimeIncludeSuggestions &&
reviewResult.suggestions &&
reviewResult.suggestions.length > 0
) {
buildSuggestionsLogEntries(reviewResult.suggestions).forEach((line) => {
logger.info(line);
});
}
if (data.autoComment) {
sendMessage(
"prReviewStatus",
buildPRReviewStatusPayload("publishing-comment"),
);
let commentText = buildReviewCommentText({
isFollowUpMode,
reviewType: data.reviewType,
reviewDetail: runtimeReviewDetail,
totalFiles: reviewChangesMetadata.totalFiles,
totalFilesInPR: reviewChangesMetadata.totalFilesInPR,
totalBlocks,
maxFilesToReview: reviewChangesMetadata.maxFilesToReview,
aiModel: data.aiModel,
technologies: reviewResult.technologies,
issues: reviewResult.issues,
includeSuggestions: runtimeIncludeSuggestions,
suggestions: reviewResult.suggestions,
ignoredFiles: reviewResult.ignoredFiles,
notReviewedFiles: reviewChangesMetadata.notReviewedFiles,
devopsOrg,
project,
repository,
prId: resolvedPrId,
});
if (!commentText || commentText.trim().length === 0) {
throw new Error("El comentario está vacío");
}
const commentLimitResult = applyAzureCommentLimit(commentText, {
maxLength: commentMaxLength,
warningRatio: 0.9,
issuesCount: reviewResult.issues?.length || 0,
});
buildCommentLimitWarningEntries(commentLimitResult).forEach((line) => {
logger.warn(line);
});
const commentsToPublish =
Array.isArray(commentLimitResult.comments) &&
commentLimitResult.comments.length > 0
? commentLimitResult.comments
: [commentLimitResult.adjustedComment];
commentsToPublish.forEach((partText, partIndex) => {
const partNumber = partIndex + 1;
if (commentsToPublish.length > 1) {
logger.info(
`🧩 Preparando Parte ${partNumber} de ${commentsToPublish.length} para publicación`,
);
}
buildCommentDebugLogEntries(partText).forEach((line) => {
logger.info(line);
});
});
// Azure muestra primero el comentario más reciente; publicamos de N -> 1 para leer 1 -> N.
const publishOrder = [...commentsToPublish].reverse();
for (let i = 0; i < publishOrder.length; i++) {
await azureService.postPRComment(project, repository, resolvedPrId, {
content: publishOrder[i],
commentType: 1,
status: "active",
});
if (publishOrder.length > 1) {
logger.info(
`✓ Comentario de revisión publicado (${i + 1}/${publishOrder.length})`,
);
}
}
if (publishOrder.length === 1) {
logger.info(`✓ Comentario de revisión publicado`);
} else {
logger.info(
`✓ ${publishOrder.length} comentario(s) de revisión publicados en partes`,
);
}
sendMessage(
"prReviewStatus",
buildPRReviewStatusPayload("completed-comment-published"),
);
} else {
logger.info(buildAutoCommentDisabledLogEntry());
sendMessage(
"prReviewStatus",
buildPRReviewStatusPayload("completed-log-only"),
);
}
buildPRReviewCompletionLogEntries().forEach((line) => {
logger.info(line);
});
}
module.exports = {
executeSidebarPrReview,
};
|