Spaces:
Paused
Paused
File size: 10,080 Bytes
440cddf 9284ad7 440cddf 9284ad7 440cddf 9284ad7 440cddf 9284ad7 440cddf 9284ad7 440cddf 9284ad7 440cddf | 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 | "use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocalContextEngine = void 0;
const fs_1 = require("fs");
const child_process_1 = require("child_process");
const inputs_1 = require("./inputs");
const patch_utils_1 = require("./utils/patch-utils");
const confidence_1 = require("./confidence");
const p_limit_1 = __importDefault(require("p-limit"));
const web_tree_sitter_1 = __importDefault(require("web-tree-sitter"));
class LocalContextEngine {
files;
project;
changes = new Map();
constructor(files) {
this.files = files;
this.project = null;
}
async initialize() {
await this.loadChanges();
this.initializeParser();
}
async loadChanges() {
for (const file of this.files) {
if (!(0, fs_1.existsSync)(file))
continue;
try {
const newContent = (0, fs_1.readFileSync)(file, 'utf8');
let oldContent = '';
let diff = '';
try {
diff = (0, child_process_1.execSync)(`git diff HEAD -- "${file}"`, {
encoding: 'utf8',
cwd: process.cwd()
});
const parentCommit = (0, child_process_1.execSync)('git rev-parse HEAD^', {
encoding: 'utf8',
cwd: process.cwd()
}).trim();
try {
oldContent = (0, child_process_1.execSync)(`git show ${parentCommit}:${file}`, {
encoding: 'utf8',
cwd: process.cwd()
});
}
catch {
oldContent = '';
}
}
catch {
diff = '';
oldContent = '';
}
const hunks = this.parseDiff(diff);
this.changes.set(file, {
filename: file,
oldContent,
newContent,
diff,
hunks
});
}
catch (e) {
console.warn(`Failed to load ${file}: ${e}`);
}
}
}
parseDiff(diff) {
const hunks = [];
const hunkRegex = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/gm;
let match;
while ((match = hunkRegex.exec(diff)) !== null) {
const oldStart = parseInt(match[1], 10);
const oldLines = parseInt(match[2] || '1', 10);
const newStart = parseInt(match[3], 10);
const newLines = parseInt(match[4] || '1', 10);
const startIdx = match.index + match[0].length;
const nextHunkIdx = diff.indexOf('@@', startIdx);
const endIdx = nextHunkIdx === -1 ? diff.length : nextHunkIdx;
const content = diff.substring(startIdx, endIdx).trim();
hunks.push({
oldStart,
oldLines,
newStart,
newLines,
content
});
}
return hunks;
}
initializeParser() {
try {
web_tree_sitter_1.default.init();
}
catch (e) {
console.warn(`Failed to initialize tree-sitter: ${e}`);
}
}
async runReview(lightBot, heavyBot, options, prompts) {
const findings = [];
const concurrencyLimit = (0, p_limit_1.default)(options.concurrencyLimit);
const reviewPromises = Array.from(this.changes.entries()).map(([filename, change]) => concurrencyLimit(async () => {
return this.reviewFile(filename, change, lightBot, heavyBot, options, prompts);
}));
const fileResults = await Promise.all(reviewPromises);
for (const result of fileResults) {
findings.push(...result);
}
return findings;
}
async reviewFile(filename, change, lightBot, heavyBot, options, prompts) {
const findings = [];
const inputs = new inputs_1.Inputs();
inputs.title = `Local review: ${filename}`;
inputs.description = '';
inputs.systemMessage = options.systemMessage;
for (const hunk of change.hunks) {
const ins = inputs.clone();
const patchContent = this.formatPatchForReview(filename, hunk, change.oldContent);
ins.fileDiff = patchContent;
ins.filename = filename;
ins.patches = hunk.content;
const prompt = prompts.renderReviewFileDiff(ins);
const [response] = await heavyBot.chat(prompt, {});
if (response && response.trim()) {
const fileFindings = this.parseFindings(response, filename, hunk.newStart, hunk.newStart + hunk.newLines);
for (const finding of fileFindings) {
if (options.meetsMinimumSeverity(finding.severity)) {
if (options.meetsConfidenceThreshold(finding.confidence)) {
findings.push(finding);
}
}
}
}
}
return findings;
}
formatPatchForReview(filename, hunk, oldContent) {
const oldLines = oldContent.split('\n');
const relevantOldLines = oldLines.slice(hunk.oldStart - 1, hunk.oldStart - 1 + hunk.oldLines);
const patchLines = hunk.content.split('\n');
const newHunkLines = patchLines.filter(l => l.startsWith('+') && !l.startsWith('+++'));
const oldHunkLines = patchLines.filter(l => l.startsWith('-') && !l.startsWith('---'));
return `## File: ${filename}
@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@
---old_hunk---
\`\`\`
${oldHunkLines.join('\n') || '(no old lines)'}
\`\`\`
---new_hunk---
\`\`\`
${newHunkLines.join('\n') || '(no new lines)'}
\`\`\`
`;
}
parseFindings(response, filename, startLine, endLine) {
const findings = [];
const lines = response.split('\n');
let currentFinding = null;
let currentMessage = '';
const lineRangeRegex = /^(\d+)-(\d+):/;
const levelTypeRegex = /^(CRITICAL|MAJOR|MINOR|INFO)\s*\|\s*(\w+)/;
const confidenceRegex = /CONFIDENCE:\s*(\d+)%?$/i;
for (const line of lines) {
const lineRangeMatch = line.match(lineRangeRegex);
if (lineRangeMatch) {
if (currentFinding && currentFinding.message) {
const calibrated = confidence_1.confidenceCalibrator.calibrate(currentFinding.confidence || 50, currentFinding.message, currentFinding.message.length, 2000, currentFinding.severity, 'local', 'local', (0, patch_utils_1.extractPatternType)(currentFinding.message), filename);
findings.push({
filename,
line: currentFinding.line || startLine,
endLine: currentFinding.endLine || endLine,
severity: currentFinding.severity || 'minor',
type: currentFinding.type || 'general',
message: currentFinding.message.trim(),
confidence: calibrated.score,
suggestion: currentFinding.suggestion,
patternType: (0, patch_utils_1.extractPatternType)(currentFinding.message)
});
}
currentFinding = {
line: parseInt(lineRangeMatch[1], 10),
endLine: parseInt(lineRangeMatch[2], 10),
severity: 'minor',
type: 'general',
confidence: 50
};
currentMessage = '';
continue;
}
const levelTypeMatch = line.match(levelTypeRegex);
if (levelTypeMatch && currentFinding) {
currentFinding.severity =
levelTypeMatch[1].toLowerCase();
currentFinding.type = levelTypeMatch[2].toLowerCase();
continue;
}
if (line.includes('```suggestion')) {
const suggestionMatch = response.match(/```suggestion\n([\s\S]*?)```/);
if (suggestionMatch && currentFinding) {
currentFinding.suggestion = suggestionMatch[1].trim();
}
}
const confidenceMatch = line.match(confidenceRegex);
if (confidenceMatch && currentFinding) {
currentFinding.confidence = parseInt(confidenceMatch[1], 10);
}
if (currentFinding) {
currentMessage += `${line}\n`;
currentFinding.message = currentMessage;
}
}
if (currentFinding && currentFinding.message) {
const calibrated = confidence_1.confidenceCalibrator.calibrate(currentFinding.confidence || 50, currentFinding.message, currentFinding.message.length, 2000, currentFinding.severity, 'local', 'local', (0, patch_utils_1.extractPatternType)(currentFinding.message), filename);
findings.push({
filename,
line: currentFinding.line || startLine,
endLine: currentFinding.endLine || endLine,
severity: currentFinding.severity || 'minor',
type: currentFinding.type || 'general',
message: currentFinding.message.trim(),
confidence: calibrated.score,
suggestion: currentFinding.suggestion,
patternType: (0, patch_utils_1.extractPatternType)(currentFinding.message)
});
}
return findings;
}
}
exports.LocalContextEngine = LocalContextEngine;
//# sourceMappingURL=local-context.js.map |