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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 5x 1x 1x 1x 1x 5x 5x 5x 5x 5x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 7x 7x 7x 7x 7x 7x 8x 8x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 3x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 11x 14x 6x 6x 6x 6x 6x 6x 2x 2x 2x 2x 2x 2x 6x 6x 6x 6x 6x 6x 6x 6x 5x 14x 3x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 2x 14x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 3x 3x 3x 3x 3x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 6x 1x 1x 5x 5x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 2x 2x 4x 4x 4x 4x 2x 2x 3x 3x 3x 3x 1x 1x 3x 3x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 3x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 6x 5x 6x 6x 6x 6x 3x 3x 3x 3x 3x 3x 3x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | const vscode = require("vscode");
const STRICT_ISSUE_LOCATION_PATTERN =
/^(?:[A-Za-z]:)?[^:\r\n]*\.[^:\r\n]+:\d+(?:-\d+)?$/;
const ALLOWED_APPROVAL_VALUES = new Set([
"approved",
"approved-with-suggestions",
"waiting-for-author",
]);
const localReviewMethods = {
/**
* Revisa cambios uncommitted (staged o unstaged) usando Git + Copilot.
* Permite revisar cambios ANTES de crear un PR.
*
* @param {string} workspaceRoot - Ruta del workspace con Git
* @param {boolean} staged - true para staged, false para unstaged
* @returns {Promise<Object>} Resultado con comentarios e issues
*/
async reviewLocalChanges(workspaceRoot, staged = false) {
try {
const changeType = staged ? "staged" : "unstaged";
this.logger.show(true);
this.logger.info(`🔍 Revisando cambios ${changeType}...`);
const diff = this._getGitDiff(workspaceRoot, staged);
if (!diff || diff.trim().length === 0) {
return {
success: true,
message: `No hay cambios ${changeType} para revisar`,
comments: [],
issues: [],
};
}
const files = this._parseFilesFromDiff(diff);
this.logger.info(` 📄 ${files.length} archivo(s) modificado(s)`);
const reviewResult = await this._reviewDiffWithCopilot(
diff,
files,
`${changeType} changes`,
);
const result = {
success: true,
message: `Revisión completada: ${reviewResult.issues.length} issue(s) detectado(s)`,
comments: reviewResult.comments,
issues: reviewResult.issues,
summary: reviewResult.summary,
};
if (this.codeReviewPanel) {
this.logger.info(`\n📊 DEBUG - Issues recibidos de Copilot:`);
this.logger.info(`Total issues: ${reviewResult.issues.length}`);
const filesWithIssues = this._buildPanelFilesWithIssues(
reviewResult.issues,
files,
{
allowSuggestedFix: true,
includeTextOnlyRecommendation: true,
logSuggestionDetails: true,
},
);
this.logger.info(
`📤 Enviando ${filesWithIssues.length} archivo(s) con issues al panel`,
);
this.codeReviewPanel.displayReviewResults({
files: filesWithIssues,
});
}
return result;
} catch (error) {
this.logger.error(`Error en reviewLocalChanges: ${error.message}`);
throw error;
}
},
/**
* Revisa cambios entre dos branches/commits/tags.
*
* @param {string} workspaceRoot - Ruta del workspace
* @param {string} baseRef - Referencia base (ej: main, develop)
* @param {string} targetRef - Referencia target (ej: feature/new-feature, HEAD)
* @returns {Promise<Object>} Resultado de la revisión
*/
async reviewBranchComparison(workspaceRoot, baseRef, targetRef) {
try {
this.logger.info(`🔍 Comparando: ${targetRef} vs ${baseRef}...`);
const diff = this._getGitDiffBetweenRefs(
workspaceRoot,
baseRef,
targetRef,
);
if (!diff || diff.trim().length === 0) {
return {
success: true,
message: "No hay diferencias entre las referencias",
comments: [],
issues: [],
};
}
const files = this._parseFilesFromDiff(diff);
this.logger.info(` 📄 ${files.length} archivo(s) modificado(s)`);
const reviewResult = await this._reviewDiffWithCopilot(
diff,
files,
`changes from ${baseRef} to ${targetRef}`,
);
const result = {
success: true,
message: `Revisión completada: ${reviewResult.issues.length} issue(s)`,
comments: reviewResult.comments,
issues: reviewResult.issues,
summary: reviewResult.summary,
baseRef,
targetRef,
};
if (this.codeReviewPanel) {
const filesWithIssues = this._buildPanelFilesWithIssues(
reviewResult.issues,
files,
{
allowSuggestedFix: false,
includeTextOnlyRecommendation: false,
logSuggestionDetails: false,
},
);
this.logger.info(
`📤 Enviando ${filesWithIssues.length} archivo(s) con issues al panel`,
);
this.codeReviewPanel.displayReviewResults({
files: filesWithIssues,
});
}
return result;
} catch (error) {
this.logger.error(`Error en reviewBranchComparison: ${error.message}`);
throw error;
}
},
/**
* Analiza nivel de riesgo de cambios uncommitted.
*
* @param {string} workspaceRoot - Ruta del workspace
* @param {boolean} staged - true para staged, false para unstaged
* @returns {Promise<Object>} Análisis de riesgo con nivel y recomendaciones
*/
async analyzeRisk(workspaceRoot, staged = false) {
try {
this.logger.info(`⚠️ Analizando riesgo de cambios...`);
const diff = this._getGitDiff(workspaceRoot, staged);
if (!diff || diff.trim().length === 0) {
return {
success: true,
riskLevel: "none",
message: "No hay cambios para analizar",
reasons: [],
recommendations: [],
};
}
const files = this._parseFilesFromDiff(diff);
const analysis = await this._analyzeRiskWithCopilot(diff, files);
return {
success: true,
riskLevel: analysis.riskLevel,
reasons: analysis.reasons,
recommendations: analysis.recommendations,
filesAffected: files.length,
};
} catch (error) {
this.logger.error(`Error en analyzeRisk: ${error.message}`);
throw error;
}
},
/**
* Convierte los issues del análisis en el formato esperado por el panel.
* @private
*/
_buildPanelFilesWithIssues(issues, files, options = {}) {
const issuesByFile = {};
for (const issue of issues) {
if (options.logSuggestionDetails) {
this.logger.info(
`\n Issue completo: ${JSON.stringify(issue, null, 2)}`,
);
}
const { fileName, lineNumber } = this._extractIssueLocation(issue);
const fullPath = files.find((f) => f.includes(fileName)) || fileName;
if (!issuesByFile[fullPath]) {
issuesByFile[fullPath] = [];
}
issuesByFile[fullPath].push({
line: lineNumber,
severity: issue.severity || "info",
message: issue.description || issue.message || "Sin descripción",
category: issue.category,
suggestion: this._buildIssueSuggestion(issue, options),
});
}
return Object.keys(issuesByFile).map((filePath) => ({
path: filePath,
issues: issuesByFile[filePath],
}));
},
/**
* Obtiene archivo y línea desde un issue de Copilot.
* @private
*/
_extractIssueLocation(issue) {
let fileName = "unknown";
let lineNumber = 1;
if (issue.location) {
const match = issue.location.match(/([^\/\\:]+\.[a-z]+):?(\d+)?/i);
if (match) {
fileName = match[1];
lineNumber = match[2] ? parseInt(match[2]) : 1;
}
}
return { fileName, lineNumber };
},
/**
* Construye la sugerencia visual para el panel.
* @private
*/
_buildIssueSuggestion(issue, options = {}) {
const {
allowSuggestedFix = false,
includeTextOnlyRecommendation = false,
logSuggestionDetails = false,
} = options;
if (allowSuggestedFix && issue.suggestedFix && issue.code) {
if (logSuggestionDetails) {
this.logger.info(` ✓ Sugerencia creada desde suggestedFix`);
}
return {
description: issue.recommendation || "Aplicar fix sugerido",
originalCode: issue.code,
adjustedCode: issue.suggestedFix,
hasSuggestedCode: true,
};
}
if (issue.code && issue.recommendation) {
const codeBlockMatch = issue.recommendation.match(
/```[\w]*\n([\s\S]+?)\n```/,
);
const suggestedCode = codeBlockMatch ? codeBlockMatch[1].trim() : null;
if (logSuggestionDetails) {
this.logger.info(
` ${
suggestedCode ? "✓" : "⚠️"
} Sugerencia creada desde markdown - tiene código: ${!!suggestedCode}`,
);
}
return {
description: issue.recommendation,
originalCode: issue.code,
adjustedCode: suggestedCode || issue.code,
hasSuggestedCode: !!suggestedCode,
};
}
if (includeTextOnlyRecommendation && issue.recommendation) {
if (logSuggestionDetails) {
this.logger.info(` ℹ️ Solo recomendación textual (sin código)`);
}
return {
description: issue.recommendation,
originalCode: null,
adjustedCode: null,
hasSuggestedCode: false,
};
}
if (logSuggestionDetails) {
this.logger.info(
` ⚠️ No hay sugerencia - code: ${!!issue.code}, recommendation: ${!!issue.recommendation}`,
);
}
return null;
},
/**
* Obtiene diff de Git para cambios uncommitted.
* @private
*/
_getGitDiff(workspaceRoot, staged) {
try {
const { execSync } = require("child_process");
const command = staged ? "git diff --cached" : "git diff";
const diff = execSync(command, {
cwd: workspaceRoot,
encoding: "utf-8",
maxBuffer: 10 * 1024 * 1024,
});
return diff;
} catch (error) {
if (error.status === 128) {
throw new Error("No es un repositorio Git válido");
}
throw error;
}
},
/**
* Obtiene diff entre dos referencias Git.
* @private
*/
_getGitDiffBetweenRefs(workspaceRoot, baseRef, targetRef) {
try {
const { execFileSync } = require("child_process");
const validRefPattern = /^[a-zA-Z0-9._\-\/]+$/;
if (!validRefPattern.test(baseRef) || !validRefPattern.test(targetRef)) {
throw new Error(
"Referencia Git inválida. Solo se permiten caracteres alfanuméricos, puntos, guiones y barras.",
);
}
const diff = execFileSync("git", ["diff", `${baseRef}...${targetRef}`], {
cwd: workspaceRoot,
encoding: "utf-8",
maxBuffer: 10 * 1024 * 1024,
});
return diff;
} catch (error) {
throw new Error(
`Error al obtener diff entre ${baseRef} y ${targetRef}: ${error.message}`,
);
}
},
/**
* Parsea archivos desde diff de Git.
* @private
*/
_parseFilesFromDiff(diff) {
const files = [];
const lines = diff.split("\n");
for (const line of lines) {
if (line.startsWith("diff --git")) {
const match = line.match(/diff --git a\/(.*?) b\/(.*?)$/);
if (match) {
files.push(match[2]);
}
}
}
return [...new Set(files)];
},
/**
* Revisa diff usando GitHub Copilot.
* @private
*/
async _reviewDiffWithCopilot(diff, files, context) {
try {
this.logger.info(" 🤖 Enviando diff a Copilot para análisis...");
await this._loadSkillDefinitions();
const models = await vscode.lm.selectChatModels({
vendor: "copilot",
family: "gpt-4o",
});
if (models.length === 0) {
throw new Error("GitHub Copilot no está disponible");
}
const model = models[0];
const prompt = this._buildDiffReviewPrompt(diff, files, context);
const messages = [vscode.LanguageModelChatMessage.User(prompt)];
const tokenSource = new vscode.CancellationTokenSource();
let response;
try {
response = await model.sendRequest(messages, {}, tokenSource.token);
} finally {
if (typeof tokenSource.dispose === "function") {
tokenSource.dispose();
}
}
let fullResponse = "";
for await (const fragment of response.text) {
fullResponse += fragment;
}
const reviewData = this._parseReviewJSONResponse(fullResponse);
this.logger.info(
` ✅ Review completado: ${reviewData.issues.length} issue(s)`,
);
return reviewData;
} catch (error) {
this.logger.error(`Error con Copilot: ${error.message}`);
throw error;
}
},
/**
* Construye prompt para revisar diff.
* @private
*/
_buildDiffReviewPrompt(diff, files, context) {
const skillContext = this._getSkillContext("full", false, true);
const maxDiffLength = 100000;
const truncatedDiff =
diff.length > maxDiffLength
? diff.substring(0, maxDiffLength) + "\n\n[... diff truncado ...]"
: diff;
return `${skillContext}
Contexto de análisis: ${context}.
Autoridad de reglas: aplica estrictamente las skills cargadas para criterios de evaluación y salida.
FILES MODIFIED (${files.length}):
${files.map((f) => `- ${f}`).join("\n")}
GIT DIFF:
\`\`\`diff
${truncatedDiff}
\`\`\`
Provide your review in the following JSON format:
{
"summary": "Brief executive summary of changes (2-3 sentences in Spanish)",
"issues": [
{
"severity": "critical|high|medium|low|info",
"category": "security|performance|best-practice|style|maintainability",
"technology": "C#|SQL|Angular|TypeScript|etc",
"location": "STRICT FORMAT: file.ext:line or file.ext:start-end (examples: service.cs:42, script.sql:10-15)",
"description": "Clear description of the issue",
"recommendation": "Specific suggestion to fix it"
}
],
"approval": "approved|approved-with-suggestions|waiting-for-author"
}
Critical formatting rules:
- location must be EXACTLY file.ext:line or file.ext:start-end.
- Do not use words like "line", "lines", "línea" or extra text in location.
Provide ONLY the JSON output, no additional text.`;
},
/**
* Valida formato estricto de location en issues de review local.
* @private
*/
_isStrictIssueLocation(location) {
if (typeof location !== "string") {
return false;
}
return STRICT_ISSUE_LOCATION_PATTERN.test(location.trim());
},
/**
* Analiza riesgo con Copilot.
* @private
*/
async _analyzeRiskWithCopilot(diff, files) {
try {
this.logger.info(" 🤖 Analizando riesgo con Copilot...");
await this._loadSkillDefinitions();
const models = await vscode.lm.selectChatModels({
vendor: "copilot",
family: "gpt-4o",
});
if (models.length === 0) {
return {
riskLevel: "unknown",
reasons: ["Copilot no disponible"],
recommendations: ["Revisar manualmente"],
};
}
const model = models[0];
const riskSkillContext = this._getSkillContext("full", false, false);
const prompt = `${riskSkillContext}
Analyze the risk level of the following code changes for production deployment.
Apply the skill principles for rigor and evidence, and follow strictly the risk JSON schema defined below.
FILES (${files.length}): ${files.join(", ")}
DIFF:
\`\`\`diff
${diff.substring(0, 50000)}
\`\`\`
Provide risk analysis in JSON:
{
"riskLevel": "low|medium|high|critical",
"reasons": ["reason 1 in Spanish", "reason 2 in Spanish"],
"recommendations": ["recommendation 1 in Spanish", "recommendation 2 in Spanish"]
}
Provide ONLY JSON output.`;
const messages = [vscode.LanguageModelChatMessage.User(prompt)];
const tokenSource = new vscode.CancellationTokenSource();
let response;
try {
response = await model.sendRequest(messages, {}, tokenSource.token);
} finally {
if (typeof tokenSource.dispose === "function") {
tokenSource.dispose();
}
}
let fullResponse = "";
for await (const fragment of response.text) {
fullResponse += fragment;
}
const riskData = this._parseRiskJSONResponse(fullResponse);
this.logger.info(
` ⚠️ Nivel de riesgo: ${riskData.riskLevel.toUpperCase()}`,
);
return riskData;
} catch (error) {
this.logger.error(`Error en análisis de riesgo: ${error.message}`);
return {
riskLevel: "unknown",
reasons: [`Error: ${error.message}`],
recommendations: ["Revisar manualmente los cambios"],
};
}
},
/**
* Parsea respuesta JSON de review.
* @private
*/
_parseReviewJSONResponse(response) {
try {
let cleaned = response.trim();
if (cleaned.startsWith("```json")) cleaned = cleaned.substring(7);
if (cleaned.startsWith("```")) cleaned = cleaned.substring(3);
if (cleaned.endsWith("```")) {
cleaned = cleaned.substring(0, cleaned.length - 3);
}
const data = JSON.parse(cleaned.trim());
const normalizedIssues = Array.isArray(data.issues)
? data.issues
.filter((item) => item && typeof item === "object")
.map((issue) => {
const normalizedIssue = { ...issue };
const location = issue.location;
if (!this._isStrictIssueLocation(location)) {
normalizedIssue.location = "unknown.file:1";
}
return normalizedIssue;
})
: [];
const sortedIssues = this._sortIssuesBySeverity(normalizedIssues);
const rawApproval = String(data.approval || "approved-with-suggestions");
const normalizedApproval = ALLOWED_APPROVAL_VALUES.has(rawApproval)
? rawApproval
: "approved-with-suggestions";
return {
summary: data.summary || "Sin resumen",
issues: sortedIssues,
approval: normalizedApproval,
comments: [],
};
} catch (error) {
this.logger.warn(`Error parseando JSON: ${error.message}`);
return {
summary: response.substring(0, 500),
issues: [],
approval: "approved-with-suggestions",
comments: [],
};
}
},
/**
* Parsea respuesta JSON de análisis de riesgo.
* @private
*/
_parseRiskJSONResponse(response) {
try {
let cleaned = response.trim();
if (cleaned.startsWith("```json")) cleaned = cleaned.substring(7);
if (cleaned.startsWith("```")) cleaned = cleaned.substring(3);
if (cleaned.endsWith("```")) {
cleaned = cleaned.substring(0, cleaned.length - 3);
}
const data = JSON.parse(cleaned.trim());
return {
riskLevel: data.riskLevel || "unknown",
reasons: data.reasons || [],
recommendations: data.recommendations || [],
};
} catch (error) {
return {
riskLevel: "unknown",
reasons: ["Error parseando respuesta"],
recommendations: ["Revisar manualmente"],
};
}
},
/**
* Obtiene lista de branches disponibles en el repositorio.
*
* @param {string} workspaceRoot - Ruta del workspace
* @returns {Array<string>} Lista de branches
*/
getBranches(workspaceRoot) {
try {
if (
typeof workspaceRoot !== "string" ||
workspaceRoot.trim().length === 0
) {
this.logger.warn("Workspace root inválido para obtener branches");
return [];
}
const { execSync } = require("child_process");
const branches = execSync("git branch -a", {
cwd: workspaceRoot,
encoding: "utf-8",
});
return branches
.split("\n")
.map((b) => b.replace("*", "").trim())
.filter((b) => b.length > 0);
} catch (error) {
this.logger.warn(`Error obteniendo branches: ${error.message}`);
return [];
}
},
/**
* Verifica si hay cambios uncommitted.
*
* @param {string} workspaceRoot - Ruta del workspace
* @param {boolean} staged - true para staged, false para unstaged
* @returns {boolean}
*/
hasUncommittedChanges(workspaceRoot, staged) {
try {
const diff = this._getGitDiff(workspaceRoot, staged);
return diff.trim().length > 0;
} catch {
return false;
}
},
/**
* Obtiene estadísticas de cambios uncommitted.
*
* @param {string} workspaceRoot - Ruta del workspace
* @param {boolean} staged - true para staged, false para unstaged
* @returns {Object} Estadísticas de cambios
*/
getChangeStats(workspaceRoot, staged) {
try {
const { execSync } = require("child_process");
const command = staged
? "git diff --cached --numstat"
: "git diff --numstat";
const output = execSync(command, {
cwd: workspaceRoot,
encoding: "utf-8",
});
const lines = output.trim().split("\n");
let additions = 0;
let deletions = 0;
const files = [];
for (const line of lines) {
if (!line) continue;
const [add, del, file] = line.split("\t");
additions += parseInt(add) || 0;
deletions += parseInt(del) || 0;
files.push(file);
}
return {
filesChanged: files.length,
additions,
deletions,
files,
};
} catch {
return {
filesChanged: 0,
additions: 0,
deletions: 0,
files: [],
};
}
},
};
module.exports = localReviewMethods;
|