diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..833b0da07f4cd95b96f5f83268c531efe183576a --- /dev/null +++ b/lib/index.js @@ -0,0 +1,283 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const options_1 = require("./src/options"); +const prompts_1 = require("./src/prompts"); +const review_1 = require("./src/review"); +const review_comment_1 = require("./src/review-comment"); +const context_1 = require("./src/context"); +const octokit_1 = require("./src/octokit"); +const checkout_1 = require("./src/checkout"); +const fs_1 = require("fs"); +const path_1 = require("path"); +const feedback_capture_1 = require("./src/feedback-capture"); +const feedback_tracker_1 = require("./src/feedback-tracker"); +/** + * PRIX (AI PR Reviewer and Auditor) + * Probot Service Entry Point + */ +exports.default = (app, { getRouter }) => { + app.log.info('PRIX module loading...'); + // 0. Health Check for Hugging Face + if (getRouter) { + const router = getRouter(); + router.get('/', (_req, res) => { + res.status(200).send('PRIX Service is Running'); + }); + router.get('/ping', (_req, res) => { + res.status(200).send('pong'); + }); + } + app.log.info('PRIX Service Started'); + function parseSeverityLevel(value) { + const validLevels = [ + 'critical', + 'major', + 'minor', + 'info' + ]; + if (value && validLevels.includes(value)) { + return value; + } + return 'minor'; + } + // Helper to initialize options from environment variables + const getOptions = () => { + return new options_1.Options(process.env.DEBUG === 'true', process.env.DISABLE_REVIEW === 'true', process.env.DISABLE_RELEASE_NOTES === 'true', process.env.MAX_FILES || '0', process.env.REVIEW_SIMPLE_CHANGES === 'true', process.env.REVIEW_COMMENT_LGTM === 'true', process.env.PATH_FILTERS ? process.env.PATH_FILTERS.split(',') : null, process.env.SYSTEM_MESSAGE || '', process.env.LIGHT_MODEL || 'llama-3.1-8b-instant', process.env.HEAVY_MODEL || 'llama-3.3-70b-versatile', process.env.MODEL_TEMPERATURE || '0.0', process.env.RETRIES || '3', process.env.TIMEOUT_MS || '120000', process.env.CONCURRENCY_LIMIT || '6', process.env.GITHUB_CONCURRENCY_LIMIT || '6', process.env.API_BASE_URL || 'https://api.groq.com/openai/v1', process.env.LANGUAGE || 'en-US', true, parseSeverityLevel(process.env.MINIMUM_SEVERITY), process.env.MIN_CONFIDENCE || '0', process.env.DENSE_MODE || 'false', process.env.SHOW_IMPACT_ANALYSIS || 'true'); + }; + // 1. Event Listeners for PR Audit + app.on([ + 'pull_request.opened', + 'pull_request.synchronize', + 'pull_request.reopened' + ], async (context) => { + const { payload } = context; + // Skip audits for PRs opened by bots to prevent recursive loops + if (payload.pull_request.user.type === 'Bot') { + app.log.info(`Skipping audit for PR #${payload.pull_request.number} because it was opened by a bot (${payload.pull_request.user.login})`); + return; + } + app.log.info(`Received ${context.name}.${payload.action} for PR #${payload.pull_request.number}`); + try { + const options = getOptions(); + const prompts = new prompts_1.Prompts(); + // Create a unique temporary directory for this audit + const tempDir = (0, path_1.join)(process.cwd(), `tmp_${payload.pull_request.id}_${Date.now()}`); + // Create a safe, isolated execution context + await context_1.als.run({ + probotContext: context, + octokit: context.octokit, + repo: context.repo(), + workingDir: tempDir + }, async () => { + try { + // Clone the repo locally so Git commands work + await (0, checkout_1.checkoutRepo)(tempDir); + // Initialize shims + (0, octokit_1.setOctokit)(context.octokit); + // Trigger the main PRIX Audit + await (0, review_1.run)(context, options, prompts); + } + finally { + // Cleanup temp directory + try { + (0, fs_1.rmSync)(tempDir, { recursive: true, force: true }); + } + catch (cleanupErr) { + app.log.error(`Failed to cleanup ${tempDir}: ${cleanupErr}`); + } + } + }); + app.log.info(`Successfully processed audit for PR #${payload.pull_request.number}`); + } + catch (err) { + app.log.error(`Failed to process audit for PR #${payload.pull_request.number}: ${err.message}`); + // Log specific reason without crashing as per requirements + } + }); + // 2. Event Listener for "Chat with Bot" (Reply to comments) and Reaction Feedback + // Handles both chat replies AND reaction capture for PR comments + app.on('pull_request_review_comment.created', async (context) => { + const { payload } = context; + app.log.info(`Received ${context.name}.${payload.action} for comment ${payload.comment.id}`); + const isBotComment = payload.comment?.user?.type === 'Bot'; + try { + // 2a. Chat with Bot handler (skip bot's own comments) + if (!isBotComment) { + const options = getOptions(); + const prompts = new prompts_1.Prompts(); + await context_1.als.run({ + probotContext: context, + octokit: context.octokit, + repo: context.repo() + }, async () => { + (0, octokit_1.setOctokit)(context.octokit); + await (0, review_comment_1.run)(context, options, prompts); + }); + app.log.info(`Successfully processed chat reply for comment ${payload.comment.id}`); + } + // 2b. Reaction Feedback handler (captures ๐Ÿ‘/โค๏ธ as acceptance, ๐Ÿ‘€/-1 as rejection) + if (!isBotComment) { + await context_1.als.run({ + probotContext: context, + octokit: context.octokit, + repo: context.repo() + }, async () => { + (0, octokit_1.setOctokit)(context.octokit); + const pullNumber = payload.pull_request?.number; + if (pullNumber) { + await feedback_capture_1.feedbackCapture.checkReactionFeedback(pullNumber); + app.log.info(`Processed reaction feedback for PR #${pullNumber}`); + } + }); + } + } + catch (err) { + app.log.error(`Failed to process pull_request_review_comment: ${err.message}`); + } + }); + // 4. Event Listener for PR Review Submission + // Tracks when a review is submitted to monitor suggestion acceptance + app.on('pull_request_review.submitted', async (context) => { + const { payload } = context; + app.log.info(`Received review submitted for PR #${payload.pull_request?.number}, review ID: ${payload.review?.id}`); + try { + await context_1.als.run({ + probotContext: context, + octokit: context.octokit, + repo: context.repo() + }, async () => { + (0, octokit_1.setOctokit)(context.octokit); + const pullNumber = payload.pull_request?.number; + const reviewId = payload.review?.id; + const commitId = payload.review?.commit_id; + if (pullNumber && reviewId && commitId) { + await feedback_capture_1.feedbackCapture.trackReviewSubmission(pullNumber, reviewId, commitId); + app.log.info(`Tracked review submission: PR #${pullNumber}`); + } + }); + } + catch (err) { + app.log.error(`Failed to track review submission: ${err.message}`); + } + }); + // 5. Event Listener for Reaction on Issues (for standalone issue comments) + app.on('issue_comment.created', async (context) => { + const { payload } = context; + // Only process user comments (not bot comments) + if (payload.comment?.user?.type === 'Bot') { + return; + } + try { + await context_1.als.run({ + probotContext: context, + octokit: context.octokit, + repo: context.repo() + }, async () => { + (0, octokit_1.setOctokit)(context.octokit); + // Check for feedback reactions on issue comments + const { data: reactions } = await context.octokit.reactions.listForIssueComment({ + owner: context.repo().owner, + repo: context.repo().repo, + // eslint-disable-next-line camelcase + comment_id: payload.comment.id + }); + for (const reaction of reactions) { + if (reaction.content === '+1' || reaction.content === 'heart') { + feedback_tracker_1.feedbackTracker.recordFeedback({ + patternType: 'general', + severity: 'info', + filenamePattern: 'issue', + repoSlug: context.repo().repo, + teamId: context.repo().owner, + confidence: 50, + feedbackType: 'accepted', + commentId: String(payload.comment.id) + }); + } + else if (reaction.content === '-1' || + reaction.content === 'eyes') { + feedback_tracker_1.feedbackTracker.recordFeedback({ + patternType: 'general', + severity: 'info', + filenamePattern: 'issue', + repoSlug: context.repo().repo, + teamId: context.repo().owner, + confidence: 50, + feedbackType: 'rejected', + commentId: String(payload.comment.id) + }); + } + } + }); + } + catch (err) { + app.log.error(`Failed to process issue reaction feedback: ${err.message}`); + } + }); + // 6. Event Listener for @prix mention in Issue Comments + // When someone mentions @prix in an issue comment, analyze the issue and generate a fix plan + app.on('issue_comment.created', async (context) => { + const { payload } = context; + const comment = payload.comment; + if (!comment || comment.user?.type === 'Bot') { + return; + } + if (!comment.body.includes('@prix')) { + return; + } + app.log.info(`Received @prix mention in issue #${payload.issue?.number} from @${comment.user?.login}`); + try { + const options = getOptions(); + const prompts = new prompts_1.Prompts(); + const { Bot } = await Promise.resolve().then(() => __importStar(require('./src/bot'))); + const heavyBot = new Bot(options, options.heavyAIOptions); + await context_1.als.run({ + probotContext: context, + octokit: context.octokit, + repo: context.repo() + }, async () => { + (0, octokit_1.setOctokit)(context.octokit); + const { handleIssueComment } = await Promise.resolve().then(() => __importStar(require('./src/issue-handler'))); + await handleIssueComment(heavyBot, options, prompts); + }); + app.log.info(`Successfully processed @prix mention in issue #${payload.issue?.number}`); + } + catch (err) { + app.log.error(`Failed to process @prix mention in issue #${payload.issue?.number}: ${err.message}`); + } + }); +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/index.js.map b/lib/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..94036bef195ac68bc1a61d65ff94982332e78c70 --- /dev/null +++ b/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,2CAAqC;AACrC,2CAAqC;AACrC,yCAA4C;AAC5C,yDAAmD;AACnD,2CAAiC;AACjC,2CAAwC;AACxC,6CAA2C;AAC3C,2BAAyB;AACzB,+BAAyB;AACzB,6DAAsD;AACtD,6DAAsD;AAEtD;;;GAGG;AACH,kBAAe,CAAC,GAAW,EAAE,EAAC,SAAS,EAAM,EAAE,EAAE;IAC/C,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAA;IAEtC,mCAAmC;IACnC,IAAI,SAAS,EAAE,CAAC;QACd,MAAM,MAAM,GAAG,S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G,wDAAa,qBAAqB,GAAC,CAAA;gBAChE,MAAM,kBAAkB,CAAC,QAAQ,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;YACtD,CAAC,CACF,CAAA;YAED,GAAG,CAAC,GAAG,CAAC,IAAI,CACV,kDAAkD,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,CAC1E,CAAA;QACH,CAAC;QAAC,OAAO,GAAQ,EAAE,CAAC;YAClB,GAAG,CAAC,GAAG,CAAC,KAAK,CACX,6CAA6C,OAAO,CAAC,KAAK,EAAE,MAAM,KAAK,GAAG,CAAC,OAAO,EAAE,CACrF,CAAA;QACH,CAAC;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"} \ No newline at end of file diff --git a/lib/src/architectural-analyzer.js b/lib/src/architectural-analyzer.js new file mode 100644 index 0000000000000000000000000000000000000000..f19b84122a901eaec9f9547303330cfd48c6f0fc --- /dev/null +++ b/lib/src/architectural-analyzer.js @@ -0,0 +1,349 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ArchitecturalAnalyzer = void 0; +exports.analyzeArchitecture = analyzeArchitecture; +const DEFAULT_LAYERS = [ + { + name: 'ui', + patterns: [ + '**/components/**', + '**/pages/**', + '**/views/**', + '**/screens/**', + '**/ui/**', + '**/frontend/**' + ], + priority: 1 + }, + { + name: 'api', + patterns: [ + '**/api/**', + '**/controllers/**', + '**/handlers/**', + '**/routes/**', + '**/endpoints/**' + ], + priority: 2 + }, + { + name: 'services', + patterns: [ + '**/services/**', + '**/business/**', + '**/domain/**', + '**/usecases/**' + ], + priority: 3 + }, + { + name: 'data', + patterns: [ + '**/models/**', + '**/schemas/**', + '**/entities/**', + '**/repositories/**', + '**/dal/**' + ], + priority: 4 + }, + { + name: 'infrastructure', + patterns: [ + '**/db/**', + '**/database/**', + '**/cache/**', + '**/queue/**', + '**/storage/**', + '**/external/**' + ], + priority: 5 + }, + { + name: 'shared', + patterns: [ + '**/shared/**', + '**/common/**', + '**/utils/**', + '**/lib/**', + '**/types/**' + ], + priority: 0 + } +]; +const DEFAULT_RULES = [ + { + fromLayer: 'ui', + toLayer: 'data', + allowed: false, + severity: 'critical', + description: 'UI should not directly access data layer' + }, + { + fromLayer: 'ui', + toLayer: 'infrastructure', + allowed: false, + severity: 'critical', + description: 'UI should not directly access infrastructure' + }, + { + fromLayer: 'api', + toLayer: 'ui', + allowed: false, + severity: 'major', + description: 'API layer should not depend on UI' + }, + { + fromLayer: 'api', + toLayer: 'infrastructure', + allowed: true, + severity: 'minor', + description: 'API may access infrastructure (database, cache)' + }, + { + fromLayer: 'services', + toLayer: 'ui', + allowed: false, + severity: 'major', + description: 'Services should not depend on UI' + }, + { + fromLayer: 'services', + toLayer: 'infrastructure', + allowed: true, + severity: 'minor', + description: 'Services may access infrastructure' + }, + { + fromLayer: 'data', + toLayer: 'api', + allowed: false, + severity: 'major', + description: 'Data layer should not depend on API layer' + }, + { + fromLayer: 'data', + toLayer: 'infrastructure', + allowed: false, + severity: 'critical', + description: 'Data layer should not depend on infrastructure' + }, + { + fromLayer: 'shared', + toLayer: 'ui', + allowed: false, + severity: 'minor', + description: 'Shared code should not depend on UI' + }, + { + fromLayer: 'shared', + toLayer: 'api', + allowed: false, + severity: 'minor', + description: 'Shared code should not depend on API' + } +]; +class ArchitecturalAnalyzer { + layers; + rules; + layerCache; + constructor(layers = DEFAULT_LAYERS, rules = DEFAULT_RULES) { + this.layers = layers; + this.rules = rules; + this.layerCache = new Map(); + } + analyze(symbolGraph) { + const violations = []; + const layerAssignments = new Map(); + const unassignedFiles = []; + for (const [key, symbol] of symbolGraph.symbols) { + const file = symbol.file; + if (!layerAssignments.has(file)) { + const layer = this.assignLayer(file); + layerAssignments.set(file, layer); + if (layer === 'unassigned') { + unassignedFiles.push(file); + } + } + } + for (const edge of symbolGraph.edges) { + const fromLayer = layerAssignments.get(edge.from) || 'unassigned'; + const toLayer = this.resolveImportToLayer(edge.to, symbolGraph); + if (fromLayer === 'unassigned' || toLayer === 'unassigned') + continue; + const rule = this.findRule(fromLayer, toLayer); + if (rule && !rule.allowed) { + violations.push({ + from: edge.from, + to: edge.to, + fromLayer, + toLayer, + severity: rule.severity, + description: rule.description, + file: edge.from + }); + } + } + const statistics = { + totalViolations: violations.length, + criticalCount: violations.filter(v => v.severity === 'critical').length, + majorCount: violations.filter(v => v.severity === 'major').length, + minorCount: violations.filter(v => v.severity === 'minor').length + }; + return { + violations, + layerAssignments, + unassignedFiles, + statistics + }; + } + assignLayer(filePath) { + const cached = this.layerCache.get(filePath); + if (cached) + return cached; + const normalizedPath = filePath.replace(/\\/g, '/').toLowerCase(); + for (const layer of this.layers) { + for (const pattern of layer.patterns) { + if (this.matchPattern(normalizedPath, pattern.toLowerCase())) { + this.layerCache.set(filePath, layer.name); + return layer.name; + } + } + } + this.layerCache.set(filePath, 'unassigned'); + return 'unassigned'; + } + matchPattern(path, pattern) { + const regexPattern = pattern + .replace(/\*\*/g, '<>') + .replace(/\*/g, '[^/]*') + .replace(/<>/g, '.*') + .replace(/\?/g, '.'); + try { + const regex = new RegExp(`^${regexPattern}$`); + return regex.test(path) || this.matchGlob(path, pattern); + } + catch { + return this.matchGlob(path, pattern); + } + } + matchGlob(path, pattern) { + const parts = path.split('/'); + const patternParts = pattern.split('/'); + let pi = 0; + let psi = 0; + while (pi < parts.length && psi < patternParts.length) { + const patternPart = patternParts[psi]; + if (patternPart === '**') { + if (psi === patternParts.length - 1) { + return true; + } + const nextPattern = patternParts[psi + 1]; + while (pi < parts.length) { + if (this.matchSingle(parts[pi], nextPattern)) { + if (this.matchGlob(parts.slice(pi).join('/'), patternParts.slice(psi + 1).join('/'))) { + return true; + } + } + pi++; + } + return false; + } + if (!this.matchSingle(parts[pi], patternPart)) { + return false; + } + pi++; + psi++; + } + return pi === parts.length && psi === patternParts.length; + } + matchSingle(part, pattern) { + if (pattern === '*') + return part.length > 0; + if (pattern === '**') + return true; + const regexPattern = pattern + .replace(/\./g, '\\.') + .replace(/\*/g, '[^/]*') + .replace(/\?/g, '.'); + try { + const regex = new RegExp(`^${regexPattern}$`); + return regex.test(part); + } + catch { + return part === pattern; + } + } + resolveImportToLayer(importPath, symbolGraph) { + const normalizedImport = importPath.replace(/['"]/g, '').replace(/\\/g, '/'); + for (const [key, symbol] of symbolGraph.symbols) { + const symbolPath = symbol.file; + if (symbolPath.includes(normalizedImport) || + normalizedImport.includes(symbolPath)) { + return this.assignLayer(symbolPath); + } + } + if (normalizedImport.startsWith('.')) { + return 'unassigned'; + } + if (normalizedImport.includes('/node_modules/')) { + return 'external'; + } + if (normalizedImport.includes('/shared/') || + normalizedImport.includes('/common/')) { + return 'shared'; + } + return 'unassigned'; + } + findRule(fromLayer, toLayer) { + return this.rules.find(r => r.fromLayer === fromLayer && r.toLayer === toLayer); + } + getDependencyGraph(layerAssignments) { + const graph = new Map(); + for (const [file, layer] of layerAssignments) { + if (!graph.has(layer)) { + graph.set(layer, new Set()); + } + } + return graph; + } + generateReport(analysis) { + const lines = []; + lines.push('# Architectural Violation Report'); + lines.push(''); + lines.push(`Total Violations: ${analysis.statistics.totalViolations}`); + lines.push(` - Critical: ${analysis.statistics.criticalCount}`); + lines.push(` - Major: ${analysis.statistics.majorCount}`); + lines.push(` - Minor: ${analysis.statistics.minorCount}`); + lines.push(''); + if (analysis.violations.length > 0) { + lines.push('## Violations'); + lines.push(''); + const groupedBySeverity = { + critical: analysis.violations.filter(v => v.severity === 'critical'), + major: analysis.violations.filter(v => v.severity === 'major'), + minor: analysis.violations.filter(v => v.severity === 'minor') + }; + for (const severity of ['critical', 'major', 'minor']) { + const violations = groupedBySeverity[severity]; + if (violations.length === 0) + continue; + lines.push(`### ${severity.toUpperCase()} (${violations.length})`); + lines.push(''); + for (const v of violations) { + lines.push(`- **${v.fromLayer}** โ†’ **${v.toLayer}**: ${v.description}`); + lines.push(` - File: \`${v.file || v.from}\``); + lines.push(` - Import: \`${v.to}\``); + } + lines.push(''); + } + } + return lines.join('\n'); + } +} +exports.ArchitecturalAnalyzer = ArchitecturalAnalyzer; +function analyzeArchitecture(symbolGraph) { + const analyzer = new ArchitecturalAnalyzer(); + return analyzer.analyze(symbolGraph); +} +//# sourceMappingURL=architectural-analyzer.js.map \ No newline at end of file diff --git a/lib/src/architectural-analyzer.js.map b/lib/src/architectural-analyzer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..575ef4705c211f287ef349681d249dc0c2448a8f --- /dev/null +++ b/lib/src/architectural-analyzer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"architectural-analyzer.js","sourceRoot":"","sources":["../../src/architectural-analyzer.ts"],"names":[],"mappings":";;;AAwbA,kDAKC;AAtZD,MAAM,cAAc,GAAsB;IACxC;QACE,IAAI,EAAE,IAAI;QACV,QAAQ,EAAE;YACR,kBAAkB;YAClB,aAAa;YACb,aAAa;YACb,eAAe;YACf,UAAU;YACV,gBAAgB;SACjB;QACD,QAAQ,EAAE,CAAC;KACZ;IACD;QACE,IAAI,EAAE,KAAK;QACX,QAAQ,EAAE;YACR,WAAW;YACX,mBAAmB;YACnB,gBAAgB;YAChB,cAAc;YACd,iBAAiB;SAClB;QACD,QAAQ,EAAE,CAAC;KACZ;IACD;QACE,IAAI,EAAE,UAAU;QAChB,QAAQ,EAAE;YACR,gBAAgB;YAChB,gBAAgB;YAChB,cAAc;YACd,gBAAgB;SACjB;QACD,QAAQ,EAAE,CAAC;KACZ;IACD;QACE,IAAI,EAAE,MAAM;QACZ,QAAQ,EAAE;YACR,cAAc;YACd,eAAe;YACf,gBAAgB;YAChB,oBAAoB;YACpB,WAAW;SACZ;QACD,QAAQ,EAAE,CAAC;KACZ;IACD;QACE,IAAI,EAAE,gBAAgB;QACtB,QAAQ,EAAE;YACR,UAAU;YACV,gBAAgB;YAChB,aAAa;YACb,aAAa;YACb,eAAe;YACf,gBAAgB;SACjB;QACD,QAAQ,EAAE,CAAC;KACZ;IACD;QACE,IAAI,EAAE,QAAQ;QACd,QAAQ,EAAE;YACR,cAAc;YACd,cAAc;YACd,aAAa;Y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AC,IAAI,CAAC,eAAe,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC,CAAA;oBAC/C,KAAK,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;gBACvC,CAAC;gBACD,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YAChB,CAAC;QACH,CAAC;QAED,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACzB,CAAC;CACF;AAhQD,sDAgQC;AAED,SAAgB,mBAAmB,CACjC,WAAwB;IAExB,MAAM,QAAQ,GAAG,IAAI,qBAAqB,EAAE,CAAA;IAC5C,OAAO,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,CAAA;AACtC,CAAC"} \ No newline at end of file diff --git a/lib/src/bot.js b/lib/src/bot.js new file mode 100644 index 0000000000000000000000000000000000000000..15ed8c1276cc244290d66d31d0b20f593b00fa8b --- /dev/null +++ b/lib/src/bot.js @@ -0,0 +1,154 @@ +"use strict"; +// Node 20 includes native fetch support +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Bot = void 0; +// AI Client for Groq with Failover Support +// Fallback shims for Probot runtime +/* eslint-disable no-console */ +const chatgpt_1 = require("chatgpt"); +const p_retry_1 = __importDefault(require("p-retry")); +const options_1 = require("./options"); +const limits_1 = require("./limits"); +const logInfo = console.log; +const logWarning = console.warn; +const logError = console.error; +/* eslint-enable no-console */ +const setFailed = (msg) => { + console.error(msg); + process.exit(1); +}; +class Bot { + api = null; + options; + aiOptions; + currentModel; + fallbackModels; + constructor(options, aiOptions) { + this.options = options; + this.aiOptions = aiOptions; + this.currentModel = aiOptions.model; + // Setup fallback chain based on tier + if (options_1.Options.HEAVY_MODELS.includes(this.currentModel)) { + this.fallbackModels = [...options_1.Options.HEAVY_MODELS]; + } + else { + this.fallbackModels = [...options_1.Options.LIGHT_MODELS]; + } + // Remove current model from fallbacks to avoid immediate repeat + this.fallbackModels = this.fallbackModels.filter(m => m !== this.currentModel); + this.initClient(); + } + initClient() { + const apiKey = process.env.GROQ_API_KEY || process.env.AI_API_KEY; + if (apiKey) { + const currentDate = new Date().toISOString().split('T')[0]; + const limits = new limits_1.TokenLimits(this.currentModel); + const systemMessage = `${this.options.systemMessage} +Knowledge cutoff: ${limits.knowledgeCutOff} +Current date: ${currentDate} +IMPORTANT: Entire response must be in ISO code: ${this.options.language} +`; + this.api = new chatgpt_1.ChatGPTAPI({ + apiBaseUrl: this.options.apiBaseUrl, + systemMessage, + apiKey, + apiOrg: process.env.AI_API_ORG || undefined, + debug: this.options.debug, + maxModelTokens: limits.maxTokens, + maxResponseTokens: limits.responseTokens, + completionParams: { + temperature: this.options.modelTemperature, + model: this.currentModel + } + }); + logInfo(`Initialized AI client with model: ${this.currentModel}`); + } + else { + throw new Error("Missing 'GROQ_API_KEY' or 'AI_API_KEY'"); + } + } + chat = async (message, ids) => { + let res = ['', {}]; + try { + res = await this.chat_(message, ids); + return res; + } + catch (e) { + if (e instanceof chatgpt_1.ChatGPTError) { + logWarning(`AI communication error: ${e.message}`); + } + return res; + } + }; + chat_ = async (message, ids) => { + const start = Date.now(); + if (!message) + return ['', {}]; + let response; + if (this.api != null) { + const opts = { + timeoutMs: this.options.timeoutMS + }; + if (ids.parentMessageId) { + opts.parentMessageId = ids.parentMessageId; + } + try { + response = await (0, p_retry_1.default)(async (attemptState) => { + try { + const result = await this.api.sendMessage(message, opts); + return result; + } + catch (e) { + if (e?.status === 429 && this.fallbackModels.length > 0) { + const nextModel = this.fallbackModels.shift(); + if (nextModel) { + logWarning(`Rate limit (429) hit for ${this.currentModel}. Switching to fallback: ${nextModel}`); + this.currentModel = nextModel; + this.initClient(); + } + } + throw e; + } + }, { + retries: this.options.retries, + onFailedAttempt: (err) => { + logInfo(`Attempt ${err.attemptNumber} failed. ${err.retriesLeft} retries left.`); + const errorResponse = err.response || err.status; + if (errorResponse === 429 && this.fallbackModels.length > 0) { + const nextModel = this.fallbackModels.shift(); + if (nextModel) { + logWarning(`Proactive switch to fallback model: ${nextModel} due to 429`); + this.currentModel = nextModel; + this.initClient(); + } + } + } + }); + } + catch (e) { + if (e instanceof chatgpt_1.ChatGPTError) { + logInfo(`AI Error: ${e.message} (Last model used: ${this.currentModel})`); + } + } + const end = Date.now(); + logInfo(`AI response time: ${end - start} ms`); + } + else { + setFailed('AI client is not initialized'); + } + let responseText = ''; + if (response != null) { + responseText = response.text; + } + const newIds = { + parentMessageId: response?.id, + conversationId: response?.conversationId + }; + return [responseText, newIds]; + }; +} +exports.Bot = Bot; +//# sourceMappingURL=bot.js.map \ No newline at end of file diff --git a/lib/src/bot.js.map b/lib/src/bot.js.map new file mode 100644 index 0000000000000000000000000000000000000000..851c73343150d7a84166579098af8ea347741155 --- /dev/null +++ b/lib/src/bot.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bot.js","sourceRoot":"","sources":["../../src/bot.ts"],"names":[],"mappings":";AAAA,wCAAwC;;;;;;AAExC,2CAA2C;AAC3C,oCAAoC;AACpC,+BAA+B;AAC/B,qCAKgB;AAChB,sDAA4B;AAC5B,uCAA4C;AAC5C,qCAAoC;AAEpC,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAA;AAC3B,MAAM,UAAU,GAAG,OAAO,CAAC,IAAI,CAAA;AAC/B,MAAM,QAAQ,GAAG,OAAO,CAAC,KAAK,CAAA;AAC9B,8BAA8B;AAC9B,MAAM,SAAS,GAAG,CAAC,GAAW,EAAE,EAAE;IAChC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAClB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;AACjB,CAAC,CAAA;AAOD,MAAa,GAAG;IACN,GAAG,GAAoB,IAAI,CAAA;IAClB,OAAO,CAAS;IAChB,SAAS,CAAW;IAC7B,YAAY,CAAQ;IACpB,cAAc,CAAU;IAEhC,YA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,EAAE,CAAC;4BAC5D,MAAM,SAAS,GAAG,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAA;4BAC7C,IAAI,SAAS,EAAE,CAAC;gCACd,UAAU,CACR,uCAAuC,SAAS,aAAa,CAC9D,CAAA;gCACD,IAAI,CAAC,YAAY,GAAG,SAAS,CAAA;gCAC7B,IAAI,CAAC,UAAU,EAAE,CAAA;4BACnB,CAAC;wBACH,CAAC;oBACH,CAAC;iBACF,CACF,CAAA;YACH,CAAC;YAAC,OAAO,CAAU,EAAE,CAAC;gBACpB,IAAI,CAAC,YAAY,sBAAO,EAAE,CAAC;oBACzB,OAAO,CACL,aAAa,CAAC,CAAC,OAAO,sBAAsB,IAAI,CAAC,YAAY,GAAG,CACjE,CAAA;gBACH,CAAC;YACH,CAAC;YAED,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;YACtB,OAAO,CAAC,qBAAqB,GAAG,GAAG,KAAK,KAAK,CAAC,CAAA;QAChD,CAAC;aAAM,CAAC;YACN,SAAS,CAAC,8BAA8B,CAAC,CAAA;QAC3C,CAAC;QAED,IAAI,YAAY,GAAG,EAAE,CAAA;QACrB,IAAI,QAAQ,IAAI,IAAI,EAAE,CAAC;YACrB,YAAY,GAAG,QAAQ,CAAC,IAAI,CAAA;QAC9B,CAAC;QAED,MAAM,MAAM,GAAQ;YAClB,eAAe,EAAE,QAAQ,EAAE,EAAE;YAC7B,cAAc,EAAE,QAAQ,EAAE,cAAc;SACzC,CAAA;QACD,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC,CAAA;IAC/B,CAAC,CAAA;CACF;AAxJD,kBAwJC"} \ No newline at end of file diff --git a/lib/src/checkout.js b/lib/src/checkout.js new file mode 100644 index 0000000000000000000000000000000000000000..6bd5886ed642c0230e798150c1fab197df097e37 --- /dev/null +++ b/lib/src/checkout.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.checkoutRepo = void 0; +const utils_1 = require("./utils"); +const fs_1 = require("fs"); +const path_1 = require("path"); +const context_1 = require("./context"); +const checkoutRepo = async (tempDir, options = {}) => { + const ctx = (0, context_1.getCurrentContext)(); + if (!ctx) + throw new Error('No context available for checkout'); + const { owner, repo } = ctx.repo; + const installationId = ctx.probotContext.payload.installation.id; + const tokenResp = await ctx.probotContext.octokit.apps.createInstallationAccessToken({ + installation_id: installationId + }); + const token = tokenResp.data.token; + if (!token) { + throw new Error('Failed to create installation access token: token is undefined'); + } + const cloneUrl = `https://x-access-token:${token}@github.com/${owner}/${repo}.git`; + const headBranch = ctx.probotContext.payload.pull_request.head.ref; + const headSha = ctx.probotContext.payload.pull_request.head.sha; + if ((0, fs_1.existsSync)(tempDir)) { + (0, fs_1.rmSync)(tempDir, { recursive: true, force: true }); + } + (0, fs_1.mkdirSync)(tempDir, { recursive: true }); + console.log(`Cloning ${owner}/${repo} into ${tempDir}...`); + if (options.sparse && options.files && options.files.length > 0) { + console.log(`Using sparse checkout for ${options.files.length} files...`); + (0, utils_1.prixExec)(`git clone --no-checkout --depth 1 ${cloneUrl} .`, { + cwd: tempDir, + stdio: 'pipe' + }); + (0, utils_1.prixExec)(`git fetch origin ${headSha} --depth 1`, { cwd: tempDir }); + const sparseConfig = options.files.join('\n'); + (0, fs_1.writeFileSync)((0, path_1.join)(tempDir, '.git/info/sparse-checkout'), sparseConfig); + (0, utils_1.prixExec)(`git config core.sparseCheckout true`, { cwd: tempDir }); + (0, utils_1.prixExec)(`git checkout ${headSha}`, { cwd: tempDir }); + } + else { + console.log(`Cloning ${owner}/${repo} with depth 1...`); + (0, utils_1.prixExec)(`git clone --no-checkout --depth 1 ${cloneUrl} .`, { + cwd: tempDir, + stdio: 'pipe' + }); + (0, utils_1.prixExec)(`git fetch origin ${headSha} --depth 1`, { cwd: tempDir }); + (0, utils_1.prixExec)(`git checkout ${headSha}`, { cwd: tempDir }); + } + (0, utils_1.prixExec)(`git config user.name "PRIX AI Auditor"`, { cwd: tempDir }); + (0, utils_1.prixExec)(`git config user.email "bot@prix.ai"`, { cwd: tempDir }); + return tempDir; +}; +exports.checkoutRepo = checkoutRepo; +//# sourceMappingURL=checkout.js.map \ No newline at end of file diff --git a/lib/src/checkout.js.map b/lib/src/checkout.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1c989e997abcbe89321b55200219af43cedec0ba --- /dev/null +++ b/lib/src/checkout.js.map @@ -0,0 +1 @@ +{"version":3,"file":"checkout.js","sourceRoot":"","sources":["../../src/checkout.ts"],"names":[],"mappings":";;;AAAA,mCAAgC;AAChC,2BAA+D;AAC/D,+BAAyB;AACzB,uCAA2C;AAOpC,MAAM,YAAY,GAAG,KAAK,EAC/B,OAAe,EACf,UAA2B,EAAE,EACZ,EAAE;IACnB,MAAM,GAAG,GAAG,IAAA,2BAAiB,GAAE,CAAA;IAC/B,IAAI,CAAC,GAAG;QAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAA;IAE9D,MAAM,EAAC,KAAK,EAAE,IAAI,EAAC,GAAG,GAAG,CAAC,IAAI,CAAA;IAC9B,MAAM,cAAc,GAAG,GAAG,CAAC,aAAa,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE,CAAA;IAEhE,MAAM,SAAS,GACb,MAAM,GAAG,CAAC,aAAa,CAAC,OAAO,CAAC,IAAI,CAAC,6BAA6B,CAAC;QACjE,eAAe,EAAE,cAAc;KAChC,CAAC,CAAA;IACJ,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,KAAK,CAAA;IAElC,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAA;IACH,CAAC;IAED,MAAM,QAAQ,GAAG,0BAA0B,KAAK,eAAe,KAAK,IAAI,IAAI,MAAM,CAAA;IAClF,MAAM,UAAU,GAAG,GAAG,CAAC,aAAa,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,GAAG,CAAA;IAClE,MAAM,OAAO,GAAG,G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,KAAK,IAAI,IAAI,kBAAkB,CAAC,CAAA;QACvD,IAAA,gBAAQ,EAAC,qCAAqC,QAAQ,IAAI,EAAE;YAC1D,GAAG,EAAE,OAAO;YACZ,KAAK,EAAE,MAAM;SACd,CAAC,CAAA;QACF,IAAA,gBAAQ,EAAC,oBAAoB,OAAO,YAAY,EAAE,EAAC,GAAG,EAAE,OAAO,EAAC,CAAC,CAAA;QACjE,IAAA,gBAAQ,EAAC,gBAAgB,OAAO,EAAE,EAAE,EAAC,GAAG,EAAE,OAAO,EAAC,CAAC,CAAA;IACrD,CAAC;IAED,IAAA,gBAAQ,EAAC,wCAAwC,EAAE,EAAC,GAAG,EAAE,OAAO,EAAC,CAAC,CAAA;IAClE,IAAA,gBAAQ,EAAC,qCAAqC,EAAE,EAAC,GAAG,EAAE,OAAO,EAAC,CAAC,CAAA;IAE/D,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA;AA7DY,QAAA,YAAY,gBA6DxB"} \ No newline at end of file diff --git a/lib/src/cli.js b/lib/src/cli.js new file mode 100644 index 0000000000000000000000000000000000000000..68c03fe82be73e7854903387b81bf521aa405042 --- /dev/null +++ b/lib/src/cli.js @@ -0,0 +1,219 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.main = main; +const options_1 = require("./options"); +const prompts_1 = require("./prompts"); +const bot_1 = require("./bot"); +const local_context_1 = require("./local-context"); +const console_reporter_1 = require("./console-reporter"); +const child_process_1 = require("child_process"); +const fs_1 = require("fs"); +const HELP_TEXT = ` +PRIX CLI - Local AI PR Reviewer + +Usage: + prix-cli [options] + +Options: + --staged Review staged files (git diff --cached) + --diff Review files changed since given git ref + --files Review specific files (comma-separated) + --model LLM model to use (default: llama-3.1-8b-instant) + --min-confidence Minimum confidence threshold (0-100) + --min-severity Minimum severity to report (critical|major|minor|info) + --disable-review Skip code review, only generate summary + --disable-notes Skip release notes generation + --max-files Maximum files to review (0 = unlimited) + --path-filters

Path filters (comma-separated, e.g., "src/**,lib/**") + --system-message Additional system message + --language Output language (default: en-US) + --output Output format: console (default) or json + --help, -h Show this help message + +Examples: + prix-cli --staged Review staged changes + prix-cli --diff HEAD~1 Review changes since last commit + prix-cli --files src/app.ts,lib/util.ts Review specific files + prix-cli --min-severity major Only show major/critical issues + +Pre-commit Hook: + Add to .git/hooks/pre-commit: + npx prix-cli --staged --output console +`; +function parseArgs(argv) { + const args = {}; + for (let i = 2; i < argv.length; i++) { + const arg = argv[i]; + switch (arg) { + case '--staged': + args.staged = true; + break; + case '--diff': + args.diff = argv[++i]; + break; + case '--files': + args.files = argv[++i].split(','); + break; + case '--model': + args.model = argv[++i]; + break; + case '--min-confidence': + args.minConfidence = parseInt(argv[++i], 10); + break; + case '--min-severity': + args.minSeverity = argv[++i]; + break; + case '--disable-review': + args.disableReview = true; + break; + case '--disable-notes': + args.disableReleaseNotes = true; + break; + case '--max-files': + args.maxFiles = parseInt(argv[++i], 10); + break; + case '--path-filters': + args.pathFilters = argv[++i].split(','); + break; + case '--system-message': + args.systemMessage = argv[++i]; + break; + case '--language': + args.language = argv[++i]; + break; + case '--output': + args.output = argv[++i]; + break; + case '--help': + case '-h': + args.help = true; + break; + } + } + return args; +} +function getStagedFiles() { + try { + const output = (0, child_process_1.execSync)('git diff --cached --name-only', { + encoding: 'utf8', + cwd: process.cwd() + }); + return output.split('\n').filter(f => f.trim()); + } + catch (e) { + console.error('Failed to get staged files:', e); + return []; + } +} +function getChangedFiles(sinceRef) { + try { + const output = (0, child_process_1.execSync)(`git diff --name-only ${sinceRef}`, { + encoding: 'utf8', + cwd: process.cwd() + }); + return output.split('\n').filter(f => f.trim()); + } + catch (e) { + console.error(`Failed to get changed files since ${sinceRef}:`, e); + return []; + } +} +async function runLocalReview(args) { + const info = console.log; + const error = console.error; + info('๐Ÿ” PRIX CLI - Starting local code review...\n'); + if (!process.env.GROQ_API_KEY && !process.env.AI_API_KEY) { + error('โŒ Error: GROQ_API_KEY or AI_API_KEY environment variable is required'); + return 1; + } + let filesToReview = []; + if (args.staged) { + filesToReview = getStagedFiles(); + info(`๐Ÿ“‹ Reviewing ${filesToReview.length} staged files\n`); + } + else if (args.diff) { + filesToReview = getChangedFiles(args.diff); + info(`๐Ÿ“‹ Reviewing ${filesToReview.length} files changed since ${args.diff}\n`); + } + else if (args.files) { + filesToReview = args.files.filter(f => (0, fs_1.existsSync)(f)); + info(`๐Ÿ“‹ Reviewing ${filesToReview.length} specified files\n`); + } + else { + error('โŒ Error: Must specify --staged, --diff , or --files '); + return 1; + } + if (filesToReview.length === 0) { + info('โœ… No files to review'); + return 0; + } + const options = new options_1.Options(false, args.disableReview || false, args.disableReleaseNotes || false, args.maxFiles?.toString() || '0', false, false, args.pathFilters || null, args.systemMessage || '', args.model || 'llama-3.1-8b-instant', 'llama-3.3-70b-versatile', '0.0', '3', '120000', '6', '6', process.env.API_BASE_URL || 'https://api.groq.com/openai/v1', args.language || 'en-US', false, args.minSeverity || 'minor', args.minConfidence?.toString() || '0', 'false', 'true'); + const prompts = new prompts_1.Prompts(); + const localContext = new local_context_1.LocalContextEngine(filesToReview); + const reporter = new console_reporter_1.LocalConsoleReporter(); + info('๐Ÿค– Initializing AI models...'); + let lightBot = null; + let heavyBot = null; + try { + lightBot = new bot_1.Bot(options, new options_1.AIOptions(options.lightModel, options.lightTokenLimits, options.modelTemperature)); + } + catch (e) { + error(`โŒ Failed to initialize light model: ${e}`); + return 1; + } + try { + heavyBot = new bot_1.Bot(options, new options_1.AIOptions(options.heavyModel, options.heavyTokenLimits, options.modelTemperature)); + } + catch (e) { + error(`โŒ Failed to initialize heavy model: ${e}`); + return 1; + } + info('โœ… AI models initialized\n'); + try { + await localContext.initialize(); + const findings = await localContext.runReview(lightBot, heavyBot, options, prompts); + reporter.printFindings(findings, { + output: args.output || 'console', + minSeverity: options.minimumSeverity, + minConfidence: options.minConfidence + }); + const critical = findings.filter(f => f.severity === 'critical').length; + const major = findings.filter(f => f.severity === 'major').length; + info(`\n๐Ÿ“Š Summary: ${critical} critical, ${major} major, ${findings.length} total findings`); + if (critical > 0) { + info('\nโš ๏ธ Critical issues found! Consider fixing before committing.'); + return 1; + } + else if (major > 0) { + info('\nโ„น๏ธ Major issues found. Review recommended before committing.'); + return 0; + } + else { + info('\nโœ… No significant issues found.'); + return 0; + } + } + catch (e) { + error(`\nโŒ Review failed: ${e}`); + return 1; + } +} +async function main(argv) { + const args = parseArgs(argv); + if (args.help) { + console.log(HELP_TEXT); + return 0; + } + return runLocalReview(args); +} +if (require.main === module) { + main(process.argv) + .then(code => { + process.exit(code); + }) + .catch(e => { + console.error('Fatal error:', e); + process.exit(1); + }); +} +//# sourceMappingURL=cli.js.map \ No newline at end of file diff --git a/lib/src/cli.js.map b/lib/src/cli.js.map new file mode 100644 index 0000000000000000000000000000000000000000..09930780a784fd97131d6e0e6e1b87c919e6fe38 --- /dev/null +++ b/lib/src/cli.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/cli.ts"],"names":[],"mappings":";;AAsRA,oBASC;AA/RD,uCAA4C;AAC5C,uCAAiC;AACjC,+BAAyB;AAEzB,mDAAkD;AAClD,yDAAuD;AAEvD,iDAAsC;AACtC,2BAA6B;AAmB7B,MAAM,SAAS,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+BjB,CAAA;AAED,SAAS,SAAS,CAAC,IAAc;IAC/B,MAAM,IAAI,GAAY,EAAE,CAAA;IACxB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACrC,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;QACnB,QAAQ,GAAG,EAAE,CAAC;YACZ,KAAK,UAAU;gBACb,IAAI,CAAC,MAAM,GAAG,IAAI,CAAA;gBAClB,MAAK;YACP,KAAK,QAAQ;gBACX,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,CAAA;gB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U,IAAI,CAAC,IAAc;IACvC,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAA;IAE5B,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;QACd,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAA;QACtB,OAAO,CAAC,CAAA;IACV,CAAC;IAED,OAAO,cAAc,CAAC,IAAI,CAAC,CAAA;AAC7B,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC5B,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;SACf,IAAI,CAAC,IAAI,CAAC,EAAE;QACX,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACpB,CAAC,CAAC;SACD,KAAK,CAAC,CAAC,CAAC,EAAE;QACT,OAAO,CAAC,KAAK,CAAC,cAAc,EAAE,CAAC,CAAC,CAAA;QAChC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;IACjB,CAAC,CAAC,CAAA;AACN,CAAC"} \ No newline at end of file diff --git a/lib/src/commenter.js b/lib/src/commenter.js new file mode 100644 index 0000000000000000000000000000000000000000..c9e76a6ac1745515307c8563b5782fe3f378c09b --- /dev/null +++ b/lib/src/commenter.js @@ -0,0 +1,684 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Commenter = exports.ISSUE_REPLY_TAG = exports.VERIFICATION_FAILED_TAG = exports.VERIFIED_TAG = exports.COMMIT_ID_END_TAG = exports.COMMIT_ID_START_TAG = exports.SHORT_SUMMARY_END_TAG = exports.SHORT_SUMMARY_START_TAG = exports.RAW_SUMMARY_END_TAG = exports.RAW_SUMMARY_START_TAG = exports.DESCRIPTION_END_TAG = exports.DESCRIPTION_START_TAG = exports.IN_PROGRESS_END_TAG = exports.IN_PROGRESS_START_TAG = exports.SUMMARIZE_TAG = exports.COMMENT_REPLY_TAG = exports.COMMENT_TAG = exports.COMMENT_GREETING = exports.setCommenterContext = exports.repo = exports.context = void 0; +// Removed @actions imports for Probot migration +const octokit_1 = require("./octokit"); +const context_1 = require("./context"); +const info = console.log; +const warning = console.warn; +const getInput = (name) => process.env[name.toUpperCase()] || ''; +exports.context = new Proxy({}, { + get(target, prop) { + return (context_1.als.getStore()?.probotContext)[prop]; + } +}); +exports.repo = new Proxy({}, { + get(target, prop) { + return (context_1.als.getStore()?.repo)[prop]; + } +}); +const setCommenterContext = (newContext) => { + // context and repo are now Proxies +}; +exports.setCommenterContext = setCommenterContext; +exports.COMMENT_GREETING = `${getInput('bot_icon')} AI PR Reviewer`; +exports.COMMENT_TAG = ''; +exports.COMMENT_REPLY_TAG = ''; +exports.SUMMARIZE_TAG = ''; +exports.IN_PROGRESS_START_TAG = ''; +exports.IN_PROGRESS_END_TAG = ''; +exports.DESCRIPTION_START_TAG = ''; +exports.DESCRIPTION_END_TAG = ''; +exports.RAW_SUMMARY_START_TAG = ` + +`; +exports.SHORT_SUMMARY_START_TAG = ` + +`; +exports.COMMIT_ID_START_TAG = ''; +exports.COMMIT_ID_END_TAG = ''; +exports.VERIFIED_TAG = ''; +exports.VERIFICATION_FAILED_TAG = ''; +exports.ISSUE_REPLY_TAG = ''; +class Commenter { + /** + * @param mode Can be "create", "replace". Default is "replace". + */ + async comment(message, tag, mode) { + let target; + if (exports.context.payload.pull_request != null) { + target = exports.context.payload.pull_request.number; + } + else if (exports.context.payload.issue != null) { + target = exports.context.payload.issue.number; + } + else { + warning('Skipped: context.payload.pull_request and context.payload.issue are both null'); + return; + } + if (!tag) { + tag = exports.COMMENT_TAG; + } + const body = `${exports.COMMENT_GREETING} + +${message} + +${tag}`; + if (mode === 'create') { + await this.create(body, target); + } + else if (mode === 'replace') { + await this.replace(body, tag, target); + } + else { + warning(`Unknown mode: ${mode}, use "replace" instead`); + await this.replace(body, tag, target); + } + } + getContentWithinTags(content, startTag, endTag) { + const start = content.indexOf(startTag); + const end = content.indexOf(endTag); + if (start >= 0 && end >= 0) { + return content.slice(start + startTag.length, end); + } + return ''; + } + removeContentWithinTags(content, startTag, endTag) { + const start = content.indexOf(startTag); + const end = content.lastIndexOf(endTag); + if (start >= 0 && end >= 0) { + return content.slice(0, start) + content.slice(end + endTag.length); + } + return content; + } + getRawSummary(summary) { + return this.getContentWithinTags(summary, exports.RAW_SUMMARY_START_TAG, exports.RAW_SUMMARY_END_TAG); + } + getShortSummary(summary) { + return this.getContentWithinTags(summary, exports.SHORT_SUMMARY_START_TAG, exports.SHORT_SUMMARY_END_TAG); + } + getDescription(description) { + return this.removeContentWithinTags(description, exports.DESCRIPTION_START_TAG, exports.DESCRIPTION_END_TAG); + } + getReleaseNotes(description) { + const releaseNotes = this.getContentWithinTags(description, exports.DESCRIPTION_START_TAG, exports.DESCRIPTION_END_TAG); + return releaseNotes.replace(/(^|\n)> .*/g, ''); + } + async updateDescription(pullNumber, message) { + // add this response to the description field of the PR as release notes by looking + // for the tag (marker) + try { + // get latest description from PR + const pr = await octokit_1.octokit.pulls.get({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber + }); + let body = ''; + if (pr.data.body) { + body = pr.data.body; + } + const description = this.getDescription(body); + const messageClean = this.removeContentWithinTags(message, exports.DESCRIPTION_START_TAG, exports.DESCRIPTION_END_TAG); + const newDescription = `${description}\n${exports.DESCRIPTION_START_TAG}\n${messageClean}\n${exports.DESCRIPTION_END_TAG}`; + await octokit_1.octokit.pulls.update({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + body: newDescription + }); + } + catch (e) { + warning(`Failed to get PR: ${e}, skipping adding release notes to description.`); + } + } + reviewCommentsBuffer = []; + async bufferReviewComment(path, startLine, endLine, message, verified, verificationFeedback) { + // Premium UI Formatting: Convert "[LEVEL] | [TYPE]" to emoji badges + const levelTypeRegex = /^(\w+)\s*\|\s*(\w+)/; + const match = message.match(levelTypeRegex); + let header = ''; + if (match != null) { + const level = match[1].toLowerCase(); + const type = match[2]; + let emoji = 'โš ๏ธ'; + let color = 'Major'; + if (level === 'critical') { + emoji = '๐Ÿšจ'; + color = 'Critical'; + } + else if (level === 'major') { + emoji = '๐Ÿ”ด'; + color = 'Major'; + } + else if (level === 'minor') { + emoji = '๐ŸŸ '; + color = 'Minor'; + } + else if (level === 'info') { + emoji = 'โ„น๏ธ'; + color = 'Info'; + } + header = `**${emoji} Potential issue | ${color} (${type})**\n\n`; + message = message.replace(levelTypeRegex, '').trim(); + } + let verificationBadge = ''; + if (verified === true) { + verificationBadge = + '\n---\nโœ… **Verified**: This suggestion passed syntax, lint, and AST validation.\n'; + } + else if (verified === false && verificationFeedback) { + verificationBadge = `\n---\nโš ๏ธ **Verification Failed**: ${verificationFeedback}\n`; + } + const formattedMessage = `${exports.COMMENT_GREETING} +${header}${message}${verificationBadge} + +${exports.COMMENT_TAG}`; + this.reviewCommentsBuffer.push({ + path, + startLine, + endLine, + message: formattedMessage, + verified, + verificationFeedback + }); + } + async deletePendingReview(pullNumber) { + try { + const reviews = await octokit_1.octokit.pulls.listReviews({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber + }); + const pendingReview = reviews.data.find(review => review.state === 'PENDING'); + if (pendingReview) { + info(`Deleting pending review for PR #${pullNumber} id: ${pendingReview.id}`); + try { + await octokit_1.octokit.pulls.deletePendingReview({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + // eslint-disable-next-line camelcase + review_id: pendingReview.id + }); + } + catch (e) { + warning(`Failed to delete pending review: ${e}`); + } + } + } + catch (e) { + warning(`Failed to list reviews: ${e}`); + } + } + async submitReview(pullNumber, commitId, statusMsg) { + const bodyHeader = `${exports.COMMENT_GREETING} + +${statusMsg} +`; + if (this.reviewCommentsBuffer.length === 0) { + // Submit empty review with statusMsg + info(`Submitting empty review for PR #${pullNumber}`); + try { + await octokit_1.octokit.pulls.createReview({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + // eslint-disable-next-line camelcase + commit_id: commitId, + event: 'COMMENT', + body: bodyHeader + }); + } + catch (e) { + warning(`Failed to submit empty review: ${e}`); + } + return; + } + // De-duplicate and clear existing bot comments in the same range + for (const comment of this.reviewCommentsBuffer) { + const comments = await this.getCommentsAtRange(pullNumber, comment.path, comment.startLine, comment.endLine); + for (const c of comments) { + if (c.body.includes(exports.COMMENT_TAG)) { + try { + await octokit_1.octokit.pulls.deleteReviewComment({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + comment_id: c.id + }); + } + catch (e) { + warning(`Failed to delete review comment: ${e}`); + } + } + } + } + await this.deletePendingReview(pullNumber); + // Unified Review: All comments are standalone threads to support suggestions + const pushableComments = this.reviewCommentsBuffer.map(comment => this.generateCommentData(comment)); + try { + const review = await octokit_1.octokit.pulls.createReview({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + // eslint-disable-next-line camelcase + commit_id: commitId, + comments: pushableComments.map(comment => comment) + }); + info(`Submitting review for PR #${pullNumber}, total comments: ${pushableComments.length}, review id: ${review.data.id}`); + await octokit_1.octokit.pulls.submitReview({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + // eslint-disable-next-line camelcase + review_id: review.data.id, + event: 'COMMENT', + body: bodyHeader + }); + } + catch (e) { + warning(`Failed to create review: ${e}. Falling back to individual comments.`); + await this.deletePendingReview(pullNumber); + let commentCounter = 0; + for (const comment of pushableComments) { + info(`Creating new review comment for ${comment.path}:${comment.startLine}-${comment.endLine}: ${comment.message}`); + const commentData = { + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + // eslint-disable-next-line camelcase + commit_id: commitId, + ...comment + }; + try { + await octokit_1.octokit.pulls.createReviewComment(commentData); + } + catch (ee) { + warning(`Failed to create review comment: ${ee}`); + } + commentCounter++; + info(`Comment ${commentCounter}/${pushableComments.length} posted`); + } + } + } + generateCommentData(comment) { + const commentData = { + path: comment.path, + body: comment.message, + line: comment.endLine + }; + if (comment.startLine !== comment.endLine) { + // eslint-disable-next-line camelcase + commentData.start_line = comment.startLine; + // eslint-disable-next-line camelcase + commentData.start_side = 'RIGHT'; + } + return commentData; + } + async reviewCommentReply(pullNumber, topLevelComment, message) { + const reply = `${exports.COMMENT_GREETING} + +${message} + +${exports.COMMENT_REPLY_TAG} +`; + try { + // Post the reply to the user comment + await octokit_1.octokit.pulls.createReplyForReviewComment({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + body: reply, + // eslint-disable-next-line camelcase + comment_id: topLevelComment.id + }); + } + catch (error) { + warning(`Failed to reply to the top-level comment ${error}`); + try { + await octokit_1.octokit.pulls.createReplyForReviewComment({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + body: `Could not post the reply to the top-level comment due to the following error: ${error}`, + // eslint-disable-next-line camelcase + comment_id: topLevelComment.id + }); + } + catch (e) { + warning(`Failed to reply to the top-level comment ${e}`); + } + } + try { + if (topLevelComment.body.includes(exports.COMMENT_TAG)) { + // replace COMMENT_TAG with COMMENT_REPLY_TAG in topLevelComment + const newBody = topLevelComment.body.replace(exports.COMMENT_TAG, exports.COMMENT_REPLY_TAG); + await octokit_1.octokit.pulls.updateReviewComment({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + comment_id: topLevelComment.id, + body: newBody + }); + } + } + catch (error) { + warning(`Failed to update the top-level comment ${error}`); + } + } + async getCommentsWithinRange(pullNumber, path, startLine, endLine) { + const comments = await this.listReviewComments(pullNumber); + return comments.filter((comment) => comment.path === path && + comment.body !== '' && + ((comment.start_line !== undefined && + comment.start_line >= startLine && + comment.line <= endLine) || + (startLine === endLine && comment.line === endLine))); + } + async getCommentsAtRange(pullNumber, path, startLine, endLine) { + const comments = await this.listReviewComments(pullNumber); + return comments.filter((comment) => comment.path === path && + comment.body !== '' && + ((comment.start_line !== undefined && + comment.start_line === startLine && + comment.line === endLine) || + (startLine === endLine && comment.line === endLine))); + } + async getCommentChainsWithinRange(pullNumber, path, startLine, endLine, tag = '') { + const existingComments = await this.getCommentsWithinRange(pullNumber, path, startLine, endLine); + // find all top most comments + const topLevelComments = []; + for (const comment of existingComments) { + if (!comment.in_reply_to_id) { + topLevelComments.push(comment); + } + } + let allChains = ''; + let chainNum = 0; + for (const topLevelComment of topLevelComments) { + // get conversation chain + const chain = await this.composeCommentChain(existingComments, topLevelComment); + if (chain && chain.includes(tag)) { + chainNum += 1; + allChains += `Conversation Chain ${chainNum}: +${chain} +--- +`; + } + } + return allChains; + } + async composeCommentChain(reviewComments, topLevelComment) { + const conversationChain = reviewComments + .filter((cmt) => cmt.in_reply_to_id === topLevelComment.id) + .map((cmt) => `${cmt.user.login}: ${cmt.body}`); + conversationChain.unshift(`${topLevelComment.user.login}: ${topLevelComment.body}`); + return conversationChain.join('\n---\n'); + } + async getCommentChain(pullNumber, comment) { + try { + const reviewComments = await this.listReviewComments(pullNumber); + const topLevelComment = await this.getTopLevelComment(reviewComments, comment); + const chain = await this.composeCommentChain(reviewComments, topLevelComment); + return { chain, topLevelComment }; + } + catch (e) { + warning(`Failed to get conversation chain: ${e}`); + return { + chain: '', + topLevelComment: null + }; + } + } + async getTopLevelComment(reviewComments, comment) { + let topLevelComment = comment; + while (topLevelComment.in_reply_to_id) { + const parentComment = reviewComments.find((cmt) => cmt.id === topLevelComment.in_reply_to_id); + if (parentComment) { + topLevelComment = parentComment; + } + else { + break; + } + } + return topLevelComment; + } + reviewCommentsCache = {}; + async listReviewComments(target) { + if (this.reviewCommentsCache[target]) { + return this.reviewCommentsCache[target]; + } + const allComments = []; + let page = 1; + try { + for (;;) { + const { data: comments } = await octokit_1.octokit.pulls.listReviewComments({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + pull_number: target, + page, + // eslint-disable-next-line camelcase + per_page: 100 + }); + allComments.push(...comments); + page++; + if (!comments || comments.length < 100) { + break; + } + } + this.reviewCommentsCache[target] = allComments; + return allComments; + } + catch (e) { + warning(`Failed to list review comments: ${e}`); + return allComments; + } + } + async create(body, target) { + try { + // get comment ID from the response + const response = await octokit_1.octokit.issues.createComment({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + issue_number: target, + body + }); + // add comment to issueCommentsCache + if (this.issueCommentsCache[target]) { + this.issueCommentsCache[target].push(response.data); + } + else { + this.issueCommentsCache[target] = [response.data]; + } + } + catch (e) { + warning(`Failed to create comment: ${e}`); + } + } + async replace(body, tag, target) { + try { + const cmt = await this.findCommentWithTag(tag, target); + if (cmt) { + await octokit_1.octokit.issues.updateComment({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + comment_id: cmt.id, + body + }); + } + else { + await this.create(body, target); + } + } + catch (e) { + warning(`Failed to replace comment: ${e}`); + } + } + async findCommentWithTag(tag, target) { + try { + const comments = await this.listComments(target); + for (const cmt of comments) { + if (cmt.body && cmt.body.includes(tag)) { + return cmt; + } + } + return null; + } + catch (e) { + warning(`Failed to find comment with tag: ${e}`); + return null; + } + } + issueCommentsCache = {}; + async listComments(target) { + if (this.issueCommentsCache[target]) { + return this.issueCommentsCache[target]; + } + const allComments = []; + let page = 1; + try { + for (;;) { + const { data: comments } = await octokit_1.octokit.issues.listComments({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + issue_number: target, + page, + // eslint-disable-next-line camelcase + per_page: 100 + }); + allComments.push(...comments); + page++; + if (!comments || comments.length < 100) { + break; + } + } + this.issueCommentsCache[target] = allComments; + return allComments; + } + catch (e) { + warning(`Failed to list comments: ${e}`); + return allComments; + } + } + // function that takes a comment body and returns the list of commit ids that have been reviewed + // commit ids are comments between the commit_ids_reviewed_start and commit_ids_reviewed_end markers + // + getReviewedCommitIds(commentBody) { + const start = commentBody.indexOf(exports.COMMIT_ID_START_TAG); + const end = commentBody.indexOf(exports.COMMIT_ID_END_TAG); + if (start === -1 || end === -1) { + return []; + } + const ids = commentBody.substring(start + exports.COMMIT_ID_START_TAG.length, end); + // remove the markers from each id and extract the id and remove empty strings + return ids + .split('', '').trim()) + .filter(id => id !== ''); + } + // get review commit ids comment block from the body as a string + // including markers + getReviewedCommitIdsBlock(commentBody) { + const start = commentBody.indexOf(exports.COMMIT_ID_START_TAG); + const end = commentBody.indexOf(exports.COMMIT_ID_END_TAG); + if (start === -1 || end === -1) { + return ''; + } + return commentBody.substring(start, end + exports.COMMIT_ID_END_TAG.length); + } + // add a commit id to the list of reviewed commit ids + // if the marker doesn't exist, add it + addReviewedCommitId(commentBody, commitId) { + const start = commentBody.indexOf(exports.COMMIT_ID_START_TAG); + const end = commentBody.indexOf(exports.COMMIT_ID_END_TAG); + if (start === -1 || end === -1) { + return `${commentBody}\n${exports.COMMIT_ID_START_TAG}\n\n${exports.COMMIT_ID_END_TAG}`; + } + const ids = commentBody.substring(start + exports.COMMIT_ID_START_TAG.length, end); + return `${commentBody.substring(0, start + exports.COMMIT_ID_START_TAG.length)}${ids}\n${commentBody.substring(end)}`; + } + // given a list of commit ids provide the highest commit id that has been reviewed + getHighestReviewedCommitId(commitIds, reviewedCommitIds) { + for (let i = commitIds.length - 1; i >= 0; i--) { + if (reviewedCommitIds.includes(commitIds[i])) { + return commitIds[i]; + } + } + return ''; + } + async getAllCommitIds() { + const allCommits = []; + let page = 1; + let commits; + if (exports.context && exports.context.payload && exports.context.payload.pull_request != null) { + do { + commits = await octokit_1.octokit.pulls.listCommits({ + owner: exports.repo.owner, + repo: exports.repo.repo, + // eslint-disable-next-line camelcase + pull_number: exports.context.payload.pull_request.number, + // eslint-disable-next-line camelcase + per_page: 100, + page + }); + allCommits.push(...commits.data.map(commit => commit.sha)); + page++; + } while (commits.data.length > 0); + } + return allCommits; + } + // add in-progress status to the comment body + addInProgressStatus(commentBody, statusMsg) { + const start = commentBody.indexOf(exports.IN_PROGRESS_START_TAG); + const end = commentBody.indexOf(exports.IN_PROGRESS_END_TAG); + // add to the beginning of the comment body if the marker doesn't exist + // otherwise do nothing + if (start === -1 || end === -1) { + return `${exports.IN_PROGRESS_START_TAG} + +Currently reviewing new changes in this PR... + +${statusMsg} + +${exports.IN_PROGRESS_END_TAG} + +--- + +${commentBody}`; + } + return commentBody; + } + // remove in-progress status from the comment body + removeInProgressStatus(commentBody) { + const start = commentBody.indexOf(exports.IN_PROGRESS_START_TAG); + const end = commentBody.indexOf(exports.IN_PROGRESS_END_TAG); + // remove the in-progress status if the marker exists + // otherwise do nothing + if (start !== -1 && end !== -1) { + return (commentBody.substring(0, start) + + commentBody.substring(end + exports.IN_PROGRESS_END_TAG.length)); + } + return commentBody; + } +} +exports.Commenter = Commenter; +//# sourceMappingURL=commenter.js.map \ No newline at end of file diff --git a/lib/src/commenter.js.map b/lib/src/commenter.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a558e15eaddeeb11a22d60d9476c06bbeb173605 --- /dev/null +++ b/lib/src/commenter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"commenter.js","sourceRoot":"","sources":["../../src/commenter.ts"],"names":[],"mappings":";;;AAAA,gDAAgD;AAChD,uCAAiC;AAEjC,uCAA6B;AAE7B,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAA;AACxB,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,CAAA;AAC5B,MAAM,QAAQ,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAA;AAE3D,QAAA,OAAO,GAAQ,IAAI,KAAK,CAAC,EAAS,EAAE;IAC/C,GAAG,CAAC,MAAM,EAAE,IAAI;QACd,OAAO,CAAC,aAAG,CAAC,QAAQ,EAAE,EAAE,aAAqB,CAAA,CAAC,IAAI,CAAC,CAAA;IACr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AO,WAAW,CAAA;IACpB,CAAC;CACF;AAnxBD,8BAmxBC"} \ No newline at end of file diff --git a/lib/src/confidence.js b/lib/src/confidence.js new file mode 100644 index 0000000000000000000000000000000000000000..888ca9d60ab01c913e0b17232857681f16b31358 --- /dev/null +++ b/lib/src/confidence.js @@ -0,0 +1,447 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.confidenceCalibrator = exports.ConfidenceCalibrator = void 0; +const KNOWN_BUG_PATTERNS = [ + { + pattern: /null.*pointer|NPE|null.*check/i, + severity: 'critical', + category: 'null-pointer' + }, + { + pattern: /sql.*injection|SELECT.*WHERE.*\+|query.*concat/i, + severity: 'critical', + category: 'sql-injection' + }, + { + pattern: /password|secret|api.*key.*=.*['"]|token.*=.*['"]/i, + severity: 'critical', + category: 'secret-exposure' + }, + { + pattern: /eval\(|new.*Function\(|innerHTML\s*=|document\.write/i, + severity: 'critical', + category: 'xss' + }, + { + pattern: /race.*condition|concurrent.*modif|deadlock|mutex/i, + severity: 'major', + category: 'concurrency' + }, + { + pattern: /memory.*leak|dispose\(|close\(|gc\./i, + severity: 'major', + category: 'resource-leak' + }, + { + pattern: /async.*without.*await|unhandled.*promise|catch.*without.*throw/i, + severity: 'major', + category: 'async-issues' + }, + { + pattern: /try.*without.*catch|catch.*empty|swallow.*exception/i, + severity: 'minor', + category: 'error-handling' + }, + { + pattern: /any.*type|cast.*any|as.*any/i, + severity: 'info', + category: 'type-safety' + }, + { + pattern: /console\.(log|debug|warn)/i, + severity: 'info', + category: 'logging' + }, + { + pattern: /TODO|FIXME|HACK|XXX|BUG:/i, + severity: 'info', + category: 'tech-debt' + }, + { + pattern: /division.*by.*zero|divide.*0|x\s*\/\s*0/i, + severity: 'major', + category: 'arithmetic' + }, + { + pattern: /off.*by.*one|index.*length|length.*-\s*1/i, + severity: 'minor', + category: 'logic-error' + }, + { + pattern: /useEffect.*missing.*dep|dependency.*array/i, + severity: 'minor', + category: 'react-hooks' + }, + { + pattern: /mutation.*props|props.*change|immutable/i, + severity: 'minor', + category: 'immutability' + }, + { + pattern: /hardcoded|hard.*coded/i, + severity: 'minor', + category: 'hardcoding' + }, + { + pattern: /circular.*depend|lazy.*load|circular/i, + severity: 'major', + category: 'architecture' + }, + { + pattern: /sql.*string|query.*build|string.*concat.*sql/i, + severity: 'critical', + category: 'sql-injection' + }, + { + pattern: /crypto.*md5|sha1.*encrypt|md5.*hash/i, + severity: 'critical', + category: 'crypto' + }, + { + pattern: /http.*not.*https|mixed.*content|insecure.*request/i, + severity: 'major', + category: 'security' + }, + { + pattern: /cookie.*without.*secure|secure.*flag.*false/i, + severity: 'major', + category: 'security' + }, + { + pattern: /sudo|chmod\s+777|root.*login/i, + severity: 'critical', + category: 'security' + }, + { + pattern: /catch.*(e|err).*{[\s]*}/i, + severity: 'minor', + category: 'error-handling' + }, + { + pattern: /setTimeout.*0|setImmediate/i, + severity: 'info', + category: 'timing' + }, + { + pattern: /double.*click|race.*click|multiple.*submit/i, + severity: 'minor', + category: 'ux' + } +]; +const POSITIVE_INDICATORS = [ + { indicator: 'suggestion', weight: 0.15 }, + { indicator: '```suggestion', weight: 0.2 }, + { indicator: 'fix:', weight: 0.1 }, + { indicator: 'fixed code', weight: 0.1 }, + { indicator: 'correct', weight: 0.05 }, + { indicator: 'instead of', weight: 0.05 }, + { indicator: 'should be', weight: 0.05 }, + { indicator: 'best practice', weight: 0.05 } +]; +const NEGATIVE_INDICATORS = [ + { indicator: 'maybe', weight: -0.15 }, + { indicator: 'might', weight: -0.1 }, + { indicator: 'possibly', weight: -0.1 }, + { indicator: 'i think', weight: -0.2 }, + { indicator: 'unclear', weight: -0.1 }, + { indicator: 'ไธ็กฎๅฎš', weight: -0.15 }, + { indicator: 'perhaps', weight: -0.1 }, + { indicator: 'could be', weight: -0.1 }, + { indicator: 'not sure', weight: -0.15 }, + { indicator: 'likely', weight: -0.05 } +]; +class ConfidenceCalibrator { + historicalAccuracies = new Map(); + feedbackHistory = []; + persistPath = '/tmp/prix_feedback.json'; + feedbackTracker = null; + constructor(feedbackTracker = null) { + this.loadPersisted(); + if (feedbackTracker) { + this.feedbackTracker = feedbackTracker; + } + else { + try { + const { FeedbackTracker } = require('./feedback-tracker'); + this.feedbackTracker = new FeedbackTracker(); + } + catch (e) { + // FeedbackTracker not available, continue without it + } + } + } + loadPersisted() { + try { + if (require('fs').existsSync(this.persistPath)) { + const data = JSON.parse(require('fs').readFileSync(this.persistPath, 'utf8')); + if (Array.isArray(data)) { + this.feedbackHistory = data.map((item) => ({ + pattern: item.pattern || '', + helpful: item.helpful || false, + timestamp: item.timestamp || Date.now() + })); + this.rebuildHistoricalAccuracies(); + } + } + } + catch (e) { + // Start fresh if persistence fails + } + } + persist() { + try { + require('fs').writeFileSync(this.persistPath, JSON.stringify(this.feedbackHistory.slice(-1000))); + } + catch (e) { + // Persistence failure is non-fatal + } + } + rebuildHistoricalAccuracies() { + const patternMap = new Map(); + for (const entry of this.feedbackHistory) { + const accuracies = patternMap.get(entry.pattern) || []; + accuracies.push(entry.helpful ? 1 : 0); + patternMap.set(entry.pattern, accuracies); + } + for (const [pattern, accuracies] of patternMap) { + this.historicalAccuracies.set(pattern, accuracies); + } + } + recordFeedback(pattern, helpful) { + this.feedbackHistory.push({ pattern, helpful, timestamp: Date.now() }); + const accuracies = this.historicalAccuracies.get(pattern) || []; + accuracies.push(helpful ? 1 : 0); + this.historicalAccuracies.set(pattern, accuracies); + this.persist(); + } + calibrate(aiReportedConfidence, comment, contextTokens, maxContextTokens, severity, teamId, repoSlug, patternType, filename) { + const factors = this.calculateFactors(comment, contextTokens, maxContextTokens, severity, teamId, repoSlug, patternType, filename); + let score; + if (aiReportedConfidence !== undefined) { + const deBiased = this.removeLLMBias(aiReportedConfidence); + score = this.combineWithFactors(deBiased, factors); + } + else { + score = this.computeFromFactorsOnly(factors); + } + score = Math.max(0, Math.min(100, score)); + return { + score: Math.round(score), + factors, + reasoning: this.generateReasoning(factors, score) + }; + } + calculateFactors(comment, contextTokens, maxContextTokens, severity, teamId, repoSlug, patternType, filename) { + const patternMatchScore = this.calculatePatternMatch(comment); + const contextRichness = Math.min(1, contextTokens / Math.max(1, maxContextTokens * 0.5)); + const historicalAccuracy = this.calculateHistoricalAccuracy(comment); + const severityMatchesKnownBug = severity + ? this.matchesKnownBugPattern(comment, severity) + : this.matchesAnyKnownBugPattern(comment); + const hasExplicitEvidence = this.hasExplicitEvidence(comment); + const { teamAcceptanceRate, patternTypeAccuracy } = this.calculateTeamMetrics(teamId, repoSlug, patternType, filename); + return { + patternMatchScore, + contextRichness, + historicalAccuracy, + severityMatchesKnownBug, + hasExplicitEvidence, + teamAcceptanceRate, + patternTypeAccuracy + }; + } + calculateTeamMetrics(teamId, repoSlug, patternType, filename) { + if (!this.feedbackTracker || !teamId || !repoSlug) { + return { teamAcceptanceRate: 0.5, patternTypeAccuracy: 0.5 }; + } + let teamAcceptanceRate = 0.5; + let patternTypeAccuracy = 0.5; + if (patternType && filename) { + teamAcceptanceRate = this.feedbackTracker.getPatternAcceptanceRate(patternType, teamId, repoSlug); + patternTypeAccuracy = this.feedbackTracker.getFilenameAcceptanceRate(filename, teamId, repoSlug); + } + return { teamAcceptanceRate, patternTypeAccuracy }; + } + calculatePatternMatch(comment) { + const lowerComment = comment.toLowerCase(); + let score = 0.5; + for (const { indicator, weight } of POSITIVE_INDICATORS) { + if (lowerComment.includes(indicator.toLowerCase())) { + score += weight; + } + } + for (const { indicator, weight } of NEGATIVE_INDICATORS) { + if (lowerComment.includes(indicator.toLowerCase())) { + score += weight; + } + } + if (lowerComment.includes('why this matters')) { + score += 0.1; + } + if (lowerComment.includes('production') || + lowerComment.includes('production environment')) { + score += 0.05; + } + return Math.max(0, Math.min(1, score)); + } + calculateHistoricalAccuracy(comment) { + const lowerComment = comment.toLowerCase(); + for (const [pattern, accuracies] of this.historicalAccuracies) { + if (lowerComment.includes(pattern.toLowerCase())) { + const avg = accuracies.reduce((a, b) => a + b, 0) / accuracies.length; + return avg; + } + } + const relevantFeedback = this.feedbackHistory.filter(f => f.pattern + .split(' ') + .some(word => word.length > 4 && lowerComment.includes(word.toLowerCase()))); + if (relevantFeedback.length === 0) { + return 0.5; + } + const accuracy = relevantFeedback.filter(f => f.helpful).length / relevantFeedback.length; + return accuracy; + } + matchesKnownBugPattern(comment, severity) { + const lowerComment = comment.toLowerCase(); + for (const { pattern, severity: patternSeverity } of KNOWN_BUG_PATTERNS) { + if (pattern.test(lowerComment) && patternSeverity === severity) { + return true; + } + } + return false; + } + matchesAnyKnownBugPattern(comment) { + const lowerComment = comment.toLowerCase(); + for (const { pattern } of KNOWN_BUG_PATTERNS) { + if (pattern.test(lowerComment)) { + return true; + } + } + return false; + } + hasExplicitEvidence(comment) { + const explicitPhrases = [ + 'this will crash', + 'this causes', + 'this leads to', + 'results in', + 'fails when', + 'breaks when', + 'error when', + 'crash if', + 'exception if', + 'undefined behavior', + 'undefined is', + 'will throw', + 'will fail' + ]; + const lowerComment = comment.toLowerCase(); + return explicitPhrases.some(phrase => lowerComment.includes(phrase)); + } + removeLLMBias(reportedConfidence) { + if (reportedConfidence >= 95) { + return 75; + } + if (reportedConfidence >= 85) { + return 70; + } + if (reportedConfidence >= 70) { + return 62; + } + if (reportedConfidence >= 60) { + return 55; + } + return reportedConfidence * 0.9; + } + combineWithFactors(baseScore, factors) { + const weights = { + base: 0.25, + pattern: 0.2, + context: 0.1, + historical: 0.15, + knownBug: 0.05, + teamAcceptance: 0.15, + patternAccuracy: 0.1 + }; + let score = baseScore * weights.base; + score += factors.patternMatchScore * 100 * weights.pattern; + score += factors.contextRichness * 100 * weights.context; + score += factors.historicalAccuracy * 100 * weights.historical; + if (factors.severityMatchesKnownBug) { + score += 10 * weights.knownBug; + } + if (factors.hasExplicitEvidence) { + score += 5; + } + score += factors.teamAcceptanceRate * 100 * weights.teamAcceptance; + score += factors.patternTypeAccuracy * 100 * weights.patternAccuracy; + return score; + } + computeFromFactorsOnly(factors) { + const weights = { + pattern: 0.3, + context: 0.15, + historical: 0.2, + knownBug: 0.15, + teamAcceptance: 0.12, + patternAccuracy: 0.08 + }; + let score = 50; + score += factors.patternMatchScore * 50 * weights.pattern; + score += factors.contextRichness * 50 * weights.context; + score += factors.historicalAccuracy * 50 * weights.historical; + if (factors.severityMatchesKnownBug) { + score += 10 * weights.knownBug; + } + if (factors.hasExplicitEvidence) { + score += 5; + } + score += factors.teamAcceptanceRate * 50 * weights.teamAcceptance; + score += factors.patternTypeAccuracy * 50 * weights.patternAccuracy; + return score; + } + generateReasoning(factors, score) { + const reasons = []; + if (factors.patternMatchScore > 0.7) { + reasons.push('strong pattern match'); + } + else if (factors.patternMatchScore < 0.4) { + reasons.push('weak pattern match'); + } + if (factors.contextRichness > 0.8) { + reasons.push('rich context'); + } + else if (factors.contextRichness < 0.3) { + reasons.push('limited context'); + } + if (factors.historicalAccuracy > 0.7) { + reasons.push('historically accurate'); + } + else if (factors.historicalAccuracy < 0.4 && + factors.historicalAccuracy !== 0.5) { + reasons.push('historically unreliable'); + } + if (factors.severityMatchesKnownBug) { + reasons.push('matches known bug pattern'); + } + if (factors.hasExplicitEvidence) { + reasons.push('has explicit evidence'); + } + if (factors.teamAcceptanceRate > 0.6) { + reasons.push('high team acceptance'); + } + else if (factors.teamAcceptanceRate < 0.3 && + factors.teamAcceptanceRate !== 0.5) { + reasons.push('low team acceptance'); + } + if (factors.patternTypeAccuracy > 0.6) { + reasons.push('matches accepted patterns'); + } + return reasons.length > 0 + ? `Calibrated based on: ${reasons.join(', ')}` + : 'Calibrated using default heuristics'; + } +} +exports.ConfidenceCalibrator = ConfidenceCalibrator; +exports.confidenceCalibrator = new ConfidenceCalibrator(); +//# sourceMappingURL=confidence.js.map \ No newline at end of file diff --git a/lib/src/confidence.js.map b/lib/src/confidence.js.map new file mode 100644 index 0000000000000000000000000000000000000000..59647e07c805fc8e76b21534a387d9511dc57fc6 --- /dev/null +++ b/lib/src/confidence.js.map @@ -0,0 +1 @@ +{"version":3,"file":"confidence.js","sourceRoot":"","sources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CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAA;QACtC,CAAC;aAAM,IACL,OAAO,CAAC,kBAAkB,GAAG,GAAG;YAChC,OAAO,CAAC,kBAAkB,KAAK,GAAG,EAClC,CAAC;YACD,OAAO,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAA;QACrC,CAAC;QAED,IAAI,OAAO,CAAC,mBAAmB,GAAG,GAAG,EAAE,CAAC;YACtC,OAAO,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAA;QAC3C,CAAC;QAED,OAAO,OAAO,CAAC,MAAM,GAAG,CAAC;YACvB,CAAC,CAAC,wBAAwB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;YAC9C,CAAC,CAAC,qCAAqC,CAAA;IAC3C,CAAC;CACF;AA7ZD,oDA6ZC;AAEY,QAAA,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAA"} \ No newline at end of file diff --git a/lib/src/config.js b/lib/src/config.js new file mode 100644 index 0000000000000000000000000000000000000000..98ad9c17dc4c8a2619345b907403b65eed3f9372 --- /dev/null +++ b/lib/src/config.js @@ -0,0 +1,234 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.configLoader = exports.PrixConfigLoader = exports.DEFAULT_PRIX_CONFIG = void 0; +exports.getConfig = getConfig; +exports.meetsConfidenceThreshold = meetsConfidenceThreshold; +exports.meetsMinimumSeverity = meetsMinimumSeverity; +exports.lintSuggestion = lintSuggestion; +const fs_1 = require("fs"); +const path_1 = require("path"); +const context_1 = require("./context"); +const utils_1 = require("./utils"); +exports.DEFAULT_PRIX_CONFIG = { + version: '1.0', + severity: { + minimumLevel: 'minor', + showConfidenceThreshold: 50 + }, + filters: { + excludePatterns: [], + includePatterns: ['**/*'], + disableTypes: [] + }, + linting: { + enabled: true, + eslint: true, + prettier: true, + failOnError: false + }, + review: { + maxFilesPerPR: 50, + maxCommentsPerFile: 10, + denseMode: false, + showImpactAnalysis: true + }, + remedies: { + enabled: false, + autoCreatePR: false, + requireApproval: true + }, + confidence: { + minCritical: 0, + minMajor: 60, + minMinor: 70, + minInfo: 80 + } +}; +class PrixConfigLoader { + config = null; + load(workingDir) { + if (this.config) { + return this.config; + } + const possiblePaths = [ + (0, path_1.join)(workingDir, '.prix.yml'), + (0, path_1.join)(workingDir, 'prix.yml'), + (0, path_1.join)(workingDir, '.prix.yaml'), + (0, path_1.join)(workingDir, 'prix.yaml') + ]; + for (const configPath of possiblePaths) { + if ((0, fs_1.existsSync)(configPath)) { + try { + const content = (0, fs_1.readFileSync)(configPath, 'utf8'); + this.config = this.mergeWithDefaults(this.parseYAML(content)); + return this.config; + } + catch (e) { + console.warn(`Failed to load prix config from ${configPath}: ${e}`); + } + } + } + this.config = exports.DEFAULT_PRIX_CONFIG; + return this.config; + } + parseYAML(content) { + const result = {}; + const lines = content.split('\n'); + let currentSection = null; + let currentSectionObj = {}; + let sectionKey = ''; + for (const line of lines) { + const sectionMatch = line.match(/^(\w+):\s*$/); + if (sectionMatch) { + if (currentSection && sectionKey) { + ; + result[sectionKey] = currentSectionObj; + } + currentSection = sectionMatch[1]; + sectionKey = currentSection; + currentSectionObj = {}; + continue; + } + const keyValueMatch = line.match(/^\s*(\w+):\s*(.+)$/); + if (keyValueMatch && currentSection) { + const key = keyValueMatch[1]; + let value = keyValueMatch[2].trim(); + if (value === 'true') + value = true; + else if (value === 'false') + value = false; + else if (!isNaN(Number(value))) + value = Number(value); + currentSectionObj[key] = value; + } + } + if (currentSection && sectionKey) { + ; + result[sectionKey] = currentSectionObj; + } + return result; + } + mergeWithDefaults(config) { + return { + version: config.version || exports.DEFAULT_PRIX_CONFIG.version, + severity: { + ...exports.DEFAULT_PRIX_CONFIG.severity, + ...config.severity + }, + filters: { + ...exports.DEFAULT_PRIX_CONFIG.filters, + ...config.filters + }, + linting: { + ...exports.DEFAULT_PRIX_CONFIG.linting, + ...config.linting + }, + review: { + ...exports.DEFAULT_PRIX_CONFIG.review, + ...config.review + }, + remedies: { + ...exports.DEFAULT_PRIX_CONFIG.remedies, + ...config.remedies + }, + confidence: { + ...exports.DEFAULT_PRIX_CONFIG.confidence, + ...config.confidence + } + }; + } + shouldIncludeFile(config, filename) { + const { excludePatterns, includePatterns } = config.filters; + for (const pattern of excludePatterns) { + if (this.matchesPattern(filename, pattern)) { + return false; + } + } + if (includePatterns.length === 0) { + return true; + } + for (const pattern of includePatterns) { + if (this.matchesPattern(filename, pattern)) { + return true; + } + } + return false; + } + matchesPattern(filename, pattern) { + const regexPattern = pattern + .replace(/\./g, '\\.') + .replace(/\*/g, '.*') + .replace(/\?/g, '.') + .replace(/\*\*/g, '.*'); + return new RegExp(`^${regexPattern}$`).test(filename); + } +} +exports.PrixConfigLoader = PrixConfigLoader; +exports.configLoader = new PrixConfigLoader(); +function getConfig() { + const ctx = context_1.als.getStore(); + const workingDir = ctx?.workingDir || process.cwd(); + return exports.configLoader.load(workingDir); +} +function meetsConfidenceThreshold(severity, confidence) { + const config = getConfig(); + const thresholds = config.confidence; + switch (severity) { + case 'critical': + return confidence >= thresholds.minCritical; + case 'major': + return confidence >= thresholds.minMajor; + case 'minor': + return confidence >= thresholds.minMinor; + case 'info': + return confidence >= thresholds.minInfo; + default: + return true; + } +} +function meetsMinimumSeverity(severity) { + const config = getConfig(); + const levels = ['critical', 'major', 'minor', 'info']; + const minimumLevel = config.severity.minimumLevel; + const minimumIndex = levels.indexOf(minimumLevel); + const severityIndex = levels.indexOf(severity.toLowerCase()); + return severityIndex >= minimumIndex; +} +async function lintSuggestion(suggestion, filename, language) { + const config = getConfig(); + if (!config.linting.enabled) { + return { valid: true, errors: [] }; + } + const errors = []; + const workingDir = context_1.als.getStore()?.workingDir || process.cwd(); + if (config.linting.prettier) { + try { + (0, utils_1.prixExec)(`echo "${suggestion.replace(/"/g, '\\"')}" | prettier --stdin-filepath ${filename}`, { + cwd: workingDir, + stdio: 'pipe' + }); + } + catch { + errors.push('Prettier formatting check failed'); + } + } + if (config.linting.eslint && + (language === 'javascript' || language === 'typescript')) { + try { + const ext = filename.endsWith('.ts') ? 'ts' : 'js'; + const tempFile = `.prix_temp_suggestion.${ext}`; + (0, utils_1.prixExec)(`echo "${suggestion.replace(/"/g, '\\"')}" > ${tempFile} && npx eslint ${tempFile} --format json 2>&1 || true`, { + cwd: workingDir, + stdio: 'pipe' + }); + } + catch { + errors.push('ESLint check failed'); + } + } + return { + valid: config.linting.failOnError ? errors.length === 0 : true, + errors + }; +} +//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/lib/src/config.js.map b/lib/src/config.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f5994a97e4b477d2d340401fa78b0091b35d130e --- /dev/null +++ b/lib/src/config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":";;;AAoNA,8BAIC;AAED,4DAmBC;AAED,oDAQC;AAED,wCAwDC;AAjTD,2BAA2C;AAC3C,+BAAyB;AACzB,uCAA6B;AAC7B,mCAAgC;AAsCnB,QAAA,mBAAmB,GAAe;IAC7C,OAAO,EAAE,KAAK;IACd,QAAQ,EAAE;QACR,YAAY,EAAE,OAAO;QACrB,uBAAuB,EAAE,EAAE;KAC5B;IACD,OAAO,EAAE;QACP,eAAe,EAAE,EAAE;QACnB,eAAe,EAAE,CAAC,MAAM,CAAC;QACzB,YAAY,EAAE,EAAE;KACjB;IACD,OAAO,EAAE;QACP,OAAO,EAAE,IAAI;QACb,MAAM,EAAE,IAAI;QACZ,QAAQ,EAAE,IAAI;QACd,WAAW,EAAE,KAAK;KACnB;IACD,MAAM,EAAE;QACN,aAAa,EAAE,EAAE;QACjB,kBAAkB,EAAE,EAAE;QACtB,SAAS,EAAE,KAAK;QAChB,kBAAkB,EAAE,IAAI;KACzB;IACD,QAAQ,EAAE;QACR,OAAO,EAAE,KAAK;QACd,YAAY,EAAE,KAAK;QACnB,eAAe,EAAE,IAAI;KACtB;IACD,UAAU,EAAE;QACV,WAAW,EAAE,CAAC;QACd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AC,CAAC,IAAI,CAAA;YAClD,MAAM,QAAQ,GAAG,yBAAyB,GAAG,EAAE,CAAA;YAC/C,IAAA,gBAAQ,EACN,SAAS,UAAU,CAAC,OAAO,CACzB,IAAI,EACJ,KAAK,CACN,OAAO,QAAQ,kBAAkB,QAAQ,6BAA6B,EACvE;gBACE,GAAG,EAAE,UAAU;gBACf,KAAK,EAAE,MAAM;aACd,CACF,CAAA;QACH,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAA;QACpC,CAAC;IACH,CAAC;IAED,OAAO;QACL,KAAK,EAAE,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI;QAC9D,MAAM;KACP,CAAA;AACH,CAAC"} \ No newline at end of file diff --git a/lib/src/console-reporter.js b/lib/src/console-reporter.js new file mode 100644 index 0000000000000000000000000000000000000000..40d1e989569a781d4b67336edd0464e7442d1c55 --- /dev/null +++ b/lib/src/console-reporter.js @@ -0,0 +1,121 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LocalConsoleReporter = void 0; +const SEVERITY_COLORS = { + critical: '\x1b[31m', + major: '\x1b[33m', + minor: '\x1b[36m', + info: '\x1b[90m' +}; +const SEVERITY_EMOJI = { + critical: '๐Ÿšจ', + major: '๐Ÿ”ด', + minor: '๐ŸŸ ', + info: 'โ„น๏ธ' +}; +const TYPE_COLORS = { + security: '\x1b[35m', + bug: '\x1b[31m', + performance: '\x1b[33m', + style: '\x1b[90m', + general: '\x1b[0m' +}; +const RESET = '\x1b[0m'; +class LocalConsoleReporter { + printFindings(findings, options) { + if (options.output === 'json') { + this.printJson(findings); + return; + } + this.printConsole(findings); + } + printConsole(findings) { + if (findings.length === 0) { + return; + } + const sortedFindings = [...findings].sort((a, b) => { + const severityOrder = { critical: 0, major: 1, minor: 2, info: 3 }; + const severityDiff = severityOrder[a.severity] - severityOrder[b.severity]; + if (severityDiff !== 0) + return severityDiff; + return b.confidence - a.confidence; + }); + const groupedByFile = new Map(); + for (const finding of sortedFindings) { + if (!groupedByFile.has(finding.filename)) { + groupedByFile.set(finding.filename, []); + } + groupedByFile.get(finding.filename).push(finding); + } + for (const [filename, fileFindings] of groupedByFile) { + console.log(`\n${'='.repeat(80)}`); + console.log(`${SEVERITY_COLORS.info}๐Ÿ“„ ${filename}${RESET}`); + console.log('='.repeat(80)); + for (const finding of fileFindings) { + this.printFinding(finding); + } + } + } + printFinding(finding) { + const severityColor = SEVERITY_COLORS[finding.severity] || ''; + const typeColor = TYPE_COLORS[finding.type] || ''; + const emoji = SEVERITY_EMOJI[finding.severity] || 'โ€ข'; + console.log(`\n${severityColor}${emoji} [${finding.severity.toUpperCase()}]${RESET} ${typeColor}${finding.type}${RESET} (${finding.confidence}% confidence)`); + console.log(`${' '.repeat(4)}๐Ÿ“ Line ${finding.line}${finding.endLine !== finding.line ? `-${finding.endLine}` : ''}`); + const messageLines = finding.message.split('\n').filter(l => l.trim()); + for (const line of messageLines) { + console.log(`${' '.repeat(4)}${line}`); + } + if (finding.suggestion) { + console.log(`${' '.repeat(4)}๐Ÿ’ก Suggested fix:`); + const suggestionLines = finding.suggestion.split('\n'); + for (const line of suggestionLines.slice(0, 10)) { + console.log(`${' '.repeat(8)}${line}`); + } + if (suggestionLines.length > 10) { + console.log(`${' '.repeat(8)}... (${suggestionLines.length - 10} more lines)`); + } + } + } + printJson(findings) { + const output = { + version: '1.0', + timestamp: new Date().toISOString(), + summary: { + total: findings.length, + critical: findings.filter(f => f.severity === 'critical').length, + major: findings.filter(f => f.severity === 'major').length, + minor: findings.filter(f => f.severity === 'minor').length, + info: findings.filter(f => f.severity === 'info').length + }, + findings: findings.map(f => ({ + filename: f.filename, + line: f.line, + endLine: f.endLine, + severity: f.severity, + type: f.type, + message: f.message, + confidence: f.confidence, + suggestion: f.suggestion, + patternType: f.patternType + })) + }; + console.log(JSON.stringify(output, null, 2)); + } + printSummary(findings) { + const critical = findings.filter(f => f.severity === 'critical').length; + const major = findings.filter(f => f.severity === 'major').length; + const minor = findings.filter(f => f.severity === 'minor').length; + const info = findings.filter(f => f.severity === 'info').length; + console.log(`\n${'='.repeat(80)}`); + console.log('๐Ÿ“Š REVIEW SUMMARY'); + console.log('='.repeat(80)); + console.log(` ๐Ÿšจ Critical: ${critical}`); + console.log(` ๐Ÿ”ด Major: ${major}`); + console.log(` ๐ŸŸ  Minor: ${minor}`); + console.log(` โ„น๏ธ Info: ${info}`); + console.log('='.repeat(80)); + } +} +exports.LocalConsoleReporter = LocalConsoleReporter; +//# sourceMappingURL=console-reporter.js.map \ No newline at end of file diff --git a/lib/src/console-reporter.js.map b/lib/src/console-reporter.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1df4e2dcdcbddf26abc186c27edc0717c2f6f215 --- /dev/null +++ b/lib/src/console-reporter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"console-reporter.js","sourceRoot":"","sources":["../../src/console-reporter.ts"],"names":[],"mappings":";;;AAQA,MAAM,eAAe,GAA2B;IAC9C,QAAQ,EAAE,UAAU;IACpB,KAAK,EAAE,UAAU;IACjB,KAAK,EAAE,UAAU;IACjB,IAAI,EAAE,UAAU;CACjB,CAAA;AAED,MAAM,cAAc,GAA2B;IAC7C,QAAQ,EAAE,IAAI;IACd,KAAK,EAAE,IAAI;IACX,KAAK,EAAE,IAAI;IACX,IAAI,EAAE,IAAI;CACX,CAAA;AAED,MAAM,WAAW,GAA2B;IAC1C,QAAQ,EAAE,UAAU;IACpB,GAAG,EAAE,UAAU;IACf,WAAW,EAAE,UAAU;IACvB,KAAK,EAAE,UAAU;IACjB,OAAO,EAAE,SAAS;CACnB,CAAA;AAED,MAAM,KAAK,GAAG,SAAS,CAAA;AAEvB,MAAa,oBAAoB;IAC/B,aAAa,CAAC,QAAwB,EAAE,OAAwB;QAC9D,IAAI,OAAO,CAAC,MAAM,KAAK,MAAM,EAAE,CAA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AQ,KAAK,MAAM,CAAC,CAAC,MAAM,CAAA;QAE/D,OAAO,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE,CAAC,CAAA;QAClC,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAA;QAChC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAA;QAC3B,OAAO,CAAC,GAAG,CAAC,kBAAkB,QAAQ,EAAE,CAAC,CAAA;QACzC,OAAO,CAAC,GAAG,CAAC,kBAAkB,KAAK,EAAE,CAAC,CAAA;QACtC,OAAO,CAAC,GAAG,CAAC,kBAAkB,KAAK,EAAE,CAAC,CAAA;QACtC,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,EAAE,CAAC,CAAA;QACtC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAA;IAC7B,CAAC;CACF;AAtHD,oDAsHC"} \ No newline at end of file diff --git a/lib/src/context.js b/lib/src/context.js new file mode 100644 index 0000000000000000000000000000000000000000..232989feed749019c6a895018e5faec75cf8c5bf --- /dev/null +++ b/lib/src/context.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getSafeRepo = exports.getSafeOctokit = exports.getCurrentContext = exports.als = void 0; +const async_hooks_1 = require("async_hooks"); +// Global context storage for current execution thread +exports.als = new async_hooks_1.AsyncLocalStorage(); +/** + * Access the current execution context safely from anywhere in the codebase. + */ +const getCurrentContext = () => { + return exports.als.getStore(); +}; +exports.getCurrentContext = getCurrentContext; +/** + * Helper to get octokit from current context + */ +const getSafeOctokit = () => { + return exports.als.getStore()?.octokit; +}; +exports.getSafeOctokit = getSafeOctokit; +/** + * Helper to get repo info from current context + */ +const getSafeRepo = () => { + return exports.als.getStore()?.repo; +}; +exports.getSafeRepo = getSafeRepo; +//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/lib/src/context.js.map b/lib/src/context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d6d35001c464e6b42631544862d7ce3a7926064e --- /dev/null +++ b/lib/src/context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/context.ts"],"names":[],"mappings":";;;AAAA,6CAA6C;AAY7C,sDAAsD;AACzC,QAAA,GAAG,GAAG,IAAI,+BAAiB,EAAe,CAAA;AAEvD;;GAEG;AACI,MAAM,iBAAiB,GAAG,GAA4B,EAAE;IAC7D,OAAO,WAAG,CAAC,QAAQ,EAAE,CAAA;AACvB,CAAC,CAAA;AAFY,QAAA,iBAAiB,qBAE7B;AAED;;GAEG;AACI,MAAM,cAAc,GAAG,GAAQ,EAAE;IACtC,OAAO,WAAG,CAAC,QAAQ,EAAE,EAAE,OAAO,CAAA;AAChC,CAAC,CAAA;AAFY,QAAA,cAAc,kBAE1B;AAED;;GAEG;AACI,MAAM,WAAW,GAAG,GAAG,EAAE;IAC9B,OAAO,WAAG,CAAC,QAAQ,EAAE,EAAE,IAAI,CAAA;AAC7B,CAAC,CAAA;AAFY,QAAA,WAAW,eAEvB"} \ No newline at end of file diff --git a/lib/src/feedback-capture.js b/lib/src/feedback-capture.js new file mode 100644 index 0000000000000000000000000000000000000000..fd412bce277f77c4e363c15ddd08c1a74ac84c45 --- /dev/null +++ b/lib/src/feedback-capture.js @@ -0,0 +1,187 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.feedbackCapture = exports.FeedbackCapture = void 0; +const octokit_1 = require("./octokit"); +const context_1 = require("./context"); +const feedback_tracker_1 = require("./feedback-tracker"); +const info = console.log; +const warning = console.warn; +const FEEDBACK_TAG = ''; +class FeedbackCapture { + commentMetadata = new Map(); + pendingFeedback = new Map(); + getCommentKey(pullNumber, path, startLine) { + return `${pullNumber}:${path}:${startLine}`; + } + trackComment(pullNumber, path, startLine, patternType, severity, confidence, commentId) { + const key = this.getCommentKey(pullNumber, path, startLine); + this.commentMetadata.set(key, { + commentId, + pullNumber, + path, + patternType, + severity, + confidence + }); + } + async checkSuggestionApplied(pullNumber, path, startLine) { + const key = this.getCommentKey(pullNumber, path, startLine); + const metadata = this.commentMetadata.get(key); + if (!metadata || !metadata.commentId) + return false; + try { + const comments = await octokit_1.octokit.pulls.listReviewComments({ + owner: context_1.als.getStore()?.repo.owner || '', + repo: context_1.als.getStore()?.repo.repo || '', + // eslint-disable-next-line camelcase + pull_number: pullNumber + }); + const originalComment = comments.data.find((c) => c.id === metadata.commentId); + if (!originalComment) + return false; + const diff = await this.getFileDiffAtComment(pullNumber, path, startLine, originalComment.original_line || startLine); + const hasAppliedSuggestion = this.detectSuggestionApplication(originalComment.body || '', diff); + if (hasAppliedSuggestion) { + this.recordFeedback(key, 'accepted'); + } + return hasAppliedSuggestion; + } + catch (e) { + warning(`Failed to check suggestion application: ${e}`); + return false; + } + } + async getFileDiffAtComment(pullNumber, path, startLine, originalLine) { + try { + const diff = await octokit_1.octokit.repos.compareCommits({ + owner: context_1.als.getStore()?.repo.owner || '', + repo: context_1.als.getStore()?.repo.repo || '', + base: `${pullNumber}-base`, + head: `${pullNumber}-head` + }); + const file = diff.data.files?.find((f) => f.filename === path); + if (!file?.patch) + return ''; + const hunk = file.patch + .split('\n') + .slice(Math.max(0, originalLine - startLine - 1), originalLine - startLine + 5) + .join('\n'); + return hunk; + } + catch (e) { + return ''; + } + } + detectSuggestionApplication(originalBody, currentDiff) { + if (!originalBody.includes('```suggestion')) + return false; + if (!currentDiff) + return false; + const suggestionMatch = originalBody.match(/```suggestion\n([\s\S]*?)```/); + if (!suggestionMatch) + return false; + const suggestedCode = suggestionMatch[1].trim(); + const hasApplied = currentDiff.includes(suggestedCode.substring(0, Math.min(50, suggestedCode.length))); + return hasApplied; + } + recordFeedback(key, type) { + const metadata = this.commentMetadata.get(key); + if (!metadata) + return; + this.pendingFeedback.set(key, type); + const ctx = context_1.als.getStore(); + const teamId = ctx?.repo?.owner || 'default'; + const repoSlug = ctx?.repo?.repo || 'default'; + feedback_tracker_1.feedbackTracker.recordFeedback({ + patternType: metadata.patternType, + severity: metadata.severity, + filenamePattern: metadata.path, + repoSlug, + teamId, + confidence: metadata.confidence, + feedbackType: type + }); + info(`Recorded ${type} feedback for ${key}`); + } + async checkReactionFeedback(pullNumber) { + const ctx = context_1.als.getStore(); + const teamId = ctx?.repo?.owner || 'default'; + const repoSlug = ctx?.repo?.repo || 'default'; + try { + const comments = await octokit_1.octokit.pulls.listReviewComments({ + owner: teamId, + repo: repoSlug, + // eslint-disable-next-line camelcase + pull_number: pullNumber + }); + for (const comment of comments.data) { + if (!comment.body?.includes(FEEDBACK_TAG)) + continue; + const reactions = await octokit_1.octokit.reactions.listForIssueComment({ + owner: teamId, + repo: repoSlug, + // eslint-disable-next-line camelcase + comment_id: comment.id + }); + for (const reaction of reactions.data) { + const key = this.getCommentKey(pullNumber, comment.path || '', comment.line || comment.original_line || 0); + if (reaction.content === '+1' || reaction.content === 'heart') { + this.recordFeedback(key, 'accepted'); + } + else if (reaction.content === '-1' || reaction.content === 'eyes') { + this.recordFeedback(key, 'rejected'); + } + } + } + } + catch (e) { + warning(`Failed to check reaction feedback: ${e}`); + } + } + async trackReviewSubmission(pullNumber, reviewId, commitId) { + const ctx = context_1.als.getStore(); + const teamId = ctx?.repo?.owner || 'default'; + const repoSlug = ctx?.repo?.repo || 'default'; + info(`Tracking review submission: PR #${pullNumber}, review ID: ${reviewId}`); + try { + const comments = await octokit_1.octokit.pulls.listReviewComments({ + owner: teamId, + repo: repoSlug, + // eslint-disable-next-line camelcase + pull_number: pullNumber + }); + for (const comment of comments.data) { + if (!comment.body?.includes(FEEDBACK_TAG)) + continue; + if (comment.user?.login !== 'github-actions[bot]') + continue; + const metadataMatch = comment.body.match(/data-pattern="([^"]+)"/); + const severityMatch = comment.body.match(/data-severity="([^"]+)"/); + const confidenceMatch = comment.body.match(/data-confidence="([^"]+)"/); + if (metadataMatch && severityMatch && confidenceMatch) { + const key = this.getCommentKey(pullNumber, comment.path || '', comment.line || comment.original_line || 0); + this.commentMetadata.set(key, { + commentId: comment.id, + pullNumber, + path: comment.path || '', + patternType: metadataMatch[1], + severity: severityMatch[1], + confidence: parseFloat(confidenceMatch[1]) + }); + } + } + } + catch (e) { + warning(`Failed to track review submission: ${e}`); + } + } + getFeedbackStats(teamId, repoSlug) { + return feedback_tracker_1.feedbackTracker.getTeamInsights(teamId, repoSlug); + } + shouldSuppressFinding(patternType, filename, teamId, repoSlug) { + return feedback_tracker_1.feedbackTracker.shouldSuppressPattern(patternType, teamId, repoSlug); + } +} +exports.FeedbackCapture = FeedbackCapture; +exports.feedbackCapture = new FeedbackCapture(); +//# sourceMappingURL=feedback-capture.js.map \ No newline at end of file diff --git a/lib/src/feedback-capture.js.map b/lib/src/feedback-capture.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f0d245ebd7e996d744d16777c2c0b52f1426cc82 --- /dev/null +++ b/lib/src/feedback-capture.js.map @@ -0,0 +1 @@ +{"version":3,"file":"feedback-capture.js","sourceRoot":"","sources":["../../src/feedback-capture.ts"],"names":[],"mappings":";;;AAAA,uCAAiC;AACjC,uCAA6B;AAC7B,yDAAkD;AAGlD,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAA;AACxB,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,CAAA;AAE5B,MAAM,YAAY,GAAG,iCAAiC,CAAA;AAWtD,MAAa,eAAe;IAClB,eAAe,GAAiC,IAAI,GAAG,EAAE,CAAA;IACzD,eAAe,GAAyC,IAAI,GAAG,EAAE,CAAA;IAEjE,aAAa,CACnB,UAAkB,EAClB,IAAY,EACZ,SAAiB;QAEjB,OAAO,GAAG,UAAU,IAAI,IAAI,IAAI,SAAS,EAAE,CAAA;IAC7C,CAAC;IAED,YAAY,CACV,UAAkB,EAClB,IAAY,EACZ,SAAiB,EACjB,WAA4B,EAC5B,QAAiD,EACjD,UAAkB,EAClB,SAAkB;QAElB,MAAM,GAAG,GAAG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edback-tracker.js b/lib/src/feedback-tracker.js new file mode 100644 index 0000000000000000000000000000000000000000..1b70e06e1ccc8c5c61fa5bd55ce49581be3e45fa --- /dev/null +++ b/lib/src/feedback-tracker.js @@ -0,0 +1,319 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.feedbackTracker = exports.FeedbackTracker = void 0; +const fs_1 = require("fs"); +const path_1 = require("path"); +const minimatch_1 = require("minimatch"); +const info = console.log; +function getPersistBaseDir() { + if (process.env.PRIX_DATA_DIR) + return process.env.PRIX_DATA_DIR; + if (process.env.HF_HOME) + return (0, path_1.join)(process.env.HF_HOME, 'prix-data'); + if (process.env.HUGGING_FACE_HUB_TOKEN) + return '/tmp/prix-hf'; + return '/tmp/prix'; +} +class FeedbackTracker { + feedbackStore = []; + teamInsights = new Map(); + persistPath; + maxStoreSize = 10000; + initialized = false; + constructor(persistDir) { + const baseDir = persistDir || getPersistBaseDir(); + this.persistPath = (0, path_1.join)(baseDir, 'feedback'); + this.ensureStorageDir(); + this.loadPersisted(); + } + ensureStorageDir() { + try { + if (!(0, fs_1.existsSync)(this.persistPath)) { + (0, fs_1.mkdirSync)(this.persistPath, { recursive: true }); + } + } + catch (e) { + info(`Failed to create feedback storage dir: ${e}`); + } + } + loadPersisted() { + try { + const feedbackFile = (0, path_1.join)(this.persistPath, 'feedback.json'); + if ((0, fs_1.existsSync)(feedbackFile)) { + const data = JSON.parse((0, fs_1.readFileSync)(feedbackFile, 'utf8')); + if (Array.isArray(data)) { + this.feedbackStore = data.slice(-this.maxStoreSize); + this.rebuildTeamInsights(); + this.initialized = true; + info(`Loaded ${this.feedbackStore.length} feedback entries`); + } + } + } + catch (e) { + info(`Failed to load feedback data: ${e}`); + } + } + persist() { + try { + const feedbackFile = (0, path_1.join)(this.persistPath, 'feedback.json'); + (0, fs_1.writeFileSync)(feedbackFile, JSON.stringify(this.feedbackStore.slice(-this.maxStoreSize))); + } + catch (e) { + info(`Failed to persist feedback: ${e}`); + } + } + rebuildTeamInsights() { + const teamMap = new Map(); + for (const fb of this.feedbackStore) { + const key = `${fb.teamId}:${fb.repoSlug}`; + if (!teamMap.has(key)) { + teamMap.set(key, []); + } + teamMap.get(key).push(fb); + } + for (const [key, feedbacks] of teamMap) { + const [teamId, repoSlug] = key.split(':'); + const insights = this.computeInsights(teamId, repoSlug, feedbacks); + this.teamInsights.set(key, insights); + } + } + computeInsights(teamId, repoSlug, feedbacks) { + const patternMap = new Map(); + for (const fb of feedbacks) { + if (!patternMap.has(fb.patternType)) { + patternMap.set(fb.patternType, []); + } + patternMap.get(fb.patternType).push(fb); + } + const patternStats = new Map(); + for (const [patternType, pFeedbacks] of patternMap) { + const accepted = pFeedbacks.filter(f => f.feedbackType === 'accepted').length; + const rejected = pFeedbacks.filter(f => f.feedbackType === 'rejected').length; + const ignored = pFeedbacks.filter(f => f.feedbackType === 'ignored').length; + const total = pFeedbacks.length; + const avgConfidence = pFeedbacks.reduce((sum, f) => sum + f.confidence, 0) / total; + patternStats.set(patternType, { + patternType, + total, + accepted, + rejected, + ignored, + acceptanceRate: total > 0 ? accepted / total : 0, + avgConfidence + }); + } + const allAccepted = feedbacks.filter(f => f.feedbackType === 'accepted').length; + const overallAcceptanceRate = feedbacks.length > 0 ? allAccepted / feedbacks.length : 0; + return { + teamId, + repoSlug, + patternStats, + overallAcceptanceRate, + lastUpdated: Date.now() + }; + } + recordFeedback(feedback) { + const id = `fb_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; + const fullFeedback = { + ...feedback, + id, + timestamp: Date.now() + }; + this.feedbackStore.push(fullFeedback); + if (this.feedbackStore.length > this.maxStoreSize) { + this.feedbackStore = this.feedbackStore.slice(-this.maxStoreSize); + } + const key = `${feedback.teamId}:${feedback.repoSlug}`; + const existing = this.teamInsights.get(key); + if (existing) { + const updatedFeedbacks = [ + ...this.feedbackStore.filter(f => f.teamId === feedback.teamId && f.repoSlug === feedback.repoSlug) + ]; + const insights = this.computeInsights(feedback.teamId, feedback.repoSlug, updatedFeedbacks); + this.teamInsights.set(key, insights); + } + this.persist(); + return id; + } + recordAcceptance(patternType, severity, filename, repoSlug, teamId, confidence, commentId, reviewId) { + return this.recordFeedback({ + patternType, + severity, + filenamePattern: filename, + repoSlug, + teamId, + confidence, + feedbackType: 'accepted', + commentId, + reviewId + }); + } + recordRejection(patternType, severity, filename, repoSlug, teamId, confidence, commentId, reviewId) { + return this.recordFeedback({ + patternType, + severity, + filenamePattern: filename, + repoSlug, + teamId, + confidence, + feedbackType: 'rejected', + commentId, + reviewId + }); + } + recordIgnored(patternType, severity, filename, repoSlug, teamId, confidence, commentId, reviewId) { + return this.recordFeedback({ + patternType, + severity, + filenamePattern: filename, + repoSlug, + teamId, + confidence, + feedbackType: 'ignored', + commentId, + reviewId + }); + } + getPatternAcceptanceRate(patternType, teamId, repoSlug) { + const key = `${teamId}:${repoSlug}`; + const insights = this.teamInsights.get(key); + if (!insights) + return 0.5; + const stats = insights.patternStats.get(patternType); + if (!stats) + return 0.5; + if (stats.total < 5) + return 0.5; + return stats.acceptanceRate; + } + getFilenameAcceptanceRate(filenamePattern, teamId, repoSlug) { + const feedbacks = this.feedbackStore.filter(f => f.teamId === teamId && + f.repoSlug === repoSlug && + f.feedbackType !== 'ignored'); + if (feedbacks.length === 0) + return 0.5; + const matching = feedbacks.filter(f => (0, minimatch_1.minimatch)(f.filenamePattern, filenamePattern) || + (0, minimatch_1.minimatch)(filenamePattern, f.filenamePattern)); + if (matching.length === 0) + return 0.5; + const accepted = matching.filter(f => f.feedbackType === 'accepted').length; + return accepted / matching.length; + } + getTeamInsights(teamId, repoSlug) { + const key = `${teamId}:${repoSlug}`; + return this.teamInsights.get(key) || null; + } + getAdjustedConfidence(baseConfidence, patternType, filename, teamId, repoSlug) { + const patternRate = this.getPatternAcceptanceRate(patternType, teamId, repoSlug); + const filenameRate = this.getFilenameAcceptanceRate(filename, teamId, repoSlug); + const feedbackWeight = 0.3; + const teamRate = patternRate * 0.6 + filenameRate * 0.4; + const adjustedConfidence = baseConfidence * (1 - feedbackWeight) + teamRate * 100 * feedbackWeight; + return Math.max(0, Math.min(100, adjustedConfidence)); + } + shouldSuppressPattern(patternType, teamId, repoSlug, threshold = 0.2, minSamples = 10) { + const key = `${teamId}:${repoSlug}`; + const insights = this.teamInsights.get(key); + if (!insights) + return false; + const stats = insights.patternStats.get(patternType); + if (!stats || stats.total < minSamples) + return false; + return stats.acceptanceRate < threshold; + } + getQuery(query) { + let results = [...this.feedbackStore]; + if (query.teamId) { + results = results.filter(f => f.teamId === query.teamId); + } + if (query.repoSlug) { + results = results.filter(f => f.repoSlug === query.repoSlug); + } + if (query.patternType) { + results = results.filter(f => f.patternType === query.patternType); + } + if (query.filenamePattern) { + results = results.filter(f => (0, minimatch_1.minimatch)(f.filenamePattern, query.filenamePattern)); + } + if (query.since) { + results = results.filter(f => f.timestamp >= query.since); + } + if (query.limit) { + results = results.slice(-query.limit); + } + return results; + } + getSummary(teamId, repoSlug) { + let feedbacks = [...this.feedbackStore]; + if (teamId) { + feedbacks = feedbacks.filter(f => f.teamId === teamId); + } + if (repoSlug) { + feedbacks = feedbacks.filter(f => f.repoSlug === repoSlug); + } + const patternMap = new Map(); + const repoMap = new Map(); + const teamMap = new Map(); + for (const fb of feedbacks) { + if (!patternMap.has(fb.patternType)) { + patternMap.set(fb.patternType, []); + } + patternMap.get(fb.patternType).push(fb); + repoMap.set(fb.repoSlug, (repoMap.get(fb.repoSlug) || 0) + 1); + teamMap.set(fb.teamId, (teamMap.get(fb.teamId) || 0) + 1); + } + const byPattern = new Map(); + for (const [patternType, pFeedbacks] of patternMap) { + const accepted = pFeedbacks.filter(f => f.feedbackType === 'accepted').length; + const rejected = pFeedbacks.filter(f => f.feedbackType === 'rejected').length; + const ignored = pFeedbacks.filter(f => f.feedbackType === 'ignored').length; + const total = pFeedbacks.length; + const avgConfidence = pFeedbacks.reduce((sum, f) => sum + f.confidence, 0) / total; + byPattern.set(patternType, { + patternType, + total, + accepted, + rejected, + ignored, + acceptanceRate: total > 0 ? accepted / total : 0, + avgConfidence + }); + } + const recentWindow = 30 * 24 * 60 * 60 * 1000; + const recentFeedbacks = feedbacks.filter(f => f.timestamp > Date.now() - recentWindow); + const olderFeedbacks = feedbacks.filter(f => f.timestamp <= Date.now() - recentWindow); + const recentAcceptance = recentFeedbacks.filter(f => f.feedbackType === 'accepted').length / + (recentFeedbacks.length || 1); + const olderAcceptance = olderFeedbacks.filter(f => f.feedbackType === 'accepted').length / + (olderFeedbacks.length || 1); + let recentTrend = 'stable'; + if (recentAcceptance > olderAcceptance + 0.05) { + recentTrend = 'improving'; + } + else if (recentAcceptance < olderAcceptance - 0.05) { + recentTrend = 'declining'; + } + return { + totalFeedback: feedbacks.length, + byPattern, + byRepo: repoMap, + byTeam: teamMap, + recentTrend + }; + } + exportForTraining() { + return this.feedbackStore + .filter(f => f.feedbackType !== 'ignored') + .map(f => ({ + patternType: f.patternType, + severity: f.severity, + filenamePattern: f.filenamePattern, + confidence: f.confidence, + accepted: f.feedbackType === 'accepted', + repoSlug: f.repoSlug + })); + } +} +exports.FeedbackTracker = FeedbackTracker; +exports.feedbackTracker = new FeedbackTracker(); +//# sourceMappingURL=feedback-tracker.js.map \ No newline at end of file diff --git a/lib/src/feedback-tracker.js.map b/lib/src/feedback-tracker.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4f70951be770c8562d19a7110eeb40e49cf077db --- /dev/null +++ b/lib/src/feedback-tracker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"feedback-tracker.js","sourceRoot":"","sources":["../../src/feedback-tracker.ts"],"names":[],"mappings":";;;AAAA,2BAAqE;AACrE,+BAAyB;AACzB,yCAAmC;AAWnC,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAA;AAExB,SAAS,iBAAiB;IACxB,IAAI,OAAO,CAAC,GAAG,CAAC,aAAa;QAAE,OAAO,OAAO,CAAC,GAAG,CAAC,aAAa,CAAA;IAC/D,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO;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AG,WAAW,CAAA;QAC3B,CAAC;QAED,OAAO;YACL,aAAa,EAAE,SAAS,CAAC,MAAM;YAC/B,SAAS;YACT,MAAM,EAAE,OAAO;YACf,MAAM,EAAE,OAAO;YACf,WAAW;SACZ,CAAA;IACH,CAAC;IAED,iBAAiB;QAQf,OAAO,IAAI,CAAC,aAAa;aACtB,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,YAAY,KAAK,SAAS,CAAC;aACzC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;YACT,WAAW,EAAE,CAAC,CAAC,WAAW;YAC1B,QAAQ,EAAE,CAAC,CAAC,QAAQ;YACpB,eAAe,EAAE,CAAC,CAAC,eAAe;YAClC,UAAU,EAAE,CAAC,CAAC,UAAU;YACxB,QAAQ,EAAE,CAAC,CAAC,YAAY,KAAK,UAAU;YACvC,QAAQ,EAAE,CAAC,CAAC,QAAQ;SACrB,CAAC,CAAC,CAAA;IACP,CAAC;CACF;AArcD,0CAqcC;AAEY,QAAA,eAAe,GAAG,IAAI,eAAe,EAAE,CAAA"} \ No newline at end of file diff --git a/lib/src/feedback-types.js b/lib/src/feedback-types.js new file mode 100644 index 0000000000000000000000000000000000000000..aa6abafba4306abbd887090022514c729ff91215 --- /dev/null +++ b/lib/src/feedback-types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=feedback-types.js.map \ No newline at end of file diff --git a/lib/src/feedback-types.js.map b/lib/src/feedback-types.js.map new file mode 100644 index 0000000000000000000000000000000000000000..db1a3bab37cc4e9e2ef58763115fefedacee50d2 --- /dev/null +++ b/lib/src/feedback-types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"feedback-types.js","sourceRoot":"","sources":["../../src/feedback-types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/src/file-discoverer.js b/lib/src/file-discoverer.js new file mode 100644 index 0000000000000000000000000000000000000000..8d585bf5fda7d30d07bd77232281cc1abbae06b9 --- /dev/null +++ b/lib/src/file-discoverer.js @@ -0,0 +1,132 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FileDiscoverer = void 0; +exports.createFileDiscoverer = createFileDiscoverer; +exports.discoverFiles = discoverFiles; +const fs_1 = require("fs"); +const path_1 = require("path"); +const DEFAULT_EXCLUDES = new Set([ + 'node_modules', + '.git', + '.svn', + '.hg', + 'dist', + 'build', + 'coverage', + '.nyc_output', + '.next', + '.nuxt', + '__pycache__', + '.pytest_cache', + 'target', + 'bin', + 'obj', + 'vendor', + '.venv', + 'env' +]); +const PLATFORM_FILE_PROTOCOL = typeof window !== 'undefined'; +class FileDiscoverer { + excludePatterns; + includeExtensions; + constructor(excludePatterns = [], includeExtensions = [ + '.ts', + '.tsx', + '.js', + '.jsx', + '.go', + '.py', + '.rs', + '.cpp', + '.c', + '.h', + '.hpp', + '.java' + ]) { + this.excludePatterns = new Set([...DEFAULT_EXCLUDES, ...excludePatterns]); + this.includeExtensions = new Set(includeExtensions.map(e => e.toLowerCase())); + } + discover(rootPath, filter) { + if (!(0, fs_1.existsSync)(rootPath)) { + console.warn(`Path does not exist: ${rootPath}`); + return []; + } + const results = []; + this.discoverRecursive(rootPath, rootPath, results, 0, filter?.maxDepth || 50); + return results; + } + discoverRecursive(rootPath, currentPath, results, depth, maxDepth) { + if (depth > maxDepth) + return; + let entries = []; + try { + entries = (0, fs_1.readdirSync)(currentPath); + } + catch (e) { + return; + } + for (const entry of entries) { + if (entry.startsWith('.') && entry !== '.gitignore') + continue; + if (this.excludePatterns.has(entry)) + continue; + const fullPath = (0, path_1.join)(currentPath, entry); + let stat = null; + try { + stat = (0, fs_1.statSync)(fullPath); + } + catch { + continue; + } + if (stat.isDirectory()) { + this.discoverRecursive(rootPath, fullPath, results, depth + 1, maxDepth); + } + else if (stat.isFile()) { + const ext = (0, path_1.extname)(entry).toLowerCase(); + if (this.includeExtensions.has(ext)) { + const relativePath = this.getRelativePath(rootPath, fullPath); + results.push({ + path: fullPath, + relativePath, + extension: ext, + size: stat.size, + mtime: stat.mtimeMs + }); + } + } + } + } + getRelativePath(root, full) { + const normalize = (p) => p.replace(/\\/g, '/'); + const rootNorm = normalize(root); + const fullNorm = normalize(full); + if (fullNorm.startsWith(rootNorm)) { + const relative = fullNorm.substring(rootNorm.length); + return relative.startsWith('/') ? relative.substring(1) : relative; + } + return fullNorm; + } + filterByExtensions(files, extensions) { + const extSet = new Set(extensions.map(e => e.toLowerCase())); + return files.filter(f => extSet.has(f.extension)); + } + groupByExtension(files) { + const groups = new Map(); + for (const file of files) { + if (!groups.has(file.extension)) { + groups.set(file.extension, []); + } + groups.get(file.extension).push(file); + } + return groups; + } +} +exports.FileDiscoverer = FileDiscoverer; +function createFileDiscoverer(excludePatterns, includeExtensions) { + return new FileDiscoverer(excludePatterns, includeExtensions); +} +function discoverFiles(rootPath, options) { + const discoverer = new FileDiscoverer(options?.exclude, options?.include); + return discoverer.discover(rootPath, { maxDepth: options?.maxDepth }); +} +//# sourceMappingURL=file-discoverer.js.map \ No newline at end of file diff --git a/lib/src/file-discoverer.js.map b/lib/src/file-discoverer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..fe23968f4b2193f9856d4cd0d84fd82396e6495c --- /dev/null +++ b/lib/src/file-discoverer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"file-discoverer.js","sourceRoot":"","sources":["../../src/file-discoverer.ts"],"names":[],"mappings":";;;AAyKA,oDAKC;AAED,sCAUC;AA1LD,2BAAoD;AACpD,+BAAkC;AAgBlC,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC;IAC/B,cAAc;IACd,MAAM;IACN,MAAM;IACN,KAAK;IACL,MAAM;IACN,OAAO;IACP,UAAU;IACV,aAAa;IACb,OAAO;IACP,OAAO;IACP,aAAa;IACb,eAAe;IACf,QAAQ;IACR,KAAK;IACL,KAAK;IACL,QAAQ;IACR,OAAO;IACP,KAAK;CACN,CAAC,CAAA;AAEF,MAAM,sBAA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A/HD,wCA+HC;AAED,SAAgB,oBAAoB,CAClC,eAA0B,EAC1B,iBAA4B;IAE5B,OAAO,IAAI,cAAc,CAAC,eAAe,EAAE,iBAAiB,CAAC,CAAA;AAC/D,CAAC;AAED,SAAgB,aAAa,CAC3B,QAAgB,EAChB,OAIC;IAED,MAAM,UAAU,GAAG,IAAI,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;IACzE,OAAO,UAAU,CAAC,QAAQ,CAAC,QAAQ,EAAE,EAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAC,CAAC,CAAA;AACrE,CAAC"} \ No newline at end of file diff --git a/lib/src/fix-verifier.js b/lib/src/fix-verifier.js new file mode 100644 index 0000000000000000000000000000000000000000..68993418e76ead20ca4b64c1ea37c6a9bebeb94f --- /dev/null +++ b/lib/src/fix-verifier.js @@ -0,0 +1,491 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FixVerifier = void 0; +exports.createVerifier = createVerifier; +const child_process_1 = require("child_process"); +const fs_1 = require("fs"); +const path_1 = require("path"); +const ts_morph_1 = require("ts-morph"); +const utils_1 = require("./utils"); +const DEFAULT_CONFIG = { + enableLint: true, + enableSyntax: true, + enableAST: true, + enableTests: false, + maxRetries: 3, + timeout: 30000 +}; +class FixVerifier { + config; + project; + constructor(config = {}, project) { + this.config = { ...DEFAULT_CONFIG, ...config }; + this.project = project || new ts_morph_1.Project(); + } + async verify(filename, remedyCode, startLine, endLine, workingDir) { + const checks = []; + let allPassed = true; + let canRetry = true; + let errorMessage; + if (this.config.enableSyntax) { + const syntaxCheck = await this.runSyntaxCheck(filename, remedyCode, workingDir); + checks.push(syntaxCheck); + if (!syntaxCheck.passed) { + allPassed = false; + errorMessage = syntaxCheck.feedback; + } + } + if (this.config.enableLint && allPassed) { + const lintCheck = await this.runLintCheck(filename, remedyCode, workingDir); + checks.push(lintCheck); + if (!lintCheck.passed) { + allPassed = false; + canRetry = false; + errorMessage = lintCheck.feedback; + } + } + if (this.config.enableAST && allPassed) { + const astCheck = this.runASTValidation(filename, remedyCode); + checks.push(astCheck); + if (!astCheck.passed) { + allPassed = false; + errorMessage = astCheck.feedback; + } + } + if (this.config.enableTests && allPassed) { + const testCheck = await this.runTestCheck(filename, remedyCode, startLine, endLine, workingDir); + checks.push(testCheck); + if (!testCheck.passed) { + allPassed = false; + canRetry = false; + errorMessage = testCheck.feedback; + } + } + const overallFeedback = checks + .map(c => `${c.passed ? 'โœ…' : 'โŒ'} ${c.name}: ${c.feedback}`) + .join('\n'); + return { + passed: allPassed, + checks, + overallFeedback, + canRetry, + errorMessage + }; + } + async runSyntaxCheck(filename, remedyCode, workingDir) { + const startTime = Date.now(); + const ext = filename.split('.').pop()?.toLowerCase() || ''; + let feedback = ''; + let passed = true; + const tempFile = (0, path_1.join)(workingDir, `__prix_verify_${Date.now()}.${ext}`); + try { + if (ext === 'ts' || ext === 'js') { + (0, fs_1.writeFileSync)(tempFile, remedyCode, 'utf8'); + feedback = await this.verifyJSTypeScript(tempFile, ext, workingDir); + passed = !feedback.includes('โŒ'); + } + else if (ext === 'py') { + (0, fs_1.writeFileSync)(tempFile, remedyCode, 'utf8'); + feedback = await this.verifyPython(tempFile); + passed = !feedback.includes('โŒ'); + } + else if (ext === 'go') { + (0, fs_1.writeFileSync)(tempFile, remedyCode, 'utf8'); + feedback = await this.verifyGo(tempFile); + passed = !feedback.includes('โŒ'); + } + else { + feedback = 'โš ๏ธ Syntax check not supported for this file type'; + } + } + catch (e) { + passed = false; + feedback = `โŒ Syntax check failed: ${e.message}`; + } + finally { + this.cleanup(tempFile); + } + return { + name: 'Syntax Check', + passed, + feedback, + duration: Date.now() - startTime + }; + } + async verifyJSTypeScript(tempFile, ext, workingDir) { + let feedback = ''; + try { + if (ext === 'ts') { + const hasTypeScript = (0, fs_1.existsSync)((0, path_1.join)(workingDir, 'node_modules/typescript')) || + (0, fs_1.existsSync)((0, path_1.join)(workingDir, 'node_modules/.bin/tsc')); + if (hasTypeScript) { + try { + (0, utils_1.prixExec)(`npx tsc "${tempFile}" --noEmit --esModuleInterop --skipLibCheck --jsx react`, { + cwd: workingDir, + timeout: 15000 + }); + feedback = 'TS check passed'; + } + catch (e) { + const errorOutput = e.stdout?.toString() || e.message || ''; + const relevantErrors = this.filterErrorsForFile(errorOutput, (0, path_1.basename)(tempFile)); + if (relevantErrors) { + feedback = `โŒ TS error: ${relevantErrors}`; + } + else { + feedback = 'โŒ TS syntax error'; + } + } + } + else { + feedback = 'โš ๏ธ TypeScript not installed, skipping TS check'; + } + } + else { + try { + (0, child_process_1.execSync)(`node --check "${tempFile}"`, { + encoding: 'utf8', + timeout: 5000 + }); + feedback = 'Syntax check passed'; + } + catch (e) { + feedback = `โŒ Syntax error: ${e.message}`; + } + } + } + catch (e) { + feedback = `โŒ Check failed: ${e.message}`; + } + return feedback; + } + async verifyPython(tempFile) { + try { + (0, child_process_1.execSync)(`python3 -m py_compile "${tempFile}"`, { + encoding: 'utf8', + timeout: 5000 + }); + return 'Python syntax passed'; + } + catch (e) { + const errorOutput = e.stderr?.toString() || e.message; + return `โŒ Python syntax error: ${errorOutput}`.substring(0, 200); + } + } + async verifyGo(tempFile) { + try { + (0, child_process_1.execSync)(`go vet "${tempFile}"`, { encoding: 'utf8', timeout: 5000 }); + return 'Go syntax passed'; + } + catch (e) { + const errorOutput = e.stderr?.toString() || e.message; + return `โŒ Go syntax error: ${errorOutput}`.substring(0, 200); + } + } + async runLintCheck(filename, remedyCode, workingDir) { + const startTime = Date.now(); + const ext = filename.split('.').pop()?.toLowerCase() || ''; + let feedback = ''; + let passed = true; + const tempFile = (0, path_1.join)(workingDir, `__prix_lint_${Date.now()}.${ext}`); + try { + if ((ext === 'ts' || ext === 'js') && + (0, fs_1.existsSync)((0, path_1.join)(workingDir, 'package.json'))) { + (0, fs_1.writeFileSync)(tempFile, remedyCode, 'utf8'); + const hasEslint = (0, fs_1.existsSync)((0, path_1.join)(workingDir, '.eslintrc.json')) || + (0, fs_1.existsSync)((0, path_1.join)(workingDir, '.eslintrc.js')) || + (0, fs_1.existsSync)((0, path_1.join)(workingDir, '.eslintrc')); + if (hasEslint) { + try { + (0, utils_1.prixExec)(`npx eslint "${tempFile}" --max-warnings 0`, { + cwd: workingDir, + timeout: 15000 + }); + feedback = 'Lint passed'; + } + catch (e) { + const errorOutput = e.stdout?.toString() || e.message || ''; + const relevantErrors = this.filterErrorsForFile(errorOutput, (0, path_1.basename)(tempFile)); + feedback = `โŒ Lint failed: ${relevantErrors || ' ESLint errors'}`; + passed = false; + } + } + else { + feedback = 'โš ๏ธ ESLint not configured'; + } + } + else if (ext === 'py') { + const hasPylint = this.commandExists('pylint'); + const hasFlake8 = this.commandExists('flake8'); + (0, fs_1.writeFileSync)(tempFile, remedyCode, 'utf8'); + if (hasPylint) { + try { + (0, child_process_1.execSync)(`pylint "${tempFile}" --disable=all --enable=E`, { + encoding: 'utf8', + timeout: 10000 + }); + feedback = 'Pylint passed'; + } + catch (e) { + feedback = `โŒ Pylint: ${e.message}`.substring(0, 200); + passed = false; + } + } + else if (hasFlake8) { + try { + (0, child_process_1.execSync)(`flake8 "${tempFile}"`, { encoding: 'utf8', timeout: 10000 }); + feedback = 'Flake8 passed'; + } + catch (e) { + feedback = `โŒ Flake8: ${e.message}`.substring(0, 200); + passed = false; + } + } + else { + feedback = 'โš ๏ธ Python linter not available'; + } + } + } + catch (e) { + passed = false; + feedback = `โŒ Lint failed: ${e.message}`; + } + finally { + this.cleanup(tempFile); + } + return { + name: 'Lint Check', + passed, + feedback, + duration: Date.now() - startTime + }; + } + runASTValidation(filename, remedyCode) { + const startTime = Date.now(); + if (!filename.endsWith('.ts') && !filename.endsWith('.js')) { + return { + name: 'AST Validation', + passed: true, + feedback: 'Not applicable for this file type', + duration: 0 + }; + } + try { + const tempFile = `__prix_ast_${Date.now()}_${filename}`; + const sourceFile = this.project.createSourceFile(tempFile, remedyCode, { + overwrite: true + }); + const diagnostics = sourceFile.getPreEmitDiagnostics(); + if (diagnostics.length > 0) { + const errorMessages = diagnostics + .slice(0, 3) + .map(d => d.getMessageText()) + .join('; '); + return { + name: 'AST Validation', + passed: false, + feedback: `โŒ AST errors: ${errorMessages}`, + duration: Date.now() - startTime + }; + } + const identifiers = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.Identifier); + const undefinedSymbols = []; + for (const id of identifiers) { + if (id.getSymbol()) + continue; + const text = id.getText(); + const skipList = [ + 'console', + 'process', + 'require', + 'exports', + 'module', + 'Buffer', + 'Array', + 'Object', + 'String', + 'Number', + 'Boolean', + 'Date', + 'Promise', + 'Math', + 'JSON', + 'Map', + 'Set', + 'RegExp', + 'Error', + 'undefined', + 'NaN', + 'Infinity', + 'parseInt', + 'parseFloat' + ]; + if (skipList.includes(text)) + continue; + if (id.getParentIfKind(ts_morph_1.SyntaxKind.ImportSpecifier)) + continue; + if (id.getParentIfKind(ts_morph_1.SyntaxKind.PropertyAccessExpression)) + continue; + const parentKind = id.getParent()?.getKind(); + if (parentKind === ts_morph_1.SyntaxKind.PropertyAssignment) + continue; + undefinedSymbols.push(text); + } + const uniqueUndefined = [...new Set(undefinedSymbols)].slice(0, 5); + if (uniqueUndefined.length > 0) { + return { + name: 'AST Validation', + passed: false, + feedback: `โŒ Hallucination detected: undefined symbols: ${uniqueUndefined.join(', ')}`, + duration: Date.now() - startTime + }; + } + return { + name: 'AST Validation', + passed: true, + feedback: 'No hallucinations detected', + duration: Date.now() - startTime + }; + } + catch (e) { + return { + name: 'AST Validation', + passed: false, + feedback: `โŒ AST validation failed: ${e.message}`, + duration: Date.now() - startTime + }; + } + } + async runTestCheck(filename, remedyCode, startLine, endLine, workingDir) { + const startTime = Date.now(); + if (!(0, fs_1.existsSync)((0, path_1.join)(workingDir, 'package.json'))) { + return { + name: 'Test Check', + passed: true, + feedback: 'โš ๏ธ No package.json found', + duration: 0 + }; + } + const testFile = this.findCorrespondingTestFile(filename); + if (!testFile) { + return { + name: 'Test Check', + passed: true, + feedback: 'โš ๏ธ No corresponding test file found', + duration: 0 + }; + } + try { + const testContent = (0, fs_1.readFileSync)(testFile, 'utf8'); + const testsForFunction = this.extractRelevantTests(testContent, filename, startLine); + if (!testsForFunction) { + return { + name: 'Test Check', + passed: true, + feedback: 'โš ๏ธ No relevant tests found for modified code', + duration: 0 + }; + } + const tempTestFile = (0, path_1.join)(workingDir, `__prix_test_${Date.now()}.test.ts`); + (0, fs_1.writeFileSync)(tempTestFile, testsForFunction, 'utf8'); + try { + const hasJest = (0, fs_1.existsSync)((0, path_1.join)(workingDir, 'node_modules/jest')) || + (0, fs_1.existsSync)((0, path_1.join)(workingDir, 'node_modules/.bin/jest')); + if (hasJest) { + try { + (0, utils_1.prixExec)(`npx jest "${tempTestFile}" --passWithNoTests`, { + cwd: workingDir, + timeout: 30000 + }); + return { + name: 'Test Check', + passed: true, + feedback: 'Test check passed', + duration: Date.now() - startTime + }; + } + catch (e) { + return { + name: 'Test Check', + passed: false, + feedback: `โŒ Test failed: ${e.message}`.substring(0, 200), + duration: Date.now() - startTime + }; + } + } + } + finally { + this.cleanup(tempTestFile); + } + return { + name: 'Test Check', + passed: true, + feedback: 'โš ๏ธ Test runner not available', + duration: 0 + }; + } + catch (e) { + return { + name: 'Test Check', + passed: false, + feedback: `โŒ Test check failed: ${e.message}`, + duration: Date.now() - startTime + }; + } + } + findCorrespondingTestFile(filename) { + const baseDir = filename.substring(0, filename.lastIndexOf('/')); + const basename = filename.substring(filename.lastIndexOf('/') + 1); + const nameWithoutExt = basename.replace(/\.[^.]+$/, ''); + const patterns = [ + (0, path_1.join)(baseDir, `${nameWithoutExt}.test.ts`), + (0, path_1.join)(baseDir, `${nameWithoutExt}.spec.ts`), + (0, path_1.join)(baseDir, '__tests__', `${nameWithoutExt}.ts`), + (0, path_1.join)(baseDir, 'test', `${nameWithoutExt}.ts`), + (0, path_1.join)(baseDir, 'tests', `${nameWithoutExt}.ts`) + ]; + for (const pattern of patterns) { + if ((0, fs_1.existsSync)(pattern)) { + return pattern; + } + } + return null; + } + extractRelevantTests(testContent, sourceFile, lineNumber) { + const functionNameMatch = testContent.match(new RegExp(`(test|it)\\(['"]{1,2}([^'"]{1,30})['"]{1,2}`)); + if (!functionNameMatch) + return null; + return testContent; + } + filterErrorsForFile(errorOutput, tempFile) { + const lines = errorOutput.split('\n'); + const relevantLines = lines.filter(l => l.includes(tempFile) || l.includes('__prix')); + if (relevantLines.length === 0) + return null; + return relevantLines.slice(0, 3).join('; '); + } + commandExists(cmd) { + try { + (0, child_process_1.execSync)(`which ${cmd}`, { encoding: 'utf8', timeout: 1000 }); + return true; + } + catch { + return false; + } + } + cleanup(tempFile) { + try { + if ((0, fs_1.existsSync)(tempFile)) { + (0, fs_1.unlinkSync)(tempFile); + } + } + catch { + // Cleanup failures are non-fatal + } + } +} +exports.FixVerifier = FixVerifier; +function createVerifier(project) { + return new FixVerifier({}, project); +} +//# sourceMappingURL=fix-verifier.js.map \ No newline at end of file diff --git a/lib/src/fix-verifier.js.map b/lib/src/fix-verifier.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cb3f459b51ee898da5708926f8b9425f79ede4c6 --- /dev/null +++ b/lib/src/fix-verifier.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fix-verifier.js","sourceRoot":"","sources":["../../src/fix-verifier.ts"],"names":[],"mappings":";;;AA6lBA,wCAEC;AA/lBD,iDAAsC;AACtC,2BAAgF;AAChF,+BAAmC;AACnC,uCAA4C;AAC5C,mCAAgC;AA0BhC,MAAM,cAAc,GAAuB;IACzC,UAAU,EAAE,IAAI;IAChB,YAAY,EAAE,IAAI;IAClB,SAAS,EAAE,IAAI;IACf,WAAW,EAAE,KAAK;IAClB,UAAU,EAAE,CAAC;IACb,OAAO,EAAE,KAAK;CACf,CAAA;AAED,MAAa,WAAW;IACd,MAAM,CAAoB;IAC1B,OAAO,CAAS;IAExB,YAAY,SAAsC,EAAE,EAAE,OAAiB;QACrE,IAAI,CAAC,MAAM,GAAG,EAAC,GA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,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAClD,CAAA;QAED,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,CAAA;QAE3C,OAAO,aAAa,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAC7C,CAAC;IAEO,aAAa,CAAC,GAAW;QAC/B,IAAI,CAAC;YACH,IAAA,wBAAQ,EAAC,SAAS,GAAG,EAAE,EAAE,EAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAC,CAAC,CAAA;YAC3D,OAAO,IAAI,CAAA;QACb,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAA;QACd,CAAC;IACH,CAAC;IAEO,OAAO,CAAC,QAAgB;QAC9B,IAAI,CAAC;YACH,IAAI,IAAA,eAAU,EAAC,QAAQ,CAAC,EAAE,CAAC;gBACzB,IAAA,eAAU,EAAC,QAAQ,CAAC,CAAA;YACtB,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,iCAAiC;QACnC,CAAC;IACH,CAAC;CACF;AApjBD,kCAojBC;AAED,SAAgB,cAAc,CAAC,OAAiB;IAC9C,OAAO,IAAI,WAAW,CAAC,EAAE,EAAE,OAAO,CAAC,CAAA;AACrC,CAAC"} \ No newline at end of file diff --git a/lib/src/inputs.js b/lib/src/inputs.js new file mode 100644 index 0000000000000000000000000000000000000000..baf317bb6a2d7e6d90894230992c5f236fd569d4 --- /dev/null +++ b/lib/src/inputs.js @@ -0,0 +1,93 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Inputs = void 0; +class Inputs { + systemMessage; + title; + description; + rawSummary; + shortSummary; + filename; + fileContent; + fileDiff; + patches; + diff; + commentChain; + comment; + suggestion; + error; + taskDescription; + constructor(systemMessage = '', title = 'no title provided', description = 'no description provided', rawSummary = '', shortSummary = '', filename = '', fileContent = 'file contents cannot be provided', fileDiff = 'file diff cannot be provided', patches = '', diff = 'no diff', commentChain = 'no other comments on this patch', comment = 'no comment provided', suggestion = '', error = '', taskDescription = '') { + this.systemMessage = systemMessage; + this.title = title; + this.description = description; + this.rawSummary = rawSummary; + this.shortSummary = shortSummary; + this.filename = filename; + this.fileContent = fileContent; + this.fileDiff = fileDiff; + this.patches = patches; + this.diff = diff; + this.commentChain = commentChain; + this.comment = comment; + this.suggestion = suggestion; + this.error = error; + this.taskDescription = taskDescription; + } + clone() { + return new Inputs(this.systemMessage, this.title, this.description, this.rawSummary, this.shortSummary, this.filename, this.fileContent, this.fileDiff, this.patches, this.diff, this.commentChain, this.comment, this.suggestion, this.error, this.taskDescription); + } + render(content) { + if (!content) { + return ''; + } + if (this.systemMessage) { + content = content.replace('$system_message', this.systemMessage); + } + if (this.title) { + content = content.replace('$title', this.title); + } + if (this.description) { + content = content.replace('$description', this.description); + } + if (this.rawSummary) { + content = content.replace('$raw_summary', this.rawSummary); + } + if (this.shortSummary) { + content = content.replace('$short_summary', this.shortSummary); + } + if (this.filename) { + content = content.replace('$filename', this.filename); + } + if (this.fileContent) { + content = content.replace('$file_content', this.fileContent); + } + if (this.fileDiff) { + content = content.replace('$file_diff', this.fileDiff); + } + if (this.patches) { + content = content.replace('$patches', this.patches); + } + if (this.diff) { + content = content.replace('$diff', this.diff); + } + if (this.taskDescription) { + content = content.replace('$task_description', this.taskDescription); + } + if (this.commentChain) { + content = content.replace('$comment_chain', this.commentChain); + } + if (this.comment) { + content = content.replace('$comment', this.comment); + } + if (this.suggestion) { + content = content.replace('$suggestion', this.suggestion); + } + if (this.error) { + content = content.replace('$error', this.error); + } + return content; + } +} +exports.Inputs = Inputs; +//# sourceMappingURL=inputs.js.map \ No newline at end of file diff --git a/lib/src/inputs.js.map b/lib/src/inputs.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1be8e9267361acaa5cfd71dcfadaebb33e151eb7 --- /dev/null +++ b/lib/src/inputs.js.map @@ -0,0 +1 @@ +{"version":3,"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AAC;QACD,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACpB,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,UAAU,CAAC,CAAA;QAC3D,CAAC;QACD,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YACf,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,CAAA;QACjD,CAAC;QACD,OAAO,OAAO,CAAA;IAChB,CAAC;CACF;AA1HD,wBA0HC"} \ No newline at end of file diff --git a/lib/src/issue-handler.js b/lib/src/issue-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..703973226118fe143edcee9acb670178856d7e49 --- /dev/null +++ b/lib/src/issue-handler.js @@ -0,0 +1,105 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.handleIssueComment = exports.repo = exports.context = void 0; +const commenter_1 = require("./commenter"); +const inputs_1 = require("./inputs"); +const octokit_1 = require("./octokit"); +const tokenizer_1 = require("./tokenizer"); +const context_1 = require("./context"); +let info = console.log; +let warning = console.warn; +exports.context = new Proxy({}, { + get(target, prop) { + return (context_1.als.getStore()?.probotContext)[prop]; + } +}); +exports.repo = new Proxy({}, { + get(target, prop) { + return (context_1.als.getStore()?.repo)[prop]; + } +}); +const ISSUE_COMMAND_TAG = '@prix'; +const handleIssueComment = async (heavyBot, options, prompts) => { + const commenter = new commenter_1.Commenter(); + const inputs = new inputs_1.Inputs(); + if (exports.context.name !== 'issue_comment') { + warning(`Skipped: ${exports.context.name} is not an issue_comment event`); + return; + } + if (!exports.context.payload) { + warning(`Skipped: issue_comment event is missing payload`); + return; + } + const comment = exports.context.payload.comment; + if (comment == null) { + warning(`Skipped: issue_comment event is missing comment`); + return; + } + const issue = exports.context.payload.issue; + if (issue == null) { + warning(`Skipped: issue_comment event is missing issue`); + return; + } + if (exports.context.payload.action !== 'created') { + warning(`Skipped: issue_comment event is not created`); + return; + } + const isBotComment = comment.user?.type === 'Bot'; + if (isBotComment) { + info(`Skipped: issue_comment event is from the bot itself`); + return; + } + if (!comment.body.includes(ISSUE_COMMAND_TAG)) { + info(`Skipped: comment does not mention @prix`); + return; + } + const issueNumber = issue.number; + const issueTitle = issue.title; + const issueBody = issue.body || ''; + const commentBody = comment.body; + const commentUser = comment.user?.login || 'unknown'; + info(`Processing issue comment for issue #${issueNumber} from @${commentUser}`); + inputs.title = issueTitle; + inputs.description = issueBody; + inputs.comment = `${commentUser}: ${commentBody}`; + const taskDescription = extractTaskFromComment(commentBody); + inputs.taskDescription = taskDescription; + const tokens = (0, tokenizer_1.getTokenCount)(prompts.renderIssueAnalysis(inputs)); + if (tokens > options.heavyTokenLimits.requestTokens) { + await postIssueComment(issueNumber, `@${commentUser} The issue content is too large to process. Please simplify or split the issue.`); + return; + } + const [analysis] = await heavyBot.chat(prompts.renderIssueAnalysis(inputs), {}); + const response = formatIssueResponse(commentUser, analysis); + await postIssueComment(issueNumber, response); + info(`Successfully processed issue comment for issue #${issueNumber}`); +}; +exports.handleIssueComment = handleIssueComment; +function extractTaskFromComment(commentBody) { + const mentionPattern = /@prix\s*(.*)$/i; + const match = commentBody.match(mentionPattern); + return match ? match[1].trim() : commentBody; +} +async function postIssueComment(issueNumber, body) { + try { + await octokit_1.octokit.issues.createComment({ + owner: exports.repo.owner, + repo: exports.repo.repo, + issue_number: issueNumber, + body + }); + } + catch (error) { + warning(`Failed to post issue comment: ${error}`); + } +} +function formatIssueResponse(user, analysis) { + return `## @${user} Issue Analysis + +${analysis} + +--- + +*This analysis was generated by PRIX. To get a complete fix prompt for an IDE, ask me to generate the IDE prompt.*`; +} +//# sourceMappingURL=issue-handler.js.map \ No newline at end of file diff --git a/lib/src/issue-handler.js.map b/lib/src/issue-handler.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5aaec0cf2d0674b27a6a28a407d0049411bfe191 --- /dev/null +++ b/lib/src/issue-handler.js.map @@ -0,0 +1 @@ +{"version":3,"file":"issue-handler.js","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AS,mBAAmB,CAAC,IAAY,EAAE,QAAgB;IACzD,OAAO,OAAO,IAAI;;EAElB,QAAQ;;;;mHAIyG,CAAA;AACnH,CAAC"} \ No newline at end of file diff --git a/lib/src/limits.js b/lib/src/limits.js new file mode 100644 index 0000000000000000000000000000000000000000..121ea065daa5bcfcd7f95a26510f4fbbd0312f49 --- /dev/null +++ b/lib/src/limits.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TokenLimits = void 0; +class TokenLimits { + maxTokens; + requestTokens; + responseTokens; + knowledgeCutOff; + constructor(model = 'llama-3.1-8b-instant') { + this.knowledgeCutOff = '2023-12-01'; + // Default for modern large context models + this.maxTokens = 128000; + this.responseTokens = 16000; + if (model.includes('kimi-k2')) { + this.maxTokens = 256000; + this.responseTokens = 16000; + } + else if (model.includes('qwen') || model.includes('llama-4')) { + this.maxTokens = 128000; + this.responseTokens = 16000; + } + else if (model.includes('gpt-oss-120b')) { + this.maxTokens = 128000; + this.responseTokens = 16000; + } + else if (model.includes('3.2-11b')) { + this.maxTokens = 128000; + this.responseTokens = 16000; + } + else if (model.includes('llama3') || + model.includes('llama-3') || + model.includes('groq') || + model.includes('mixtral')) { + this.maxTokens = 128000; + this.responseTokens = 16000; + } + else { + this.maxTokens = 128000; + this.responseTokens = 4000; + } + // Provide some margin + this.requestTokens = this.maxTokens - this.responseTokens - 500; + } + string() { + return `max_tokens=${this.maxTokens}, request_tokens=${this.requestTokens}, response_tokens=${this.responseTokens}`; + } +} +exports.TokenLimits = TokenLimits; +//# sourceMappingURL=limits.js.map \ No newline at end of file diff --git a/lib/src/limits.js.map b/lib/src/limits.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d61ac79f5d4f28965071cf4a19732e00b3d8583c --- /dev/null +++ b/lib/src/limits.js.map @@ -0,0 +1 @@ +{"version":3,"file":"limits.js","sourceRoot":"","sources":["../../src/limits.ts"],"names":[],"mappings":";;;AAAA,MAAa,WAAW;IACtB,SAA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IAAI,CAAC,SAAS,GAAG,MAAM,CAAA;YACvB,IAAI,CAAC,cAAc,GAAG,IAAI,CAAA;QAC5B,CAAC;QAED,sBAAsB;QACtB,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,cAAc,GAAG,GAAG,CAAA;IACjE,CAAC;IAED,MAAM;QACJ,OAAO,cAAc,IAAI,CAAC,SAAS,oBAAoB,IAAI,CAAC,aAAa,qBAAqB,IAAI,CAAC,cAAc,EAAE,CAAA;IACrH,CAAC;CACF;AA7CD,kCA6CC"} \ No newline at end of file diff --git a/lib/src/local-context.js b/lib/src/local-context.js new file mode 100644 index 0000000000000000000000000000000000000000..ea77c28a150c963d6c72cdf0193ee0011d520c1b --- /dev/null +++ b/lib/src/local-context.js @@ -0,0 +1,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 review_1 = require("./review"); +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, review_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, review_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, review_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, review_1.extractPatternType)(currentFinding.message) + }); + } + return findings; + } +} +exports.LocalContextEngine = LocalContextEngine; +//# sourceMappingURL=local-context.js.map \ No newline at end of file diff --git a/lib/src/local-context.js.map b/lib/src/local-context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cf76c21a8ed39d66d633d7cb6d6d4fc123d86361 --- /dev/null +++ b/lib/src/local-context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"local-context.js","sourceRoot":"","sources":["../../src/local-context.ts"],"names":[],"mappings":";;;;;;AAAA,2BAA2C;AAC3C,iDAAsC;AAItC,qCAA+B;AAC/B,qCAAuD;AACvD,6CAAiD;AAGjD,sDAA4B;AAC5B,sEAAoC;AA4BpC,MAAa,kBAAkB;IACrB,KAAK,CAAU;IACf,OAAO,CAAK;IACZ,OAAO,GAAiC,IA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B,cAAc,CAAC,OAAO,GAAG,cAAc,CAAA;YACzC,CAAC;QACH,CAAC;QAED,IAAI,cAAc,IAAI,cAAc,CAAC,OAAO,EAAE,CAAC;YAC7C,MAAM,UAAU,GAAG,iCAAoB,CAAC,SAAS,CAC/C,cAAc,CAAC,UAAU,IAAI,EAAE,EAC/B,cAAc,CAAC,OAAO,EACtB,cAAc,CAAC,OAAO,CAAC,MAAM,EAC7B,IAAI,EACJ,cAAc,CAAC,QAAQ,EACvB,OAAO,EACP,OAAO,EACP,IAAA,2BAAkB,EAAC,cAAc,CAAC,OAAO,CAAC,EAC1C,QAAQ,CACT,CAAA;YAED,QAAQ,CAAC,IAAI,CAAC;gBACZ,QAAQ;gBACR,IAAI,EAAE,cAAc,CAAC,IAAI,IAAI,SAAS;gBACtC,OAAO,EAAE,cAAc,CAAC,OAAO,IAAI,OAAO;gBAC1C,QAAQ,EAAE,cAAc,CAAC,QAAQ,IAAI,OAAO;gBAC5C,IAAI,EAAE,cAAc,CAAC,IAAI,IAAI,SAAS;gBACtC,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC,IAAI,EAAE;gBACtC,UAAU,EAAE,UAAU,CAAC,KAAK;gBAC5B,UAAU,EAAE,cAAc,CAAC,UAAU;gBACrC,WAAW,EAAE,IAAA,2BAAkB,EAAC,cAAc,CAAC,OAAO,CAAC;aACxD,CAAC,CAAA;QACJ,CAAC;QAED,OAAO,QAAQ,CAAA;IACjB,CAAC;CACF;AA1UD,gDA0UC"} \ No newline at end of file diff --git a/lib/src/logger.js b/lib/src/logger.js new file mode 100644 index 0000000000000000000000000000000000000000..f4fc357c3cdf1a75dfb3c5dbea0eefb4c457fa03 --- /dev/null +++ b/lib/src/logger.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.logger = exports.setLogger = void 0; +class ConsoleLogger { + info(message) { + // eslint-disable-next-line no-console + console.log(message); + } + warn(message) { + // eslint-disable-next-line no-console + console.warn(message); + } + error(message) { + // eslint-disable-next-line no-console + console.error(message); + } + debug(message) { + // eslint-disable-next-line no-console + console.debug(message); + } +} +let activeLogger = new ConsoleLogger(); +const setLogger = (logger) => { + activeLogger = logger; +}; +exports.setLogger = setLogger; +const logger = () => activeLogger; +exports.logger = logger; +//# sourceMappingURL=logger.js.map \ No newline at end of file diff --git a/lib/src/logger.js.map b/lib/src/logger.js.map new file mode 100644 index 0000000000000000000000000000000000000000..07ba9bdb04a606eceb9bd5416b0a869a2009da7b --- /dev/null +++ b/lib/src/logger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logger.js","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":";;;AAOA,MAAM,aAAa;IACjB,IAAI,CAAC,OAAe;QAClB,sCAAsC;QACtC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;IACtB,CAAC;IACD,IAAI,CAAC,OAAe;QAClB,sCAAsC;QACtC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IACvB,CAAC;IACD,KAAK,CAAC,OAAe;QACnB,sCAAsC;QACtC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;IACxB,CAAC;IACD,KAAK,CAAC,OAAe;QACnB,sCAAsC;QACtC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;IACxB,CAAC;CACF;AAED,IAAI,YAAY,GAAW,IAAI,aAAa,EAAE,CAAA;AAEvC,MAAM,SAAS,GAAG,CAAC,MAAc,EAAQ,EAAE;IAChD,YAAY,GAAG,MAAM,CAAA;AACvB,CAAC,CAAA;AAFY,QAAA,SAAS,aAErB;AAEM,MAAM,MAAM,GAAG,GAAW,EAAE,CAAC,YAAY,CAAA;AAAnC,QAAA,MAAM,UAA6B"} \ No newline at end of file diff --git a/lib/src/octokit.js b/lib/src/octokit.js new file mode 100644 index 0000000000000000000000000000000000000000..bca148d29b51f09fb8b4b07256d114635cf7a62f --- /dev/null +++ b/lib/src/octokit.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.octokit = void 0; +exports.setOctokit = setOctokit; +const context_1 = require("./context"); +const warning = console.warn; +function createSafeOctokitFallback() { + const handler = { + get(_target, prop) { + warning(`Octokit accessed outside of context: ${String(prop)}`); + return () => { + throw new Error(`Octokit.${String(prop)} is not available outside of an isolated context. Use als.run() to wrap your code.`); + }; + } + }; + return new Proxy({}, handler); +} +const safeFallback = createSafeOctokitFallback(); +exports.octokit = new Proxy({}, { + get(target, prop) { + const context = context_1.als.getStore(); + if (!context || !context.octokit) { + warning(`Octokit accessed outside of an isolated context. Property: ${String(prop)}`); + return safeFallback[prop]; + } + return context.octokit[prop]; + } +}); +function setOctokit(newOctokit) { } +//# sourceMappingURL=octokit.js.map \ No newline at end of file diff --git a/lib/src/octokit.js.map b/lib/src/octokit.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e47adf28423996a675fb29f7f5213036afed8122 --- /dev/null +++ b/lib/src/octokit.js.map @@ -0,0 +1 @@ +{"version":3,"file":"octokit.js","sourceRoot":"","sources":["../../src/octokit.ts"],"names":[],"mappings":";;;AAsCA,gCAA8C;AArC9C,uCAA6B;AAE7B,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,CAAA;AAE5B,SAAS,yBAAyB;IAChC,MAAM,OAAO,GAAG;QACd,GAAG,CAAC,OAAY,EAAE,IAAY;YAC5B,OAAO,CAAC,wCAAwC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YAC/D,OAAO,GAAG,EAAE;gBACV,MAAM,IAAI,KAAK,CACb,WAAW,MAAM,CACf,IAAI,CACL,oFAAoF,CACtF,CAAA;YACH,CAAC,CAAA;QACH,CAAC;KACF,CAAA;IACD,OAAO,IAAI,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAA;AAC/B,CAAC;AAED,MAAM,YAAY,GAAG,yBAAyB,EAAE,CAAA;AAEnC,QAAA,OAAO,GAAG,IAAI,KAAK,CAAC,EAAa,EAAE;IAC9C,GAAG,CAAC,MAAM,EAAE,IAAI;QACd,MAAM,OAAO,GAAG,aAAG,CAAC,QAAQ,EAAE,CAAA;QAC9B,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;YACjC,OAAO,CACL,8DAA8D,MAAM,CAClE,IAAI,CACL,EAAE,CACJ,CAAA;YACD,OAAQ,YAAoB,CAAC,IAAI,CAAC,CAAA;QACpC,CAAC;QACD,OAAQ,OAAO,CAAC,OAAe,CAAC,IAAI,CAAC,CAAA;IACvC,CAAC;CACF,CAAC,CAAA;AAEF,SAAgB,UAAU,CAAC,UAAe,IAAG,CAAC"} \ No newline at end of file diff --git a/lib/src/options.js b/lib/src/options.js new file mode 100644 index 0000000000000000000000000000000000000000..4a570110a7b98a031c8bd25b5f04b99a9749fc8f --- /dev/null +++ b/lib/src/options.js @@ -0,0 +1,181 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AIOptions = exports.PathFilter = exports.Options = void 0; +const minimatch_1 = require("minimatch"); +const limits_1 = require("./limits"); +const info = console.log; +class Options { + debug; + disableReview; + disableReleaseNotes; + maxFiles; + reviewSimpleChanges; + reviewCommentLGTM; + pathFilters; + systemMessage; + lightModel; + heavyModel; + modelTemperature; + retries; + timeoutMS; + concurrencyLimit; + githubConcurrencyLimit; + lightTokenLimits; + heavyTokenLimits; + apiBaseUrl; + language; + createRemedyPR; + minimumSeverity; + minConfidence; + denseMode; + showImpactAnalysis; + static HEAVY_MODELS = [ + 'openai/gpt-oss-120b', + 'moonshotai/kimi-k2-instruct-0905', + 'qwen/qwen3-32b', + 'deepseek-r1-distill-llama-70b', + 'llama-3.3-70b-versatile', + 'openai/gpt-oss-20b', + 'meta-llama/llama-4-scout-17b-16e-instruct' + ]; + static LIGHT_MODELS = [ + 'llama-3.1-8b-instant', + 'groq/compound', + 'groq/compound-mini', + 'llama-3.2-11b-vision-preview' + ]; + static SECURITY_MODELS = [ + 'openai/gpt-oss-safeguard-20b', + 'meta-llama/llama-guard-4-12b', + 'meta-llama/llama-prompt-guard-2-86m', + 'meta-llama/llama-prompt-guard-2-22m' + ]; + constructor(debug, disableReview, disableReleaseNotes, maxFiles = '0', reviewSimpleChanges = false, reviewCommentLGTM = false, pathFilters = null, systemMessage = '', lightModel = 'llama-3.1-8b-instant', heavyModel = 'llama-3.3-70b-versatile', modelTemperature = '0.0', retries = '3', timeoutMS = '120000', concurrencyLimit = '6', githubConcurrencyLimit = '6', apiBaseUrl = 'https://api.groq.com/openai/v1', language = 'en-US', createRemedyPR = false, minimumSeverity = 'minor', minConfidence = '0', denseMode = 'false', showImpactAnalysis = 'true') { + this.debug = debug; + this.disableReview = disableReview; + this.disableReleaseNotes = disableReleaseNotes; + this.maxFiles = parseInt(maxFiles); + this.reviewSimpleChanges = reviewSimpleChanges; + this.reviewCommentLGTM = reviewCommentLGTM; + this.pathFilters = new PathFilter(pathFilters); + this.systemMessage = systemMessage; + this.lightModel = lightModel; + this.heavyModel = heavyModel; + this.modelTemperature = parseFloat(modelTemperature); + this.retries = parseInt(retries); + this.timeoutMS = parseInt(timeoutMS); + this.concurrencyLimit = parseInt(concurrencyLimit); + this.githubConcurrencyLimit = parseInt(githubConcurrencyLimit); + this.apiBaseUrl = apiBaseUrl; + this.language = language; + this.createRemedyPR = createRemedyPR; + this.minimumSeverity = minimumSeverity; + this.minConfidence = parseInt(minConfidence); + this.denseMode = denseMode === 'true'; + this.showImpactAnalysis = showImpactAnalysis === 'true'; + this.lightTokenLimits = new limits_1.TokenLimits(this.lightModel); + this.heavyTokenLimits = new limits_1.TokenLimits(this.heavyModel); + } + // print all options using core.info + print() { + info(`debug: ${this.debug}`); + info(`disable_review: ${this.disableReview}`); + info(`disable_release_notes: ${this.disableReleaseNotes}`); + info(`max_files: ${this.maxFiles}`); + info(`review_simple_changes: ${this.reviewSimpleChanges}`); + info(`review_comment_lgtm: ${this.reviewCommentLGTM}`); + info(`path_filters: ${this.pathFilters}`); + info(`system_message: ${this.systemMessage}`); + info(`light_model: ${this.lightModel}`); + info(`heavy_model: ${this.heavyModel}`); + info(`model_temperature: ${this.modelTemperature}`); + info(`retries: ${this.retries}`); + info(`timeout_ms: ${this.timeoutMS}`); + info(`concurrency_limit: ${this.concurrencyLimit}`); + info(`github_concurrency_limit: ${this.githubConcurrencyLimit}`); + info(`summary_token_limits: ${this.lightTokenLimits.string()}`); + info(`review_token_limits: ${this.heavyTokenLimits.string()}`); + info(`api_base_url: ${this.apiBaseUrl}`); + info(`language: ${this.language}`); + info(`create_remedy_pr: ${this.createRemedyPR}`); + } + checkPath(path) { + const ok = this.pathFilters.check(path); + info(`checking path: ${path} => ${ok}`); + return ok; + } + static SEVERITY_ORDER = [ + 'critical', + 'major', + 'minor', + 'info' + ]; + meetsMinimumSeverity(findingSeverity) { + const minIndex = Options.SEVERITY_ORDER.indexOf(this.minimumSeverity); + const findingIndex = Options.SEVERITY_ORDER.indexOf(findingSeverity); + return findingIndex >= minIndex; + } + meetsConfidenceThreshold(confidence) { + return confidence >= this.minConfidence; + } +} +exports.Options = Options; +class PathFilter { + rules; + constructor(rules = null) { + this.rules = []; + if (rules != null) { + for (const rule of rules) { + const trimmed = rule?.trim(); + if (trimmed) { + if (trimmed.startsWith('!')) { + this.rules.push([trimmed.substring(1).trim(), true]); + } + else { + this.rules.push([trimmed, false]); + } + } + } + } + } + check(path) { + if (this.rules.length === 0) { + return true; + } + let included = false; + let excluded = false; + let inclusionRuleExists = false; + for (const [rule, exclude] of this.rules) { + if ((0, minimatch_1.minimatch)(path, rule)) { + if (exclude) { + excluded = true; + } + else { + included = true; + } + } + if (!exclude) { + inclusionRuleExists = true; + } + } + return (!inclusionRuleExists || included) && !excluded; + } +} +exports.PathFilter = PathFilter; +class AIOptions { + model; + tokenLimits; + temperature; + constructor(model = 'llama-3.1-8b-instant', tokenLimits = null, temperature = 0.0) { + this.model = model; + this.temperature = temperature; + if (tokenLimits != null) { + this.tokenLimits = tokenLimits; + } + else { + this.tokenLimits = new limits_1.TokenLimits(model); + } + } +} +exports.AIOptions = AIOptions; +//# sourceMappingURL=options.js.map \ No newline at end of file diff --git a/lib/src/options.js.map b/lib/src/options.js.map new file mode 100644 index 0000000000000000000000000000000000000000..52c4e3ca5d883355bd07c70daeefe194e1d05832 --- /dev/null +++ b/lib/src/options.js.map @@ -0,0 +1 @@ +{"version":3,"file":"options.js","sourceRoot":"","sources":["../../src/options.ts"],"names":[],"mappings":";;;AAAA,yCAAmC;AACnC,qCAAoC;AACpC,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAA;AAIxB,MAAa,OAAO;IAClB,KAAK,CAAS;IACd,aAAa,CAAS;IACtB,mBAAmB,CAAS;IAC5B,QAAQ,CAAQ;IAChB,mBAAmB,CAAS;IAC5B,iBAAiB,CAAS;IAC1B,WAAW,CAAY;IACvB,aAAa,CAAQ;IACrB,UAAU,CAAQ;IAClB,UAAU,CAAQ;IAClB,gBAAgB,CAAQ;IACxB,OAAO,CAAQ;IACf,SAAS,CAAQ;IACjB,gBAAgB,CAAQ;IACxB,sBAAsB,CAAQ;IAC9B,gBAAgB,CAAa;IAC7B,gBAAgB,CAAa;IAC7B,UAAU,CAAQ;IAClB,QAAQ,CAAQ;IAChB,cAAc,CAAS;IACvB,eAAe,CAAe;IAC9B,aAAa,CAAQ;IACrB,SAAS,CAAS;IAClB,kBAAkB,CAAS;IAE3B,MAAM,CAAU,YAAY,GAAG;QAC7B,qBAAqB;QACrB,kCAAkC;QAClC,gBAAgB;QAChB,+BAA+B;QAC/B,yBAAyB;QACzB,oBAAoB;QACpB,2CAA2C;KAC5C,CAAA;IACD,MAAM,CAAU,YAAY,GAAG;QAC7B,sBAAsB;QACtB,eAAe;QACf,oBAAoB;QACpB,8BAA8B;KAC/B,CAAA;IACD,MAAM,CAAU,eAAe,GAAG;QAChC,8BAA8B;QAC9B,8BAA8B;QAC9B,qCAAqC;QACrC,qCAAqC;KACtC,CAAA;IAED,YACE,KAAc,EACd,aAAsB,EACtB,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N,QAAQ,GAAG,IAAI,CAAA;gBACjB,CAAC;YACH,CAAC;YACD,IAAI,CAAC,OAAO,EAAE,CAAC;gBACb,mBAAmB,GAAG,IAAI,CAAA;YAC5B,CAAC;QACH,CAAC;QAED,OAAO,CAAC,CAAC,mBAAmB,IAAI,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAA;IACxD,CAAC;CACF;AA3CD,gCA2CC;AAED,MAAa,SAAS;IACpB,KAAK,CAAQ;IACb,WAAW,CAAa;IACxB,WAAW,CAAQ;IAEnB,YACE,KAAK,GAAG,sBAAsB,EAC9B,cAAkC,IAAI,EACtC,WAAW,GAAG,GAAG;QAEjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;QAClB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;QAC9B,IAAI,WAAW,IAAI,IAAI,EAAE,CAAC;YACxB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;QAChC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,WAAW,GAAG,IAAI,oBAAW,CAAC,KAAK,CAAC,CAAA;QAC3C,CAAC;IACH,CAAC;CACF;AAlBD,8BAkBC"} \ No newline at end of file diff --git a/lib/src/prompts.js b/lib/src/prompts.js new file mode 100644 index 0000000000000000000000000000000000000000..a916aca40bef6355a8f3fbb1930c311b75b6d326 --- /dev/null +++ b/lib/src/prompts.js @@ -0,0 +1,159 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Prompts = void 0; +class Prompts { + summarize; + summarizeReleaseNotes; + summarizeFileDiff = `## GitHub PR Title +\`$title\` + +## Description +\`$description\` + +## Diff +\`\`\`diff +$file_diff +\`\`\` + +## Instructions +Succinctly summarize the diff within 100 words. +Include alterations to signatures, global data, and external interfaces. +`; + triageFileDiff = `Below the summary, triage as \`NEEDS_REVIEW\` or \`APPROVED\`: +- \`NEEDS_REVIEW\`: Any logic, function, or variable changes. +- \`APPROVED\`: Only typos, formatting, or documentation. +Format: [TRIAGE]: +Important: Do not justify triage or mention it in summary. +`; + summarizeChangesets = `Group and deduplicate the following changesets in this PR. +Respond with updated changesets using the same format. +Important: Provide ONLY the final summarized result. Do NOT include reasoning steps, "Step 1", "Step 2", or any other conversational filler. + +$raw_summary +`; + summarizePrefix = `Summary of changes: +\`\`\` +$raw_summary +\`\`\` +`; + summarizeShort = `Provide a concise, direct summary of changes and architectural impact. +- Focus strictly on PR facts. +- Architectural Summary: High-level overview of design changes. +- Max 500 words. No metadata, no reasoning steps, and no conversational filler. +`; + reviewFileDiff = `## PR: $title +## Description: +\`$description\` +## Summary: +\`$short_summary\` + +## Instructions +Review new hunks for substantive issues. Format comments starting with line range (e.g., "22-25:"). + +- **Categorization**: Start each comment with: \`[LEVEL] | [TYPE]\` (Critical, Major, Minor, Info | Security, Bug, Performance, Style, Optimization). +- **Consequence**: Briefly explain why this matters and the worst-case production failure. +- **Fix**: Combine audit note and code fix into one comment. +- **Suggestion**: Use GitHub suggestions: \\\`\\\`\\\`suggestion [FIXED_CODE] \\\`\\\`\\\`. +- **Confidence**: Score 0-100% at the end. Only show findings with confidence >= 60%. +- If no issues: Respond ONLY with \`LGTM!\`. + +## Changes in $filename: +$patches +`; + comment = `Reply to this instruction in the context of the PR. + +## PR: $title +## Description: +\`$description\` +## Summary: +\`$short_summary\` + +## Instructions +Reply directly to the comment below. Begin with "@user". + +## New Comment +\`\`\` +$comment +\`\`\` + +## Context (Diff) +\`\`\`diff +$diff +\`\`\` +`; + constructor(summarize = '', summarizeReleaseNotes = '') { + this.summarize = summarize; + this.summarizeReleaseNotes = summarizeReleaseNotes; + } + renderSummarizeFileDiff(inputs, reviewSimpleChanges) { + let prompt = this.summarizeFileDiff; + if (reviewSimpleChanges === false) { + prompt += this.triageFileDiff; + } + return inputs.render(prompt); + } + renderSummarizeChangesets(inputs) { + return inputs.render(this.summarizeChangesets); + } + renderSummarize(inputs) { + const prompt = this.summarizePrefix + this.summarize; + return inputs.render(prompt); + } + renderSummarizeShort(inputs) { + const prompt = this.summarizePrefix + this.summarizeShort; + return inputs.render(prompt); + } + renderSummarizeReleaseNotes(inputs) { + const prompt = this.summarizePrefix + this.summarizeReleaseNotes; + return inputs.render(prompt); + } + renderComment(inputs) { + return inputs.render(this.comment); + } + renderReviewFileDiff(inputs) { + return inputs.render(this.reviewFileDiff); + } + fixSuggestion = `The code suggestion for \`$filename\` failed CI: +\`\`\` +$suggestion +\`\`\` +CI Error: $error +Correct the suggestion block. Respond ONLY with the fixed block. +`; + renderFixSuggestion(inputs, suggestion, error) { + const ins = inputs.clone(); + ins.suggestion = suggestion; + ins.error = error; + return ins.render(this.fixSuggestion); + } + issueAnalysis = `## GitHub Issue +Title: $title + +Description: +$description + +## Task Requested +$task_description + +## Instructions +You are PRIX, an expert software engineering assistant. Analyze the issue above and provide: + +1. **Problem Summary**: A clear, concise description of the issue (2-3 sentences) + +2. **Root Cause Analysis**: Identify potential root causes based on the description + +3. **Fix Plan**: A numbered list of steps to fix this issue + +4. **IDE Prompt**: A complete, detailed prompt that could be given to an AI IDE or agent to fix this issue. This prompt should: + - Clearly describe the problem + - Include relevant context from the issue + - Specify what a successful fix looks like + - Be detailed enough for an autonomous agent to implement + +Format your response clearly with headers for each section.`; + renderIssueAnalysis(inputs) { + return inputs.render(this.issueAnalysis); + } +} +exports.Prompts = Prompts; +//# sourceMappingURL=prompts.js.map \ No newline at end of file diff --git a/lib/src/prompts.js.map b/lib/src/prompts.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d35e9dd62d70910f6b5e998c7460e3127daac333 --- /dev/null +++ b/lib/src/prompts.js.map @@ -0,0 +1 @@ +{"version":3,"file":"prompts.js","sourceRoot":"","sources":["../../src/prompts.ts"],"names":[],"mappings":";;;AAEA,MAAa,OAAO;IAClB,SAAS,CAAQ;IACjB,qBAAqB,CAAQ;IAE7B,iBAAiB,GAAG;;;;;;;;;;;;;;CAcrB,CAAA;IAEC,cAAc,GAAG;;;;;CAKlB,CAAA;IAEC,mBAAmB,GAAG;;;;;CAKvB,CA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MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IACpC,CAAC;IAED,oBAAoB,CAAC,MAAc;QACjC,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAA;IAC3C,CAAC;IAED,aAAa,GAAG;;;;;;CAMjB,CAAA;IAEC,mBAAmB,CACjB,MAAc,EACd,UAAkB,EAClB,KAAa;QAEb,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,EAAE,CAAA;QAC1B,GAAG,CAAC,UAAU,GAAG,UAAU,CAAA;QAC3B,GAAG,CAAC,KAAK,GAAG,KAAK,CAAA;QACjB,OAAO,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,CAAA;IACvC,CAAC;IAED,aAAa,GAAG;;;;;;;;;;;;;;;;;;;;;;;;4DAwB0C,CAAA;IAE1D,mBAAmB,CAAC,MAAc;QAChC,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,CAAA;IAC1C,CAAC;CACF;AAnLD,0BAmLC"} \ No newline at end of file diff --git a/lib/src/review-comment.js b/lib/src/review-comment.js new file mode 100644 index 0000000000000000000000000000000000000000..47fb221f8b3623c09f8b2db7f5968a07ea3fcd7f --- /dev/null +++ b/lib/src/review-comment.js @@ -0,0 +1,170 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.run = exports.handleReviewComment = exports.repo = exports.context = void 0; +// Removed @actions imports for Probot migration +const commenter_1 = require("./commenter"); +const inputs_1 = require("./inputs"); +const options_1 = require("./options"); +const octokit_1 = require("./octokit"); +const bot_1 = require("./bot"); +const tokenizer_1 = require("./tokenizer"); +const context_1 = require("./context"); +let info = console.log; +let warning = console.warn; +exports.context = new Proxy({}, { + get(target, prop) { + return (context_1.als.getStore()?.probotContext)[prop]; + } +}); +exports.repo = new Proxy({}, { + get(target, prop) { + return (context_1.als.getStore()?.repo)[prop]; + } +}); +const ASK_BOT = '@prix'; +const handleReviewComment = async (heavyBot, options, prompts) => { + const commenter = new commenter_1.Commenter(); + const inputs = new inputs_1.Inputs(); + if (exports.context.name !== 'pull_request_review_comment') { + warning(`Skipped: ${exports.context.name} is not a pull_request_review_comment event`); + return; + } + if (!exports.context.payload) { + warning(`Skipped: ${exports.context.name} event is missing payload`); + return; + } + const comment = exports.context.payload.comment; + if (comment == null) { + warning(`Skipped: ${exports.context.name} event is missing comment`); + return; + } + if (exports.context.payload.pull_request == null || + exports.context.payload.repository == null) { + warning(`Skipped: ${exports.context.name} event is missing pull_request`); + return; + } + inputs.title = exports.context.payload.pull_request.title; + if (exports.context.payload.pull_request.body) { + inputs.description = commenter.getDescription(exports.context.payload.pull_request.body); + } + // check if the comment was created and not edited or deleted + if (exports.context.payload.action !== 'created') { + warning(`Skipped: ${exports.context.name} event is not created`); + return; + } + // Check if the comment is not from the bot itself + if (!comment.body.includes(commenter_1.COMMENT_TAG) && + !comment.body.includes(commenter_1.COMMENT_REPLY_TAG)) { + const pullNumber = exports.context.payload.pull_request.number; + inputs.comment = `${comment.user.login}: ${comment.body}`; + inputs.diff = comment.diff_hunk; + inputs.filename = comment.path; + const { chain: commentChain, topLevelComment } = await commenter.getCommentChain(pullNumber, comment); + if (!topLevelComment) { + warning('Failed to find the top-level comment to reply to'); + return; + } + inputs.commentChain = commentChain; + // check whether this chain contains replies from the bot + if (commentChain.includes(commenter_1.COMMENT_TAG) || + commentChain.includes(commenter_1.COMMENT_REPLY_TAG) || + comment.body.includes(ASK_BOT)) { + let fileDiff = ''; + try { + // get diff for this file by comparing the base and head commits + const diffAll = await octokit_1.octokit.repos.compareCommits({ + owner: exports.repo.owner, + repo: exports.repo.repo, + base: exports.context.payload.pull_request.base.sha, + head: exports.context.payload.pull_request.head.sha + }); + if (diffAll.data) { + const files = diffAll.data.files; + if (files != null) { + const file = files.find(f => f.filename === comment.path); + if (file != null && file.patch) { + fileDiff = file.patch; + } + } + } + } + catch (error) { + warning(`Failed to get file diff: ${error}, skipping.`); + } + // use file diff if no diff was found in the comment + if (inputs.diff.length === 0) { + if (fileDiff.length > 0) { + inputs.diff = fileDiff; + fileDiff = ''; + } + else { + await commenter.reviewCommentReply(pullNumber, topLevelComment, 'Cannot reply to this comment as diff could not be found.'); + return; + } + } + // get tokens so far + let tokens = (0, tokenizer_1.getTokenCount)(prompts.renderComment(inputs)); + if (tokens > options.heavyTokenLimits.requestTokens) { + await commenter.reviewCommentReply(pullNumber, topLevelComment, 'Cannot reply to this comment as diff being commented is too large and exceeds the token limit.'); + return; + } + // pack file diff into the inputs if they are not too long + if (fileDiff.length > 0) { + // count occurrences of $file_diff in prompt + const fileDiffCount = prompts.comment.split('$file_diff').length - 1; + const fileDiffTokens = (0, tokenizer_1.getTokenCount)(fileDiff); + if (fileDiffCount > 0 && + tokens + fileDiffTokens * fileDiffCount <= + options.heavyTokenLimits.requestTokens) { + tokens += fileDiffTokens * fileDiffCount; + inputs.fileDiff = fileDiff; + } + } + // get summary of the PR + const summary = await commenter.findCommentWithTag(commenter_1.SUMMARIZE_TAG, pullNumber); + if (summary) { + // pack short summary into the inputs if it is not too long + const shortSummary = commenter.getShortSummary(summary.body); + const shortSummaryTokens = (0, tokenizer_1.getTokenCount)(shortSummary); + if (tokens + shortSummaryTokens <= + options.heavyTokenLimits.requestTokens) { + tokens += shortSummaryTokens; + inputs.shortSummary = shortSummary; + } + } + const [reply] = await heavyBot.chat(prompts.renderComment(inputs), {}); + await commenter.reviewCommentReply(pullNumber, topLevelComment, reply); + } + } + else { + info(`Skipped: ${exports.context.name} event is from the bot itself`); + } +}; +exports.handleReviewComment = handleReviewComment; +/** + * PRIX entry point for Review Comments (Chat with Bot). + * Adapts the action logic to Probot context. + */ +const run = async (probotContext, options, prompts) => { + // Setup logger shim + info = (msg) => probotContext.log.info(msg); + warning = (msg) => probotContext.log.warn(msg); + // context and repo are now handled via Proxy + AsyncLocalStorage + (0, commenter_1.setCommenterContext)(probotContext); + // Setup octokit shim + (0, octokit_1.setOctokit)(probotContext.octokit); + // Initialize heavy bot (used for comments) + const heavyAIOptions = new options_1.AIOptions(options.heavyModel, options.heavyTokenLimits); + const heavyBot = new bot_1.Bot(options, heavyAIOptions); + probotContext.log.info(`PRIX Chat starting for Comment in PR #${probotContext.payload.pull_request.number}`); + try { + await (0, exports.handleReviewComment)(heavyBot, options, prompts); + probotContext.log.info(`PRIX Chat completed for PR #${probotContext.payload.pull_request.number}`); + } + catch (err) { + probotContext.log.error(`PRIX Chat failed: ${err.message}`); + throw err; + } +}; +exports.run = run; +//# sourceMappingURL=review-comment.js.map \ No newline at end of file diff --git a/lib/src/review-comment.js.map b/lib/src/review-comment.js.map new file mode 100644 index 0000000000000000000000000000000000000000..91ea7d0821245681c048ae31ae2bcc60266bfb77 --- /dev/null +++ b/lib/src/review-comment.js.map @@ -0,0 +1 @@ +{"version":3,"file":"review-comment.js","sourceRoot":"","sources":["../../src/review-comment.ts"],"names":[],"mappings":";;;AAAA,gDAAgD;AAChD,2CAMoB;AACpB,qCAA+B;AAC/B,uCAAiD;AACjD,uCAA6C;AAC7C,+BAAyB;AAGzB,2CAAyC;AAEzC,uCAA6B;AAE7B,IAAI,IAAI,GAAG,OAAO,CAAC,GAAG,CAAA;AACtB,IAAI,OAAO,GAAG,OAAO,CAAC,IAAI,CAAA;AAEb,QAAA,OAAO,GAAQ,IAAI,KAAK,CAAC,EAAS,EAAE;IAC/C,GAAG,CAAC,MAAM,EAAE,IAAI;QACd,OAAO,CAAC,aAAG,CAAC,QAAQ,EAAE,EAAE,aAAqB,CAAA,CAAC,IAAI,CAAC,CAAA;IACrD,CAAC;CACF,CAAC,CAAA;AAEW,QAAA,IAAI,GAAQ,IAAI,KAAK,CAAC,EAAS,EAAE;IAC5C,GAAG,CAAC,MAAM,EAAE,IAAI;QACd,OAAO,CAAC,aAAG,CAAC,QAAQ,EAAE,EAAE,IAAY,CAAA,CAAC,IAAI,CAAC,CAAA;IAC5C,CAAC;CACF,CAAC,CAAA;AAEF,MAAM,OAAO,GA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,CAAA;AAnCY,QAAA,GAAG,OAmCf"} \ No newline at end of file diff --git a/lib/src/review.js b/lib/src/review.js new file mode 100644 index 0000000000000000000000000000000000000000..7bb76eaed6fca4a2af7b9a0138e34435ad83face --- /dev/null +++ b/lib/src/review.js @@ -0,0 +1,1495 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.run = exports.codeReview = exports.repo = exports.context = void 0; +exports.extractPatternType = extractPatternType; +const utils_1 = require("./utils"); +const ts_morph_1 = require("ts-morph"); +const p_limit_1 = __importDefault(require("p-limit")); +const bot_1 = require("./bot"); +const commenter_1 = require("./commenter"); +const inputs_1 = require("./inputs"); +const options_1 = require("./options"); +const octokit_1 = require("./octokit"); +const tokenizer_1 = require("./tokenizer"); +const context_1 = require("./context"); +const symbol_graph_1 = require("./symbol-graph"); +const semantic_search_1 = require("./semantic-search"); +const confidence_1 = require("./confidence"); +const test_generator_1 = require("./test-generator"); +const fix_verifier_1 = require("./fix-verifier"); +let error = console.error; +let info = console.log; +let warning = console.warn; +exports.context = new Proxy({}, { + get(target, prop) { + return (context_1.als.getStore()?.probotContext)[prop]; + } +}); +exports.repo = new Proxy({}, { + get(target, prop) { + return (context_1.als.getStore()?.repo)[prop]; + } +}); +const ignoreKeyword = '@ai-pr-reviewer: ignore'; +const codeReview = async (lightBot, heavyBot, options, prompts) => { + const commenter = new commenter_1.Commenter(); + const project = new ts_morph_1.Project(); + // Initialize shared context engine once at the start + try { + const workingDir = (0, utils_1.prixExec)('pwd', { encoding: 'utf8' }).trim(); + await symbol_graph_1.unifiedContextEngine.initialize(workingDir); + } + catch (e) { + info(`Context engine initialization failed: ${e}`); + } + const aiConcurrencyLimit = (0, p_limit_1.default)(options.concurrencyLimit); + const githubConcurrencyLimit = (0, p_limit_1.default)(options.githubConcurrencyLimit); + if (exports.context.name !== 'pull_request' && + exports.context.name !== 'pull_request_target') { + warning(`Skipped: current event is ${exports.context.name}, only support pull_request event`); + return; + } + if (exports.context.payload.pull_request == null) { + warning('Skipped: context.payload.pull_request is null'); + return; + } + // Skip audit for PRs opened by bots to prevent recursive loops + // Also skip if the branch name indicates it's an AI remedy branch + const prAuthor = exports.context.payload.pull_request.user.type; + const branchName = exports.context.payload.pull_request.head.ref; + if (prAuthor === 'Bot' || + branchName.startsWith('ai-remedy/') || + branchName.startsWith('github-actions[bot]')) { + info(`Skipping audit: PR author type=${prAuthor}, branch=${branchName}`); + return; + } + const inputs = new inputs_1.Inputs(); + inputs.title = exports.context.payload.pull_request.title; + if (exports.context.payload.pull_request.body != null) { + inputs.description = commenter.getDescription(exports.context.payload.pull_request.body); + } + // if the description contains ignore_keyword, skip + if (inputs.description.includes(ignoreKeyword)) { + info('Skipped: description contains ignore_keyword'); + return; + } + // ensure system message is included in inputs + inputs.systemMessage = options.systemMessage; + // get SUMMARIZE_TAG message + const existingSummarizeCmt = await commenter.findCommentWithTag(commenter_1.SUMMARIZE_TAG, exports.context.payload.pull_request.number); + let existingCommitIdsBlock = ''; + let existingSummarizeCmtBody = ''; + if (existingSummarizeCmt != null) { + existingSummarizeCmtBody = existingSummarizeCmt.body; + inputs.rawSummary = commenter.getRawSummary(existingSummarizeCmtBody); + inputs.shortSummary = commenter.getShortSummary(existingSummarizeCmtBody); + existingCommitIdsBlock = commenter.getReviewedCommitIdsBlock(existingSummarizeCmtBody); + } + const allCommitIds = await commenter.getAllCommitIds(); + // find highest reviewed commit id + let highestReviewedCommitId = ''; + if (existingCommitIdsBlock !== '') { + highestReviewedCommitId = commenter.getHighestReviewedCommitId(allCommitIds, commenter.getReviewedCommitIds(existingCommitIdsBlock)); + } + if (highestReviewedCommitId === '' || + highestReviewedCommitId === exports.context.payload.pull_request.head.sha) { + info(`Will review from the base commit: ${exports.context.payload.pull_request.base.sha}`); + highestReviewedCommitId = exports.context.payload.pull_request.base.sha; + } + else { + info(`Will review from commit: ${highestReviewedCommitId}`); + } + // Fetch the diff between the highest reviewed commit and the latest commit of the PR branch + const incrementalDiff = await octokit_1.octokit.repos.compareCommits({ + owner: exports.repo.owner, + repo: exports.repo.repo, + base: highestReviewedCommitId, + head: exports.context.payload.pull_request.head.sha + }); + // Fetch the diff between the target branch's base commit and the latest commit of the PR branch + const targetBranchDiff = await octokit_1.octokit.repos.compareCommits({ + owner: exports.repo.owner, + repo: exports.repo.repo, + base: exports.context.payload.pull_request.base.sha, + head: exports.context.payload.pull_request.head.sha + }); + const incrementalFiles = incrementalDiff.data.files; + const targetBranchFiles = targetBranchDiff.data.files; + if (incrementalFiles == null || targetBranchFiles == null) { + warning('Skipped: files data is missing'); + return; + } + // Filter out any file that is changed compared to the incremental changes + const files = targetBranchFiles.filter(targetBranchFile => incrementalFiles.some(incrementalFile => incrementalFile.filename === targetBranchFile.filename)); + if (files.length === 0) { + warning('Skipped: files is null'); + return; + } + // skip files if they are filtered out + const filterSelectedFiles = []; + const filterIgnoredFiles = []; + for (const file of files) { + if (!options.checkPath(file.filename)) { + info(`skip for excluded path: ${file.filename}`); + filterIgnoredFiles.push(file); + } + else { + filterSelectedFiles.push(file); + } + } + if (filterSelectedFiles.length === 0) { + warning('Skipped: filterSelectedFiles is null'); + return; + } + const commits = incrementalDiff.data.commits; + if (commits.length === 0) { + warning('Skipped: commits is null'); + return; + } + // find hunks to review + const filteredFiles = await Promise.all(filterSelectedFiles.map(file => githubConcurrencyLimit(async () => { + // retrieve file contents + let fileContent = ''; + if (exports.context.payload.pull_request == null) { + warning('Skipped: context.payload.pull_request is null'); + return null; + } + try { + const contents = await octokit_1.octokit.repos.getContent({ + owner: exports.repo.owner, + repo: exports.repo.repo, + path: file.filename, + ref: exports.context.payload.pull_request.base.sha + }); + if (contents.data != null) { + if (!Array.isArray(contents.data)) { + if (contents.data.type === 'file' && + contents.data.content != null) { + fileContent = Buffer.from(contents.data.content, 'base64').toString(); + } + } + } + } + catch (e) { + warning(`Failed to get file contents: ${e}. This is OK if it's a new file.`); + } + let fileDiff = ''; + if (file.patch != null) { + fileDiff = file.patch; + } + const patches = []; + for (const patch of splitPatch(file.patch)) { + const patchLines = patchStartEndLine(patch); + if (patchLines == null) { + continue; + } + const hunks = parsePatch(patch); + if (hunks == null) { + continue; + } + const hunksStr = ` +---new_hunk--- +\`\`\` +${hunks.newHunk} +\`\`\` + +---old_hunk--- +\`\`\` +${hunks.oldHunk} +\`\`\` +`; + patches.push([ + patchLines.newHunk.startLine, + patchLines.newHunk.endLine, + hunksStr + ]); + } + if (patches.length > 0) { + return [file.filename, fileContent, fileDiff, patches]; + } + else { + return null; + } + }))); + // Filter out any null results + const filesAndChanges = filteredFiles.filter(file => file !== null); + if (filesAndChanges.length === 0) { + error('Skipped: no files to review'); + return; + } + let statusMsg = `

+Commits +Files that changed from the base of the PR and between ${highestReviewedCommitId} and ${exports.context.payload.pull_request.head.sha} commits. +
+${filesAndChanges.length > 0 + ? ` +
+Files selected (${filesAndChanges.length}) + +* ${filesAndChanges + .map(([filename, , , patches]) => `${filename} (${patches.length})`) + .join('\n* ')} +
+` + : ''} +${filterIgnoredFiles.length > 0 + ? ` +
+Files ignored due to filter (${filterIgnoredFiles.length}) + +* ${filterIgnoredFiles.map(file => file.filename).join('\n* ')} + +
+` + : ''} +`; + const summariesFailed = []; + const doSummary = async (filename, fileContent, fileDiff) => { + info(`summarize: ${filename}`); + const ins = inputs.clone(); + if (fileDiff.length === 0) { + warning(`summarize: file_diff is empty, skip ${filename}`); + summariesFailed.push(`${filename} (empty diff)`); + return null; + } + ins.filename = filename; + ins.fileDiff = fileDiff; + // Architectural Guard: Check for architecture rules + let archRules = ''; + try { + const fs = require('fs'); + if (fs.existsSync('clean-architecture.md')) { + archRules = fs.readFileSync('clean-architecture.md', 'utf8'); + } + else if (fs.existsSync('arch-rules.md')) { + archRules = fs.readFileSync('arch-rules.md', 'utf8'); + } + } + catch (e) { + info(`Failed to read architectural rules: ${e}`); + } + if (archRules !== '') { + ins.description += `\n\n### Architectural Rules\n${archRules}`; + } + // render prompt based on inputs so far + const summarizePrompt = prompts.renderSummarizeFileDiff(ins, options.reviewSimpleChanges); + const tokens = (0, tokenizer_1.getTokenCount)(summarizePrompt); + if (tokens > options.lightTokenLimits.requestTokens) { + info(`summarize: diff tokens exceeds limit, skip ${filename}`); + summariesFailed.push(`${filename} (diff tokens exceeds limit)`); + return null; + } + // summarize content + try { + // Before calling AI, check if it's just comments/docs + const isDocumentationOnly = checkIfDocumentationOnly(fileDiff); + if (isDocumentationOnly && options.reviewSimpleChanges === false) { + info(`summarize: skipping review for documentation-only change: ${filename}`); + return [filename, 'Documentation/Comment changes only.', false]; + } + const [summarizeResp] = await lightBot.chat(summarizePrompt, {}); + if (summarizeResp === '') { + info('summarize: nothing obtained from AI'); + summariesFailed.push(`${filename} (nothing obtained from AI)`); + return null; + } + else { + if (options.reviewSimpleChanges === false) { + // parse the comment to look for triage classification + // Format is : [TRIAGE]: + // if the change needs review return true, else false + const triageRegex = /\[TRIAGE\]:\s*(NEEDS_REVIEW|APPROVED)/; + const triageMatch = summarizeResp.match(triageRegex); + if (triageMatch != null) { + const triage = triageMatch[1]; + const needsReview = triage === 'NEEDS_REVIEW'; + // remove this line from the comment + const summary = summarizeResp.replace(triageRegex, '').trim(); + info(`filename: ${filename}, triage: ${triage}`); + return [filename, summary, needsReview]; + } + } + return [filename, summarizeResp, true]; + } + } + catch (e) { + warning(`summarize: error from AI: ${e}`); + summariesFailed.push(`${filename} (error from AI: ${e})})`); + return null; + } + }; + const summaryPromises = []; + const skippedFiles = []; + for (const [filename, fileContent, fileDiff] of filesAndChanges) { + if (options.maxFiles <= 0 || summaryPromises.length < options.maxFiles) { + summaryPromises.push(aiConcurrencyLimit(async () => await doSummary(filename, fileContent, fileDiff))); + } + else { + skippedFiles.push(filename); + } + } + const summaries = (await Promise.all(summaryPromises)).filter(summary => summary !== null); + if (summaries.length > 0) { + const batchSize = 10; + // join summaries into one in the batches of batchSize + // and ask the bot to summarize the summaries + for (let i = 0; i < summaries.length; i += batchSize) { + const summariesBatch = summaries.slice(i, i + batchSize); + for (const [filename, summary] of summariesBatch) { + inputs.rawSummary += `--- +${filename}: ${summary} +`; + } + // ask AI to summarize the summaries + const [summarizeResp] = await heavyBot.chat(prompts.renderSummarizeChangesets(inputs), {}); + if (summarizeResp === '') { + warning('summarize: nothing obtained from AI'); + } + else { + inputs.rawSummary = summarizeResp; + } + } + } + // Generate PR Impact Map early to feed into summary + const impactMap = await generateImpactMap(filesAndChanges, project); + inputs.description += `\n\n### Downstream Impact Analysis\n${impactMap}`; + // Semantic Bug Search: Find similar historical bugs + let similarBugsWarning = ''; + try { + const allChangedCode = filesAndChanges + .map(([filename, , fileDiff]) => `${filename}\n${fileDiff}`) + .join('\n\n'); + const similarBugs = await semantic_search_1.semanticBugSearch.searchSimilarBugs(allChangedCode, filesAndChanges.map(([f]) => f).join(','), exports.repo.owner, exports.repo.repo, heavyBot); + if (similarBugs.length > 0) { + similarBugsWarning = + semantic_search_1.semanticBugSearch.formatSimilarBugWarning(similarBugs); + inputs.description += similarBugsWarning; + } + } + catch (e) { + info(`Semantic bug search skipped: ${e}`); + } + // final summary + const [summarizeFinalResponse] = await heavyBot.chat(prompts.renderSummarize(inputs), {}); + if (summarizeFinalResponse === '') { + info('summarize: nothing obtained from AI'); + } + // generate a short summary as well + const [summarizeShortResponse] = await heavyBot.chat(prompts.renderSummarizeShort(inputs), {}); + inputs.shortSummary = summarizeShortResponse; + // Build the consolidated technical report + const technicalReport = ` +
+๐Ÿ› ๏ธ PRIX Technical Audit Report + +### Summary +${summarizeFinalResponse} + +### PR Impact Map +${impactMap} + +### Architectural Impact +${inputs.shortSummary} + +${commenter_1.SHORT_SUMMARY_START_TAG} +${inputs.shortSummary} +${commenter_1.SHORT_SUMMARY_END_TAG} + +--- +*Generated by PRIX AI Auditor* +
+`; + // Update PR Description with Release Notes + Technical Report + if (options.disableReleaseNotes === false) { + const [releaseNotesResponse] = await heavyBot.chat(prompts.renderSummarizeReleaseNotes(inputs), {}); + if (releaseNotesResponse !== '') { + let message = '### Summary by AI PR Reviewer\n\n'; + message += releaseNotesResponse; + message += `\n\n${technicalReport}`; + try { + await commenter.updateDescription(exports.context.payload.pull_request.number, message); + } + catch (e) { + warning(`Failed to update PR description: ${e.message}`); + } + } + } + // We no longer post a separate SUMMARIZE_TAG comment to reduce noise. + // Instead, everything is consolidated in the PR description above. + statusMsg += ` +${skippedFiles.length > 0 + ? ` +
+Files not processed due to max files limit (${skippedFiles.length}) + +* ${skippedFiles.join('\n* ')} + +
+` + : ''} +${summariesFailed.length > 0 + ? ` +
+Files not summarized due to errors (${summariesFailed.length}) + +* ${summariesFailed.join('\n* ')} + +
+` + : ''} +`; + const verifiedSuggestions = []; + if (!options.disableReview) { + const filesAndChangesReview = filesAndChanges.filter(([filename]) => { + const needsReview = summaries.find(([summaryFilename]) => summaryFilename === filename)?.[2] ?? true; + return needsReview; + }); + const reviewsSkipped = filesAndChanges + .filter(([filename]) => !filesAndChangesReview.some(([reviewFilename]) => reviewFilename === filename)) + .map(([filename]) => filename); + // failed reviews array + const reviewsFailed = []; + let lgtmCount = 0; + let reviewCount = 0; + const severityCounts = { critical: 0, major: 0, minor: 0, info: 0 }; + const confidenceSum = { total: 0, count: 0 }; + const doReview = async (filename, fileContent, patches, project, verifiedSuggestions, severityCounts, confidenceStats) => { + info(`reviewing ${filename}`); + // make a copy of inputs + const ins = inputs.clone(); + ins.filename = filename; + // Architectural Guard: Check for architecture rules + let archRules = ''; + try { + const fs = require('fs'); + if (fs.existsSync('clean-architecture.md')) { + archRules = fs.readFileSync('clean-architecture.md', 'utf8'); + } + else if (fs.existsSync('arch-rules.md')) { + archRules = fs.readFileSync('arch-rules.md', 'utf8'); + } + } + catch (e) { + info(`Failed to read architectural rules: ${e}`); + } + if (archRules !== '') { + const trimmedRules = archRules.length > 2000 + ? `${archRules.substring(0, 2000)}\n... [Rules truncated for token efficiency]` + : archRules; + ins.description += `\n\n### Architectural Rules\n${trimmedRules}`; + } + // Get context for exported symbols in this file + const usages = await findUsages(filename, fileContent, project); + if (usages !== '') { + ins.description += `\n\n### Usage Context for ${filename}\n\`\`\`text\n${usages}\n\`\`\``; + } + // Unified Context Engine: Use pre-initialized shared engine + try { + const symbolKey = `${filename}:*`; + const symbolContext = symbol_graph_1.unifiedContextEngine.getContextForSymbol(symbolKey); + const downstream = symbol_graph_1.unifiedContextEngine.getDownstreamImpact(`${filename}:*`); + if (symbolContext) { + ins.description += `\n\n### Unified Symbol Graph Context\n\`\`\`text\n${symbolContext}\n\`\`\`\``; + } + if (downstream.length > 0) { + ins.description += `\n\n### Transitive Downstream Impact (${downstream.length} files)\n`; + for (const dep of downstream.slice(0, 10)) { + ins.description += `- \`${dep}\`\n`; + } + if (downstream.length > 10) { + ins.description += `- ... and ${downstream.length - 10} more\n`; + } + } + } + catch (e) { + info(`Unified context engine skipped: ${e}`); + } + // Architectural Violation Detection + try { + const changedFileNames = filesAndChanges.map(([f]) => f); + const archLayers = symbol_graph_1.unifiedContextEngine.inferArchitecturalLayers(); + const violations = symbol_graph_1.unifiedContextEngine.detectArchitecturalViolations(changedFileNames, archLayers); + if (violations.length > 0) { + ins.description += `\n\n### ๐Ÿ›๏ธ Architectural Violations Detected\n`; + for (const v of violations.slice(0, 5)) { + const icon = v.severity === 'critical' + ? '๐Ÿ”ด' + : v.severity === 'major' + ? '๐ŸŸ ' + : '๐ŸŸก'; + ins.description += `\n${icon} **${v.fromLayer} โ†’ ${v.toLayer}**\n`; + ins.description += ` - ${v.description}\n`; + ins.description += ` - From: \`${v.from}\`\n`; + ins.description += ` - To: \`${v.to}\`\n`; + } + if (violations.length > 5) { + ins.description += `\n *... and ${violations.length - 5} more violations*\n`; + } + } + } + catch (e) { + info(`Architectural violation detection skipped: ${e}`); + } + // calculate tokens based on inputs so far + let tokens = (0, tokenizer_1.getTokenCount)(prompts.renderReviewFileDiff(ins)); + // loop to calculate total patch tokens + let patchesToPack = 0; + for (const [, , patch] of patches) { + const patchTokens = (0, tokenizer_1.getTokenCount)(patch); + if (tokens + patchTokens > options.heavyTokenLimits.requestTokens) { + info(`only packing ${patchesToPack} / ${patches.length} patches, tokens: ${tokens} / ${options.heavyTokenLimits.requestTokens}`); + break; + } + tokens += patchTokens; + patchesToPack += 1; + } + let patchesPacked = 0; + for (const [startLine, endLine, patch] of patches) { + if (exports.context.payload.pull_request == null) { + warning('No pull request found, skipping.'); + continue; + } + // see if we can pack more patches into this request + if (patchesPacked >= patchesToPack) { + info(`unable to pack more patches into this request, packed: ${patchesPacked}, total patches: ${patches.length}, skipping.`); + if (options.debug) { + info(`prompt so far: ${prompts.renderReviewFileDiff(ins)}`); + } + break; + } + patchesPacked += 1; + let commentChain = ''; + try { + const allChains = await commenter.getCommentChainsWithinRange(exports.context.payload.pull_request.number, filename, startLine, endLine, commenter_1.COMMENT_REPLY_TAG); + if (allChains.length > 0) { + info(`Found comment chains: ${allChains} for ${filename}`); + commentChain = allChains; + } + } + catch (e) { + warning(`Failed to get comments: ${e}, skipping. backtrace: ${e.stack}`); + } + // try packing comment_chain into this request + const commentChainTokens = (0, tokenizer_1.getTokenCount)(commentChain); + if (tokens + commentChainTokens > + options.heavyTokenLimits.requestTokens) { + commentChain = ''; + } + else { + tokens += commentChainTokens; + } + ins.patches += ` +${patch} +`; + if (commentChain !== '') { + ins.patches += ` +---comment_chains--- +\`\`\` +${commentChain} +\`\`\` +`; + } + ins.patches += ` +---end_change_section--- +`; + } + if (patchesPacked > 0) { + // perform review + try { + const [response] = await heavyBot.chat(prompts.renderReviewFileDiff(ins), {}); + if (response === '') { + info('review: nothing obtained from AI'); + reviewsFailed.push(`${filename} (no response)`); + return; + } + // parse review + const reviews = parseReview(response, patches, filename, options.debug); + for (const review of reviews) { + // CI Feedback Loop: If remedy is provided, try to lint it + // --- AGENTIC REMEDY LOOP (Self-Correction) --- + let currentRemedy = review.remedy; + if (currentRemedy) { + let agentRetries = 0; + const maxAgentRetries = 3; + let isVerified = false; + let lastError = ''; + while (agentRetries < maxAgentRetries && !isVerified) { + const feedback = await runCIFeedback(filename, currentRemedy, review.startLine, review.endLine); + if (feedback === '' || !feedback.includes('โŒ')) { + // Further AST validation to prevent hallucinations + const astValid = validateRemedyAST(filename, currentRemedy, project); + if (astValid) { + isVerified = true; + review.remedy = currentRemedy; // Store the working version + } + else { + lastError = + 'โŒ Hallucination Detected: Remedy refers to undefined local symbols or uses incorrect logic.'; + } + } + else { + lastError = feedback; + } + if (!isVerified && agentRetries < maxAgentRetries - 1) { + agentRetries++; + info(`Agent Retrying Remedy for ${filename} (Attempt ${agentRetries + 1}/${maxAgentRetries})...`); + // Re-prompt for fix with error context + const [retryResponse] = await heavyBot.chat(prompts.renderFixSuggestion(ins, currentRemedy, lastError), {}); + // Extract new remedy from retry response + const { remedy: newRemedy } = parseReview(retryResponse, patches, filename, options.debug)[0] || {}; + if (newRemedy) { + currentRemedy = newRemedy; + } + else { + break; // If AI stops providing remedy blocks, stop + } + } + else { + break; // Max retries or success + } + } + if (!isVerified) { + warning(`Remedy for ${filename} discarded after ${agentRetries + 1} failed attempts: ${lastError}`); + delete review.remedy; + review.verified = false; + review.verificationFeedback = lastError; + } + else { + ; + review.verified = true; + review.verificationFeedback = + 'All verification checks passed'; + } + // If remedy exists and passed, collect it + const finalRemedy = review.remedy; + if (finalRemedy) { + // Collision Detection + const hasCollision = verifiedSuggestions.some(s => s.filename === filename && + ((review.startLine >= s.startLine && + review.startLine <= s.endLine) || + (review.endLine >= s.startLine && + review.endLine <= s.endLine))); + if (!hasCollision) { + verifiedSuggestions.push({ + filename, + startLine: review.startLine, + endLine: review.endLine, + suggestion: finalRemedy, + testCase: undefined, + verified: isVerified, + verificationFeedback: isVerified + ? 'All verification checks passed' + : lastError + }); + // Generate test case for this verified remedy + if (review.comment && finalRemedy) { + try { + const testResult = await test_generator_1.testGenerator.generateTestCase(filename, review.comment, finalRemedy, heavyBot); + if (testResult) { + const testEntry = verifiedSuggestions.find(s => s.filename === filename && + s.startLine === review.startLine && + s.endLine === review.endLine); + if (testEntry) { + testEntry.testCase = + test_generator_1.testGenerator.formatTestSuggestion(testResult); + } + } + } + catch (e) { + info(`Test generation skipped: ${e}`); + } + } + } + } + } + // check for LGTM + if (!options.reviewCommentLGTM && + (review.comment.includes('LGTM') || + review.comment.includes('looks good to me'))) { + lgtmCount += 1; + continue; + } + // Severity and confidence filtering + if (review.severity && + !options.meetsMinimumSeverity(review.severity)) { + info(`Skipping ${review.severity} finding below minimum severity threshold`); + continue; + } + if (review.confidence !== undefined && + !options.meetsConfidenceThreshold(review.confidence)) { + info(`Skipping finding with confidence ${review.confidence}% below threshold ${options.minConfidence}%`); + continue; + } + // Track severity counts for summary dashboard + if (review.severity) { + severityCounts[review.severity]++; + } + if (review.confidence !== undefined) { + confidenceStats.total += review.confidence; + confidenceStats.count++; + } + if (exports.context.payload.pull_request == null) { + warning('No pull request found, skipping.'); + continue; + } + try { + reviewCount += 1; + await commenter.bufferReviewComment(filename, review.startLine, review.endLine, `${review.comment}`, review.verified, review.verificationFeedback); + } + catch (e) { + reviewsFailed.push(`${filename} comment failed (${e})`); + } + } + } + catch (e) { + warning(`Failed to review: ${e}, skipping. backtrace: ${e.stack}`); + reviewsFailed.push(`${filename} (${e})`); + } + } + else { + reviewsSkipped.push(`${filename} (diff too large)`); + } + }; + const reviewPromises = []; + for (const [filename, fileContent, , patches] of filesAndChangesReview) { + if (options.maxFiles <= 0 || reviewPromises.length < options.maxFiles) { + reviewPromises.push(aiConcurrencyLimit(async () => { + await doReview(filename, fileContent, patches, project, verifiedSuggestions, severityCounts, confidenceSum); + })); + } + else { + skippedFiles.push(filename); + } + } + await Promise.all(reviewPromises); + if (options.createRemedyPR && verifiedSuggestions.length > 0) { + try { + await createRemedyPR(verifiedSuggestions, options); + } + catch (e) { + warning(`Failed to create Remedy PR: ${e}`); + } + } + statusMsg += ` +${reviewsFailed.length > 0 + ? `
+Files not reviewed due to errors (${reviewsFailed.length}) + +* ${reviewsFailed.join('\n* ')} + +
+` + : ''} +${reviewsSkipped.length > 0 + ? `
+Files skipped from review due to trivial changes (${reviewsSkipped.length}) + +* ${reviewsSkipped.join('\n* ')} + +
+` + : ''} +
+๐Ÿ›ก๏ธ PRIX Review Summary (${reviewCount + lgtmCount} findings) + +| Severity | Count | +|----------|-------| +| ๐Ÿ”ด Critical | ${severityCounts.critical} | +| ๐ŸŸ  Major | ${severityCounts.major} | +| ๐ŸŸก Minor | ${severityCounts.minor} | +| ๐Ÿ”ต Info | ${severityCounts.info} | +${confidenceSum.count > 0 + ? `| **Avg Confidence** | **${Math.round(confidenceSum.total / confidenceSum.count)}%** |` + : ''} +
+ +--- + +
+Tips + +### Chat with Image description PRIX AI Auditor (\`@prix\`) +- Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file. +- Invite the bot into a review comment chain by tagging \`@prix\` in a reply. + +### Code suggestions +- The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned. +- You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off. + +### Pausing incremental reviews +- Add \`@prix: ignore\` anywhere in the PR description to pause further reviews from the bot. + +
+`; + // add existing_commit_ids_block with latest head sha + statusMsg += `\n${commenter.addReviewedCommitId(existingCommitIdsBlock, exports.context.payload.pull_request.head.sha)}`; + // post the review (summary + comments) + await commenter.submitReview(exports.context.payload.pull_request.number, commits[commits.length - 1].sha, statusMsg); + } +}; +exports.codeReview = codeReview; +const splitPatch = (patch) => { + if (patch == null) { + return []; + } + const pattern = /(^@@ -(\d+),(\d+) \+(\d+),(\d+) @@).*$/gm; + const result = []; + let last = -1; + let match; + while ((match = pattern.exec(patch)) !== null) { + if (last === -1) { + last = match.index; + } + else { + result.push(patch.substring(last, match.index)); + last = match.index; + } + } + if (last !== -1) { + result.push(patch.substring(last)); + } + return result; +}; +const patchStartEndLine = (patch) => { + const pattern = /(^@@ -(\d+),(\d+) \+(\d+),(\d+) @@)/gm; + const match = pattern.exec(patch); + if (match != null) { + const oldBegin = parseInt(match[2]); + const oldDiff = parseInt(match[3]); + const newBegin = parseInt(match[4]); + const newDiff = parseInt(match[5]); + return { + oldHunk: { + startLine: oldBegin, + endLine: oldBegin + oldDiff - 1 + }, + newHunk: { + startLine: newBegin, + endLine: newBegin + newDiff - 1 + } + }; + } + else { + return null; + } +}; +const parsePatch = (patch) => { + const hunkInfo = patchStartEndLine(patch); + if (hunkInfo == null) { + return null; + } + const oldHunkLines = []; + const newHunkLines = []; + let newLine = hunkInfo.newHunk.startLine; + const lines = patch.split('\n').slice(1); // Skip the @@ line + // Remove the last line if it's empty + if (lines[lines.length - 1] === '') { + lines.pop(); + } + // Skip annotations for the first 3 and last 3 lines + const skipStart = 3; + const skipEnd = 3; + let currentLine = 0; + const removalOnly = !lines.some(line => line.startsWith('+')); + for (const line of lines) { + currentLine++; + if (line.startsWith('-')) { + oldHunkLines.push(`${line.substring(1)}`); + } + else if (line.startsWith('+')) { + newHunkLines.push(`${newLine}: ${line.substring(1)}`); + newLine++; + } + else { + // context line + oldHunkLines.push(`${line}`); + if (removalOnly || + (currentLine > skipStart && currentLine <= lines.length - skipEnd)) { + newHunkLines.push(`${newLine}: ${line}`); + } + else { + newHunkLines.push(`${line}`); + } + newLine++; + } + } + return { + oldHunk: oldHunkLines.join('\n'), + newHunk: newHunkLines.join('\n') + }; +}; +function parseReview(response, patches, filename, debug = false) { + const reviews = []; + response = sanitizeResponse(response.trim()); + const lines = response.split('\n'); + const lineNumberRangeRegex = /(?:^|\s)(\d+)-(\d+):\s*$/; + const commentSeparator = '---'; + let currentStartLine = null; + let currentEndLine = null; + let currentComment = ''; + function storeReview() { + if (currentStartLine !== null && currentEndLine !== null) { + const review = { + startLine: currentStartLine, + endLine: currentEndLine, + comment: currentComment, + filename + }; + let withinPatch = false; + let bestPatchStartLine = -1; + let bestPatchEndLine = -1; + let maxIntersection = 0; + for (const [startLine, endLine] of patches) { + const intersectionStart = Math.max(review.startLine, startLine); + const intersectionEnd = Math.min(review.endLine, endLine); + const intersectionLength = Math.max(0, intersectionEnd - intersectionStart + 1); + if (intersectionLength > maxIntersection) { + maxIntersection = intersectionLength; + bestPatchStartLine = startLine; + bestPatchEndLine = endLine; + withinPatch = + intersectionLength === review.endLine - review.startLine + 1; + } + if (withinPatch) + break; + } + if (!withinPatch) { + if (bestPatchStartLine !== -1 && bestPatchEndLine !== -1) { + review.comment = `> Note: This review was outside of the patch, so it was mapped to the patch with the greatest overlap. Original lines [${review.startLine}-${review.endLine}] + +${review.comment}`; + review.startLine = bestPatchStartLine; + review.endLine = bestPatchEndLine; + } + else { + review.comment = `> Note: This review was outside of the patch, but no patch was found that overlapped with it. Original lines [${review.startLine}-${review.endLine}] + +${review.comment}`; + review.startLine = patches[0][0]; + review.endLine = patches[0][1]; + } + } + reviews.push(review); + info(`Stored comment for line range ${currentStartLine}-${currentEndLine}: ${currentComment.trim()}`); + } + } + function sanitizeCodeBlock(comment, codeBlockLabel) { + const codeBlockStart = `\`\`\`${codeBlockLabel}`; + const codeBlockEnd = '```'; + const lineNumberRegex = /^ *(\d+): /gm; + let codeBlockStartIndex = comment.indexOf(codeBlockStart); + while (codeBlockStartIndex !== -1) { + const codeBlockEndIndex = comment.indexOf(codeBlockEnd, codeBlockStartIndex + codeBlockStart.length); + if (codeBlockEndIndex === -1) + break; + const codeBlock = comment.substring(codeBlockStartIndex + codeBlockStart.length, codeBlockEndIndex); + const sanitizedBlock = codeBlock.replace(lineNumberRegex, ''); + comment = + comment.slice(0, codeBlockStartIndex + codeBlockStart.length) + + sanitizedBlock + + comment.slice(codeBlockEndIndex); + codeBlockStartIndex = comment.indexOf(codeBlockStart, codeBlockStartIndex + + codeBlockStart.length + + sanitizedBlock.length + + codeBlockEnd.length); + } + return comment; + } + function extractRemedy(comment) { + const remedyStart = '```suggestion'; + const remedyEnd = '```'; + const startIndex = comment.indexOf(remedyStart); + if (startIndex === -1) + return { sanitizedComment: comment, remedy: null }; + const endIndex = comment.indexOf(remedyEnd, startIndex + remedyStart.length); + if (endIndex === -1) + return { sanitizedComment: comment, remedy: null }; + const remedy = comment + .substring(startIndex + remedyStart.length, endIndex) + .trim(); + // For unified comments, we KEEP the suggestion in the comment body + // but we still return it separately so the autonomous PR flow can use it. + return { sanitizedComment: comment, remedy }; + } + function sanitizeResponse(comment) { + comment = sanitizeCodeBlock(comment, 'suggestion'); + comment = sanitizeCodeBlock(comment, 'diff'); + return comment; + } + for (const line of lines) { + const lineNumberRangeMatch = line.match(lineNumberRangeRegex); + if (lineNumberRangeMatch != null) { + storeReview(); + currentStartLine = parseInt(lineNumberRangeMatch[1], 10); + currentEndLine = parseInt(lineNumberRangeMatch[2], 10); + currentComment = ''; + if (debug) { + info(`Found line number range: ${currentStartLine}-${currentEndLine}`); + } + continue; + } + if (line.trim() === commentSeparator) { + storeReview(); + currentStartLine = null; + currentEndLine = null; + currentComment = ''; + if (debug) { + info('Found comment separator'); + } + continue; + } + if (currentStartLine !== null && currentEndLine !== null) { + currentComment += `${line}\n`; + } + } + storeReview(); + // Post-processing to extract remedies, severity, and confidence + for (const review of reviews) { + const { sanitizedComment, remedy } = extractRemedy(review.comment); + review.comment = sanitizedComment; + if (remedy) { + ; + review.remedy = remedy; + } + // Extract severity from [LEVEL] | [TYPE] pattern + const severityMatch = review.comment.match(/\[(CRITICAL|MAJOR|MINOR|INFO)\]\s*\|/i); + if (severityMatch) { + review.severity = severityMatch[1].toLowerCase(); + } + // Extract confidence score and calibrate it to remove LLM bias + const confidenceMatch = review.comment.match(/CONFIDENCE:\s*(\d+)%?/); + const aiReportedConfidence = confidenceMatch + ? parseInt(confidenceMatch[1], 10) + : undefined; + if (aiReportedConfidence !== undefined) { + const store = context_1.als.getStore(); + const teamId = store?.repo?.owner || 'default'; + const repoSlug = store?.repo?.repo || 'default'; + const calibrated = confidence_1.confidenceCalibrator.calibrate(aiReportedConfidence, review.comment, review.comment.length, 2000, review.severity, teamId, repoSlug, extractPatternType(review.comment), review.filename); + review.confidence = calibrated.score; + } + } + return reviews; +} +function extractPatternType(comment) { + const lowerComment = comment.toLowerCase(); + if (/null.*pointer|npe|null.*check/i.test(lowerComment)) + return 'null-pointer'; + if (/sql.*injection|SELECT.*WHERE.*\+|query.*concat/i.test(lowerComment)) + return 'sql-injection'; + if (/password|secret|api.*key.*=.*['"]|token.*=.*['"]/i.test(lowerComment)) + return 'secret-exposure'; + if (/eval\(|new.*Function\(|innerHTML\s*=|document\.write/i.test(lowerComment)) + return 'xss'; + if (/race.*condition|concurrent.*modif|deadlock|mutex/i.test(lowerComment)) + return 'concurrency'; + if (/memory.*leak|dispose\(|close\(|gc\./i.test(lowerComment)) + return 'resource-leak'; + if (/async.*without.*await|unhandled.*promise|catch.*without.*throw/i.test(lowerComment)) + return 'async-issues'; + if (/try.*without.*catch|catch.*empty|swallow.*exception/i.test(lowerComment)) + return 'error-handling'; + if (/division.*by.*zero|divide.*0|x\s*\/\s*0/i.test(lowerComment)) + return 'arithmetic'; + if (/off.*by.*one|index.*bound/i.test(lowerComment)) + return 'logic-error'; + if (/hardcoded|hard.*coded/i.test(lowerComment)) + return 'hardcoding'; + if (/circular.*depend|lazy.*load|circular/i.test(lowerComment)) + return 'architecture'; + if (/http.*not.*https|mixed.*content|insecure.*request/i.test(lowerComment)) + return 'security'; + if (/crypto.*md5|sha1.*encrypt|md5.*hash/i.test(lowerComment)) + return 'crypto'; + if (/any.*type|cast.*any|as.*any/i.test(lowerComment)) + return 'type-safety'; + if (/console\.(log|debug|warn)/i.test(lowerComment)) + return 'logging'; + if (/todo|fixme|hack|bug:/i.test(lowerComment)) + return 'tech-debt'; + return 'general'; +} +const validateRemedyAST = (filename, remedyCode, project) => { + // Only TS/JS validation for now + if (!filename.endsWith('.ts') && !filename.endsWith('.js')) + return true; + try { + const tempFile = `__val_remedy_${Date.now()}_${filename}`; + const sourceFile = project.createSourceFile(tempFile, remedyCode, { + overwrite: true + }); + // Check for obvious syntax errors in the snippet itself + const diagnostics = sourceFile.getPreEmitDiagnostics(); + if (diagnostics.length > 0) + return false; + // Check for undefined identifiers - classic hallucination signal + // This is a heuristic: check if any variable used is neither defined in snippet nor global + const identifiers = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.Identifier); + for (const id of identifiers) { + if (id.getSymbol()) + continue; // Symbol exists, so it's linked + const text = id.getText(); + // Skip common globals and common names + if ([ + 'console', + 'process', + 'require', + 'exports', + 'Buffer', + 'Array', + 'Object', + 'String', + 'Number', + 'Boolean', + 'Date', + 'Promise', + 'Math', + 'JSON' + ].includes(text)) + continue; + // If no symbol and not a common global, it's a potential hallucination + // BUT: it might be an import that's not in the snippet. So we skip if it looks like an import name. + if (id.getParentIfKind(ts_morph_1.SyntaxKind.ImportSpecifier)) + continue; + // For snippets, we only flag if it's very likely a typo or missing variable + // (Advanced: compare against existing file context if needed) + } + project.removeSourceFile(sourceFile); + return true; + } + catch (e) { + return false; + } +}; +async function generateImpactMap(filesAndChanges, project) { + const impactedModules = {}; + for (const [filename, content] of filesAndChanges) { + const exports = findExports(filename, content, project); + for (const exp of exports) { + try { + // Deep Static Analysis: Use actual AST references if it's a TS/JS file + if (filename.endsWith('.ts') || filename.endsWith('.js')) { + const sourceFile = project.getSourceFile(filename) || + project.createSourceFile(filename, content, { overwrite: true }); + const declarations = sourceFile + .getDescendantsOfKind(ts_morph_1.SyntaxKind.Identifier) + .filter(id => id.getText() === exp); + for (const decl of declarations) { + const sym = decl.getSymbol(); + if (sym) { + const nodes = sym.getDeclarations(); + const refs = nodes.length > 0 ? nodes[0].findReferences() || [] : []; + for (const refEntry of refs) { + for (const ref of refEntry.getReferences()) { + const refPath = ref.getSourceFile().getFilePath(); + if (!refPath.includes(filename) && + !refPath.includes('node_modules')) { + if (!impactedModules[filename]) + impactedModules[filename] = { + usages: [], + type: 'AST API/Ref Change' + }; + impactedModules[filename].usages.push(refPath); + } + } + } + } + } + } + else { + // Fallback to Grep for other languages + const grepResult = (0, utils_1.prixExec)(`git grep -lE "import.*${exp}|require.*${exp}|${exp}\\." -- . ":(exclude)${filename}"`, { encoding: 'utf8' }); + const usages = grepResult.split('\n').filter(f => f.trim() !== ''); + if (usages.length > 0) { + if (!impactedModules[filename]) + impactedModules[filename] = { + usages: [], + type: 'Heuristic Usage Detect' + }; + impactedModules[filename].usages = [ + ...new Set([...impactedModules[filename].usages, ...usages]) + ]; + } + } + } + catch (e) { + // Heuristic search failed, skip this file + } + } + } + if (Object.keys(impactedModules).length === 0) { + return '> No significant downstream impact detected for the changed symbols.'; + } + let mermaid = 'graph TD\n'; + mermaid += ' subgraph "Changed Files"\n'; + for (const mod of Object.keys(impactedModules)) { + const safeMod = mod.replace(/[^a-zA-Z0-9]/g, '_'); + mermaid += ` ${safeMod}["${mod}"]\n`; + } + mermaid += ' end\n'; + mermaid += ' subgraph "Impacted Modules"\n'; + for (const [mod, data] of Object.entries(impactedModules)) { + const safeMod = mod.replace(/[^a-zA-Z0-9]/g, '_'); + const uniqueUsages = [...new Set(data.usages)]; + uniqueUsages.slice(0, 5).forEach(u => { + const safeU = u.replace(/[^a-zA-Z0-9]/g, '_'); + mermaid += ` ${safeU}["${u}"]\n`; + mermaid += ` ${safeMod} -- "${data.type}" --> ${safeU}\n`; + // Architectural Guard: Detect potential violations + if (mod.toLowerCase().includes('controller') && + (u.toLowerCase().includes('db') || + u.toLowerCase().includes('repository'))) { + mermaid += ` ${safeU} -- "โŒ VIOLATION: Controller to DB" --> ${safeMod}\n`; + } + }); + if (uniqueUsages.length > 5) { + const moreId = `more_${safeMod}`; + mermaid += ` ${moreId}["... and ${uniqueUsages.length - 5} more"]\n`; + mermaid += ` ${safeMod} -.-> ${moreId}\n`; + } + } + mermaid += ' end\n'; + return `\n
\nVisual Impact Graph (Mermaid)\n\n\`\`\`mermaid\n${mermaid}\`\`\`\n\n
\n`; +} +const findExports = (filename, content, project) => { + if (filename.endsWith('.py')) { + // Python symbols (functions, classes) + const pyRegex = /^\s*(?:def|class)\s+([a-zA-Z0-9_$]+)/gm; + const exports = []; + let match; + while ((match = pyRegex.exec(content)) !== null) { + exports.push(match[1]); + } + return exports; + } + if (filename.endsWith('.go')) { + // Go symbols (exported functions, types, vars - starting with uppercase) + const goRegex = /^\s*(?:func|type|const|var)\s+([A-Z][a-zA-Z0-9_$]*)/gm; + const exports = []; + let match; + while ((match = goRegex.exec(content)) !== null) { + exports.push(match[1]); + } + return exports; + } + if (!filename.endsWith('.ts') && + !filename.endsWith('.tsx') && + !filename.endsWith('.js') && + !filename.endsWith('.jsx')) { + // Fallback to generic regex for other files + const exportRegex = /export\s+(?:async\s+)?(?:function|class|interface|type|const|let|var)\s+([a-zA-Z0-9_$]+)/g; + const exports = []; + let match; + while ((match = exportRegex.exec(content)) !== null) { + exports.push(match[1]); + } + return exports; + } + try { + const sourceFile = project.createSourceFile(filename, content, { + overwrite: true + }); + const exports = []; + sourceFile.getExportedDeclarations().forEach((declarations, name) => { + exports.push(name); + }); + return exports; + } + catch (e) { + info(`ts-morph failed for ${filename}: ${e}`); + return []; + } +}; +const findUsages = async (filename, content, project) => { + const exports = findExports(filename, content, project); + let usagesSummary = ''; + for (const exp of exports) { + try { + // Use smarter grep patterns for JS/TS + const grepResult = (0, utils_1.prixExec)(`git grep -nE "import.*${exp}|require.*${exp}|${exp}\\." -- . ":(exclude)${filename}"`, { encoding: 'utf8' }); + const lines = grepResult.split('\n').filter(l => l.trim() !== ''); + if (lines.length > 0) { + usagesSummary += `\nUsages of ${exp} in codebase (Potential breakages): \n`; + lines.slice(0, 5).forEach(l => { + usagesSummary += ` - ${l}\n`; + }); + if (lines.length > 5) { + usagesSummary += ` - ... and ${lines.length - 5} more potential usages.\n`; + } + } + } + catch (e) { + // no usages found + } + } + return usagesSummary.trim(); +}; +const checkIfDocumentationOnly = (diff) => { + const lines = diff.split('\n'); + let hasLogicChange = false; + for (const line of lines) { + if (line.startsWith('+') || line.startsWith('-')) { + const content = line.substring(1).trim(); + // Skip empty or purely comment/doc lines + if (content === '') + continue; + if (content.startsWith('//') || + content.startsWith('/*') || + content.startsWith('*') || + content.startsWith('#') || + content.startsWith('"""') || + content.startsWith("'''")) { + continue; + } + // If it's not a comment, it might be logic + hasLogicChange = true; + break; + } + } + return !hasLogicChange; +}; +const runCIFeedback = async (filename, remedy, startLine, endLine) => { + try { + if (remedy === '') + return ''; + info(`Running verification for remedy in ${filename}`); + const store = context_1.als.getStore(); + const workingDir = store?.workingDir || process.cwd(); + const verifier = new fix_verifier_1.FixVerifier({ + enableLint: true, + enableSyntax: true, + enableAST: true, + enableTests: false + }); + const result = await verifier.verify(filename, remedy, startLine, endLine, workingDir); + if (result.passed) { + return result.overallFeedback; + } + else { + return `โŒ Verification failed: ${result.errorMessage || 'Unknown error'}\n${result.overallFeedback}`; + } + } + catch (e) { + info(`CI feedback failed: ${e}`); + return ''; + } +}; +const createRemedyPR = async (suggestions, options) => { + info(`Creating Remedy PR with ${suggestions.length} suggestions`); + const fs = require('fs'); + const path = require('path'); + const store = context_1.als.getStore(); + const workingDir = store?.workingDir || process.cwd(); + // Group suggestions by file + const suggestionsByFile = {}; + for (const s of suggestions) { + if (suggestionsByFile[s.filename] == null) { + suggestionsByFile[s.filename] = []; + } + suggestionsByFile[s.filename].push(s); + } + const modifiedFiles = []; + // To avoid issues with line number shifts, we apply suggestions from bottom to top for each file + for (const filename of Object.keys(suggestionsByFile)) { + const absFilename = path.resolve(workingDir, filename); + if (!fs.existsSync(absFilename)) { + warning(`File ${filename} not found in ${workingDir}, skipping remedy.`); + continue; + } + const content = fs.readFileSync(absFilename, 'utf8'); + const lines = content.split('\n'); + // Sort suggestions by startLine descending + const fileSuggestions = suggestionsByFile[filename].sort((a, b) => b.startLine - a.startLine); + for (const s of fileSuggestions) { + // Line numbers are 1-indexed + const startIndex = s.startLine - 1; + const numLinesToRemove = s.endLine - s.startLine + 1; + lines.splice(startIndex, numLinesToRemove, s.suggestion); + } + fs.writeFileSync(absFilename, lines.join('\n')); + modifiedFiles.push(filename); + info(`Applied ${fileSuggestions.length} suggestions to ${filename}`); + } + if (modifiedFiles.length === 0) { + warning('No files were modified, skipping Remedy PR creation.'); + return; + } + // Git operations + if (exports.context.payload.pull_request == null) { + warning('No pull request found in context, cannot create remedy PR.'); + return; + } + const prNumber = exports.context.payload.pull_request.number; + const headBranch = exports.context.payload.pull_request.head.ref; + const remedyBranch = `ai-remedy/pr-${prNumber}-${Date.now()}`; + try { + // Check if we are in a git repo + (0, utils_1.prixExec)('git rev-parse --is-inside-work-tree'); + (0, utils_1.prixExec)(`git checkout -b ${remedyBranch}`); + (0, utils_1.prixExec)(`git config user.name "github-actions[bot]"`); + (0, utils_1.prixExec)(`git config user.email "github-actions[bot]@users.noreply.github.com"`); + (0, utils_1.prixExec)(`git add ${modifiedFiles.join(' ')}`); + // ignore if no changes (shouldn't happen if we reach here) + try { + (0, utils_1.prixExec)(`git commit -m "[AI-REMEDY] Automated fixes for PR #${prNumber}"`); + } + catch (e) { + info('No changes to commit for remedy branch.'); + return; + } + (0, utils_1.prixExec)(`git push origin ${remedyBranch}`); + // Create PR using Octokit + const { data: remedyPR } = await octokit_1.octokit.pulls.create({ + owner: exports.repo.owner, + repo: exports.repo.repo, + title: `[AI-REMEDY] Verified Fixes for PR #${prNumber}`, + head: remedyBranch, + base: headBranch, + body: `This PR contains autonomous fixes for PR #${prNumber} generated by the AI PR Reviewer. + +### Summary of Changes: +${suggestions + .map(s => `- **${s.filename}**: lines ${s.startLine}-${s.endLine}`) + .join('\n')} + +These suggestions have been verified to pass basic CI checks (lint/syntax). Please review and merge into your branch.` + }); + info(`Created Remedy PR: ${remedyPR.html_url}`); + } + catch (e) { + warning(`Failed to push remedy branch or create PR: ${e.message}`); + } +}; +/** + * PRIX main entry point for PR Audit. + * Adapts the action logic to Probot context. + */ +const run = async (probotContext, options, prompts) => { + // Setup logger shim using context.log + info = (msg) => probotContext.log.info(msg); + warning = (msg) => probotContext.log.warn(msg); + error = (msg) => probotContext.log.error(msg); + // global 'context' and 'repo' are now Proxy objects linked to ALS + (0, commenter_1.setCommenterContext)(probotContext); + // Legacy shim + (0, octokit_1.setOctokit)(probotContext.octokit); + // Initialize bots + const lightAIOptions = new options_1.AIOptions(options.lightModel, options.lightTokenLimits); + const heavyAIOptions = new options_1.AIOptions(options.heavyModel, options.heavyTokenLimits); + const lightBot = new bot_1.Bot(options, lightAIOptions); + const heavyBot = new bot_1.Bot(options, heavyAIOptions); + probotContext.log.info(`PRIX Audit starting for PR #${probotContext.payload.pull_request.number}`); + try { + await (0, exports.codeReview)(lightBot, heavyBot, options, prompts); + probotContext.log.info(`PRIX Audit completed for PR #${probotContext.payload.pull_request.number}`); + } + catch (err) { + probotContext.log.error(`PRIX Audit failed: ${err.message}`); + throw err; + } +}; +exports.run = run; +//# sourceMappingURL=review.js.map \ No newline at end of file diff --git a/lib/src/review.js.map b/lib/src/review.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a315e9ca2f5648c150ae3859f1e2527643cca79d --- /dev/null +++ b/lib/src/review.js.map @@ -0,0 +1 @@ +{"version":3,"file":"review.js","sourceRoot":"","sources":["../../src/review.ts"],"names":[],"mappings":";;;;;;AA89CA,gDAsCC;AApgDD,mCAAgC;AAChC,uCAA4C;AAE5C,sDAA4B;AAC5B,+BAAyB;AACzB,2CASoB;AACpB,qCAA+B;AAC/B,uCAAiD;AACjD,uCAA6C;AAE7C,2CAAyC;AAEzC,uCAA6B;AAC7B,iDAAyE;AACzE,uDAAqE;AACrE,6CAAiD;AACjD,qDAA8C;AAC9C,iDAA8D;AAE9D,IAAI,KAAK,GAAG,OAAO,CAAC,KAAK,CAAA;AACzB,IAAI,IAAI,GAAG,OAAO,CAAC,GAAG,CAAA;AACtB,IAAI,OAAO,GAAG,OAAO,CAAC,IAAI,CAAA;AAEb,QAAA,OAAO,GAAQ,IAAI,KAAK,CAAC,EAAS,EAAE;IAC/C,GAAG,CAAC,MAAM,EAAE,IAAI;QACd,OAAO,CAAC,aAAG,CAAC,QAAQ,EAAE,EAAE,aAAqB,CAAA,CAAC,IAAI,CAAC,CAAA;IACrD,CAAC;CACF,CAAC,CAAA;AAEW,QAAA,IAAI,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aAAa,CAAC,OAAO,CAAC,YAAY,CAAC,MAAM,EAAE,CAC5E,CAAA;IACH,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,sBAAsB,GAAG,CAAC,OAAO,EAAE,CAAC,CAAA;QAC5D,MAAM,GAAG,CAAA;IACX,CAAC;AACH,CAAC,CAAA;AA1CY,QAAA,GAAG,OA0Cf"} \ No newline at end of file diff --git a/lib/src/semantic-search.js b/lib/src/semantic-search.js new file mode 100644 index 0000000000000000000000000000000000000000..492bc2bd49eb300b980575362169807815ecdf66 --- /dev/null +++ b/lib/src/semantic-search.js @@ -0,0 +1,317 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.semanticBugSearch = exports.SemanticBugSearch = void 0; +const utils_1 = require("./utils"); +class SemanticBugSearch { + bugCache = new Map(); + embeddingCache = new Map(); + SIMILARITY_THRESHOLD = 0.75; + MAX_RESULTS = 5; + async searchSimilarBugs(codeChange, filename, owner, repo, bot) { + const cachedBugs = await this.getBugHistory(owner, repo); + if (cachedBugs.length === 0) + return []; + const queryEmbedding = await this.getEmbedding(codeChange, bot); + if (!queryEmbedding) + return []; + const scored = []; + for (const bug of cachedBugs) { + let bugEmbedding = this.embeddingCache.get(bug.id); + if (!bugEmbedding) { + bugEmbedding = await this.getEmbedding(`${bug.title} ${bug.description}`, bot); + if (bugEmbedding) { + this.embeddingCache.set(bug.id, bugEmbedding); + } + } + if (bugEmbedding) { + const similarity = this.cosineSimilarity(queryEmbedding, bugEmbedding); + if (similarity >= this.SIMILARITY_THRESHOLD) { + scored.push({ + pattern: bug, + similarity, + context: this.extractRelevantContext(bug, filename) + }); + } + } + } + scored.sort((a, b) => b.similarity - a.similarity); + return scored.slice(0, this.MAX_RESULTS); + } + async getBugHistory(owner, repo) { + const cacheKey = `${owner}/${repo}`; + if (this.bugCache.has(cacheKey)) { + return this.bugCache.get(cacheKey); + } + const bugs = []; + try { + const ghOutput = (0, utils_1.prixExec)(`gh issue list --repo ${owner}/${repo} --state all --limit 100 --json number,title,body,labels`, { encoding: 'utf8', timeout: 15000 }); + const issues = JSON.parse(ghOutput); + for (const issue of issues) { + const labels = issue.labels || []; + const hasBugLabel = labels.some((l) => l.name.toLowerCase().includes('bug') || + l.name.toLowerCase().includes('fix') || + l.name.toLowerCase().includes('defect')); + if (hasBugLabel || + issue.body.toLowerCase().includes('crash') || + issue.body.toLowerCase().includes('error') || + issue.body.toLowerCase().includes('failure')) { + bugs.push({ + id: `issue-${issue.number}`, + title: issue.title, + description: issue.body || '', + severity: this.inferSeverity(issue.title, issue.body, labels), + files: this.extractFiles(issue.body), + lines: this.extractLines(issue.body), + fix: this.extractFix(issue.body) + }); + } + } + } + catch (e) { + // gh CLI not available or no access + } + try { + const prOutput = (0, utils_1.prixExec)(`gh pr list --repo ${owner}/${repo} --state all --limit 100 --json number,title,body,labels`, { encoding: 'utf8', timeout: 15000 }); + const prs = JSON.parse(prOutput); + for (const pr of prs) { + if (pr.title.toLowerCase().includes('fix') || + pr.title.toLowerCase().includes('bug') || + pr.title.toLowerCase().includes('patch')) { + bugs.push({ + id: `pr-${pr.number}`, + title: pr.title, + description: pr.body || '', + severity: this.inferSeverity(pr.title, pr.body, pr.labels), + files: this.extractFiles(pr.body), + lines: this.extractLines(pr.body), + fix: this.extractFix(pr.body) + }); + } + } + } + catch (e) { + // gh CLI not available or no access + } + try { + const commitsOutput = (0, utils_1.prixExec)(`git log --all --grep="fix\|bug\|crash\|error" --oneline -100`, { encoding: 'utf8', timeout: 15000 }); + const commitLines = commitsOutput.split('\n').filter(l => l.trim()); + for (const line of commitLines) { + const match = line.match(/^([a-f0-9]+)\s+(.+)/); + if (match) { + bugs.push({ + id: `commit-${match[1].substring(0, 7)}`, + title: match[2], + description: line, + severity: this.inferSeverity(match[2], '', []), + files: [], + lines: [], + fix: match[1] + }); + } + } + } + catch (e) { } + this.bugCache.set(cacheKey, bugs); + return bugs; + } + inferSeverity(title, body, labels) { + const text = `${title} ${body}`.toLowerCase(); + if (labels.some((l) => l.name.toLowerCase().includes('critical') || + l.name.toLowerCase().includes('p0'))) { + return 'critical'; + } + if (text.includes('security') || + text.includes('vulnerability') || + text.includes('breach') || + text.includes('leak')) { + return 'critical'; + } + if (text.includes('data loss') || + text.includes('corruption') || + text.includes('crash')) { + return 'major'; + } + if (labels.some((l) => l.name.toLowerCase().includes('major') || + l.name.toLowerCase().includes('p1'))) { + return 'major'; + } + if (labels.some((l) => l.name.toLowerCase().includes('minor') || + l.name.toLowerCase().includes('p2'))) { + return 'minor'; + } + return 'info'; + } + extractFiles(body) { + const files = []; + const patterns = [ + /src\/([^\s)]+\.[a-z]+)/gi, + /lib\/([^\s)]+\.[a-z]+)/gi, + /([a-zA-Z0-9_/-]+\.[a-z]+):/gi, + /\*\*(?:changed|modified|file):\s*`([^`]+)`/gi + ]; + for (const pattern of patterns) { + let match; + while ((match = pattern.exec(body)) !== null) { + const file = match[1] || match[0]; + if (!files.includes(file) && !file.includes('node_modules')) { + files.push(file); + } + } + } + return files; + } + extractLines(body) { + const lines = []; + const pattern = /(?::)(\d+)(?::|\s)/g; + let match; + while ((match = pattern.exec(body)) !== null) { + lines.push(match[1]); + } + return lines; + } + extractFix(body) { + const fixPatterns = [ + /\*\*Fixed:\*\*[\s\n]+```[\s\S]*?```/, + /\*\*Solution:\*\*[\s\n]+```[\s\S]*?```/, + /```(?:fix|solution|patch)[\s\S]*?```/ + ]; + for (const pattern of fixPatterns) { + const match = body.match(pattern); + if (match) { + return match[0].replace(/```[a-z]*\n?/g, '').trim(); + } + } + return undefined; + } + extractRelevantContext(bug, targetFile) { + const context = []; + if (bug.title) { + context.push(`**Title:** ${bug.title}`); + } + if (bug.severity) { + context.push(`**Severity:** ${bug.severity}`); + } + if (bug.files.length > 0) { + const relevantFiles = bug.files.filter(f => f.includes(targetFile) || targetFile.includes(f)); + if (relevantFiles.length > 0) { + context.push(`**Files:** ${relevantFiles.join(', ')}`); + } + } + if (bug.fix) { + context.push(`**Fix:** ${bug.fix.substring(0, 200)}...`); + } + return context.join(' | '); + } + async getEmbedding(text, bot) { + const textHash = this.simpleHash(text); + if (this.embeddingCache.has(textHash)) { + return this.embeddingCache.get(textHash); + } + try { + const [response] = await bot.chat(`Generate a semantic embedding vector for the following text. Respond ONLY with a JSON array of 384 numbers representing the embedding. Do not include any other text.\n\nText: ${text.substring(0, 1000)}`, {}); + const numbers = response + .replace(/[[\]]/g, '') + .split(',') + .map(s => parseFloat(s.trim())) + .filter(n => !isNaN(n)); + if (numbers.length >= 100) { + const embedding = numbers.slice(0, 384); + this.embeddingCache.set(textHash, embedding); + return embedding; + } + } + catch (e) { + // Fallback: use TF-IDF-like hashing + } + return this.generateFallbackEmbedding(text); + } + generateFallbackEmbedding(text) { + const words = text + .toLowerCase() + .split(/\W+/) + .filter(w => w.length > 2); + const embedding = new Array(384).fill(0); + const seedPhrases = [ + 'security', + 'bug', + 'crash', + 'memory', + 'leak', + 'null', + 'undefined', + 'race', + 'condition', + 'deadlock', + 'timeout', + 'performance', + 'scalability', + 'api', + 'database', + 'cache', + 'auth', + 'validation', + 'error', + 'exception' + ]; + for (let i = 0; i < words.length; i++) { + const word = words[i]; + for (let j = 0; j < seedPhrases.length; j++) { + if (word.includes(seedPhrases[j])) { + embedding[(j * 20) % 384] += 1; + embedding[(j * 7 + i) % 384] += 1; + } + } + } + const magnitude = Math.sqrt(embedding.reduce((sum, val) => sum + val * val, 0)); + if (magnitude > 0) { + for (let i = 0; i < embedding.length; i++) { + embedding[i] /= magnitude; + } + } + return embedding; + } + cosineSimilarity(a, b) { + if (a.length !== b.length) + return 0; + let dotProduct = 0; + let normA = 0; + let normB = 0; + for (let i = 0; i < a.length; i++) { + dotProduct += a[i] * b[i]; + normA += a[i] * a[i]; + normB += b[i] * b[i]; + } + const denominator = Math.sqrt(normA) * Math.sqrt(normB); + if (denominator === 0) + return 0; + return dotProduct / denominator; + } + simpleHash(text) { + let hash = 0; + for (let i = 0; i < text.length; i++) { + const char = text.charCodeAt(i); + hash = (hash << 5) - hash + char; + hash = hash & hash; + } + return hash.toString(36); + } + formatSimilarBugWarning(results) { + if (results.length === 0) + return ''; + let output = `\n\n---\n### ๐Ÿ” Similar Historical Bugs Detected\n\n`; + for (const result of results) { + const similarityPct = Math.round(result.similarity * 100); + output += `**โš ๏ธ ${result.pattern.title}** (${similarityPct}% match)\n`; + output += `${result.context}\n`; + if (result.pattern.fix) { + output += `> **Historical Fix:** \`\`\`\n${result.pattern.fix.substring(0, 300)}\n\`\`\`\n`; + } + output += `---\n`; + } + output += `*This PR contains patterns similar to ${results.length} historical bug(s). Review the fixes above to avoid repeating the same mistakes.*\n`; + return output; + } +} +exports.SemanticBugSearch = SemanticBugSearch; +exports.semanticBugSearch = new SemanticBugSearch(); +//# sourceMappingURL=semantic-search.js.map \ No newline at end of file diff --git a/lib/src/semantic-search.js.map b/lib/src/semantic-search.js.map new file mode 100644 index 0000000000000000000000000000000000000000..71b14039cb0a87d134ed17c6ab8a84dc2fac47ee --- /dev/null +++ b/lib/src/semantic-search.js.map @@ -0,0 +1 @@ +{"version":3,"file":"semantic-search.js","sourceRoot":"","sources":["../../src/semantic-search.ts"],"names":[],"mappings":";;;AACA,mCAAgC;AAoBhC,MAAa,iBAAiB;IACpB,QAAQ,GAA8B,IAAI,GAAG,EAAE,CAAA;IAC/C,cAAc,GAA0B,IAAI,GAAG,EAAE,CAAA;IACxC,oBAAoB,GAAG,IAAI,CAAA;IAC3B,WAAW,GAAG,CAAC,CAAA;IAEhC,KAAK,CAAC,iBAAiB,CACrB,UAAkB,EAClB,QAAgB,EAChB,KAAa,EACb,IAAY,EACZ,GAAQ;QAER,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;QACxD,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,CAAA;QAEtC,MAAM,cAAc,GAAG,MAAM,IAAI,CAAC,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C,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACrC,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAA;YAC/B,IAAI,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,GAAG,IAAI,CAAA;YAChC,IAAI,GAAG,IAAI,GAAG,IAAI,CAAA;QACpB,CAAC;QACD,OAAO,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAA;IAC1B,CAAC;IAED,uBAAuB,CAAC,OAA2B;QACjD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,CAAA;QAEnC,IAAI,MAAM,GAAG,sDAAsD,CAAA;QAEnE,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,MAAM,aAAa,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,UAAU,GAAG,GAAG,CAAC,CAAA;YAEzD,MAAM,IAAI,QAAQ,MAAM,CAAC,OAAO,CAAC,KAAK,OAAO,aAAa,YAAY,CAAA;YACtE,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,IAAI,CAAA;YAE/B,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;gBACvB,MAAM,IAAI,iCAAiC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CACrE,CAAC,EACD,GAAG,CACJ,YAAY,CAAA;YACf,CAAC;YAED,MAAM,IAAI,OAAO,CAAA;QACnB,CAAC;QAED,MAAM,IAAI,yCAAyC,OAAO,CAAC,MAAM,qFAAqF,CAAA;QAEtJ,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AA1aD,8CA0aC;AAEY,QAAA,iBAAiB,GAAG,IAAI,iBAAiB,EAAE,CAAA"} \ No newline at end of file diff --git a/lib/src/symbol-graph-cache.js b/lib/src/symbol-graph-cache.js new file mode 100644 index 0000000000000000000000000000000000000000..5b7347d82b89e5dc7da452ae4f0e5e3cc167998d --- /dev/null +++ b/lib/src/symbol-graph-cache.js @@ -0,0 +1,280 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createIncrementalGraph = exports.IncrementalSymbolGraph = exports.SymbolGraphCache = void 0; +const fs_1 = require("fs"); +const path_1 = require("path"); +const CACHE_VERSION = '2.0.0'; +function getPersistBaseDir() { + if (process.env.PRIX_DATA_DIR) + return process.env.PRIX_DATA_DIR; + if (process.env.HF_HOME) + return (0, path_1.join)(process.env.HF_HOME, 'prix-data'); + if (process.env.HUGGING_FACE_HUB_TOKEN) + return '/tmp/prix-hf'; + return '/tmp/prix'; +} +class SymbolGraphCache { + cache = new Map(); + repoPath; + persistPath; + cacheHits = 0; + cacheMisses = 0; + constructor(repoPath, persistDir) { + this.repoPath = repoPath; + const baseDir = persistDir || getPersistBaseDir(); + this.persistPath = (0, path_1.join)(baseDir, 'symbol-graph-cache'); + this.load(); + } + get(file) { + if (!(0, fs_1.existsSync)(file)) + return undefined; + try { + const stats = (0, fs_1.statSync)(file); + const cached = this.cache.get(file); + if (!cached) { + this.cacheMisses++; + return undefined; + } + if (cached.mtime !== stats.mtimeMs || cached.size !== stats.size) { + this.cacheMisses++; + this.cache.delete(file); + return undefined; + } + this.cacheHits++; + return cached; + } + catch { + return undefined; + } + } + set(file, entry) { + this.cache.set(file, entry); + } + invalidate(file) { + this.cache.delete(file); + } + invalidateContaining(changedFiles) { + const affectedFiles = new Set(); + const changedSet = new Set(changedFiles.map(f => this.normalizePath(f))); + for (const cachedFile of this.cache.keys()) { + const normalizedCached = this.normalizePath(cachedFile); + if (changedSet.has(normalizedCached)) { + affectedFiles.add(cachedFile); + continue; + } + const cached = this.cache.get(cachedFile); + if (!cached) + continue; + for (const edge of cached.edges) { + const normalizedEdge = this.normalizePath(edge.to); + if (changedSet.has(normalizedEdge)) { + affectedFiles.add(cachedFile); + break; + } + const normalizedFrom = this.normalizePath(edge.from); + if (changedSet.has(normalizedFrom)) { + affectedFiles.add(cachedFile); + break; + } + } + for (const symbol of cached.symbols) { + for (const imp of symbol.imports) { + const normalizedImp = this.normalizeImport(imp); + if (this.pathMatchesImport(normalizedImp, changedSet)) { + affectedFiles.add(cachedFile); + break; + } + } + } + } + for (const affected of affectedFiles) { + this.cache.delete(affected); + } + return affectedFiles; + } + normalizePath(p) { + return p.replace(/\\/g, '/').toLowerCase(); + } + normalizeImport(imp) { + return imp.replace(/['"]/g, '').replace(/\\/g, '/').toLowerCase(); + } + pathMatchesImport(imp, changedSet) { + for (const changed of changedSet) { + if (imp.endsWith(changed) || changed.endsWith(imp)) { + return true; + } + const impParts = imp.split('/'); + const changedParts = changed.split('/'); + if (impParts[impParts.length - 1] === changedParts[changedParts.length - 1]) { + return true; + } + } + return false; + } + getStats() { + const total = this.cacheHits + this.cacheMisses; + return { + hits: this.cacheHits, + misses: this.cacheMisses, + size: this.cache.size, + hitRate: total > 0 ? this.cacheHits / total : 0 + }; + } + prune(maxAge = 7 * 24 * 60 * 60 * 1000) { + const now = Date.now(); + let pruned = 0; + for (const [file, entry] of this.cache.entries()) { + if (now - entry.parsedAt > maxAge) { + this.cache.delete(file); + pruned++; + } + } + return pruned; + } + clear() { + this.cache.clear(); + this.cacheHits = 0; + this.cacheMisses = 0; + } + persist() { + try { + const { mkdirSync, writeFileSync, existsSync } = require('fs'); + if (!existsSync(this.persistPath)) { + mkdirSync(this.persistPath, { recursive: true }); + } + const cacheData = { + version: CACHE_VERSION, + repoPath: this.repoPath, + lastUpdated: Date.now(), + entries: Array.from(this.cache.entries()) + }; + const cacheFile = (0, path_1.join)(this.persistPath, `${this.sanitizeFilename(this.repoPath)}.json`); + writeFileSync(cacheFile, JSON.stringify(cacheData), 'utf8'); + } + catch (e) { + console.warn(`Failed to persist graph cache: ${e}`); + } + } + load() { + try { + const { readFileSync, existsSync } = require('fs'); + const cacheFile = (0, path_1.join)(this.persistPath, `${this.sanitizeFilename(this.repoPath)}.json`); + if (!existsSync(cacheFile)) + return; + const data = JSON.parse(readFileSync(cacheFile, 'utf8')); + if (data.version !== CACHE_VERSION) { + console.log('Graph cache version mismatch, rebuilding...'); + return; + } + if (data.repoPath !== this.repoPath) { + console.log('Repo path changed, rebuilding...'); + return; + } + const entries = new Map(data.entries); + this.cache = entries; + } + catch (e) { + console.warn(`Failed to load graph cache: ${e}`); + } + } + sanitizeFilename(path) { + return path.replace(/[^a-z0-9]/gi, '_').substring(0, 100); + } + rebuildIfNeeded(changedFiles) { + if (changedFiles.length === 0) { + return { rebuild: false, filesToRebuild: new Set() }; + } + const filesToRebuild = this.invalidateContaining(changedFiles); + return { + rebuild: filesToRebuild.size > 0 || this.cache.size === 0, + filesToRebuild + }; + } +} +exports.SymbolGraphCache = SymbolGraphCache; +class IncrementalSymbolGraph { + cache; + graph; + pendingUpdates = new Map(); + constructor(repoPath, persistDir) { + this.cache = new SymbolGraphCache(repoPath, persistDir); + this.graph = { + symbols: new Map(), + edges: [], + fileIndex: new Map() + }; + } + async update(changedFiles, deletedFiles) { + for (const file of deletedFiles) { + this.removeFile(file); + } + const { filesToRebuild } = this.cache.rebuildIfNeeded(changedFiles); + let removedSymbols = 0; + let addedSymbols = 0; + for (const file of filesToRebuild) { + const removed = this.removeFile(file); + removedSymbols += removed; + } + for (const file of changedFiles) { + if ((0, fs_1.existsSync)(file)) { + const added = await this.addOrUpdateFile(file); + addedSymbols += added; + } + } + this.cache.persist(); + return { + updatedFiles: [...filesToRebuild, ...changedFiles].filter(f => (0, fs_1.existsSync)(f)), + removedSymbols, + addedSymbols, + cacheStats: this.cache.getStats() + }; + } + removeFile(file) { + const cached = this.cache.get(file); + if (cached) { + for (const symbol of cached.symbols) { + this.graph.symbols.delete(`${file}:${symbol.name}`); + } + this.graph.fileIndex.delete(file); + this.graph.edges = this.graph.edges.filter(e => !e.from.startsWith(file) && !e.to.startsWith(file)); + this.cache.invalidate(file); + return cached.symbols.length; + } + return 0; + } + async addOrUpdateFile(file) { + const existing = this.cache.get(file); + if (existing) { + for (const symbol of existing.symbols) { + this.graph.symbols.set(`${file}:${symbol.name}`, symbol); + } + this.graph.fileIndex.set(file, existing.symbols); + this.graph.edges.push(...existing.edges); + return existing.symbols.length; + } + return 0; + } + getGraph() { + return this.graph; + } + getCacheStats() { + return this.cache.getStats(); + } + clearCache() { + this.cache.clear(); + this.graph = { + symbols: new Map(), + edges: [], + fileIndex: new Map() + }; + } + persist() { + this.cache.persist(); + } +} +exports.IncrementalSymbolGraph = IncrementalSymbolGraph; +const createIncrementalGraph = (repoPath, persistDir) => { + return new IncrementalSymbolGraph(repoPath, persistDir); +}; +exports.createIncrementalGraph = createIncrementalGraph; +//# sourceMappingURL=symbol-graph-cache.js.map \ No newline at end of file diff --git a/lib/src/symbol-graph-cache.js.map b/lib/src/symbol-graph-cache.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5870e68d5661506b6dc8c9b1b800a10e66900021 --- /dev/null +++ b/lib/src/symbol-graph-cache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"symbol-graph-cache.js","sourceRoot":"","sources":["../../src/symbol-graph-cache.ts"],"names":[],"mappings":";;;AAAA,2BAAoE;AACpE,+BAAkC;AAoBlC,MAAM,aAAa,GAAG,OAAO,CAAA;AAE7B,SAAS,iBAAiB;IACxB,IAAI,OAAO,CAAC,GAAG,CAAC,aAAa;QAAE,OAAO,OAAO,CAAC,GAAG,CAAC,aAAa,CAAA;IAC/D,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO;QAAE,OAAO,IAAA,WAAI,EAAC,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,WAAW,CAAC,CAAA;IACtE,IAAI,OAAO,CAAC,GAAG,CAAC,sBAAsB;QAAE,OAAO,cAAc,CAAA;IAC7D,OAAO,WAAW,CAAA;AACpB,CAAC;AAED,MAAa,gBAAgB;IACnB,KAAK,GAAgC,IAAI,GAAG,EAAE,CAAA;IAC9C,QAAQ,CAAQ;IAChB,WAAW,CAAQ;IACnB,SAAS,GAAG,CAAC,CAAA;IACb,WAAW,G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ED,QAAQ;QACN,OAAO,IAAI,CAAC,KAAK,CAAA;IACnB,CAAC;IAED,aAAa;QACX,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAA;IAC9B,CAAC;IAED,UAAU;QACR,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAA;QAClB,IAAI,CAAC,KAAK,GAAG;YACX,OAAO,EAAE,IAAI,GAAG,EAAE;YAClB,KAAK,EAAE,EAAE;YACT,SAAS,EAAE,IAAI,GAAG,EAAE;SACrB,CAAA;IACH,CAAC;IAED,OAAO;QACL,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAA;IACtB,CAAC;CACF;AApGD,wDAoGC;AAEM,MAAM,sBAAsB,GAAG,CACpC,QAAgB,EAChB,UAAmB,EACK,EAAE;IAC1B,OAAO,IAAI,sBAAsB,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;AACzD,CAAC,CAAA;AALY,QAAA,sBAAsB,0BAKlC"} \ No newline at end of file diff --git a/lib/src/symbol-graph.js b/lib/src/symbol-graph.js new file mode 100644 index 0000000000000000000000000000000000000000..80f3cd89c8a7ef5789ee8ed9f31a7b813faccb49 --- /dev/null +++ b/lib/src/symbol-graph.js @@ -0,0 +1,991 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unifiedContextEngine = exports.UnifiedContextEngine = void 0; +/* eslint-disable no-console */ +const web_tree_sitter_1 = __importDefault(require("web-tree-sitter")); +const ts_morph_1 = require("ts-morph"); +const symbol_graph_cache_1 = require("./symbol-graph-cache"); +const crypto_1 = require("crypto"); +const file_discoverer_1 = require("./file-discoverer"); +const fs = require('fs'); +const PARSER_DIR = process.env.PARSER_DIR || '/app/parsers'; +const LANGUAGE_LOADERS = { + '.ts': async () => web_tree_sitter_1.default.Language.load(`${PARSER_DIR}/tree-sitter-typescript.wasm`), + '.tsx': async () => web_tree_sitter_1.default.Language.load(`${PARSER_DIR}/tree-sitter-tsx.wasm`), + '.js': async () => web_tree_sitter_1.default.Language.load(`${PARSER_DIR}/tree-sitter-javascript.wasm`), + '.jsx': async () => web_tree_sitter_1.default.Language.load(`${PARSER_DIR}/tree-sitter-javascript.wasm`), + '.go': async () => web_tree_sitter_1.default.Language.load(`${PARSER_DIR}/tree-sitter-go.wasm`), + '.py': async () => web_tree_sitter_1.default.Language.load(`${PARSER_DIR}/tree-sitter-python.wasm`), + '.rs': async () => { + try { + return web_tree_sitter_1.default.Language.load(`${PARSER_DIR}/tree-sitter-rust.wasm`); + } + catch { + return null; + } + }, + '.cpp': async () => { + try { + return web_tree_sitter_1.default.Language.load(`${PARSER_DIR}/tree-sitter-cpp.wasm`); + } + catch { + return null; + } + }, + '.c': async () => { + try { + return web_tree_sitter_1.default.Language.load(`${PARSER_DIR}/tree-sitter-c.wasm`); + } + catch { + return null; + } + }, + '.java': async () => { + try { + return web_tree_sitter_1.default.Language.load(`${PARSER_DIR}/tree-sitter-java.wasm`); + } + catch { + return null; + } + } +}; +const LANGUAGE_LOADER_CACHE_TTL_MS = 30 * 60 * 1000; +const LANGUAGE_LOADER_MAX_SIZE = 10; +function computeContentHash(content) { + return (0, crypto_1.createHash)('sha256').update(content).digest('hex').substring(0, 16); +} +class UnifiedContextEngine { + graph = { + symbols: new Map(), + edges: [], + fileIndex: new Map() + }; + project; + languageCache = new Map(); + graphCache; + incrementalGraph; + repoPath = ''; + constructor() { + this.project = new ts_morph_1.Project(); + } + async initialize(repoPath) { + this.repoPath = repoPath; + this.graphCache = new symbol_graph_cache_1.SymbolGraphCache(repoPath); + this.incrementalGraph = new symbol_graph_cache_1.IncrementalSymbolGraph(repoPath); + await this.buildSymbolGraph(repoPath); + return this.buildRepoContext(); + } + async updateForChanges(changedFiles, deletedFiles) { + if (!this.incrementalGraph) { + return { updatedFiles: [], cacheStats: { hits: 0, misses: 0, hitRate: 0 } }; + } + const result = await this.incrementalGraph.update(changedFiles, deletedFiles); + return { + updatedFiles: result.updatedFiles, + cacheStats: result.cacheStats + }; + } + async buildSymbolGraph(repoPath) { + try { + await web_tree_sitter_1.default.init(); + } + catch (e) { + console.log(`Tree-sitter init failed: ${e}, using fallback`); + return; + } + const discovered = (0, file_discoverer_1.discoverFiles)(repoPath, { + include: [ + '.ts', + '.tsx', + '.js', + '.jsx', + '.go', + '.py', + '.rs', + '.cpp', + '.c', + '.h', + '.java' + ] + }); + const filesByExt = new file_discoverer_1.FileDiscoverer().groupByExtension(discovered); + const tsFiles = [ + ...(filesByExt.get('.ts') || []), + ...(filesByExt.get('.tsx') || []), + ...(filesByExt.get('.js') || []), + ...(filesByExt.get('.jsx') || []) + ].map(f => f.path); + const goFiles = (filesByExt.get('.go') || []).map(f => f.path); + const pyFiles = (filesByExt.get('.py') || []).map(f => f.path); + const rsFiles = (filesByExt.get('.rs') || []).map(f => f.path); + const cppFiles = [ + ...(filesByExt.get('.cpp') || []), + ...(filesByExt.get('.c') || []), + ...(filesByExt.get('.h') || []), + ...(filesByExt.get('.hpp') || []), + ...(filesByExt.get('.java') || []) + ].map(f => f.path); + console.log(`[Graph] Discovered: ${tsFiles.length} TS/JS, ${goFiles.length} Go, ${pyFiles.length} Python, ${rsFiles.length} Rust, ${cppFiles.length} C++/Java files`); + await Promise.all([ + this.processTSFilesWithCache(tsFiles), + this.processGoFilesWithCache(goFiles), + this.processPythonFilesWithCache(pyFiles), + this.processRustFilesWithCache(rsFiles), + this.processCppJavaFilesWithCache(cppFiles) + ]); + this.buildDependencyEdges(); + this.graphCache?.persist(); + } + async processTSFilesWithCache(files) { + const uncachedFiles = []; + for (const file of files) { + const cached = this.graphCache?.get(file); + if (cached) { + for (const sym of cached.symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym); + } + if (!this.graph.fileIndex.has(file)) { + this.graph.fileIndex.set(file, []); + } + this.graph.fileIndex.get(file).push(...cached.symbols); + this.graph.edges.push(...cached.edges); + } + else { + uncachedFiles.push(file); + } + } + if (uncachedFiles.length === 0) { + console.log(`[GraphCache] TS: All ${files.length} files served from cache`); + return; + } + console.log(`[GraphCache] TS: ${uncachedFiles.length}/${files.length} files need parsing`); + for (const file of uncachedFiles) { + try { + const content = fs.readFileSync(file, 'utf8'); + await this.analyzeTypeScriptFile(file, content); + } + catch (e) { + this.analyzeWithTsMorph(file); + } + } + } + async processGoFilesWithCache(files) { + const uncachedFiles = []; + for (const file of files) { + const cached = this.graphCache?.get(file); + if (cached) { + for (const sym of cached.symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym); + } + if (!this.graph.fileIndex.has(file)) { + this.graph.fileIndex.set(file, []); + } + this.graph.fileIndex.get(file).push(...cached.symbols); + this.graph.edges.push(...cached.edges); + } + else { + uncachedFiles.push(file); + } + } + if (uncachedFiles.length === 0) { + console.log(`[GraphCache] Go: All ${files.length} files served from cache`); + return; + } + console.log(`[GraphCache] Go: ${uncachedFiles.length}/${files.length} files need parsing`); + for (const file of uncachedFiles) { + try { + const content = fs.readFileSync(file, 'utf8'); + await this.analyzeGoFile(file, content); + } + catch (e) { + // Skip files that can't be read + } + } + } + async processPythonFilesWithCache(files) { + const uncachedFiles = []; + for (const file of files) { + const cached = this.graphCache?.get(file); + if (cached) { + for (const sym of cached.symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym); + } + if (!this.graph.fileIndex.has(file)) { + this.graph.fileIndex.set(file, []); + } + this.graph.fileIndex.get(file).push(...cached.symbols); + this.graph.edges.push(...cached.edges); + } + else { + uncachedFiles.push(file); + } + } + if (uncachedFiles.length === 0) { + console.log(`[GraphCache] Python: All ${files.length} files served from cache`); + return; + } + console.log(`[GraphCache] Python: ${uncachedFiles.length}/${files.length} files need parsing`); + for (const file of uncachedFiles) { + try { + const content = fs.readFileSync(file, 'utf8'); + await this.analyzePythonFile(file, content); + } + catch (e) { + // Skip files that can't be read + } + } + } + async analyzeRustFile(file, content) { + try { + const lang = await this.getLanguage(file); + if (!lang) + return; + const parser = new web_tree_sitter_1.default(); + parser.setLanguage(lang); + const tree = parser.parse(content); + const symbols = []; + const fnQuery = lang.query(` + (function_item name: (identifier) @name) @func + (struct_item name: (type_identifier) @name) @struct + (enum_item name: (type_identifier) @name) @enum + (trait_item name: (type_identifier) @name) @trait + `); + for (const match of fnQuery.captures(tree.rootNode)) { + const name = match.node.text; + let type = 'function'; + if (match.name === 'struct') + type = 'class'; + if (match.name === 'enum') + type = 'type'; + if (match.name === 'trait') + type = 'interface'; + symbols.push({ + name, + type, + file, + line: match.node.startPosition.row, + exports: [], + imports: [], + references: [] + }); + } + for (const sym of symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym); + } + if (!this.graph.fileIndex.has(file)) + this.graph.fileIndex.set(file, []); + this.graph.fileIndex.get(file).push(...symbols); + if (this.graphCache) { + const { statSync } = require('fs'); + const stats = statSync(file); + this.graphCache.set(file, { + mtime: stats.mtimeMs, + size: stats.size, + contentHash: computeContentHash(content), + symbols, + edges: [], + parsedAt: Date.now() + }); + } + } + catch { } + } + async analyzeCppJavaFile(file, content) { + try { + const lang = await this.getLanguage(file); + if (!lang) + return; + const parser = new web_tree_sitter_1.default(); + parser.setLanguage(lang); + const tree = parser.parse(content); + const symbols = []; + const query = lang.query(` + (class_declaration name: (identifier) @name) @class + (method_declaration name: (identifier) @name) @method + (function_definition declarator: (function_declarator declarator: (identifier) @name)) @func + `); + for (const match of query.captures(tree.rootNode)) { + const name = match.node.text; + let type = 'variable'; + if (match.name === 'class') + type = 'class'; + if (match.name === 'method') + type = 'method'; + if (match.name === 'func') + type = 'function'; + symbols.push({ + name, + type, + file, + line: match.node.startPosition.row, + exports: [], + imports: [], + references: [] + }); + } + for (const sym of symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym); + } + if (!this.graph.fileIndex.has(file)) + this.graph.fileIndex.set(file, []); + this.graph.fileIndex.get(file).push(...symbols); + if (this.graphCache) { + const { statSync } = require('fs'); + const stats = statSync(file); + this.graphCache.set(file, { + mtime: stats.mtimeMs, + size: stats.size, + contentHash: computeContentHash(content), + symbols, + edges: [], + parsedAt: Date.now() + }); + } + } + catch { } + } + async processRustFilesWithCache(files) { + const uncached = []; + for (const file of files) { + const cached = this.graphCache?.get(file); + if (cached) { + for (const sym of cached.symbols) + this.graph.symbols.set(`${file}:${sym.name}`, sym); + if (!this.graph.fileIndex.has(file)) + this.graph.fileIndex.set(file, []); + this.graph.fileIndex.get(file).push(...cached.symbols); + } + else { + uncached.push(file); + } + } + for (const file of uncached) { + try { + const content = fs.readFileSync(file, 'utf8'); + await this.analyzeRustFile(file, content); + } + catch { } + } + } + async processCppJavaFilesWithCache(files) { + const uncached = []; + for (const file of files) { + const cached = this.graphCache?.get(file); + if (cached) { + for (const sym of cached.symbols) + this.graph.symbols.set(`${file}:${sym.name}`, sym); + if (!this.graph.fileIndex.has(file)) + this.graph.fileIndex.set(file, []); + this.graph.fileIndex.get(file).push(...cached.symbols); + } + else { + uncached.push(file); + } + } + for (const file of uncached) { + try { + const content = fs.readFileSync(file, 'utf8'); + await this.analyzeCppJavaFile(file, content); + } + catch { } + } + } + async analyzeTypeScriptFile(file, content) { + const lang = await this.getLanguage(file); + if (!lang) + return; + const parser = new web_tree_sitter_1.default(); + parser.setLanguage(lang); + try { + const tree = parser.parse(content); + const symbols = this.extractTSSymbols(file, tree, lang); + const edges = this.extractTSEdges(file, tree, lang, symbols); + for (const sym of symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym); + if (!this.graph.fileIndex.has(file)) { + this.graph.fileIndex.set(file, []); + } + this.graph.fileIndex.get(file).push(sym); + } + this.graph.edges.push(...edges); + if (this.graphCache) { + try { + const { statSync } = require('fs'); + const stats = statSync(file); + this.graphCache.set(file, { + mtime: stats.mtimeMs, + size: stats.size, + contentHash: computeContentHash(content), + symbols, + edges, + parsedAt: Date.now() + }); + } + catch { } + } + } + catch (e) { + this.analyzeWithTsMorph(file); + } + } + extractTSEdges(file, tree, lang, symbols) { + const edges = []; + for (const sym of symbols) { + for (const imp of sym.imports) { + edges.push({ + from: file, + to: imp, + type: 'imports' + }); + } + } + return edges; + } + extractTSSymbols(file, tree, lang) { + const symbols = []; + const query = lang.query(` + (function_declaration + name: (identifier) @name + parameters: (parameter_list) @params) @func + (class_declaration + name: (identifier) @name + heritage: (class_heritage)?) @class + (interface_declaration + name: (type_identifier) @name) @iface + (type_alias_declaration + name: (type_identifier) @name) @type + (variable_declaration + name: (identifier) @name + value: (assignment_expression) @val) @var + (method_definition + name: (property_identifier) @name) @method + `); + const queryMatches = query.captures(tree.rootNode); + for (const match of queryMatches) { + const name = match.node.text; + const symbol = { + name, + type: this.inferSymbolType(match.name), + file, + line: match.node.startPosition.row, + exports: [], + imports: [], + references: [] + }; + symbols.push(symbol); + } + return symbols; + } + inferSymbolType(captureName) { + switch (captureName) { + case 'func': + return 'function'; + case 'class': + return 'class'; + case 'iface': + return 'interface'; + case 'type': + return 'type'; + case 'var': + return 'variable'; + case 'method': + return 'method'; + default: + return 'variable'; + } + } + analyzeWithTsMorph(file) { + try { + const sourceFile = this.project.addSourceFileAtPath(file); + sourceFile.getExportedDeclarations().forEach((declarations, name) => { + const decl = declarations[0]; + if (!decl) + return; + const symbol = { + name, + type: this.getTsMorphSymbolType(decl.getKind()), + file, + line: decl.getStartLineNumber(), + exports: [name], + imports: this.extractImports(sourceFile), + references: [] + }; + this.graph.symbols.set(`${file}:${name}`, symbol); + if (!this.graph.fileIndex.has(file)) { + this.graph.fileIndex.set(file, []); + } + this.graph.fileIndex.get(file).push(symbol); + }); + } + catch (e) { + // Skip files that can't be parsed + } + } + getTsMorphSymbolType(kind) { + const map = { + [ts_morph_1.SyntaxKind.FunctionDeclaration]: 'function', + [ts_morph_1.SyntaxKind.ClassDeclaration]: 'class', + [ts_morph_1.SyntaxKind.InterfaceDeclaration]: 'interface', + [ts_morph_1.SyntaxKind.TypeAliasDeclaration]: 'type', + [ts_morph_1.SyntaxKind.VariableDeclaration]: 'const', + [ts_morph_1.SyntaxKind.MethodDeclaration]: 'method', + [ts_morph_1.SyntaxKind.PropertyDeclaration]: 'variable' + }; + return map[kind] || 'variable'; + } + extractImports(sourceFile) { + const imports = []; + try { + const importDefs = sourceFile.getImportDeclarations(); + for (const imp of importDefs) { + const moduleName = imp.getModuleSpecifier().getText(); + imports.push(moduleName.replace(/['"]/g, '')); + } + } + catch (e) { } + return imports; + } + async extractGoSymbolsTreeSitter(file, content) { + const symbols = []; + try { + const lang = await this.getLanguage(file); + if (!lang) + return this.extractGoSymbolsRegex(content, file); + const parser = new web_tree_sitter_1.default(); + parser.setLanguage(lang); + const tree = parser.parse(content); + const funcQuery = lang.query(` + (function_declaration + name: (identifier) @funcName) @func + (method_declaration + receiver: (parameter_list) + name: (field_identifier) @methodName) @method + (type_declaration + name: (type_identifier) @typeName) @type + `); + for (const match of funcQuery.captures(tree.rootNode)) { + const name = match.node.text; + const line = match.node.startPosition.row + 1; + if (match.name === 'funcName') { + const isExported = name[0] === name[0].toUpperCase(); + symbols.push({ + name, + type: 'function', + file, + line, + exports: isExported ? [name] : [], + imports: this.extractGoImports(content), + references: [] + }); + } + else if (match.name === 'methodName') { + const isExported = name[0] === name[0].toUpperCase(); + symbols.push({ + name, + type: 'method', + file, + line, + exports: isExported ? [name] : [], + imports: this.extractGoImports(content), + references: [] + }); + } + else if (match.name === 'typeName') { + symbols.push({ + name, + type: 'class', + file, + line, + exports: [name], + imports: [], + references: [] + }); + } + } + } + catch (e) { + return this.extractGoSymbolsRegex(content, file); + } + return symbols; + } + extractGoSymbolsRegex(content, file) { + const symbols = []; + const lines = content.split('\n'); + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + let match = line.match(/^func\s+(\([^*]+\)\s+)?(\*)?([A-Z][a-zA-Z0-9_]*)/); + if (match) { + symbols.push({ + name: match[3], + type: match[2] ? 'method' : 'function', + file, + line: i + 1, + exports: match[3][0] === match[3][0].toUpperCase() ? [match[3]] : [], + imports: this.extractGoImports(content), + references: [] + }); + } + match = line.match(/^type\s+([A-Z][a-zA-Z0-9_]*)\s+(struct|interface)/); + if (match) { + symbols.push({ + name: match[1], + type: match[2] === 'struct' ? 'class' : 'interface', + file, + line: i + 1, + exports: [match[1]], + imports: [], + references: [] + }); + } + } + return symbols; + } + async extractGoSymbols(file, content) { + return this.extractGoSymbolsTreeSitter(file, content); + } + extractGoImports(content) { + const imports = []; + const importMatch = content.match(/import\s+\(([\s\S]*?)\)/); + if (importMatch) { + const importBlock = importMatch[1]; + const quoteMatches = importBlock.match(/"([^"]+)"/g); + if (quoteMatches) { + for (const m of quoteMatches) { + imports.push(m.replace(/"/g, '')); + } + } + } + return imports; + } + async analyzeGoFile(file, content) { + const symbols = await this.extractGoSymbols(file, content); + for (const sym of symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym); + if (!this.graph.fileIndex.has(file)) + this.graph.fileIndex.set(file, []); + this.graph.fileIndex.get(file).push(sym); + } + } + async analyzePythonFile(file, content) { + const symbols = this.extractPythonSymbols(file, content); + for (const sym of symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym); + if (!this.graph.fileIndex.has(file)) + this.graph.fileIndex.set(file, []); + this.graph.fileIndex.get(file).push(sym); + } + } + extractPythonSymbols(file, content) { + const symbols = []; + const lines = content.split('\n'); + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + let match = line.match(/^class\s+([A-Z][a-zA-Z0-9_]*)/); + if (match) { + symbols.push({ + name: match[1], + type: 'class', + file, + line: i + 1, + exports: [match[1]], + imports: this.extractPythonImports(content), + references: [] + }); + } + match = line.match(/^def\s+([a-z_][a-zA-Z0-9_]*)/); + if (match) { + symbols.push({ + name: match[1], + type: 'function', + file, + line: i + 1, + exports: [], + imports: [], + references: [] + }); + } + match = line.match(/^([A-Z_][A-Z0-9_]*)\s*=/); + if (match) { + symbols.push({ + name: match[1], + type: 'const', + file, + line: i + 1, + exports: [match[1]], + imports: [], + references: [] + }); + } + } + return symbols; + } + extractPythonImports(content) { + const imports = []; + const importRegex = /^(?:from\s+([.\w]+)\s+)?import\s+([.\w, ]+)/gm; + let match; + while ((match = importRegex.exec(content)) !== null) { + const module = match[1] || match[2]; + imports.push(module.trim()); + } + return imports; + } + async getLanguage(file) { + const ext = file.substring(file.lastIndexOf('.')); + if (this.languageCache.has(ext)) { + const cached = this.languageCache.get(ext); + if (Date.now() - cached.cachedAt < LANGUAGE_LOADER_CACHE_TTL_MS) { + return cached.language; + } + this.languageCache.delete(ext); + } + const loader = LANGUAGE_LOADERS[ext]; + if (loader) { + try { + const lang = await loader(); + if (this.languageCache.size >= LANGUAGE_LOADER_MAX_SIZE) { + const oldestKey = Array.from(this.languageCache.entries()).sort((a, b) => a[1].cachedAt - b[1].cachedAt)[0][0]; + this.languageCache.delete(oldestKey); + } + this.languageCache.set(ext, { language: lang, cachedAt: Date.now() }); + return lang; + } + catch (e) { + return null; + } + } + return null; + } + buildDependencyEdges() { + for (const [key, sym] of this.graph.symbols) { + for (const imported of sym.imports) { + for (const [otherKey, otherSym] of this.graph.symbols) { + if (otherSym.file.includes(imported) || + imported.includes(otherSym.name)) { + this.graph.edges.push({ + from: key, + to: otherKey, + type: 'imports' + }); + } + } + } + } + } + buildRepoContext() { + const typeHierarchy = new Map(); + const callGraph = new Map(); + for (const [key, sym] of this.graph.symbols) { + if (sym.type === 'class' || sym.type === 'interface') { + const children = this.findTypeChildren(sym.name); + typeHierarchy.set(key, children); + } + if (sym.type === 'function' || sym.type === 'method') { + const callers = this.findFunctionCallers(sym.name); + callGraph.set(key, callers); + } + } + const architecturalLayers = this.inferArchitecturalLayers(); + return { + symbolGraph: this.graph, + typeHierarchy, + callGraph, + architecturalLayers + }; + } + findTypeChildren(typeName) { + const children = []; + for (const [, sym] of this.graph.symbols) { + if (sym.type === 'class' && sym.exports.includes(typeName)) { + children.push(`${sym.file}:${sym.name}`); + } + } + return children; + } + findFunctionCallers(funcName) { + const callers = []; + for (const [key, sym] of this.graph.symbols) { + if (sym.references.includes(funcName)) { + callers.push(key); + } + } + return callers; + } + inferFileLayer(file) { + const lowerFile = file.toLowerCase(); + const patterns = [ + { + layer: 'controller', + patterns: ['controller', 'handler', 'route', 'endpoint', 'api'] + }, + { layer: 'service', patterns: ['service', 'business', 'manager'] }, + { + layer: 'repository', + patterns: ['repository', 'repo', 'dal', 'dataaccess'] + }, + { layer: 'model', patterns: ['model', 'entity', 'domain', 'schema'] }, + { layer: 'util', patterns: ['util', 'helper', 'common', 'shared'] } + ]; + for (const { layer, patterns: layerPatterns } of patterns) { + if (layerPatterns.some(p => lowerFile.includes(p))) { + return layer; + } + } + return null; + } + isAllowedCrossing(fromLayer, toLayer, allowedCrossings) { + const allowed = allowedCrossings[fromLayer]; + return allowed ? allowed.includes(toLayer) : false; + } + calculateViolationSeverity(fromLayer, toLayer) { + if (fromLayer === 'model' || toLayer === 'model') { + return fromLayer === 'model' ? 'critical' : 'major'; + } + if (fromLayer === 'controller' && + (toLayer === 'repository' || toLayer === 'model')) { + return 'major'; + } + return 'minor'; + } + inferArchitecturalLayers() { + const layers = new Map(); + const layerPatterns = [ + { + layer: 'controller', + patterns: ['controller', 'handler', 'route', 'endpoint', 'api'] + }, + { layer: 'service', patterns: ['service', 'business', 'logic', 'manager'] }, + { + layer: 'repository', + patterns: ['repository', 'repo', 'dal', 'dataaccess'] + }, + { layer: 'model', patterns: ['model', 'entity', 'domain', 'schema'] }, + { layer: 'util', patterns: ['util', 'helper', 'common', 'shared'] } + ]; + for (const [file] of this.graph.fileIndex) { + const lowerFile = file.toLowerCase(); + for (const { layer, patterns } of layerPatterns) { + if (patterns.some(p => lowerFile.includes(p))) { + for (const sym of this.graph.fileIndex.get(file) || []) { + layers.set(`${file}:${sym.name}`, layer); + } + break; + } + } + } + return layers; + } + detectArchitecturalViolations(changedFiles, architecturalLayers) { + const violations = []; + const layerHierarchy = { + controller: 1, + handler: 1, + service: 2, + business: 2, + repository: 3, + repo: 3, + dal: 3, + model: 4, + entity: 4, + domain: 4, + util: 5, + helper: 5 + }; + const allowedCrossings = { + controller: ['service', 'handler'], + handler: ['service'], + service: ['repository', 'model', 'util'], + repository: ['model', 'dal'] + }; + for (const file of changedFiles) { + const fileLayer = this.inferFileLayer(file); + if (!fileLayer) + continue; + const fileDeps = this.getFileDependencies(file); + const fileLayerRank = layerHierarchy[fileLayer] || 0; + for (const dep of fileDeps) { + const depFile = dep.split(':')[0]; + const depLayer = this.inferFileLayer(depFile); + if (!depLayer) + continue; + const depRank = layerHierarchy[depLayer] || 0; + if (fileLayerRank > depRank && + !this.isAllowedCrossing(fileLayer, depLayer, allowedCrossings)) { + violations.push({ + from: file, + to: depFile, + fromLayer: fileLayer, + toLayer: depLayer, + severity: this.calculateViolationSeverity(fileLayer, depLayer), + description: `Layer violation: \`${fileLayer}\` should not depend on \`${depLayer}\`` + }); + } + } + } + return violations; + } + querySymbol(symbolName) { + for (const [, sym] of this.graph.symbols) { + if (sym.name === symbolName) { + return sym; + } + } + return null; + } + getFileDependencies(file) { + const deps = []; + for (const edge of this.graph.edges) { + if (edge.from.startsWith(file)) { + deps.push(edge.to); + } + } + return deps; + } + getDownstreamImpact(symbolKey) { + const impacted = []; + const maxDepth = 2; + for (const edge of this.graph.edges) { + if (edge.to === symbolKey) { + impacted.push(edge.from); + } + } + const transitive = new Set(impacted); + const queue = impacted.map(k => ({ + key: k, + depth: 1 + })); + while (queue.length > 0) { + const { key: current, depth } = queue.shift(); + if (depth >= maxDepth) + continue; + for (const edge of this.graph.edges) { + if (edge.to === current && !transitive.has(edge.from)) { + transitive.add(edge.from); + queue.push({ key: edge.from, depth: depth + 1 }); + } + } + } + return Array.from(transitive); + } + getContextForSymbol(symbolKey) { + const sym = this.graph.symbols.get(symbolKey); + if (!sym) + return ''; + const layer = this.inferFileLayer(sym.file) || 'unknown'; + const deps = this.getFileDependencies(sym.file); + const downstream = this.getDownstreamImpact(symbolKey); + return ` +Symbol: ${sym.name} +Type: ${sym.type} +File: ${sym.file}:${sym.line} +Layer: ${layer} +Dependencies: ${deps.length} +Downstream Impact: ${downstream.length} files +`.trim(); + } +} +exports.UnifiedContextEngine = UnifiedContextEngine; +exports.unifiedContextEngine = new UnifiedContextEngine(); +//# sourceMappingURL=symbol-graph.js.map \ No newline at end of file diff --git a/lib/src/symbol-graph.js.map b/lib/src/symbol-graph.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e78d1447c365b808018a2448e1c99f261b5a67ae --- /dev/null +++ b/lib/src/symbol-graph.js.map @@ -0,0 +1 @@ +{"version":3,"file":"symbol-graph.js","sourceRoot":"","sources":["../../src/symbol-graph.ts"],"names":[],"mappings":";;;;;;AAAA,+BAA+B;AAC/B,sEAAmD;AAEnD,uCAA4C;AAC5C,6DAA6E;AAC7E,mCAAiC;AACjC,uDAA+D;AAC/D,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;AA+CxB,MAAM,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,IAAI,cAAc,CAAA;AAE3D,MAAM,gBAAgB,GAAuC;IAC3D,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,yBAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,UAAU,8BAA8B,CAAC;IACpF,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,yBAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,UAAU,uBAAuB,CAAC;IAC9E,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,yBAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,UAAU,8BAA8B,CAAC;IACpF,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,yBAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,UAAU,8BAA8B,CAAC;IACrF,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,yBAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,UAAU,sBAAsB,CAAC;IAC5E,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,yBAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,UAAU,0BAA0B,C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G,CAAC,IAAI,CAAC,IAAI,SAAS,CAAA;QACxD,MAAM,IAAI,GAAG,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QAC/C,MAAM,UAAU,GAAG,IAAI,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAA;QAEtD,OAAO;UACD,GAAG,CAAC,IAAI;QACV,GAAG,CAAC,IAAI;QACR,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,IAAI;SACnB,KAAK;gBACE,IAAI,CAAC,MAAM;qBACN,UAAU,CAAC,MAAM;CACrC,CAAC,IAAI,EAAE,CAAA;IACN,CAAC;CACF;AAxjCD,oDAwjCC;AAEY,QAAA,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAA"} \ No newline at end of file diff --git a/lib/src/test-generator.js b/lib/src/test-generator.js new file mode 100644 index 0000000000000000000000000000000000000000..5dac11e7866bfc64dfbd3a0b77ae2172c43b47e1 --- /dev/null +++ b/lib/src/test-generator.js @@ -0,0 +1,303 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.testGenerator = exports.TestGenerator = void 0; +/* eslint-disable no-console */ +const logInfo = console.log; +class TestGenerator { + MIN_CONFIDENCE = 0.75; + async generateTestCase(filename, bugComment, remedy, heavyBot) { + try { + const bugAnalysis = this.parseBugComment(bugComment); + if (!bugAnalysis) { + logInfo('Could not parse bug comment for test generation'); + return null; + } + const ext = filename.split('.').pop()?.toLowerCase(); + const language = this.getLanguage(ext); + const [testCaseResponse] = await heavyBot.chat(this.buildTestPrompt(filename, bugAnalysis, remedy, language), {}); + if (!testCaseResponse || testCaseResponse.length < 20) { + return null; + } + const testCase = this.extractTestCode(testCaseResponse, language); + if (!testCase) { + return null; + } + const testFile = this.findTestFile(filename); + const testType = this.inferTestType(bugAnalysis); + const confidence = this.estimateConfidence(bugAnalysis); + if (confidence < this.MIN_CONFIDENCE) { + logInfo(`Test generation confidence ${confidence} below threshold`); + return null; + } + return { + testCase, + testFile, + language, + testType, + confidence + }; + } + catch (e) { + logInfo(`Test generation failed: ${e}`); + return null; + } + } + parseBugComment(comment) { + try { + const bugType = this.extractBugType(comment); + const severity = this.extractSeverity(comment); + const functionName = this.extractFunctionName(comment); + const parameters = this.extractParameters(comment); + const { expected, actual } = this.extractBehavior(comment); + if (!bugType && !functionName) { + return null; + } + return { + bugType: bugType || 'general', + severity: severity || 'minor', + functionName: functionName || '', + parameters, + expectedBehavior: expected || '', + actualBehavior: actual || '' + }; + } + catch (e) { + return null; + } + } + extractBugType(comment) { + const patterns = [ + /null\s*pointer|NPE|null\s*check/i, + /division\s*by\s*zero|divide\s*by\s*0/i, + /race\s*condition|concurrent|deadlock/i, + /memory\s*leak|dispose|resource/i, + /sql\s*injection|injection/i, + /xss|cross.*site|innerHTML/i, + /async.*await|promise/i, + /off\s*by\s*one|index.*bound/i, + /type.*error|cannot\s*read|i[is] undefined/i, + /security|vulnerability|auth/i + ]; + const keywords = [ + 'null pointer', + 'division by zero', + 'race condition', + 'memory leak', + 'sql injection', + 'xss', + 'async await', + 'off by one', + 'type error', + 'security vulnerability' + ]; + const lowerComment = comment.toLowerCase(); + for (let i = 0; i < patterns.length; i++) { + if (patterns[i].test(lowerComment)) { + return keywords[i]; + } + } + return null; + } + extractSeverity(comment) { + if (/\[CRITICAL\]|critical|severe|p0|critical/i.test(comment)) + return 'critical'; + if (/\[MAJOR\]|major|important|p1/i.test(comment)) + return 'major'; + if (/\[MINOR\]|minor|p2/i.test(comment)) + return 'minor'; + return 'info'; + } + extractFunctionName(comment) { + const patterns = [ + /function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/i, + /([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/, + /method\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/i, + /`([a-zA-Z_$][a-zA-Z0-9_$]*)`/ + ]; + for (const pattern of patterns) { + const match = comment.match(pattern); + if (match && match[1]) { + return match[1]; + } + } + return null; + } + extractParameters(comment) { + const params = []; + const paramPatterns = [ + /`(.*?)`/g, + /parameter[s]?:\s*([a-zA-Z0-9_$,\s]+)/gi, + /arg[s]?\s+([a-zA-Z0-9_$,\s]+)/gi + ]; + for (const pattern of paramPatterns) { + let match; + while ((match = pattern.exec(comment)) !== null) { + if (match[1]) { + const parts = match[1].split(/[,\s]+/).filter(p => p.length > 0); + params.push(...parts); + } + } + } + return [...new Set(params)].slice(0, 5); + } + extractBehavior(comment) { + let expected = ''; + let actual = ''; + const expectedMatch = comment.match(/expected[:\s]+([^.]+)/i); + if (expectedMatch) + expected = expectedMatch[1].trim(); + const actualMatch = comment.match(/(?:actual|got|but\s*got)[:\s]+([^.]+)/i); + if (actualMatch) + actual = actualMatch[1].trim(); + const returnMatch = comment.match(/returns?\s+([^.]+)/i); + if (returnMatch && !actual) + actual = returnMatch[1].trim(); + return { expected, actual }; + } + getLanguage(ext) { + const map = { + ts: 'TypeScript', + tsx: 'TypeScript', + js: 'JavaScript', + jsx: 'JavaScript', + py: 'Python', + go: 'Go', + java: 'Java', + rs: 'Rust', + rb: 'Ruby', + cs: 'C#' + }; + return map[ext || ''] || 'JavaScript'; + } + findTestFile(sourceFile) { + const testPatterns = [ + { + pattern: /^(src|lib|app)\/(.+)\.(ts|js|py|go)$/, + replacement: '$1/$2.test.$3' + }, + { + pattern: /^(src|lib|app)\/(.+)\.(ts|js|py|go)$/, + replacement: '$1/$2.spec.$3' + }, + { pattern: /^(.+)\.(ts|js|py|go)$/, replacement: '$1.test.$2' }, + { pattern: /^(.+)\.(ts|js|py|go)$/, replacement: '$1.spec.$2' } + ]; + for (const { pattern, replacement } of testPatterns) { + const testFile = sourceFile.replace(pattern, replacement); + if (testFile !== sourceFile) { + return testFile; + } + } + const ext = sourceFile.split('.').pop(); + return sourceFile.replace(`.${ext}`, `.test.${ext}`); + } + inferTestType(bug) { + const dbPatterns = /database|query|sql|crud|repository/i; + const apiPatterns = /api|endpoint|http|fetch|request/i; + const uiPatterns = /click|render|component|ui|button/i; + const content = `${bug.bugType} ${bug.functionName}`.toLowerCase(); + if (dbPatterns.test(content)) + return 'integration'; + if (apiPatterns.test(content)) + return 'integration'; + if (uiPatterns.test(content)) + return 'e2e'; + return 'unit'; + } + estimateConfidence(bug) { + let confidence = 0.3; + if (!bug.functionName || !bug.bugType) { + return confidence; + } + confidence = 0.5; + if (bug.functionName) + confidence += 0.15; + if (bug.bugType) + confidence += 0.1; + if (bug.expectedBehavior && bug.actualBehavior) + confidence += 0.15; + if (bug.parameters.length > 0) + confidence += 0.05; + if (bug.bugType === 'null pointer' || bug.bugType === 'division by zero') { + confidence += 0.1; + } + if (bug.bugType === 'sql injection' || + bug.bugType === 'security vulnerability') { + confidence += 0.15; + } + return Math.min(1, confidence); + } + buildTestPrompt(filename, bug, remedy, language) { + return `Generate a minimal unit test that reproduces a bug in ${filename}. + +Bug Analysis: +- Type: ${bug.bugType} +- Severity: ${bug.severity} +- Function: ${bug.functionName} +- Parameters: ${bug.parameters.join(', ') || 'unknown'} +- Expected behavior: ${bug.expectedBehavior || 'correct handling'} +- Actual behavior: ${bug.actualBehavior || 'incorrect handling'} + +Remediation applied: +\`\`\` +${remedy} +\`\`\` + +Requirements: +1. Generate ONLY the test code, no explanations +2. The test should FAIL before the fix and PASS after the fix +3. Include realistic test data that triggers the bug +4. Use ${language} testing conventions +5. Keep it minimal - just enough to reproduce the issue +6. Include a comment explaining what edge case is being tested + +Format: Return ONLY the test code in a code block labeled with the language.`; + } + extractTestCode(response, language) { + const patterns = [ + new RegExp(`\`\`\`${language.toLowerCase()}[\\s\\S]*?\`\`\``), + new RegExp(`\`\`\`${language}[\\s\\S]*?\`\`\``), + new RegExp('```[a-z]*\\n([\\s\\S]*?)```') + ]; + for (const pattern of patterns) { + const match = response.match(pattern); + if (match) { + return match[1].trim(); + } + } + const codeBlockMatch = response.match(/```[\s\S]*?\n([\s\S]*?)```/); + if (codeBlockMatch) { + return codeBlockMatch[1].trim(); + } + return response.trim().length > 50 ? response.trim() : null; + } + formatTestSuggestion(result) { + const confidenceLabel = result.confidence >= 0.8 + ? 'High' + : result.confidence >= 0.6 + ? 'Medium' + : 'Low'; + const autoGenWarning = `// โš ๏ธ AUTO-GENERATED BY PRIX - REVIEW BEFORE COMMIT +// DO NOT COMMIT WITHOUT UNDERSTANDING THIS TEST +`; + return ` +
+๐Ÿงช Auto-Generated Test Case (${confidenceLabel} confidence) + +**Test File:** \`${result.testFile}\` +**Type:** ${result.testType} +**Confidence:** ${Math.round(result.confidence * 100)}% + +\`\`\`${result.language.toLowerCase()} +${autoGenWarning}${result.testCase} +\`\`\` + +> โš ๏ธ Review this test carefully before committing. It was auto-generated based on the bug analysis. + +
+`; + } +} +exports.TestGenerator = TestGenerator; +exports.testGenerator = new TestGenerator(); +//# sourceMappingURL=test-generator.js.map \ No newline at end of file diff --git a/lib/src/test-generator.js.map b/lib/src/test-generator.js.map new file mode 100644 index 0000000000000000000000000000000000000000..feb7c516509d0f610c7f27cfcae6f558870f15f8 --- /dev/null +++ b/lib/src/test-generator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-generator.js","sourceRoot":"","sources":["../../src/test-generator.ts"],"names":[],"mappings":";;;AACA,+BAA+B;AAC/B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAA;AAoB3B,MAAa,aAAa;IACP,cAAc,GAAG,IAAI,CAAA;IAEtC,KAAK,CAAC,gBAAgB,CACpB,QAAgB,EAChB,UAAkB,EAClB,MAAc,EACd,QAAa;QAEb,IAAI,CAAC;YACH,MAAM,WAAW,GAAG,IAAI,CAAC,eAAe,CAAC,UAAU,CAAC,CAAA;YACpD,IAAI,CAAC,WAAW,EAAE,CAAC;gBACjB,OAAO,CAAC,iDAAiD,CAAC,CAAA;gBAC1D,OAAO,IAAI,CAAA;YACb,CAAC;YAED,MAAM,GAAG,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,WAAW,EAAE,CAAA;YACpD,MAAM,QAAQ,GAAG,IAAI,CAAC,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,GAAG,GAAG,CAAC;;QAE7C,MAAM,CAAC,QAAQ,CAAC,WAAW,EAAE;EACnC,cAAc,GAAG,MAAM,CAAC,QAAQ;;;;;;CAMjC,CAAA;IACC,CAAC;CACF;AAxVD,sCAwVC;AAEY,QAAA,aAAa,GAAG,IAAI,aAAa,EAAE,CAAA"} \ No newline at end of file diff --git a/lib/src/tokenizer.js b/lib/src/tokenizer.js new file mode 100644 index 0000000000000000000000000000000000000000..c39f19cb0f6ef9e0f8951a0c3e08762f3b220cfa --- /dev/null +++ b/lib/src/tokenizer.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encode = encode; +exports.getTokenCount = getTokenCount; +// eslint-disable-next-line camelcase +const tiktoken_1 = require("@dqbd/tiktoken"); +const tokenizer = (0, tiktoken_1.get_encoding)('cl100k_base'); +function encode(input) { + return tokenizer.encode(input); +} +function getTokenCount(input) { + input = input.replace(/<\|endoftext\|>/g, ''); + return encode(input).length; +} +//# sourceMappingURL=tokenizer.js.map \ No newline at end of file diff --git a/lib/src/tokenizer.js.map b/lib/src/tokenizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f25a46ec3a3a94a25c5d30d755ee33a0c9c5be0b --- /dev/null +++ b/lib/src/tokenizer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tokenizer.js","sourceRoot":"","sources":["../../src/tokenizer.ts"],"names":[],"mappings":";;AAKA,wBAEC;AAED,sCAGC;AAZD,qCAAqC;AACrC,6CAA2C;AAE3C,MAAM,SAAS,GAAG,IAAA,uBAAY,EAAC,aAAa,CAAC,CAAA;AAE7C,SAAgB,MAAM,CAAC,KAAa;IAClC,OAAO,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAChC,CAAC;AAED,SAAgB,aAAa,CAAC,KAAa;IACzC,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,kBAAkB,EAAE,EAAE,CAAC,CAAA;IAC7C,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAA;AAC7B,CAAC"} \ No newline at end of file diff --git a/lib/src/utils.js b/lib/src/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..fc34df300557d11ca41c96557c7a0544a4d5e59c --- /dev/null +++ b/lib/src/utils.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.prixExec = void 0; +const child_process_1 = require("child_process"); +const context_1 = require("./context"); +/** + * Executes a shell command using the current context's working directory. + * Thread-safe for Probot. + */ +const prixExec = (command, options = {}) => { + const context = context_1.als.getStore(); + const cwd = options.cwd || context?.workingDir || process.cwd(); + const result = (0, child_process_1.execSync)(command, { + ...options, + cwd, + encoding: 'utf8' + }); + return result ? result.toString() : ''; +}; +exports.prixExec = prixExec; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/lib/src/utils.js.map b/lib/src/utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c04dcabb2360d56a62f11fa0a22a69662fabe291 --- /dev/null +++ b/lib/src/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";;;AAAA,iDAAuD;AACvD,uCAA6B;AAE7B;;;GAGG;AACI,MAAM,QAAQ,GAAG,CACtB,OAAe,EACf,UAA2B,EAAE,EACrB,EAAE;IACV,MAAM,OAAO,GAAG,aAAG,CAAC,QAAQ,EAAE,CAAA;IAC9B,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,IAAI,OAAO,EAAE,UAAU,IAAI,OAAO,CAAC,GAAG,EAAE,CAAA;IAE/D,MAAM,MAAM,GAAG,IAAA,wBAAQ,EAAC,OAAO,EAAE;QAC/B,GAAG,OAAO;QACV,GAAG;QACH,QAAQ,EAAE,MAAM;KACjB,CAAC,CAAA;IAEF,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;AACxC,CAAC,CAAA;AAdY,QAAA,QAAQ,YAcpB"} \ No newline at end of file diff --git a/scripts/download-parsers.sh b/scripts/download-parsers.sh new file mode 100644 index 0000000000000000000000000000000000000000..7b7537354e53ae21c81d163123f5e6b62205e6dc --- /dev/null +++ b/scripts/download-parsers.sh @@ -0,0 +1,10 @@ +#!/bin/bash +mkdir -p parsers +BASE_URL="https://github.com/PR-AUTOMATE/tree-sitter-wasm/raw/main" + +languages=("javascript" "typescript" "python" "go" "cpp" "rust" "java" "c" "tsx") + +for lang in "${languages[@]}"; do + echo "Downloading $lang.wasm..." + curl -L "$BASE_URL/tree-sitter-$lang.wasm" -o "parsers/tree-sitter-$lang.wasm" || echo "Failed to download $lang" +done diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.sh new file mode 100644 index 0000000000000000000000000000000000000000..8b91c9398e1146cfc6e3b770bee6eeb9b895f507 --- /dev/null +++ b/scripts/install-hooks.sh @@ -0,0 +1,96 @@ +#!/bin/bash +# PRIX Pre-commit Hook Installer +# Usage: ./install-hooks.sh + +set -e + +HOOK_DIR="$(git rev-parse --show-toplevel)/.git/hooks" +PRECOMMIT_HOOK="$HOOK_DIR/pre-commit" + +echo "๐Ÿ”ง Installing PRIX pre-commit hook..." + +if [ ! -d "$HOOK_DIR" ]; then + echo "โŒ Error: .git/hooks directory not found. Are you in a git repository?" + exit 1 +fi + +if [ -f "$PRECOMMIT_HOOK" ]; then + echo "โš ๏ธ Existing pre-commit hook found. Backing up to pre-commit.bak" + cp "$PRECOMMIT_HOOK" "$HOOK_DIR/pre-commit.bak" +fi + +cat > "$PRECOMMIT_HOOK" << 'EOF' +#!/bin/bash +# PRIX AI Code Review - Pre-commit Hook +# Generated by PRIX + +# Configuration +PRIX_MIN_SEVERITY="${PRIX_MIN_SEVERITY:-minor}" +PRIX_MIN_CONFIDENCE="${PRIX_MIN_CONFIDENCE:-60}" +PRIX_DISABLE="${PRIX_DISABLE:-false}" + +# Colors +RED='\033[0;31m' +YELLOW='\033[0;33m' +GREEN='\033[0;32m' +NC='\033[0m' + +if [ "$PRIX_DISABLE" = "true" ]; then + echo "โ„น๏ธ PRIX pre-commit disabled (PRIX_DISABLE=true)" + exit 0 +fi + +echo "๐Ÿ” PRIX: Running AI code review on staged files..." + +# Check for required environment variables +if [ -z "$GROQ_API_KEY" ] && [ -z "$AI_API_KEY" ]; then + echo -e "${YELLOW}โš ๏ธ Warning: GROQ_API_KEY or AI_API_KEY not set. Skipping PRIX review.${NC}" + echo " Set these environment variables to enable pre-commit review." + exit 0 +fi + +# Get staged files +STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(ts|tsx|js|jsx|go|py)$' || true) + +if [ -z "$STAGED_FILES" ]; then + echo "โ„น๏ธ No supported files staged for review" + exit 0 +fi + +FILE_COUNT=$(echo "$STAGED_FILES" | wc -l) +echo "๐Ÿ“‹ Found $FILE_COUNT file(s) to review" + +# Run PRIX CLI +npx prix-cli \ + --staged \ + --min-severity "$PRIX_MIN_SEVERITY" \ + --min-confidence "$PRIX_MIN_CONFIDENCE" \ + --output console 2>&1 + +EXIT_CODE=$? + +if [ $EXIT_CODE -eq 0 ]; then + echo -e "${GREEN}โœ… PRIX: No critical issues found${NC}" +elif [ $EXIT_CODE -eq 1 ]; then + if [ -n "$CI" ]; then + echo -e "${RED}โŒ PRIX: Critical issues found. Commit blocked in CI.${NC}" + echo " To bypass this hook in local development, use: git commit --no-verify" + else + echo -e "${YELLOW}โš ๏ธ PRIX: Issues found. Review recommended but not blocking.${NC}" + EXIT_CODE=0 + fi +fi + +exit $EXIT_CODE +EOF + +chmod +x "$PRECOMMIT_HOOK" + +echo -e "${GREEN}โœ… PRIX pre-commit hook installed!${NC}" +echo "" +echo "Configuration (environment variables):" +echo " PRIX_MIN_SEVERITY - Minimum severity to report (critical|major|minor|info) [default: minor]" +echo " PRIX_MIN_CONFIDENCE - Minimum confidence threshold 0-100 [default: 60]" +echo " PRIX_DISABLE - Set to 'true' to skip review [default: false]" +echo "" +echo "To bypass this hook locally: git commit --no-verify" diff --git a/src/architectural-analyzer.ts b/src/architectural-analyzer.ts new file mode 100644 index 0000000000000000000000000000000000000000..4d6236db05b46f12d56b23289a36ba33fdefb276 --- /dev/null +++ b/src/architectural-analyzer.ts @@ -0,0 +1,446 @@ +import {SymbolGraph, Symbol, DependencyEdge} from './symbol-graph' + +export interface LayerDefinition { + name: string + patterns: string[] + priority: number +} + +export interface ArchitecturalRule { + fromLayer: string + toLayer: string + allowed: boolean + severity: 'critical' | 'major' | 'minor' + description: string +} + +export interface ArchitecturalViolation { + from: string + to: string + fromLayer: string + toLayer: string + severity: 'critical' | 'major' | 'minor' + description: string + file?: string + suggestedFix?: string +} + +export interface ArchitectureAnalysis { + violations: ArchitecturalViolation[] + layerAssignments: Map + unassignedFiles: string[] + statistics: { + totalViolations: number + criticalCount: number + majorCount: number + minorCount: number + } +} + +const DEFAULT_LAYERS: LayerDefinition[] = [ + { + name: 'ui', + patterns: [ + '**/components/**', + '**/pages/**', + '**/views/**', + '**/screens/**', + '**/ui/**', + '**/frontend/**' + ], + priority: 1 + }, + { + name: 'api', + patterns: [ + '**/api/**', + '**/controllers/**', + '**/handlers/**', + '**/routes/**', + '**/endpoints/**' + ], + priority: 2 + }, + { + name: 'services', + patterns: [ + '**/services/**', + '**/business/**', + '**/domain/**', + '**/usecases/**' + ], + priority: 3 + }, + { + name: 'data', + patterns: [ + '**/models/**', + '**/schemas/**', + '**/entities/**', + '**/repositories/**', + '**/dal/**' + ], + priority: 4 + }, + { + name: 'infrastructure', + patterns: [ + '**/db/**', + '**/database/**', + '**/cache/**', + '**/queue/**', + '**/storage/**', + '**/external/**' + ], + priority: 5 + }, + { + name: 'shared', + patterns: [ + '**/shared/**', + '**/common/**', + '**/utils/**', + '**/lib/**', + '**/types/**' + ], + priority: 0 + } +] + +const DEFAULT_RULES: ArchitecturalRule[] = [ + { + fromLayer: 'ui', + toLayer: 'data', + allowed: false, + severity: 'critical', + description: 'UI should not directly access data layer' + }, + { + fromLayer: 'ui', + toLayer: 'infrastructure', + allowed: false, + severity: 'critical', + description: 'UI should not directly access infrastructure' + }, + { + fromLayer: 'api', + toLayer: 'ui', + allowed: false, + severity: 'major', + description: 'API layer should not depend on UI' + }, + { + fromLayer: 'api', + toLayer: 'infrastructure', + allowed: true, + severity: 'minor', + description: 'API may access infrastructure (database, cache)' + }, + { + fromLayer: 'services', + toLayer: 'ui', + allowed: false, + severity: 'major', + description: 'Services should not depend on UI' + }, + { + fromLayer: 'services', + toLayer: 'infrastructure', + allowed: true, + severity: 'minor', + description: 'Services may access infrastructure' + }, + { + fromLayer: 'data', + toLayer: 'api', + allowed: false, + severity: 'major', + description: 'Data layer should not depend on API layer' + }, + { + fromLayer: 'data', + toLayer: 'infrastructure', + allowed: false, + severity: 'critical', + description: 'Data layer should not depend on infrastructure' + }, + { + fromLayer: 'shared', + toLayer: 'ui', + allowed: false, + severity: 'minor', + description: 'Shared code should not depend on UI' + }, + { + fromLayer: 'shared', + toLayer: 'api', + allowed: false, + severity: 'minor', + description: 'Shared code should not depend on API' + } +] + +export class ArchitecturalAnalyzer { + private layers: LayerDefinition[] + private rules: ArchitecturalRule[] + private layerCache: Map + + constructor( + layers: LayerDefinition[] = DEFAULT_LAYERS, + rules: ArchitecturalRule[] = DEFAULT_RULES + ) { + this.layers = layers + this.rules = rules + this.layerCache = new Map() + } + + analyze(symbolGraph: SymbolGraph): ArchitectureAnalysis { + const violations: ArchitecturalViolation[] = [] + const layerAssignments = new Map() + const unassignedFiles: string[] = [] + + for (const [key, symbol] of symbolGraph.symbols) { + const file = symbol.file + if (!layerAssignments.has(file)) { + const layer = this.assignLayer(file) + layerAssignments.set(file, layer) + if (layer === 'unassigned') { + unassignedFiles.push(file) + } + } + } + + for (const edge of symbolGraph.edges) { + const fromLayer = layerAssignments.get(edge.from) || 'unassigned' + const toLayer = this.resolveImportToLayer(edge.to, symbolGraph) + + if (fromLayer === 'unassigned' || toLayer === 'unassigned') continue + + const rule = this.findRule(fromLayer, toLayer) + if (rule && !rule.allowed) { + violations.push({ + from: edge.from, + to: edge.to, + fromLayer, + toLayer, + severity: rule.severity, + description: rule.description, + file: edge.from + }) + } + } + + const statistics = { + totalViolations: violations.length, + criticalCount: violations.filter(v => v.severity === 'critical').length, + majorCount: violations.filter(v => v.severity === 'major').length, + minorCount: violations.filter(v => v.severity === 'minor').length + } + + return { + violations, + layerAssignments, + unassignedFiles, + statistics + } + } + + private assignLayer(filePath: string): string { + const cached = this.layerCache.get(filePath) + if (cached) return cached + + const normalizedPath = filePath.replace(/\\/g, '/').toLowerCase() + + for (const layer of this.layers) { + for (const pattern of layer.patterns) { + if (this.matchPattern(normalizedPath, pattern.toLowerCase())) { + this.layerCache.set(filePath, layer.name) + return layer.name + } + } + } + + this.layerCache.set(filePath, 'unassigned') + return 'unassigned' + } + + private matchPattern(path: string, pattern: string): boolean { + const regexPattern = pattern + .replace(/\*\*/g, '<>') + .replace(/\*/g, '[^/]*') + .replace(/<>/g, '.*') + .replace(/\?/g, '.') + + try { + const regex = new RegExp(`^${regexPattern}$`) + return regex.test(path) || this.matchGlob(path, pattern) + } catch { + return this.matchGlob(path, pattern) + } + } + + private matchGlob(path: string, pattern: string): boolean { + const parts = path.split('/') + const patternParts = pattern.split('/') + + let pi = 0 + let psi = 0 + + while (pi < parts.length && psi < patternParts.length) { + const patternPart = patternParts[psi] + + if (patternPart === '**') { + if (psi === patternParts.length - 1) { + return true + } + const nextPattern = patternParts[psi + 1] + while (pi < parts.length) { + if (this.matchSingle(parts[pi], nextPattern)) { + if ( + this.matchGlob( + parts.slice(pi).join('/'), + patternParts.slice(psi + 1).join('/') + ) + ) { + return true + } + } + pi++ + } + return false + } + + if (!this.matchSingle(parts[pi], patternPart)) { + return false + } + + pi++ + psi++ + } + + return pi === parts.length && psi === patternParts.length + } + + private matchSingle(part: string, pattern: string): boolean { + if (pattern === '*') return part.length > 0 + if (pattern === '**') return true + + const regexPattern = pattern + .replace(/\./g, '\\.') + .replace(/\*/g, '[^/]*') + .replace(/\?/g, '.') + + try { + const regex = new RegExp(`^${regexPattern}$`) + return regex.test(part) + } catch { + return part === pattern + } + } + + private resolveImportToLayer( + importPath: string, + symbolGraph: SymbolGraph + ): string { + const normalizedImport = importPath.replace(/['"]/g, '').replace(/\\/g, '/') + + for (const [key, symbol] of symbolGraph.symbols) { + const symbolPath = symbol.file + if ( + symbolPath.includes(normalizedImport) || + normalizedImport.includes(symbolPath) + ) { + return this.assignLayer(symbolPath) + } + } + + if (normalizedImport.startsWith('.')) { + return 'unassigned' + } + + if (normalizedImport.includes('/node_modules/')) { + return 'external' + } + + if ( + normalizedImport.includes('/shared/') || + normalizedImport.includes('/common/') + ) { + return 'shared' + } + + return 'unassigned' + } + + private findRule( + fromLayer: string, + toLayer: string + ): ArchitecturalRule | undefined { + return this.rules.find( + r => r.fromLayer === fromLayer && r.toLayer === toLayer + ) + } + + getDependencyGraph( + layerAssignments: Map + ): Map> { + const graph = new Map>() + + for (const [file, layer] of layerAssignments) { + if (!graph.has(layer)) { + graph.set(layer, new Set()) + } + } + + return graph + } + + generateReport(analysis: ArchitectureAnalysis): string { + const lines: string[] = [] + + lines.push('# Architectural Violation Report') + lines.push('') + lines.push(`Total Violations: ${analysis.statistics.totalViolations}`) + lines.push(` - Critical: ${analysis.statistics.criticalCount}`) + lines.push(` - Major: ${analysis.statistics.majorCount}`) + lines.push(` - Minor: ${analysis.statistics.minorCount}`) + lines.push('') + + if (analysis.violations.length > 0) { + lines.push('## Violations') + lines.push('') + + const groupedBySeverity = { + critical: analysis.violations.filter(v => v.severity === 'critical'), + major: analysis.violations.filter(v => v.severity === 'major'), + minor: analysis.violations.filter(v => v.severity === 'minor') + } + + for (const severity of ['critical', 'major', 'minor'] as const) { + const violations = groupedBySeverity[severity] + if (violations.length === 0) continue + + lines.push(`### ${severity.toUpperCase()} (${violations.length})`) + lines.push('') + + for (const v of violations) { + lines.push( + `- **${v.fromLayer}** โ†’ **${v.toLayer}**: ${v.description}` + ) + lines.push(` - File: \`${v.file || v.from}\``) + lines.push(` - Import: \`${v.to}\``) + } + lines.push('') + } + } + + return lines.join('\n') + } +} + +export function analyzeArchitecture( + symbolGraph: SymbolGraph +): ArchitectureAnalysis { + const analyzer = new ArchitecturalAnalyzer() + return analyzer.analyze(symbolGraph) +} diff --git a/src/bot.ts b/src/bot.ts new file mode 100644 index 0000000000000000000000000000000000000000..861859874fadb645d7c35f35fbddf6ad84fda87b --- /dev/null +++ b/src/bot.ts @@ -0,0 +1,182 @@ +// Node 20 includes native fetch support + +// AI Client for Groq with Failover Support +// Fallback shims for Probot runtime +/* eslint-disable no-console */ +import { + ChatGPTAPI as AIClient, + ChatGPTError as AIError, + ChatMessage, + SendMessageOptions +} from 'chatgpt' +import pRetry from 'p-retry' +import {AIOptions, Options} from './options' +import {TokenLimits} from './limits' + +const logInfo = console.log +const logWarning = console.warn +const logError = console.error +/* eslint-enable no-console */ +const setFailed = (msg: string) => { + console.error(msg) + process.exit(1) +} + +export interface Ids { + parentMessageId?: string + conversationId?: string +} + +export class Bot { + private api: AIClient | null = null + private readonly options: Options + private readonly aiOptions: AIOptions + private currentModel: string + private fallbackModels: string[] + + constructor(options: Options, aiOptions: AIOptions) { + this.options = options + this.aiOptions = aiOptions + this.currentModel = aiOptions.model + + // Setup fallback chain based on tier + if (Options.HEAVY_MODELS.includes(this.currentModel)) { + this.fallbackModels = [...Options.HEAVY_MODELS] + } else { + this.fallbackModels = [...Options.LIGHT_MODELS] + } + + // Remove current model from fallbacks to avoid immediate repeat + this.fallbackModels = this.fallbackModels.filter( + m => m !== this.currentModel + ) + + this.initClient() + } + + private initClient(): void { + const apiKey = process.env.GROQ_API_KEY || process.env.AI_API_KEY + if (apiKey) { + const currentDate = new Date().toISOString().split('T')[0] + const limits = new TokenLimits(this.currentModel) + const systemMessage = `${this.options.systemMessage} +Knowledge cutoff: ${limits.knowledgeCutOff} +Current date: ${currentDate} +IMPORTANT: Entire response must be in ISO code: ${this.options.language} +` + + this.api = new AIClient({ + apiBaseUrl: this.options.apiBaseUrl, + systemMessage, + apiKey, + apiOrg: process.env.AI_API_ORG || undefined, + debug: this.options.debug, + maxModelTokens: limits.maxTokens, + maxResponseTokens: limits.responseTokens, + completionParams: { + temperature: this.options.modelTemperature, + model: this.currentModel + } + }) + logInfo(`Initialized AI client with model: ${this.currentModel}`) + } else { + throw new Error("Missing 'GROQ_API_KEY' or 'AI_API_KEY'") + } + } + + chat = async (message: string, ids: Ids): Promise<[string, Ids]> => { + let res: [string, Ids] = ['', {}] + try { + res = await this.chat_(message, ids) + return res + } catch (e: unknown) { + if (e instanceof AIError) { + logWarning(`AI communication error: ${e.message}`) + } + return res + } + } + + private readonly chat_ = async ( + message: string, + ids: Ids + ): Promise<[string, Ids]> => { + const start = Date.now() + if (!message) return ['', {}] + + let response: ChatMessage | undefined + + if (this.api != null) { + const opts: SendMessageOptions = { + timeoutMs: this.options.timeoutMS + } + if (ids.parentMessageId) { + opts.parentMessageId = ids.parentMessageId + } + + try { + response = await pRetry( + async attemptState => { + try { + const result = await this.api!.sendMessage(message, opts) + return result + } catch (e: any) { + if (e?.status === 429 && this.fallbackModels.length > 0) { + const nextModel = this.fallbackModels.shift() + if (nextModel) { + logWarning( + `Rate limit (429) hit for ${this.currentModel}. Switching to fallback: ${nextModel}` + ) + this.currentModel = nextModel + this.initClient() + } + } + throw e + } + }, + { + retries: this.options.retries, + onFailedAttempt: (err: any) => { + logInfo( + `Attempt ${err.attemptNumber} failed. ${err.retriesLeft} retries left.` + ) + const errorResponse = (err as any).response || (err as any).status + if (errorResponse === 429 && this.fallbackModels.length > 0) { + const nextModel = this.fallbackModels.shift() + if (nextModel) { + logWarning( + `Proactive switch to fallback model: ${nextModel} due to 429` + ) + this.currentModel = nextModel + this.initClient() + } + } + } + } + ) + } catch (e: unknown) { + if (e instanceof AIError) { + logInfo( + `AI Error: ${e.message} (Last model used: ${this.currentModel})` + ) + } + } + + const end = Date.now() + logInfo(`AI response time: ${end - start} ms`) + } else { + setFailed('AI client is not initialized') + } + + let responseText = '' + if (response != null) { + responseText = response.text + } + + const newIds: Ids = { + parentMessageId: response?.id, + conversationId: response?.conversationId + } + return [responseText, newIds] + } +} diff --git a/src/checkout.ts b/src/checkout.ts new file mode 100644 index 0000000000000000000000000000000000000000..8ab2d3e0bf8f034a511a57bc01d1aae48e751965 --- /dev/null +++ b/src/checkout.ts @@ -0,0 +1,72 @@ +import {prixExec} from './utils' +import {mkdirSync, existsSync, rmSync, writeFileSync} from 'fs' +import {join} from 'path' +import {getCurrentContext} from './context' + +export interface CheckoutOptions { + sparse?: boolean + files?: string[] +} + +export const checkoutRepo = async ( + tempDir: string, + options: CheckoutOptions = {} +): Promise => { + const ctx = getCurrentContext() + if (!ctx) throw new Error('No context available for checkout') + + const {owner, repo} = ctx.repo + const installationId = ctx.probotContext.payload.installation.id + + const tokenResp = + await ctx.probotContext.octokit.apps.createInstallationAccessToken({ + installation_id: installationId + }) + const token = tokenResp.data.token + + if (!token) { + throw new Error( + 'Failed to create installation access token: token is undefined' + ) + } + + const cloneUrl = `https://x-access-token:${token}@github.com/${owner}/${repo}.git` + const headBranch = ctx.probotContext.payload.pull_request.head.ref + const headSha = ctx.probotContext.payload.pull_request.head.sha + + if (existsSync(tempDir)) { + rmSync(tempDir, {recursive: true, force: true}) + } + mkdirSync(tempDir, {recursive: true}) + + console.log(`Cloning ${owner}/${repo} into ${tempDir}...`) + + if (options.sparse && options.files && options.files.length > 0) { + console.log(`Using sparse checkout for ${options.files.length} files...`) + + prixExec(`git clone --no-checkout --depth 1 ${cloneUrl} .`, { + cwd: tempDir, + stdio: 'pipe' + }) + prixExec(`git fetch origin ${headSha} --depth 1`, {cwd: tempDir}) + + const sparseConfig = options.files.join('\n') + writeFileSync(join(tempDir, '.git/info/sparse-checkout'), sparseConfig) + + prixExec(`git config core.sparseCheckout true`, {cwd: tempDir}) + prixExec(`git checkout ${headSha}`, {cwd: tempDir}) + } else { + console.log(`Cloning ${owner}/${repo} with depth 1...`) + prixExec(`git clone --no-checkout --depth 1 ${cloneUrl} .`, { + cwd: tempDir, + stdio: 'pipe' + }) + prixExec(`git fetch origin ${headSha} --depth 1`, {cwd: tempDir}) + prixExec(`git checkout ${headSha}`, {cwd: tempDir}) + } + + prixExec(`git config user.name "PRIX AI Auditor"`, {cwd: tempDir}) + prixExec(`git config user.email "bot@prix.ai"`, {cwd: tempDir}) + + return tempDir +} diff --git a/src/cli.ts b/src/cli.ts new file mode 100644 index 0000000000000000000000000000000000000000..bed1ccb54bd54b9175d84c9e3ee1dcbb633de609 --- /dev/null +++ b/src/cli.ts @@ -0,0 +1,299 @@ +import {Options, AIOptions} from './options' +import {Prompts} from './prompts' +import {Bot} from './bot' +import {codeReview} from './review' +import {LocalContextEngine} from './local-context' +import {LocalConsoleReporter} from './console-reporter' +import {feedbackTracker} from './feedback-tracker' +import {execSync} from 'child_process' +import {existsSync} from 'fs' + +interface CLIArgs { + staged?: boolean + diff?: string + files?: string[] + model?: string + minConfidence?: number + minSeverity?: 'critical' | 'major' | 'minor' | 'info' + disableReview?: boolean + disableReleaseNotes?: boolean + maxFiles?: number + pathFilters?: string[] + systemMessage?: string + language?: string + output?: 'console' | 'json' + help?: boolean +} + +const HELP_TEXT = ` +PRIX CLI - Local AI PR Reviewer + +Usage: + prix-cli [options] + +Options: + --staged Review staged files (git diff --cached) + --diff Review files changed since given git ref + --files Review specific files (comma-separated) + --model LLM model to use (default: llama-3.1-8b-instant) + --min-confidence Minimum confidence threshold (0-100) + --min-severity Minimum severity to report (critical|major|minor|info) + --disable-review Skip code review, only generate summary + --disable-notes Skip release notes generation + --max-files Maximum files to review (0 = unlimited) + --path-filters

Path filters (comma-separated, e.g., "src/**,lib/**") + --system-message Additional system message + --language Output language (default: en-US) + --output Output format: console (default) or json + --help, -h Show this help message + +Examples: + prix-cli --staged Review staged changes + prix-cli --diff HEAD~1 Review changes since last commit + prix-cli --files src/app.ts,lib/util.ts Review specific files + prix-cli --min-severity major Only show major/critical issues + +Pre-commit Hook: + Add to .git/hooks/pre-commit: + npx prix-cli --staged --output console +` + +function parseArgs(argv: string[]): CLIArgs { + const args: CLIArgs = {} + for (let i = 2; i < argv.length; i++) { + const arg = argv[i] + switch (arg) { + case '--staged': + args.staged = true + break + case '--diff': + args.diff = argv[++i] + break + case '--files': + args.files = argv[++i].split(',') + break + case '--model': + args.model = argv[++i] + break + case '--min-confidence': + args.minConfidence = parseInt(argv[++i], 10) + break + case '--min-severity': + args.minSeverity = argv[++i] as any + break + case '--disable-review': + args.disableReview = true + break + case '--disable-notes': + args.disableReleaseNotes = true + break + case '--max-files': + args.maxFiles = parseInt(argv[++i], 10) + break + case '--path-filters': + args.pathFilters = argv[++i].split(',') + break + case '--system-message': + args.systemMessage = argv[++i] + break + case '--language': + args.language = argv[++i] + break + case '--output': + args.output = argv[++i] as any + break + case '--help': + case '-h': + args.help = true + break + } + } + return args +} + +function getStagedFiles(): string[] { + try { + const output = execSync('git diff --cached --name-only', { + encoding: 'utf8', + cwd: process.cwd() + }) + return output.split('\n').filter(f => f.trim()) + } catch (e) { + console.error('Failed to get staged files:', e) + return [] + } +} + +function getChangedFiles(sinceRef: string): string[] { + try { + const output = execSync(`git diff --name-only ${sinceRef}`, { + encoding: 'utf8', + cwd: process.cwd() + }) + return output.split('\n').filter(f => f.trim()) + } catch (e) { + console.error(`Failed to get changed files since ${sinceRef}:`, e) + return [] + } +} + +async function runLocalReview(args: CLIArgs): Promise { + const info = console.log + const error = console.error + + info('๐Ÿ” PRIX CLI - Starting local code review...\n') + + if (!process.env.GROQ_API_KEY && !process.env.AI_API_KEY) { + error( + 'โŒ Error: GROQ_API_KEY or AI_API_KEY environment variable is required' + ) + return 1 + } + + let filesToReview: string[] = [] + + if (args.staged) { + filesToReview = getStagedFiles() + info(`๐Ÿ“‹ Reviewing ${filesToReview.length} staged files\n`) + } else if (args.diff) { + filesToReview = getChangedFiles(args.diff) + info( + `๐Ÿ“‹ Reviewing ${filesToReview.length} files changed since ${args.diff}\n` + ) + } else if (args.files) { + filesToReview = args.files.filter(f => existsSync(f)) + info(`๐Ÿ“‹ Reviewing ${filesToReview.length} specified files\n`) + } else { + error('โŒ Error: Must specify --staged, --diff , or --files ') + return 1 + } + + if (filesToReview.length === 0) { + info('โœ… No files to review') + return 0 + } + + const options = new Options( + false, + args.disableReview || false, + args.disableReleaseNotes || false, + args.maxFiles?.toString() || '0', + false, + false, + args.pathFilters || null, + args.systemMessage || '', + args.model || 'llama-3.1-8b-instant', + 'llama-3.3-70b-versatile', + '0.0', + '3', + '120000', + '6', + '6', + process.env.API_BASE_URL || 'https://api.groq.com/openai/v1', + args.language || 'en-US', + false, + args.minSeverity || 'minor', + args.minConfidence?.toString() || '0', + 'false', + 'true' + ) + + const prompts = new Prompts() + const localContext = new LocalContextEngine(filesToReview) + const reporter = new LocalConsoleReporter() + + info('๐Ÿค– Initializing AI models...') + + let lightBot: Bot | null = null + let heavyBot: Bot | null = null + + try { + lightBot = new Bot( + options, + new AIOptions( + options.lightModel, + options.lightTokenLimits, + options.modelTemperature + ) + ) + } catch (e) { + error(`โŒ Failed to initialize light model: ${e}`) + return 1 + } + + try { + heavyBot = new Bot( + options, + new AIOptions( + options.heavyModel, + options.heavyTokenLimits, + options.modelTemperature + ) + ) + } catch (e) { + error(`โŒ Failed to initialize heavy model: ${e}`) + return 1 + } + + info('โœ… AI models initialized\n') + + try { + await localContext.initialize() + + const findings = await localContext.runReview( + lightBot, + heavyBot, + options, + prompts + ) + + reporter.printFindings(findings, { + output: args.output || 'console', + minSeverity: options.minimumSeverity, + minConfidence: options.minConfidence + }) + + const critical = findings.filter(f => f.severity === 'critical').length + const major = findings.filter(f => f.severity === 'major').length + + info( + `\n๐Ÿ“Š Summary: ${critical} critical, ${major} major, ${findings.length} total findings` + ) + + if (critical > 0) { + info('\nโš ๏ธ Critical issues found! Consider fixing before committing.') + return 1 + } else if (major > 0) { + info('\nโ„น๏ธ Major issues found. Review recommended before committing.') + return 0 + } else { + info('\nโœ… No significant issues found.') + return 0 + } + } catch (e) { + error(`\nโŒ Review failed: ${e}`) + return 1 + } +} + +export async function main(argv: string[]): Promise { + const args = parseArgs(argv) + + if (args.help) { + console.log(HELP_TEXT) + return 0 + } + + return runLocalReview(args) +} + +if (require.main === module) { + main(process.argv) + .then(code => { + process.exit(code) + }) + .catch(e => { + console.error('Fatal error:', e) + process.exit(1) + }) +} diff --git a/src/commenter.ts b/src/commenter.ts new file mode 100644 index 0000000000000000000000000000000000000000..87ade7ae3f5ca15c76295297794c7c7a68fdcd08 --- /dev/null +++ b/src/commenter.ts @@ -0,0 +1,857 @@ +// Removed @actions imports for Probot migration +import {octokit} from './octokit' + +import {als} from './context' + +const info = console.log +const warning = console.warn +const getInput = (name: string) => process.env[name.toUpperCase()] || '' + +export const context: any = new Proxy({} as any, { + get(target, prop) { + return (als.getStore()?.probotContext as any)[prop] + } +}) + +export const repo: any = new Proxy({} as any, { + get(target, prop) { + return (als.getStore()?.repo as any)[prop] + } +}) + +export const setCommenterContext = (newContext: any) => { + // context and repo are now Proxies +} + +export const COMMENT_GREETING = `${getInput('bot_icon')} AI PR Reviewer` + +export const COMMENT_TAG = + '' + +export const COMMENT_REPLY_TAG = + '' + +export const SUMMARIZE_TAG = + '' + +export const IN_PROGRESS_START_TAG = + '' + +export const IN_PROGRESS_END_TAG = + '' + +export const DESCRIPTION_START_TAG = + '' +export const DESCRIPTION_END_TAG = + '' + +export const RAW_SUMMARY_START_TAG = ` + +` + +export const SHORT_SUMMARY_START_TAG = ` + +` + +export const COMMIT_ID_START_TAG = '' +export const COMMIT_ID_END_TAG = '' + +export const VERIFIED_TAG = '' +export const VERIFICATION_FAILED_TAG = '' + +export const ISSUE_REPLY_TAG = + '' + +export class Commenter { + /** + * @param mode Can be "create", "replace". Default is "replace". + */ + async comment(message: string, tag: string, mode: string) { + let target: number + if (context.payload.pull_request != null) { + target = context.payload.pull_request.number + } else if (context.payload.issue != null) { + target = context.payload.issue.number + } else { + warning( + 'Skipped: context.payload.pull_request and context.payload.issue are both null' + ) + return + } + + if (!tag) { + tag = COMMENT_TAG + } + + const body = `${COMMENT_GREETING} + +${message} + +${tag}` + + if (mode === 'create') { + await this.create(body, target) + } else if (mode === 'replace') { + await this.replace(body, tag, target) + } else { + warning(`Unknown mode: ${mode}, use "replace" instead`) + await this.replace(body, tag, target) + } + } + + getContentWithinTags(content: string, startTag: string, endTag: string) { + const start = content.indexOf(startTag) + const end = content.indexOf(endTag) + if (start >= 0 && end >= 0) { + return content.slice(start + startTag.length, end) + } + return '' + } + + removeContentWithinTags(content: string, startTag: string, endTag: string) { + const start = content.indexOf(startTag) + const end = content.lastIndexOf(endTag) + if (start >= 0 && end >= 0) { + return content.slice(0, start) + content.slice(end + endTag.length) + } + return content + } + + getRawSummary(summary: string) { + return this.getContentWithinTags( + summary, + RAW_SUMMARY_START_TAG, + RAW_SUMMARY_END_TAG + ) + } + + getShortSummary(summary: string) { + return this.getContentWithinTags( + summary, + SHORT_SUMMARY_START_TAG, + SHORT_SUMMARY_END_TAG + ) + } + + getDescription(description: string) { + return this.removeContentWithinTags( + description, + DESCRIPTION_START_TAG, + DESCRIPTION_END_TAG + ) + } + + getReleaseNotes(description: string) { + const releaseNotes = this.getContentWithinTags( + description, + DESCRIPTION_START_TAG, + DESCRIPTION_END_TAG + ) + return releaseNotes.replace(/(^|\n)> .*/g, '') + } + + async updateDescription(pullNumber: number, message: string) { + // add this response to the description field of the PR as release notes by looking + // for the tag (marker) + try { + // get latest description from PR + const pr = await octokit.pulls.get({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber + }) + let body = '' + if (pr.data.body) { + body = pr.data.body + } + const description = this.getDescription(body) + + const messageClean = this.removeContentWithinTags( + message, + DESCRIPTION_START_TAG, + DESCRIPTION_END_TAG + ) + const newDescription = `${description}\n${DESCRIPTION_START_TAG}\n${messageClean}\n${DESCRIPTION_END_TAG}` + await octokit.pulls.update({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + body: newDescription + }) + } catch (e) { + warning( + `Failed to get PR: ${e}, skipping adding release notes to description.` + ) + } + } + + private readonly reviewCommentsBuffer: Array<{ + path: string + startLine: number + endLine: number + message: string + verified?: boolean + verificationFeedback?: string + }> = [] + + async bufferReviewComment( + path: string, + startLine: number, + endLine: number, + message: string, + verified?: boolean, + verificationFeedback?: string + ) { + // Premium UI Formatting: Convert "[LEVEL] | [TYPE]" to emoji badges + const levelTypeRegex = /^(\w+)\s*\|\s*(\w+)/ + const match = message.match(levelTypeRegex) + + let header = '' + if (match != null) { + const level = match[1].toLowerCase() + const type = match[2] + let emoji = 'โš ๏ธ' + let color = 'Major' + + if (level === 'critical') { + emoji = '๐Ÿšจ' + color = 'Critical' + } else if (level === 'major') { + emoji = '๐Ÿ”ด' + color = 'Major' + } else if (level === 'minor') { + emoji = '๐ŸŸ ' + color = 'Minor' + } else if (level === 'info') { + emoji = 'โ„น๏ธ' + color = 'Info' + } + + header = `**${emoji} Potential issue | ${color} (${type})**\n\n` + message = message.replace(levelTypeRegex, '').trim() + } + + let verificationBadge = '' + if (verified === true) { + verificationBadge = + '\n---\nโœ… **Verified**: This suggestion passed syntax, lint, and AST validation.\n' + } else if (verified === false && verificationFeedback) { + verificationBadge = `\n---\nโš ๏ธ **Verification Failed**: ${verificationFeedback}\n` + } + + const formattedMessage = `${COMMENT_GREETING} +${header}${message}${verificationBadge} + +${COMMENT_TAG}` + + this.reviewCommentsBuffer.push({ + path, + startLine, + endLine, + message: formattedMessage, + verified, + verificationFeedback + }) + } + + async deletePendingReview(pullNumber: number) { + try { + const reviews = await octokit.pulls.listReviews({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber + }) + + const pendingReview = reviews.data.find( + review => review.state === 'PENDING' + ) + + if (pendingReview) { + info( + `Deleting pending review for PR #${pullNumber} id: ${pendingReview.id}` + ) + try { + await octokit.pulls.deletePendingReview({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + // eslint-disable-next-line camelcase + review_id: pendingReview.id + }) + } catch (e) { + warning(`Failed to delete pending review: ${e}`) + } + } + } catch (e) { + warning(`Failed to list reviews: ${e}`) + } + } + + async submitReview(pullNumber: number, commitId: string, statusMsg: string) { + const bodyHeader = `${COMMENT_GREETING} + +${statusMsg} +` + + if (this.reviewCommentsBuffer.length === 0) { + // Submit empty review with statusMsg + info(`Submitting empty review for PR #${pullNumber}`) + try { + await octokit.pulls.createReview({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + // eslint-disable-next-line camelcase + commit_id: commitId, + event: 'COMMENT', + body: bodyHeader + }) + } catch (e) { + warning(`Failed to submit empty review: ${e}`) + } + return + } + + // De-duplicate and clear existing bot comments in the same range + for (const comment of this.reviewCommentsBuffer) { + const comments = await this.getCommentsAtRange( + pullNumber, + comment.path, + comment.startLine, + comment.endLine + ) + for (const c of comments) { + if (c.body.includes(COMMENT_TAG)) { + try { + await octokit.pulls.deleteReviewComment({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + comment_id: c.id + }) + } catch (e) { + warning(`Failed to delete review comment: ${e}`) + } + } + } + } + + await this.deletePendingReview(pullNumber) + + // Unified Review: All comments are standalone threads to support suggestions + const pushableComments = this.reviewCommentsBuffer.map(comment => + this.generateCommentData(comment) + ) + + try { + const review = await octokit.pulls.createReview({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + // eslint-disable-next-line camelcase + commit_id: commitId, + comments: pushableComments.map(comment => comment) + }) + + info( + `Submitting review for PR #${pullNumber}, total comments: ${pushableComments.length}, review id: ${review.data.id}` + ) + + await octokit.pulls.submitReview({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + // eslint-disable-next-line camelcase + review_id: review.data.id, + event: 'COMMENT', + body: bodyHeader + }) + } catch (e) { + warning( + `Failed to create review: ${e}. Falling back to individual comments.` + ) + await this.deletePendingReview(pullNumber) + let commentCounter = 0 + for (const comment of pushableComments) { + info( + `Creating new review comment for ${comment.path}:${comment.startLine}-${comment.endLine}: ${comment.message}` + ) + const commentData: any = { + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + // eslint-disable-next-line camelcase + commit_id: commitId, + ...comment + } + + try { + await octokit.pulls.createReviewComment(commentData) + } catch (ee) { + warning(`Failed to create review comment: ${ee}`) + } + + commentCounter++ + info(`Comment ${commentCounter}/${pushableComments.length} posted`) + } + } + } + + private generateCommentData(comment: any) { + const commentData: any = { + path: comment.path, + body: comment.message, + line: comment.endLine + } + + if (comment.startLine !== comment.endLine) { + // eslint-disable-next-line camelcase + commentData.start_line = comment.startLine + // eslint-disable-next-line camelcase + commentData.start_side = 'RIGHT' + } + + return commentData + } + + async reviewCommentReply( + pullNumber: number, + topLevelComment: any, + message: string + ) { + const reply = `${COMMENT_GREETING} + +${message} + +${COMMENT_REPLY_TAG} +` + try { + // Post the reply to the user comment + await octokit.pulls.createReplyForReviewComment({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + body: reply, + // eslint-disable-next-line camelcase + comment_id: topLevelComment.id + }) + } catch (error) { + warning(`Failed to reply to the top-level comment ${error}`) + try { + await octokit.pulls.createReplyForReviewComment({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + pull_number: pullNumber, + body: `Could not post the reply to the top-level comment due to the following error: ${error}`, + // eslint-disable-next-line camelcase + comment_id: topLevelComment.id + }) + } catch (e) { + warning(`Failed to reply to the top-level comment ${e}`) + } + } + try { + if (topLevelComment.body.includes(COMMENT_TAG)) { + // replace COMMENT_TAG with COMMENT_REPLY_TAG in topLevelComment + const newBody = topLevelComment.body.replace( + COMMENT_TAG, + COMMENT_REPLY_TAG + ) + await octokit.pulls.updateReviewComment({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + comment_id: topLevelComment.id, + body: newBody + }) + } + } catch (error) { + warning(`Failed to update the top-level comment ${error}`) + } + } + + async getCommentsWithinRange( + pullNumber: number, + path: string, + startLine: number, + endLine: number + ) { + const comments = await this.listReviewComments(pullNumber) + return comments.filter( + (comment: any) => + comment.path === path && + comment.body !== '' && + ((comment.start_line !== undefined && + comment.start_line >= startLine && + comment.line <= endLine) || + (startLine === endLine && comment.line === endLine)) + ) + } + + async getCommentsAtRange( + pullNumber: number, + path: string, + startLine: number, + endLine: number + ) { + const comments = await this.listReviewComments(pullNumber) + return comments.filter( + (comment: any) => + comment.path === path && + comment.body !== '' && + ((comment.start_line !== undefined && + comment.start_line === startLine && + comment.line === endLine) || + (startLine === endLine && comment.line === endLine)) + ) + } + + async getCommentChainsWithinRange( + pullNumber: number, + path: string, + startLine: number, + endLine: number, + tag = '' + ) { + const existingComments = await this.getCommentsWithinRange( + pullNumber, + path, + startLine, + endLine + ) + // find all top most comments + const topLevelComments = [] + for (const comment of existingComments) { + if (!comment.in_reply_to_id) { + topLevelComments.push(comment) + } + } + + let allChains = '' + let chainNum = 0 + for (const topLevelComment of topLevelComments) { + // get conversation chain + const chain = await this.composeCommentChain( + existingComments, + topLevelComment + ) + if (chain && chain.includes(tag)) { + chainNum += 1 + allChains += `Conversation Chain ${chainNum}: +${chain} +--- +` + } + } + return allChains + } + + async composeCommentChain(reviewComments: any[], topLevelComment: any) { + const conversationChain = reviewComments + .filter((cmt: any) => cmt.in_reply_to_id === topLevelComment.id) + .map((cmt: any) => `${cmt.user.login}: ${cmt.body}`) + + conversationChain.unshift( + `${topLevelComment.user.login}: ${topLevelComment.body}` + ) + + return conversationChain.join('\n---\n') + } + + async getCommentChain(pullNumber: number, comment: any) { + try { + const reviewComments = await this.listReviewComments(pullNumber) + const topLevelComment = await this.getTopLevelComment( + reviewComments, + comment + ) + const chain = await this.composeCommentChain( + reviewComments, + topLevelComment + ) + return {chain, topLevelComment} + } catch (e) { + warning(`Failed to get conversation chain: ${e}`) + return { + chain: '', + topLevelComment: null + } + } + } + + async getTopLevelComment(reviewComments: any[], comment: any) { + let topLevelComment = comment + + while (topLevelComment.in_reply_to_id) { + const parentComment = reviewComments.find( + (cmt: any) => cmt.id === topLevelComment.in_reply_to_id + ) + + if (parentComment) { + topLevelComment = parentComment + } else { + break + } + } + + return topLevelComment + } + + private reviewCommentsCache: Record = {} + + async listReviewComments(target: number) { + if (this.reviewCommentsCache[target]) { + return this.reviewCommentsCache[target] + } + + const allComments: any[] = [] + let page = 1 + try { + for (;;) { + const {data: comments} = await octokit.pulls.listReviewComments({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + pull_number: target, + page, + // eslint-disable-next-line camelcase + per_page: 100 + }) + allComments.push(...comments) + page++ + if (!comments || comments.length < 100) { + break + } + } + + this.reviewCommentsCache[target] = allComments + return allComments + } catch (e) { + warning(`Failed to list review comments: ${e}`) + return allComments + } + } + + async create(body: string, target: number) { + try { + // get comment ID from the response + const response = await octokit.issues.createComment({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + issue_number: target, + body + }) + // add comment to issueCommentsCache + if (this.issueCommentsCache[target]) { + this.issueCommentsCache[target].push(response.data) + } else { + this.issueCommentsCache[target] = [response.data] + } + } catch (e) { + warning(`Failed to create comment: ${e}`) + } + } + + async replace(body: string, tag: string, target: number) { + try { + const cmt = await this.findCommentWithTag(tag, target) + if (cmt) { + await octokit.issues.updateComment({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + comment_id: cmt.id, + body + }) + } else { + await this.create(body, target) + } + } catch (e) { + warning(`Failed to replace comment: ${e}`) + } + } + + async findCommentWithTag(tag: string, target: number) { + try { + const comments = await this.listComments(target) + for (const cmt of comments) { + if (cmt.body && cmt.body.includes(tag)) { + return cmt + } + } + + return null + } catch (e: unknown) { + warning(`Failed to find comment with tag: ${e}`) + return null + } + } + + private issueCommentsCache: Record = {} + + async listComments(target: number) { + if (this.issueCommentsCache[target]) { + return this.issueCommentsCache[target] + } + + const allComments: any[] = [] + let page = 1 + try { + for (;;) { + const {data: comments} = await octokit.issues.listComments({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + issue_number: target, + page, + // eslint-disable-next-line camelcase + per_page: 100 + }) + allComments.push(...comments) + page++ + if (!comments || comments.length < 100) { + break + } + } + + this.issueCommentsCache[target] = allComments + return allComments + } catch (e: any) { + warning(`Failed to list comments: ${e}`) + return allComments + } + } + + // function that takes a comment body and returns the list of commit ids that have been reviewed + // commit ids are comments between the commit_ids_reviewed_start and commit_ids_reviewed_end markers + // + getReviewedCommitIds(commentBody: string): string[] { + const start = commentBody.indexOf(COMMIT_ID_START_TAG) + const end = commentBody.indexOf(COMMIT_ID_END_TAG) + if (start === -1 || end === -1) { + return [] + } + const ids = commentBody.substring(start + COMMIT_ID_START_TAG.length, end) + // remove the markers from each id and extract the id and remove empty strings + return ids + .split('', '').trim()) + .filter(id => id !== '') + } + + // get review commit ids comment block from the body as a string + // including markers + getReviewedCommitIdsBlock(commentBody: string): string { + const start = commentBody.indexOf(COMMIT_ID_START_TAG) + const end = commentBody.indexOf(COMMIT_ID_END_TAG) + if (start === -1 || end === -1) { + return '' + } + return commentBody.substring(start, end + COMMIT_ID_END_TAG.length) + } + + // add a commit id to the list of reviewed commit ids + // if the marker doesn't exist, add it + addReviewedCommitId(commentBody: string, commitId: string): string { + const start = commentBody.indexOf(COMMIT_ID_START_TAG) + const end = commentBody.indexOf(COMMIT_ID_END_TAG) + if (start === -1 || end === -1) { + return `${commentBody}\n${COMMIT_ID_START_TAG}\n\n${COMMIT_ID_END_TAG}` + } + const ids = commentBody.substring(start + COMMIT_ID_START_TAG.length, end) + return `${commentBody.substring( + 0, + start + COMMIT_ID_START_TAG.length + )}${ids}\n${commentBody.substring(end)}` + } + + // given a list of commit ids provide the highest commit id that has been reviewed + getHighestReviewedCommitId( + commitIds: string[], + reviewedCommitIds: string[] + ): string { + for (let i = commitIds.length - 1; i >= 0; i--) { + if (reviewedCommitIds.includes(commitIds[i])) { + return commitIds[i] + } + } + return '' + } + + async getAllCommitIds(): Promise { + const allCommits = [] + let page = 1 + let commits + if (context && context.payload && context.payload.pull_request != null) { + do { + commits = await octokit.pulls.listCommits({ + owner: repo.owner, + repo: repo.repo, + // eslint-disable-next-line camelcase + pull_number: context.payload.pull_request.number, + // eslint-disable-next-line camelcase + per_page: 100, + page + }) + + allCommits.push(...commits.data.map(commit => commit.sha)) + page++ + } while (commits.data.length > 0) + } + + return allCommits + } + + // add in-progress status to the comment body + addInProgressStatus(commentBody: string, statusMsg: string): string { + const start = commentBody.indexOf(IN_PROGRESS_START_TAG) + const end = commentBody.indexOf(IN_PROGRESS_END_TAG) + // add to the beginning of the comment body if the marker doesn't exist + // otherwise do nothing + if (start === -1 || end === -1) { + return `${IN_PROGRESS_START_TAG} + +Currently reviewing new changes in this PR... + +${statusMsg} + +${IN_PROGRESS_END_TAG} + +--- + +${commentBody}` + } + return commentBody + } + + // remove in-progress status from the comment body + removeInProgressStatus(commentBody: string): string { + const start = commentBody.indexOf(IN_PROGRESS_START_TAG) + const end = commentBody.indexOf(IN_PROGRESS_END_TAG) + // remove the in-progress status if the marker exists + // otherwise do nothing + if (start !== -1 && end !== -1) { + return ( + commentBody.substring(0, start) + + commentBody.substring(end + IN_PROGRESS_END_TAG.length) + ) + } + return commentBody + } +} diff --git a/src/confidence.ts b/src/confidence.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5973fb01328d3300396ae4f41b52967afbcac4c --- /dev/null +++ b/src/confidence.ts @@ -0,0 +1,588 @@ +export interface ConfidenceFactors { + patternMatchScore: number + contextRichness: number + historicalAccuracy: number + severityMatchesKnownBug: boolean + hasExplicitEvidence: boolean + teamAcceptanceRate: number + patternTypeAccuracy: number +} + +export interface CalibratedConfidence { + score: number + factors: ConfidenceFactors + reasoning: string +} + +const KNOWN_BUG_PATTERNS: Array<{ + pattern: RegExp + severity: 'critical' | 'major' | 'minor' | 'info' + category: string +}> = [ + { + pattern: /null.*pointer|NPE|null.*check/i, + severity: 'critical', + category: 'null-pointer' + }, + { + pattern: /sql.*injection|SELECT.*WHERE.*\+|query.*concat/i, + severity: 'critical', + category: 'sql-injection' + }, + { + pattern: /password|secret|api.*key.*=.*['"]|token.*=.*['"]/i, + severity: 'critical', + category: 'secret-exposure' + }, + { + pattern: /eval\(|new.*Function\(|innerHTML\s*=|document\.write/i, + severity: 'critical', + category: 'xss' + }, + { + pattern: /race.*condition|concurrent.*modif|deadlock|mutex/i, + severity: 'major', + category: 'concurrency' + }, + { + pattern: /memory.*leak|dispose\(|close\(|gc\./i, + severity: 'major', + category: 'resource-leak' + }, + { + pattern: /async.*without.*await|unhandled.*promise|catch.*without.*throw/i, + severity: 'major', + category: 'async-issues' + }, + { + pattern: /try.*without.*catch|catch.*empty|swallow.*exception/i, + severity: 'minor', + category: 'error-handling' + }, + { + pattern: /any.*type|cast.*any|as.*any/i, + severity: 'info', + category: 'type-safety' + }, + { + pattern: /console\.(log|debug|warn)/i, + severity: 'info', + category: 'logging' + }, + { + pattern: /TODO|FIXME|HACK|XXX|BUG:/i, + severity: 'info', + category: 'tech-debt' + }, + { + pattern: /division.*by.*zero|divide.*0|x\s*\/\s*0/i, + severity: 'major', + category: 'arithmetic' + }, + { + pattern: /off.*by.*one|index.*length|length.*-\s*1/i, + severity: 'minor', + category: 'logic-error' + }, + { + pattern: /useEffect.*missing.*dep|dependency.*array/i, + severity: 'minor', + category: 'react-hooks' + }, + { + pattern: /mutation.*props|props.*change|immutable/i, + severity: 'minor', + category: 'immutability' + }, + { + pattern: /hardcoded|hard.*coded/i, + severity: 'minor', + category: 'hardcoding' + }, + { + pattern: /circular.*depend|lazy.*load|circular/i, + severity: 'major', + category: 'architecture' + }, + { + pattern: /sql.*string|query.*build|string.*concat.*sql/i, + severity: 'critical', + category: 'sql-injection' + }, + { + pattern: /crypto.*md5|sha1.*encrypt|md5.*hash/i, + severity: 'critical', + category: 'crypto' + }, + { + pattern: /http.*not.*https|mixed.*content|insecure.*request/i, + severity: 'major', + category: 'security' + }, + { + pattern: /cookie.*without.*secure|secure.*flag.*false/i, + severity: 'major', + category: 'security' + }, + { + pattern: /sudo|chmod\s+777|root.*login/i, + severity: 'critical', + category: 'security' + }, + { + pattern: /catch.*(e|err).*{[\s]*}/i, + severity: 'minor', + category: 'error-handling' + }, + { + pattern: /setTimeout.*0|setImmediate/i, + severity: 'info', + category: 'timing' + }, + { + pattern: /double.*click|race.*click|multiple.*submit/i, + severity: 'minor', + category: 'ux' + } +] + +const POSITIVE_INDICATORS = [ + {indicator: 'suggestion', weight: 0.15}, + {indicator: '```suggestion', weight: 0.2}, + {indicator: 'fix:', weight: 0.1}, + {indicator: 'fixed code', weight: 0.1}, + {indicator: 'correct', weight: 0.05}, + {indicator: 'instead of', weight: 0.05}, + {indicator: 'should be', weight: 0.05}, + {indicator: 'best practice', weight: 0.05} +] + +const NEGATIVE_INDICATORS = [ + {indicator: 'maybe', weight: -0.15}, + {indicator: 'might', weight: -0.1}, + {indicator: 'possibly', weight: -0.1}, + {indicator: 'i think', weight: -0.2}, + {indicator: 'unclear', weight: -0.1}, + {indicator: 'ไธ็กฎๅฎš', weight: -0.15}, + {indicator: 'perhaps', weight: -0.1}, + {indicator: 'could be', weight: -0.1}, + {indicator: 'not sure', weight: -0.15}, + {indicator: 'likely', weight: -0.05} +] + +export class ConfidenceCalibrator { + private historicalAccuracies: Map = new Map() + private feedbackHistory: Array<{ + pattern: string + helpful: boolean + timestamp: number + }> = [] + private readonly persistPath = '/tmp/prix_feedback.json' + private feedbackTracker: any = null + + constructor(feedbackTracker: any = null) { + this.loadPersisted() + if (feedbackTracker) { + this.feedbackTracker = feedbackTracker + } else { + try { + const {FeedbackTracker} = require('./feedback-tracker') + this.feedbackTracker = new FeedbackTracker() + } catch (e) { + // FeedbackTracker not available, continue without it + } + } + } + + private loadPersisted(): void { + try { + if (require('fs').existsSync(this.persistPath)) { + const data = JSON.parse( + require('fs').readFileSync(this.persistPath, 'utf8') + ) + if (Array.isArray(data)) { + this.feedbackHistory = data.map((item: any) => ({ + pattern: item.pattern || '', + helpful: item.helpful || false, + timestamp: item.timestamp || Date.now() + })) + this.rebuildHistoricalAccuracies() + } + } + } catch (e) { + // Start fresh if persistence fails + } + } + + private persist(): void { + try { + require('fs').writeFileSync( + this.persistPath, + JSON.stringify(this.feedbackHistory.slice(-1000)) + ) + } catch (e) { + // Persistence failure is non-fatal + } + } + + private rebuildHistoricalAccuracies(): void { + const patternMap = new Map() + for (const entry of this.feedbackHistory) { + const accuracies = patternMap.get(entry.pattern) || [] + accuracies.push(entry.helpful ? 1 : 0) + patternMap.set(entry.pattern, accuracies) + } + for (const [pattern, accuracies] of patternMap) { + this.historicalAccuracies.set(pattern, accuracies) + } + } + + recordFeedback(pattern: string, helpful: boolean): void { + this.feedbackHistory.push({pattern, helpful, timestamp: Date.now()}) + const accuracies = this.historicalAccuracies.get(pattern) || [] + accuracies.push(helpful ? 1 : 0) + this.historicalAccuracies.set(pattern, accuracies) + this.persist() + } + + calibrate( + aiReportedConfidence: number | undefined, + comment: string, + contextTokens: number, + maxContextTokens: number, + severity: string | undefined, + teamId?: string, + repoSlug?: string, + patternType?: string, + filename?: string + ): CalibratedConfidence { + const factors = this.calculateFactors( + comment, + contextTokens, + maxContextTokens, + severity, + teamId, + repoSlug, + patternType, + filename + ) + + let score: number + + if (aiReportedConfidence !== undefined) { + const deBiased = this.removeLLMBias(aiReportedConfidence) + score = this.combineWithFactors(deBiased, factors) + } else { + score = this.computeFromFactorsOnly(factors) + } + + score = Math.max(0, Math.min(100, score)) + + return { + score: Math.round(score), + factors, + reasoning: this.generateReasoning(factors, score) + } + } + + private calculateFactors( + comment: string, + contextTokens: number, + maxContextTokens: number, + severity: string | undefined, + teamId?: string, + repoSlug?: string, + patternType?: string, + filename?: string + ): ConfidenceFactors { + const patternMatchScore = this.calculatePatternMatch(comment) + const contextRichness = Math.min( + 1, + contextTokens / Math.max(1, maxContextTokens * 0.5) + ) + const historicalAccuracy = this.calculateHistoricalAccuracy(comment) + const severityMatchesKnownBug = severity + ? this.matchesKnownBugPattern(comment, severity) + : this.matchesAnyKnownBugPattern(comment) + const hasExplicitEvidence = this.hasExplicitEvidence(comment) + const {teamAcceptanceRate, patternTypeAccuracy} = this.calculateTeamMetrics( + teamId, + repoSlug, + patternType, + filename + ) + + return { + patternMatchScore, + contextRichness, + historicalAccuracy, + severityMatchesKnownBug, + hasExplicitEvidence, + teamAcceptanceRate, + patternTypeAccuracy + } + } + + private calculateTeamMetrics( + teamId?: string, + repoSlug?: string, + patternType?: string, + filename?: string + ): {teamAcceptanceRate: number; patternTypeAccuracy: number} { + if (!this.feedbackTracker || !teamId || !repoSlug) { + return {teamAcceptanceRate: 0.5, patternTypeAccuracy: 0.5} + } + + let teamAcceptanceRate = 0.5 + let patternTypeAccuracy = 0.5 + + if (patternType && filename) { + teamAcceptanceRate = this.feedbackTracker.getPatternAcceptanceRate( + patternType, + teamId, + repoSlug + ) + patternTypeAccuracy = this.feedbackTracker.getFilenameAcceptanceRate( + filename, + teamId, + repoSlug + ) + } + + return {teamAcceptanceRate, patternTypeAccuracy} + } + + private calculatePatternMatch(comment: string): number { + const lowerComment = comment.toLowerCase() + let score = 0.5 + + for (const {indicator, weight} of POSITIVE_INDICATORS) { + if (lowerComment.includes(indicator.toLowerCase())) { + score += weight + } + } + + for (const {indicator, weight} of NEGATIVE_INDICATORS) { + if (lowerComment.includes(indicator.toLowerCase())) { + score += weight + } + } + + if (lowerComment.includes('why this matters')) { + score += 0.1 + } + + if ( + lowerComment.includes('production') || + lowerComment.includes('production environment') + ) { + score += 0.05 + } + + return Math.max(0, Math.min(1, score)) + } + + private calculateHistoricalAccuracy(comment: string): number { + const lowerComment = comment.toLowerCase() + + for (const [pattern, accuracies] of this.historicalAccuracies) { + if (lowerComment.includes(pattern.toLowerCase())) { + const avg = accuracies.reduce((a, b) => a + b, 0) / accuracies.length + return avg + } + } + + const relevantFeedback = this.feedbackHistory.filter(f => + f.pattern + .split(' ') + .some( + word => word.length > 4 && lowerComment.includes(word.toLowerCase()) + ) + ) + + if (relevantFeedback.length === 0) { + return 0.5 + } + + const accuracy = + relevantFeedback.filter(f => f.helpful).length / relevantFeedback.length + return accuracy + } + + private matchesKnownBugPattern(comment: string, severity: string): boolean { + const lowerComment = comment.toLowerCase() + + for (const {pattern, severity: patternSeverity} of KNOWN_BUG_PATTERNS) { + if (pattern.test(lowerComment) && patternSeverity === severity) { + return true + } + } + + return false + } + + private matchesAnyKnownBugPattern(comment: string): boolean { + const lowerComment = comment.toLowerCase() + + for (const {pattern} of KNOWN_BUG_PATTERNS) { + if (pattern.test(lowerComment)) { + return true + } + } + + return false + } + + private hasExplicitEvidence(comment: string): boolean { + const explicitPhrases = [ + 'this will crash', + 'this causes', + 'this leads to', + 'results in', + 'fails when', + 'breaks when', + 'error when', + 'crash if', + 'exception if', + 'undefined behavior', + 'undefined is', + 'will throw', + 'will fail' + ] + + const lowerComment = comment.toLowerCase() + return explicitPhrases.some(phrase => lowerComment.includes(phrase)) + } + + private removeLLMBias(reportedConfidence: number): number { + if (reportedConfidence >= 95) { + return 75 + } + if (reportedConfidence >= 85) { + return 70 + } + if (reportedConfidence >= 70) { + return 62 + } + if (reportedConfidence >= 60) { + return 55 + } + return reportedConfidence * 0.9 + } + + private combineWithFactors( + baseScore: number, + factors: ConfidenceFactors + ): number { + const weights = { + base: 0.25, + pattern: 0.2, + context: 0.1, + historical: 0.15, + knownBug: 0.05, + teamAcceptance: 0.15, + patternAccuracy: 0.1 + } + + let score = baseScore * weights.base + + score += factors.patternMatchScore * 100 * weights.pattern + score += factors.contextRichness * 100 * weights.context + score += factors.historicalAccuracy * 100 * weights.historical + + if (factors.severityMatchesKnownBug) { + score += 10 * weights.knownBug + } + + if (factors.hasExplicitEvidence) { + score += 5 + } + + score += factors.teamAcceptanceRate * 100 * weights.teamAcceptance + score += factors.patternTypeAccuracy * 100 * weights.patternAccuracy + + return score + } + + private computeFromFactorsOnly(factors: ConfidenceFactors): number { + const weights = { + pattern: 0.3, + context: 0.15, + historical: 0.2, + knownBug: 0.15, + teamAcceptance: 0.12, + patternAccuracy: 0.08 + } + + let score = 50 + + score += factors.patternMatchScore * 50 * weights.pattern + score += factors.contextRichness * 50 * weights.context + score += factors.historicalAccuracy * 50 * weights.historical + + if (factors.severityMatchesKnownBug) { + score += 10 * weights.knownBug + } + + if (factors.hasExplicitEvidence) { + score += 5 + } + + score += factors.teamAcceptanceRate * 50 * weights.teamAcceptance + score += factors.patternTypeAccuracy * 50 * weights.patternAccuracy + + return score + } + + private generateReasoning(factors: ConfidenceFactors, score: number): string { + const reasons: string[] = [] + + if (factors.patternMatchScore > 0.7) { + reasons.push('strong pattern match') + } else if (factors.patternMatchScore < 0.4) { + reasons.push('weak pattern match') + } + + if (factors.contextRichness > 0.8) { + reasons.push('rich context') + } else if (factors.contextRichness < 0.3) { + reasons.push('limited context') + } + + if (factors.historicalAccuracy > 0.7) { + reasons.push('historically accurate') + } else if ( + factors.historicalAccuracy < 0.4 && + factors.historicalAccuracy !== 0.5 + ) { + reasons.push('historically unreliable') + } + + if (factors.severityMatchesKnownBug) { + reasons.push('matches known bug pattern') + } + + if (factors.hasExplicitEvidence) { + reasons.push('has explicit evidence') + } + + if (factors.teamAcceptanceRate > 0.6) { + reasons.push('high team acceptance') + } else if ( + factors.teamAcceptanceRate < 0.3 && + factors.teamAcceptanceRate !== 0.5 + ) { + reasons.push('low team acceptance') + } + + if (factors.patternTypeAccuracy > 0.6) { + reasons.push('matches accepted patterns') + } + + return reasons.length > 0 + ? `Calibrated based on: ${reasons.join(', ')}` + : 'Calibrated using default heuristics' + } +} + +export const confidenceCalibrator = new ConfidenceCalibrator() diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 0000000000000000000000000000000000000000..b51def108ee7627f636506370858bbd9f6263e5e --- /dev/null +++ b/src/config.ts @@ -0,0 +1,306 @@ +import {readFileSync, existsSync} from 'fs' +import {join} from 'path' +import {als} from './context' +import {prixExec} from './utils' + +export interface PrixConfig { + version: string + severity: { + minimumLevel: 'critical' | 'major' | 'minor' | 'info' + showConfidenceThreshold: number + } + filters: { + excludePatterns: string[] + includePatterns: string[] + disableTypes: string[] + } + linting: { + enabled: boolean + eslint: boolean + prettier: boolean + failOnError: boolean + } + review: { + maxFilesPerPR: number + maxCommentsPerFile: number + denseMode: boolean + showImpactAnalysis: boolean + } + remedies: { + enabled: boolean + autoCreatePR: boolean + requireApproval: boolean + } + confidence: { + minCritical: number + minMajor: number + minMinor: number + minInfo: number + } +} + +export const DEFAULT_PRIX_CONFIG: PrixConfig = { + version: '1.0', + severity: { + minimumLevel: 'minor', + showConfidenceThreshold: 50 + }, + filters: { + excludePatterns: [], + includePatterns: ['**/*'], + disableTypes: [] + }, + linting: { + enabled: true, + eslint: true, + prettier: true, + failOnError: false + }, + review: { + maxFilesPerPR: 50, + maxCommentsPerFile: 10, + denseMode: false, + showImpactAnalysis: true + }, + remedies: { + enabled: false, + autoCreatePR: false, + requireApproval: true + }, + confidence: { + minCritical: 0, + minMajor: 60, + minMinor: 70, + minInfo: 80 + } +} + +export class PrixConfigLoader { + private config: PrixConfig | null = null + + load(workingDir: string): PrixConfig { + if (this.config) { + return this.config + } + + const possiblePaths = [ + join(workingDir, '.prix.yml'), + join(workingDir, 'prix.yml'), + join(workingDir, '.prix.yaml'), + join(workingDir, 'prix.yaml') + ] + + for (const configPath of possiblePaths) { + if (existsSync(configPath)) { + try { + const content = readFileSync(configPath, 'utf8') + this.config = this.mergeWithDefaults(this.parseYAML(content)) + return this.config + } catch (e) { + console.warn(`Failed to load prix config from ${configPath}: ${e}`) + } + } + } + + this.config = DEFAULT_PRIX_CONFIG + return this.config + } + + private parseYAML(content: string): Partial { + const result: Partial = {} + const lines = content.split('\n') + let currentSection: string | null = null + let currentSectionObj: Record = {} + let sectionKey = '' + + for (const line of lines) { + const sectionMatch = line.match(/^(\w+):\s*$/) + if (sectionMatch) { + if (currentSection && sectionKey) { + ;(result as any)[sectionKey] = currentSectionObj + } + currentSection = sectionMatch[1] + sectionKey = currentSection + currentSectionObj = {} + continue + } + + const keyValueMatch = line.match(/^\s*(\w+):\s*(.+)$/) + if (keyValueMatch && currentSection) { + const key = keyValueMatch[1] + let value: any = keyValueMatch[2].trim() + + if (value === 'true') value = true + else if (value === 'false') value = false + else if (!isNaN(Number(value))) value = Number(value) + + currentSectionObj[key] = value + } + } + + if (currentSection && sectionKey) { + ;(result as any)[sectionKey] = currentSectionObj + } + + return result + } + + private mergeWithDefaults(config: Partial): PrixConfig { + return { + version: config.version || DEFAULT_PRIX_CONFIG.version, + severity: { + ...DEFAULT_PRIX_CONFIG.severity, + ...config.severity + }, + filters: { + ...DEFAULT_PRIX_CONFIG.filters, + ...config.filters + }, + linting: { + ...DEFAULT_PRIX_CONFIG.linting, + ...config.linting + }, + review: { + ...DEFAULT_PRIX_CONFIG.review, + ...config.review + }, + remedies: { + ...DEFAULT_PRIX_CONFIG.remedies, + ...config.remedies + }, + confidence: { + ...DEFAULT_PRIX_CONFIG.confidence, + ...config.confidence + } + } + } + + shouldIncludeFile(config: PrixConfig, filename: string): boolean { + const {excludePatterns, includePatterns} = config.filters + + for (const pattern of excludePatterns) { + if (this.matchesPattern(filename, pattern)) { + return false + } + } + + if (includePatterns.length === 0) { + return true + } + + for (const pattern of includePatterns) { + if (this.matchesPattern(filename, pattern)) { + return true + } + } + + return false + } + + private matchesPattern(filename: string, pattern: string): boolean { + const regexPattern = pattern + .replace(/\./g, '\\.') + .replace(/\*/g, '.*') + .replace(/\?/g, '.') + .replace(/\*\*/g, '.*') + + return new RegExp(`^${regexPattern}$`).test(filename) + } +} + +export const configLoader = new PrixConfigLoader() + +export function getConfig(): PrixConfig { + const ctx = als.getStore() + const workingDir = ctx?.workingDir || process.cwd() + return configLoader.load(workingDir) +} + +export function meetsConfidenceThreshold( + severity: 'critical' | 'major' | 'minor' | 'info', + confidence: number +): boolean { + const config = getConfig() + const thresholds = config.confidence + + switch (severity) { + case 'critical': + return confidence >= thresholds.minCritical + case 'major': + return confidence >= thresholds.minMajor + case 'minor': + return confidence >= thresholds.minMinor + case 'info': + return confidence >= thresholds.minInfo + default: + return true + } +} + +export function meetsMinimumSeverity(severity: string): boolean { + const config = getConfig() + const levels = ['critical', 'major', 'minor', 'info'] + const minimumLevel = config.severity.minimumLevel + const minimumIndex = levels.indexOf(minimumLevel) + const severityIndex = levels.indexOf(severity.toLowerCase()) + + return severityIndex >= minimumIndex +} + +export async function lintSuggestion( + suggestion: string, + filename: string, + language: string +): Promise<{valid: boolean; errors: string[]}> { + const config = getConfig() + if (!config.linting.enabled) { + return {valid: true, errors: []} + } + + const errors: string[] = [] + const workingDir = als.getStore()?.workingDir || process.cwd() + + if (config.linting.prettier) { + try { + prixExec( + `echo "${suggestion.replace( + /"/g, + '\\"' + )}" | prettier --stdin-filepath ${filename}`, + { + cwd: workingDir, + stdio: 'pipe' + } + ) + } catch { + errors.push('Prettier formatting check failed') + } + } + + if ( + config.linting.eslint && + (language === 'javascript' || language === 'typescript') + ) { + try { + const ext = filename.endsWith('.ts') ? 'ts' : 'js' + const tempFile = `.prix_temp_suggestion.${ext}` + prixExec( + `echo "${suggestion.replace( + /"/g, + '\\"' + )}" > ${tempFile} && npx eslint ${tempFile} --format json 2>&1 || true`, + { + cwd: workingDir, + stdio: 'pipe' + } + ) + } catch { + errors.push('ESLint check failed') + } + } + + return { + valid: config.linting.failOnError ? errors.length === 0 : true, + errors + } +} diff --git a/src/console-reporter.ts b/src/console-reporter.ts new file mode 100644 index 0000000000000000000000000000000000000000..289692f7d2a7de5761aaff14cf961d654a6515fc --- /dev/null +++ b/src/console-reporter.ts @@ -0,0 +1,151 @@ +import {LocalFinding} from './local-context' + +export interface ReporterOptions { + output: 'console' | 'json' + minSeverity: 'critical' | 'major' | 'minor' | 'info' + minConfidence: number +} + +const SEVERITY_COLORS: Record = { + critical: '\x1b[31m', + major: '\x1b[33m', + minor: '\x1b[36m', + info: '\x1b[90m' +} + +const SEVERITY_EMOJI: Record = { + critical: '๐Ÿšจ', + major: '๐Ÿ”ด', + minor: '๐ŸŸ ', + info: 'โ„น๏ธ' +} + +const TYPE_COLORS: Record = { + security: '\x1b[35m', + bug: '\x1b[31m', + performance: '\x1b[33m', + style: '\x1b[90m', + general: '\x1b[0m' +} + +const RESET = '\x1b[0m' + +export class LocalConsoleReporter { + printFindings(findings: LocalFinding[], options: ReporterOptions): void { + if (options.output === 'json') { + this.printJson(findings) + return + } + + this.printConsole(findings) + } + + private printConsole(findings: LocalFinding[]): void { + if (findings.length === 0) { + return + } + + const sortedFindings = [...findings].sort((a, b) => { + const severityOrder = {critical: 0, major: 1, minor: 2, info: 3} + const severityDiff = severityOrder[a.severity] - severityOrder[b.severity] + if (severityDiff !== 0) return severityDiff + return b.confidence - a.confidence + }) + + const groupedByFile = new Map() + for (const finding of sortedFindings) { + if (!groupedByFile.has(finding.filename)) { + groupedByFile.set(finding.filename, []) + } + groupedByFile.get(finding.filename)!.push(finding) + } + + for (const [filename, fileFindings] of groupedByFile) { + console.log(`\n${'='.repeat(80)}`) + console.log(`${SEVERITY_COLORS.info}๐Ÿ“„ ${filename}${RESET}`) + console.log('='.repeat(80)) + + for (const finding of fileFindings) { + this.printFinding(finding) + } + } + } + + private printFinding(finding: LocalFinding): void { + const severityColor = SEVERITY_COLORS[finding.severity] || '' + const typeColor = TYPE_COLORS[finding.type] || '' + const emoji = SEVERITY_EMOJI[finding.severity] || 'โ€ข' + + console.log( + `\n${severityColor}${emoji} [${finding.severity.toUpperCase()}]${RESET} ${typeColor}${ + finding.type + }${RESET} (${finding.confidence}% confidence)` + ) + console.log( + `${' '.repeat(4)}๐Ÿ“ Line ${finding.line}${ + finding.endLine !== finding.line ? `-${finding.endLine}` : '' + }` + ) + + const messageLines = finding.message.split('\n').filter(l => l.trim()) + for (const line of messageLines) { + console.log(`${' '.repeat(4)}${line}`) + } + + if (finding.suggestion) { + console.log(`${' '.repeat(4)}๐Ÿ’ก Suggested fix:`) + const suggestionLines = finding.suggestion.split('\n') + for (const line of suggestionLines.slice(0, 10)) { + console.log(`${' '.repeat(8)}${line}`) + } + if (suggestionLines.length > 10) { + console.log( + `${' '.repeat(8)}... (${suggestionLines.length - 10} more lines)` + ) + } + } + } + + private printJson(findings: LocalFinding[]): void { + const output = { + version: '1.0', + timestamp: new Date().toISOString(), + summary: { + total: findings.length, + critical: findings.filter(f => f.severity === 'critical').length, + major: findings.filter(f => f.severity === 'major').length, + minor: findings.filter(f => f.severity === 'minor').length, + info: findings.filter(f => f.severity === 'info').length + }, + findings: findings.map(f => ({ + filename: f.filename, + line: f.line, + endLine: f.endLine, + severity: f.severity, + type: f.type, + message: f.message, + confidence: f.confidence, + suggestion: f.suggestion, + patternType: f.patternType + })) + } + + console.log(JSON.stringify(output, null, 2)) + } + + printSummary(findings: LocalFinding[]): void { + const critical = findings.filter(f => f.severity === 'critical').length + const major = findings.filter(f => f.severity === 'major').length + const minor = findings.filter(f => f.severity === 'minor').length + const info = findings.filter(f => f.severity === 'info').length + + console.log(`\n${'='.repeat(80)}`) + console.log('๐Ÿ“Š REVIEW SUMMARY') + console.log('='.repeat(80)) + console.log(` ๐Ÿšจ Critical: ${critical}`) + console.log(` ๐Ÿ”ด Major: ${major}`) + console.log(` ๐ŸŸ  Minor: ${minor}`) + console.log(` โ„น๏ธ Info: ${info}`) + console.log('='.repeat(80)) + } +} diff --git a/src/context.ts b/src/context.ts new file mode 100644 index 0000000000000000000000000000000000000000..4492a1eb9630b9c5e4903de03325313841f82eed --- /dev/null +++ b/src/context.ts @@ -0,0 +1,35 @@ +import {AsyncLocalStorage} from 'async_hooks' + +export interface PRIXContext { + probotContext: any + octokit: any + repo: { + owner: string + repo: string + } + workingDir?: string +} + +// Global context storage for current execution thread +export const als = new AsyncLocalStorage() + +/** + * Access the current execution context safely from anywhere in the codebase. + */ +export const getCurrentContext = (): PRIXContext | undefined => { + return als.getStore() +} + +/** + * Helper to get octokit from current context + */ +export const getSafeOctokit = (): any => { + return als.getStore()?.octokit +} + +/** + * Helper to get repo info from current context + */ +export const getSafeRepo = () => { + return als.getStore()?.repo +} diff --git a/src/feedback-capture.ts b/src/feedback-capture.ts new file mode 100644 index 0000000000000000000000000000000000000000..c3854b530948f56982c8b873a4c9019d40930156 --- /dev/null +++ b/src/feedback-capture.ts @@ -0,0 +1,281 @@ +import {octokit} from './octokit' +import {als} from './context' +import {feedbackTracker} from './feedback-tracker' +import {PatternCategory} from './feedback-types' + +const info = console.log +const warning = console.warn + +const FEEDBACK_TAG = '' + +export interface CommentMetadata { + commentId?: number + pullNumber: number + path: string + patternType: PatternCategory + severity: 'critical' | 'major' | 'minor' | 'info' + confidence: number +} + +export class FeedbackCapture { + private commentMetadata: Map = new Map() + private pendingFeedback: Map = new Map() + + private getCommentKey( + pullNumber: number, + path: string, + startLine: number + ): string { + return `${pullNumber}:${path}:${startLine}` + } + + trackComment( + pullNumber: number, + path: string, + startLine: number, + patternType: PatternCategory, + severity: 'critical' | 'major' | 'minor' | 'info', + confidence: number, + commentId?: number + ): void { + const key = this.getCommentKey(pullNumber, path, startLine) + this.commentMetadata.set(key, { + commentId, + pullNumber, + path, + patternType, + severity, + confidence + }) + } + + async checkSuggestionApplied( + pullNumber: number, + path: string, + startLine: number + ): Promise { + const key = this.getCommentKey(pullNumber, path, startLine) + const metadata = this.commentMetadata.get(key) + if (!metadata || !metadata.commentId) return false + + try { + const comments = await octokit.pulls.listReviewComments({ + owner: als.getStore()?.repo.owner || '', + repo: als.getStore()?.repo.repo || '', + // eslint-disable-next-line camelcase + pull_number: pullNumber + }) + + const originalComment = comments.data.find( + (c: any) => c.id === metadata.commentId + ) + + if (!originalComment) return false + + const diff = await this.getFileDiffAtComment( + pullNumber, + path, + startLine, + originalComment.original_line || startLine + ) + + const hasAppliedSuggestion = this.detectSuggestionApplication( + originalComment.body || '', + diff + ) + + if (hasAppliedSuggestion) { + this.recordFeedback(key, 'accepted') + } + + return hasAppliedSuggestion + } catch (e) { + warning(`Failed to check suggestion application: ${e}`) + return false + } + } + + private async getFileDiffAtComment( + pullNumber: number, + path: string, + startLine: number, + originalLine: number + ): Promise { + try { + const diff = await octokit.repos.compareCommits({ + owner: als.getStore()?.repo.owner || '', + repo: als.getStore()?.repo.repo || '', + base: `${pullNumber}-base`, + head: `${pullNumber}-head` + }) + + const file = diff.data.files?.find((f: any) => f.filename === path) + if (!file?.patch) return '' + + const hunk = file.patch + .split('\n') + .slice( + Math.max(0, originalLine - startLine - 1), + originalLine - startLine + 5 + ) + .join('\n') + + return hunk + } catch (e) { + return '' + } + } + + private detectSuggestionApplication( + originalBody: string, + currentDiff: string + ): boolean { + if (!originalBody.includes('```suggestion')) return false + if (!currentDiff) return false + + const suggestionMatch = originalBody.match(/```suggestion\n([\s\S]*?)```/) + if (!suggestionMatch) return false + + const suggestedCode = suggestionMatch[1].trim() + const hasApplied = currentDiff.includes( + suggestedCode.substring(0, Math.min(50, suggestedCode.length)) + ) + + return hasApplied + } + + recordFeedback(key: string, type: 'accepted' | 'rejected'): void { + const metadata = this.commentMetadata.get(key) + if (!metadata) return + + this.pendingFeedback.set(key, type) + + const ctx = als.getStore() + const teamId = ctx?.repo?.owner || 'default' + const repoSlug = ctx?.repo?.repo || 'default' + + feedbackTracker.recordFeedback({ + patternType: metadata.patternType, + severity: metadata.severity, + filenamePattern: metadata.path, + repoSlug, + teamId, + confidence: metadata.confidence, + feedbackType: type + }) + + info(`Recorded ${type} feedback for ${key}`) + } + + async checkReactionFeedback(pullNumber: number): Promise { + const ctx = als.getStore() + const teamId = ctx?.repo?.owner || 'default' + const repoSlug = ctx?.repo?.repo || 'default' + + try { + const comments = await octokit.pulls.listReviewComments({ + owner: teamId, + repo: repoSlug, + // eslint-disable-next-line camelcase + pull_number: pullNumber + }) + + for (const comment of comments.data) { + if (!comment.body?.includes(FEEDBACK_TAG)) continue + + const reactions = await octokit.reactions.listForIssueComment({ + owner: teamId, + repo: repoSlug, + // eslint-disable-next-line camelcase + comment_id: comment.id + }) + + for (const reaction of reactions.data) { + const key = this.getCommentKey( + pullNumber, + comment.path || '', + comment.line || comment.original_line || 0 + ) + + if (reaction.content === '+1' || reaction.content === 'heart') { + this.recordFeedback(key, 'accepted') + } else if (reaction.content === '-1' || reaction.content === 'eyes') { + this.recordFeedback(key, 'rejected') + } + } + } + } catch (e) { + warning(`Failed to check reaction feedback: ${e}`) + } + } + + async trackReviewSubmission( + pullNumber: number, + reviewId: number, + commitId: string + ): Promise { + const ctx = als.getStore() + const teamId = ctx?.repo?.owner || 'default' + const repoSlug = ctx?.repo?.repo || 'default' + + info( + `Tracking review submission: PR #${pullNumber}, review ID: ${reviewId}` + ) + + try { + const comments = await octokit.pulls.listReviewComments({ + owner: teamId, + repo: repoSlug, + // eslint-disable-next-line camelcase + pull_number: pullNumber + }) + + for (const comment of comments.data) { + if (!comment.body?.includes(FEEDBACK_TAG)) continue + if (comment.user?.login !== 'github-actions[bot]') continue + + const metadataMatch = comment.body.match(/data-pattern="([^"]+)"/) + const severityMatch = comment.body.match(/data-severity="([^"]+)"/) + const confidenceMatch = comment.body.match(/data-confidence="([^"]+)"/) + + if (metadataMatch && severityMatch && confidenceMatch) { + const key = this.getCommentKey( + pullNumber, + comment.path || '', + comment.line || comment.original_line || 0 + ) + + this.commentMetadata.set(key, { + commentId: comment.id, + pullNumber, + path: comment.path || '', + patternType: metadataMatch[1] as PatternCategory, + severity: severityMatch[1] as + | 'critical' + | 'major' + | 'minor' + | 'info', + confidence: parseFloat(confidenceMatch[1]) + }) + } + } + } catch (e) { + warning(`Failed to track review submission: ${e}`) + } + } + + getFeedbackStats(teamId: string, repoSlug: string) { + return feedbackTracker.getTeamInsights(teamId, repoSlug) + } + + shouldSuppressFinding( + patternType: PatternCategory, + filename: string, + teamId: string, + repoSlug: string + ): boolean { + return feedbackTracker.shouldSuppressPattern(patternType, teamId, repoSlug) + } +} + +export const feedbackCapture = new FeedbackCapture() diff --git a/src/feedback-tracker.ts b/src/feedback-tracker.ts new file mode 100644 index 0000000000000000000000000000000000000000..c818cc89a4e9250d5aad94df8560b6c55107e002 --- /dev/null +++ b/src/feedback-tracker.ts @@ -0,0 +1,478 @@ +import {writeFileSync, readFileSync, existsSync, mkdirSync} from 'fs' +import {join} from 'path' +import {minimatch} from 'minimatch' +import { + PatternFeedback, + PatternStats, + TeamPatternInsights, + FeedbackQuery, + FeedbackSummary, + FeedbackType, + PatternCategory +} from './feedback-types' + +const info = console.log + +function getPersistBaseDir(): string { + if (process.env.PRIX_DATA_DIR) return process.env.PRIX_DATA_DIR + if (process.env.HF_HOME) return join(process.env.HF_HOME, 'prix-data') + if (process.env.HUGGING_FACE_HUB_TOKEN) return '/tmp/prix-hf' + return '/tmp/prix' +} + +export class FeedbackTracker { + private feedbackStore: PatternFeedback[] = [] + private teamInsights: Map = new Map() + private readonly persistPath: string + private readonly maxStoreSize = 10000 + private initialized = false + + constructor(persistDir?: string) { + const baseDir = persistDir || getPersistBaseDir() + this.persistPath = join(baseDir, 'feedback') + this.ensureStorageDir() + this.loadPersisted() + } + + private ensureStorageDir(): void { + try { + if (!existsSync(this.persistPath)) { + mkdirSync(this.persistPath, {recursive: true}) + } + } catch (e) { + info(`Failed to create feedback storage dir: ${e}`) + } + } + + private loadPersisted(): void { + try { + const feedbackFile = join(this.persistPath, 'feedback.json') + if (existsSync(feedbackFile)) { + const data = JSON.parse(readFileSync(feedbackFile, 'utf8')) + if (Array.isArray(data)) { + this.feedbackStore = data.slice(-this.maxStoreSize) + this.rebuildTeamInsights() + this.initialized = true + info(`Loaded ${this.feedbackStore.length} feedback entries`) + } + } + } catch (e) { + info(`Failed to load feedback data: ${e}`) + } + } + + private persist(): void { + try { + const feedbackFile = join(this.persistPath, 'feedback.json') + writeFileSync( + feedbackFile, + JSON.stringify(this.feedbackStore.slice(-this.maxStoreSize)) + ) + } catch (e) { + info(`Failed to persist feedback: ${e}`) + } + } + + private rebuildTeamInsights(): void { + const teamMap = new Map() + + for (const fb of this.feedbackStore) { + const key = `${fb.teamId}:${fb.repoSlug}` + if (!teamMap.has(key)) { + teamMap.set(key, []) + } + teamMap.get(key)!.push(fb) + } + + for (const [key, feedbacks] of teamMap) { + const [teamId, repoSlug] = key.split(':') + const insights = this.computeInsights(teamId, repoSlug, feedbacks) + this.teamInsights.set(key, insights) + } + } + + private computeInsights( + teamId: string, + repoSlug: string, + feedbacks: PatternFeedback[] + ): TeamPatternInsights { + const patternMap = new Map() + + for (const fb of feedbacks) { + if (!patternMap.has(fb.patternType)) { + patternMap.set(fb.patternType, []) + } + patternMap.get(fb.patternType)!.push(fb) + } + + const patternStats = new Map() + + for (const [patternType, pFeedbacks] of patternMap) { + const accepted = pFeedbacks.filter( + f => f.feedbackType === 'accepted' + ).length + const rejected = pFeedbacks.filter( + f => f.feedbackType === 'rejected' + ).length + const ignored = pFeedbacks.filter( + f => f.feedbackType === 'ignored' + ).length + const total = pFeedbacks.length + const avgConfidence = + pFeedbacks.reduce((sum, f) => sum + f.confidence, 0) / total + + patternStats.set(patternType, { + patternType, + total, + accepted, + rejected, + ignored, + acceptanceRate: total > 0 ? accepted / total : 0, + avgConfidence + }) + } + + const allAccepted = feedbacks.filter( + f => f.feedbackType === 'accepted' + ).length + const overallAcceptanceRate = + feedbacks.length > 0 ? allAccepted / feedbacks.length : 0 + + return { + teamId, + repoSlug, + patternStats, + overallAcceptanceRate, + lastUpdated: Date.now() + } + } + + recordFeedback(feedback: Omit): string { + const id = `fb_${Date.now()}_${Math.random().toString(36).substr(2, 9)}` + + const fullFeedback: PatternFeedback = { + ...feedback, + id, + timestamp: Date.now() + } + + this.feedbackStore.push(fullFeedback) + + if (this.feedbackStore.length > this.maxStoreSize) { + this.feedbackStore = this.feedbackStore.slice(-this.maxStoreSize) + } + + const key = `${feedback.teamId}:${feedback.repoSlug}` + const existing = this.teamInsights.get(key) + if (existing) { + const updatedFeedbacks = [ + ...this.feedbackStore.filter( + f => f.teamId === feedback.teamId && f.repoSlug === feedback.repoSlug + ) + ] + const insights = this.computeInsights( + feedback.teamId, + feedback.repoSlug, + updatedFeedbacks + ) + this.teamInsights.set(key, insights) + } + + this.persist() + return id + } + + recordAcceptance( + patternType: PatternCategory, + severity: 'critical' | 'major' | 'minor' | 'info', + filename: string, + repoSlug: string, + teamId: string, + confidence: number, + commentId?: string, + reviewId?: string + ): string { + return this.recordFeedback({ + patternType, + severity, + filenamePattern: filename, + repoSlug, + teamId, + confidence, + feedbackType: 'accepted', + commentId, + reviewId + }) + } + + recordRejection( + patternType: PatternCategory, + severity: 'critical' | 'major' | 'minor' | 'info', + filename: string, + repoSlug: string, + teamId: string, + confidence: number, + commentId?: string, + reviewId?: string + ): string { + return this.recordFeedback({ + patternType, + severity, + filenamePattern: filename, + repoSlug, + teamId, + confidence, + feedbackType: 'rejected', + commentId, + reviewId + }) + } + + recordIgnored( + patternType: PatternCategory, + severity: 'critical' | 'major' | 'minor' | 'info', + filename: string, + repoSlug: string, + teamId: string, + confidence: number, + commentId?: string, + reviewId?: string + ): string { + return this.recordFeedback({ + patternType, + severity, + filenamePattern: filename, + repoSlug, + teamId, + confidence, + feedbackType: 'ignored', + commentId, + reviewId + }) + } + + getPatternAcceptanceRate( + patternType: PatternCategory, + teamId: string, + repoSlug: string + ): number { + const key = `${teamId}:${repoSlug}` + const insights = this.teamInsights.get(key) + if (!insights) return 0.5 + + const stats = insights.patternStats.get(patternType) + if (!stats) return 0.5 + + if (stats.total < 5) return 0.5 + + return stats.acceptanceRate + } + + getFilenameAcceptanceRate( + filenamePattern: string, + teamId: string, + repoSlug: string + ): number { + const feedbacks = this.feedbackStore.filter( + f => + f.teamId === teamId && + f.repoSlug === repoSlug && + f.feedbackType !== 'ignored' + ) + + if (feedbacks.length === 0) return 0.5 + + const matching = feedbacks.filter( + f => + minimatch(f.filenamePattern, filenamePattern) || + minimatch(filenamePattern, f.filenamePattern) + ) + if (matching.length === 0) return 0.5 + + const accepted = matching.filter(f => f.feedbackType === 'accepted').length + return accepted / matching.length + } + + getTeamInsights( + teamId: string, + repoSlug: string + ): TeamPatternInsights | null { + const key = `${teamId}:${repoSlug}` + return this.teamInsights.get(key) || null + } + + getAdjustedConfidence( + baseConfidence: number, + patternType: PatternCategory, + filename: string, + teamId: string, + repoSlug: string + ): number { + const patternRate = this.getPatternAcceptanceRate( + patternType, + teamId, + repoSlug + ) + const filenameRate = this.getFilenameAcceptanceRate( + filename, + teamId, + repoSlug + ) + + const feedbackWeight = 0.3 + const teamRate = patternRate * 0.6 + filenameRate * 0.4 + + const adjustedConfidence = + baseConfidence * (1 - feedbackWeight) + teamRate * 100 * feedbackWeight + + return Math.max(0, Math.min(100, adjustedConfidence)) + } + + shouldSuppressPattern( + patternType: PatternCategory, + teamId: string, + repoSlug: string, + threshold = 0.2, + minSamples = 10 + ): boolean { + const key = `${teamId}:${repoSlug}` + const insights = this.teamInsights.get(key) + if (!insights) return false + + const stats = insights.patternStats.get(patternType) + if (!stats || stats.total < minSamples) return false + + return stats.acceptanceRate < threshold + } + + getQuery(query: FeedbackQuery): PatternFeedback[] { + let results = [...this.feedbackStore] + + if (query.teamId) { + results = results.filter(f => f.teamId === query.teamId) + } + if (query.repoSlug) { + results = results.filter(f => f.repoSlug === query.repoSlug) + } + if (query.patternType) { + results = results.filter(f => f.patternType === query.patternType) + } + if (query.filenamePattern) { + results = results.filter(f => + minimatch(f.filenamePattern, query.filenamePattern!) + ) + } + if (query.since) { + results = results.filter(f => f.timestamp >= query.since!) + } + + if (query.limit) { + results = results.slice(-query.limit) + } + + return results + } + + getSummary(teamId?: string, repoSlug?: string): FeedbackSummary { + let feedbacks = [...this.feedbackStore] + + if (teamId) { + feedbacks = feedbacks.filter(f => f.teamId === teamId) + } + if (repoSlug) { + feedbacks = feedbacks.filter(f => f.repoSlug === repoSlug) + } + + const patternMap = new Map() + const repoMap = new Map() + const teamMap = new Map() + + for (const fb of feedbacks) { + if (!patternMap.has(fb.patternType)) { + patternMap.set(fb.patternType, []) + } + patternMap.get(fb.patternType)!.push(fb) + + repoMap.set(fb.repoSlug, (repoMap.get(fb.repoSlug) || 0) + 1) + teamMap.set(fb.teamId, (teamMap.get(fb.teamId) || 0) + 1) + } + + const byPattern = new Map() + for (const [patternType, pFeedbacks] of patternMap) { + const accepted = pFeedbacks.filter( + f => f.feedbackType === 'accepted' + ).length + const rejected = pFeedbacks.filter( + f => f.feedbackType === 'rejected' + ).length + const ignored = pFeedbacks.filter( + f => f.feedbackType === 'ignored' + ).length + const total = pFeedbacks.length + const avgConfidence = + pFeedbacks.reduce((sum, f) => sum + f.confidence, 0) / total + + byPattern.set(patternType, { + patternType, + total, + accepted, + rejected, + ignored, + acceptanceRate: total > 0 ? accepted / total : 0, + avgConfidence + }) + } + + const recentWindow = 30 * 24 * 60 * 60 * 1000 + const recentFeedbacks = feedbacks.filter( + f => f.timestamp > Date.now() - recentWindow + ) + const olderFeedbacks = feedbacks.filter( + f => f.timestamp <= Date.now() - recentWindow + ) + + const recentAcceptance = + recentFeedbacks.filter(f => f.feedbackType === 'accepted').length / + (recentFeedbacks.length || 1) + const olderAcceptance = + olderFeedbacks.filter(f => f.feedbackType === 'accepted').length / + (olderFeedbacks.length || 1) + + let recentTrend: 'improving' | 'declining' | 'stable' = 'stable' + if (recentAcceptance > olderAcceptance + 0.05) { + recentTrend = 'improving' + } else if (recentAcceptance < olderAcceptance - 0.05) { + recentTrend = 'declining' + } + + return { + totalFeedback: feedbacks.length, + byPattern, + byRepo: repoMap, + byTeam: teamMap, + recentTrend + } + } + + exportForTraining(): Array<{ + patternType: PatternCategory + severity: 'critical' | 'major' | 'minor' | 'info' + filenamePattern: string + confidence: number + accepted: boolean + repoSlug: string + }> { + return this.feedbackStore + .filter(f => f.feedbackType !== 'ignored') + .map(f => ({ + patternType: f.patternType, + severity: f.severity, + filenamePattern: f.filenamePattern, + confidence: f.confidence, + accepted: f.feedbackType === 'accepted', + repoSlug: f.repoSlug + })) + } +} + +export const feedbackTracker = new FeedbackTracker() diff --git a/src/feedback-types.ts b/src/feedback-types.ts new file mode 100644 index 0000000000000000000000000000000000000000..28d41a95c23a69ccc35299bf616abb2be7a8015d --- /dev/null +++ b/src/feedback-types.ts @@ -0,0 +1,65 @@ +export type FeedbackType = 'accepted' | 'rejected' | 'ignored' +export type PatternCategory = + | 'security' + | 'null-pointer' + | 'sql-injection' + | 'xss' + | 'concurrency' + | 'resource-leak' + | 'async-issues' + | 'error-handling' + | 'type-safety' + | 'arithmetic' + | 'logic-error' + | 'performance' + | 'style' + | 'general' + +export interface PatternFeedback { + id: string + patternType: PatternCategory + severity: 'critical' | 'major' | 'minor' | 'info' + filenamePattern: string + repoSlug: string + teamId: string + confidence: number + feedbackType: FeedbackType + timestamp: number + commentId?: string + reviewId?: string +} + +export interface PatternStats { + patternType: PatternCategory + total: number + accepted: number + rejected: number + ignored: number + acceptanceRate: number + avgConfidence: number +} + +export interface TeamPatternInsights { + teamId: string + repoSlug: string + patternStats: Map + overallAcceptanceRate: number + lastUpdated: number +} + +export interface FeedbackQuery { + teamId?: string + repoSlug?: string + patternType?: PatternCategory + filenamePattern?: string + since?: number + limit?: number +} + +export interface FeedbackSummary { + totalFeedback: number + byPattern: Map + byRepo: Map + byTeam: Map + recentTrend: 'improving' | 'declining' | 'stable' +} diff --git a/src/file-discoverer.ts b/src/file-discoverer.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ec852deab748175fa852bfc5f06c85d549e7071 --- /dev/null +++ b/src/file-discoverer.ts @@ -0,0 +1,187 @@ +import {readdirSync, statSync, existsSync} from 'fs' +import {join, extname} from 'path' + +export interface FileFilter { + include?: string[] + exclude?: string[] + maxDepth?: number +} + +export interface DiscoveredFile { + path: string + relativePath: string + extension: string + size: number + mtime: number +} + +const DEFAULT_EXCLUDES = new Set([ + 'node_modules', + '.git', + '.svn', + '.hg', + 'dist', + 'build', + 'coverage', + '.nyc_output', + '.next', + '.nuxt', + '__pycache__', + '.pytest_cache', + 'target', + 'bin', + 'obj', + 'vendor', + '.venv', + 'env' +]) + +const PLATFORM_FILE_PROTOCOL = typeof window !== 'undefined' + +export class FileDiscoverer { + private excludePatterns: Set + private includeExtensions: Set + + constructor( + excludePatterns: string[] = [], + includeExtensions: string[] = [ + '.ts', + '.tsx', + '.js', + '.jsx', + '.go', + '.py', + '.rs', + '.cpp', + '.c', + '.h', + '.hpp', + '.java' + ] + ) { + this.excludePatterns = new Set([...DEFAULT_EXCLUDES, ...excludePatterns]) + this.includeExtensions = new Set( + includeExtensions.map(e => e.toLowerCase()) + ) + } + + discover(rootPath: string, filter?: FileFilter): DiscoveredFile[] { + if (!existsSync(rootPath)) { + console.warn(`Path does not exist: ${rootPath}`) + return [] + } + + const results: DiscoveredFile[] = [] + this.discoverRecursive( + rootPath, + rootPath, + results, + 0, + filter?.maxDepth || 50 + ) + + return results + } + + private discoverRecursive( + rootPath: string, + currentPath: string, + results: DiscoveredFile[], + depth: number, + maxDepth: number + ): void { + if (depth > maxDepth) return + + let entries: string[] = [] + + try { + entries = readdirSync(currentPath) + } catch (e) { + return + } + + for (const entry of entries) { + if (entry.startsWith('.') && entry !== '.gitignore') continue + + if (this.excludePatterns.has(entry)) continue + + const fullPath = join(currentPath, entry) + + let stat = null + try { + stat = statSync(fullPath) + } catch { + continue + } + + if (stat.isDirectory()) { + this.discoverRecursive(rootPath, fullPath, results, depth + 1, maxDepth) + } else if (stat.isFile()) { + const ext = extname(entry).toLowerCase() + + if (this.includeExtensions.has(ext)) { + const relativePath = this.getRelativePath(rootPath, fullPath) + results.push({ + path: fullPath, + relativePath, + extension: ext, + size: stat.size, + mtime: stat.mtimeMs + }) + } + } + } + } + + private getRelativePath(root: string, full: string): string { + const normalize = (p: string) => p.replace(/\\/g, '/') + const rootNorm = normalize(root) + const fullNorm = normalize(full) + + if (fullNorm.startsWith(rootNorm)) { + const relative = fullNorm.substring(rootNorm.length) + return relative.startsWith('/') ? relative.substring(1) : relative + } + return fullNorm + } + + filterByExtensions( + files: DiscoveredFile[], + extensions: string[] + ): DiscoveredFile[] { + const extSet = new Set(extensions.map(e => e.toLowerCase())) + return files.filter(f => extSet.has(f.extension)) + } + + groupByExtension(files: DiscoveredFile[]): Map { + const groups = new Map() + + for (const file of files) { + if (!groups.has(file.extension)) { + groups.set(file.extension, []) + } + groups.get(file.extension)!.push(file) + } + + return groups + } +} + +export function createFileDiscoverer( + excludePatterns?: string[], + includeExtensions?: string[] +): FileDiscoverer { + return new FileDiscoverer(excludePatterns, includeExtensions) +} + +export function discoverFiles( + rootPath: string, + options?: { + include?: string[] + exclude?: string[] + maxDepth?: number + } +): DiscoveredFile[] { + const discoverer = new FileDiscoverer(options?.exclude, options?.include) + return discoverer.discover(rootPath, {maxDepth: options?.maxDepth}) +} diff --git a/src/fix-verifier.ts b/src/fix-verifier.ts new file mode 100644 index 0000000000000000000000000000000000000000..f0aaae301911017e2f05d25fb20ae3fd2960939e --- /dev/null +++ b/src/fix-verifier.ts @@ -0,0 +1,608 @@ +import {execSync} from 'child_process' +import {readFileSync, writeFileSync, existsSync, unlinkSync, statSync} from 'fs' +import {join, basename} from 'path' +import {Project, SyntaxKind} from 'ts-morph' +import {prixExec} from './utils' + +export interface VerificationResult { + passed: boolean + checks: VerificationCheck[] + overallFeedback: string + canRetry: boolean + errorMessage?: string +} + +export interface VerificationCheck { + name: string + passed: boolean + feedback: string + duration?: number +} + +export interface VerificationConfig { + enableLint: boolean + enableSyntax: boolean + enableAST: boolean + enableTests: boolean + maxRetries: number + timeout: number +} + +const DEFAULT_CONFIG: VerificationConfig = { + enableLint: true, + enableSyntax: true, + enableAST: true, + enableTests: false, + maxRetries: 3, + timeout: 30000 +} + +export class FixVerifier { + private config: VerificationConfig + private project: Project + + constructor(config: Partial = {}, project?: Project) { + this.config = {...DEFAULT_CONFIG, ...config} + this.project = project || new Project() + } + + async verify( + filename: string, + remedyCode: string, + startLine: number, + endLine: number, + workingDir: string + ): Promise { + const checks: VerificationCheck[] = [] + let allPassed = true + let canRetry = true + let errorMessage: string | undefined + + if (this.config.enableSyntax) { + const syntaxCheck = await this.runSyntaxCheck( + filename, + remedyCode, + workingDir + ) + checks.push(syntaxCheck) + if (!syntaxCheck.passed) { + allPassed = false + errorMessage = syntaxCheck.feedback + } + } + + if (this.config.enableLint && allPassed) { + const lintCheck = await this.runLintCheck( + filename, + remedyCode, + workingDir + ) + checks.push(lintCheck) + if (!lintCheck.passed) { + allPassed = false + canRetry = false + errorMessage = lintCheck.feedback + } + } + + if (this.config.enableAST && allPassed) { + const astCheck = this.runASTValidation(filename, remedyCode) + checks.push(astCheck) + if (!astCheck.passed) { + allPassed = false + errorMessage = astCheck.feedback + } + } + + if (this.config.enableTests && allPassed) { + const testCheck = await this.runTestCheck( + filename, + remedyCode, + startLine, + endLine, + workingDir + ) + checks.push(testCheck) + if (!testCheck.passed) { + allPassed = false + canRetry = false + errorMessage = testCheck.feedback + } + } + + const overallFeedback = checks + .map(c => `${c.passed ? 'โœ…' : 'โŒ'} ${c.name}: ${c.feedback}`) + .join('\n') + + return { + passed: allPassed, + checks, + overallFeedback, + canRetry, + errorMessage + } + } + + private async runSyntaxCheck( + filename: string, + remedyCode: string, + workingDir: string + ): Promise { + const startTime = Date.now() + const ext = filename.split('.').pop()?.toLowerCase() || '' + let feedback = '' + let passed = true + + const tempFile = join(workingDir, `__prix_verify_${Date.now()}.${ext}`) + + try { + if (ext === 'ts' || ext === 'js') { + writeFileSync(tempFile, remedyCode, 'utf8') + feedback = await this.verifyJSTypeScript(tempFile, ext, workingDir) + passed = !feedback.includes('โŒ') + } else if (ext === 'py') { + writeFileSync(tempFile, remedyCode, 'utf8') + feedback = await this.verifyPython(tempFile) + passed = !feedback.includes('โŒ') + } else if (ext === 'go') { + writeFileSync(tempFile, remedyCode, 'utf8') + feedback = await this.verifyGo(tempFile) + passed = !feedback.includes('โŒ') + } else { + feedback = 'โš ๏ธ Syntax check not supported for this file type' + } + } catch (e: any) { + passed = false + feedback = `โŒ Syntax check failed: ${e.message}` + } finally { + this.cleanup(tempFile) + } + + return { + name: 'Syntax Check', + passed, + feedback, + duration: Date.now() - startTime + } + } + + private async verifyJSTypeScript( + tempFile: string, + ext: string, + workingDir: string + ): Promise { + let feedback = '' + + try { + if (ext === 'ts') { + const hasTypeScript = + existsSync(join(workingDir, 'node_modules/typescript')) || + existsSync(join(workingDir, 'node_modules/.bin/tsc')) + + if (hasTypeScript) { + try { + prixExec( + `npx tsc "${tempFile}" --noEmit --esModuleInterop --skipLibCheck --jsx react`, + { + cwd: workingDir, + timeout: 15000 + } + ) + feedback = 'TS check passed' + } catch (e: any) { + const errorOutput = e.stdout?.toString() || e.message || '' + const relevantErrors = this.filterErrorsForFile( + errorOutput, + basename(tempFile) + ) + if (relevantErrors) { + feedback = `โŒ TS error: ${relevantErrors}` + } else { + feedback = 'โŒ TS syntax error' + } + } + } else { + feedback = 'โš ๏ธ TypeScript not installed, skipping TS check' + } + } else { + try { + execSync(`node --check "${tempFile}"`, { + encoding: 'utf8', + timeout: 5000 + }) + feedback = 'Syntax check passed' + } catch (e: any) { + feedback = `โŒ Syntax error: ${e.message}` + } + } + } catch (e: any) { + feedback = `โŒ Check failed: ${e.message}` + } + + return feedback + } + + private async verifyPython(tempFile: string): Promise { + try { + execSync(`python3 -m py_compile "${tempFile}"`, { + encoding: 'utf8', + timeout: 5000 + }) + return 'Python syntax passed' + } catch (e: any) { + const errorOutput = e.stderr?.toString() || e.message + return `โŒ Python syntax error: ${errorOutput}`.substring(0, 200) + } + } + + private async verifyGo(tempFile: string): Promise { + try { + execSync(`go vet "${tempFile}"`, {encoding: 'utf8', timeout: 5000}) + return 'Go syntax passed' + } catch (e: any) { + const errorOutput = e.stderr?.toString() || e.message + return `โŒ Go syntax error: ${errorOutput}`.substring(0, 200) + } + } + + private async runLintCheck( + filename: string, + remedyCode: string, + workingDir: string + ): Promise { + const startTime = Date.now() + const ext = filename.split('.').pop()?.toLowerCase() || '' + let feedback = '' + let passed = true + + const tempFile = join(workingDir, `__prix_lint_${Date.now()}.${ext}`) + + try { + if ( + (ext === 'ts' || ext === 'js') && + existsSync(join(workingDir, 'package.json')) + ) { + writeFileSync(tempFile, remedyCode, 'utf8') + + const hasEslint = + existsSync(join(workingDir, '.eslintrc.json')) || + existsSync(join(workingDir, '.eslintrc.js')) || + existsSync(join(workingDir, '.eslintrc')) + + if (hasEslint) { + try { + prixExec(`npx eslint "${tempFile}" --max-warnings 0`, { + cwd: workingDir, + timeout: 15000 + }) + feedback = 'Lint passed' + } catch (e: any) { + const errorOutput = e.stdout?.toString() || e.message || '' + const relevantErrors = this.filterErrorsForFile( + errorOutput, + basename(tempFile) + ) + feedback = `โŒ Lint failed: ${relevantErrors || ' ESLint errors'}` + passed = false + } + } else { + feedback = 'โš ๏ธ ESLint not configured' + } + } else if (ext === 'py') { + const hasPylint = this.commandExists('pylint') + const hasFlake8 = this.commandExists('flake8') + + writeFileSync(tempFile, remedyCode, 'utf8') + + if (hasPylint) { + try { + execSync(`pylint "${tempFile}" --disable=all --enable=E`, { + encoding: 'utf8', + timeout: 10000 + }) + feedback = 'Pylint passed' + } catch (e: any) { + feedback = `โŒ Pylint: ${e.message}`.substring(0, 200) + passed = false + } + } else if (hasFlake8) { + try { + execSync(`flake8 "${tempFile}"`, {encoding: 'utf8', timeout: 10000}) + feedback = 'Flake8 passed' + } catch (e: any) { + feedback = `โŒ Flake8: ${e.message}`.substring(0, 200) + passed = false + } + } else { + feedback = 'โš ๏ธ Python linter not available' + } + } + } catch (e: any) { + passed = false + feedback = `โŒ Lint failed: ${e.message}` + } finally { + this.cleanup(tempFile) + } + + return { + name: 'Lint Check', + passed, + feedback, + duration: Date.now() - startTime + } + } + + private runASTValidation( + filename: string, + remedyCode: string + ): VerificationCheck { + const startTime = Date.now() + + if (!filename.endsWith('.ts') && !filename.endsWith('.js')) { + return { + name: 'AST Validation', + passed: true, + feedback: 'Not applicable for this file type', + duration: 0 + } + } + + try { + const tempFile = `__prix_ast_${Date.now()}_${filename}` + const sourceFile = this.project.createSourceFile(tempFile, remedyCode, { + overwrite: true + }) + + const diagnostics = sourceFile.getPreEmitDiagnostics() + if (diagnostics.length > 0) { + const errorMessages = diagnostics + .slice(0, 3) + .map(d => d.getMessageText()) + .join('; ') + return { + name: 'AST Validation', + passed: false, + feedback: `โŒ AST errors: ${errorMessages}`, + duration: Date.now() - startTime + } + } + + const identifiers = sourceFile.getDescendantsOfKind(SyntaxKind.Identifier) + const undefinedSymbols: string[] = [] + + for (const id of identifiers) { + if (id.getSymbol()) continue + + const text = id.getText() + const skipList = [ + 'console', + 'process', + 'require', + 'exports', + 'module', + 'Buffer', + 'Array', + 'Object', + 'String', + 'Number', + 'Boolean', + 'Date', + 'Promise', + 'Math', + 'JSON', + 'Map', + 'Set', + 'RegExp', + 'Error', + 'undefined', + 'NaN', + 'Infinity', + 'parseInt', + 'parseFloat' + ] + + if (skipList.includes(text)) continue + if (id.getParentIfKind(SyntaxKind.ImportSpecifier)) continue + if (id.getParentIfKind(SyntaxKind.PropertyAccessExpression)) continue + + const parentKind = id.getParent()?.getKind() + if (parentKind === SyntaxKind.PropertyAssignment) continue + + undefinedSymbols.push(text) + } + + const uniqueUndefined = [...new Set(undefinedSymbols)].slice(0, 5) + + if (uniqueUndefined.length > 0) { + return { + name: 'AST Validation', + passed: false, + feedback: `โŒ Hallucination detected: undefined symbols: ${uniqueUndefined.join( + ', ' + )}`, + duration: Date.now() - startTime + } + } + + return { + name: 'AST Validation', + passed: true, + feedback: 'No hallucinations detected', + duration: Date.now() - startTime + } + } catch (e: any) { + return { + name: 'AST Validation', + passed: false, + feedback: `โŒ AST validation failed: ${e.message}`, + duration: Date.now() - startTime + } + } + } + + private async runTestCheck( + filename: string, + remedyCode: string, + startLine: number, + endLine: number, + workingDir: string + ): Promise { + const startTime = Date.now() + + if (!existsSync(join(workingDir, 'package.json'))) { + return { + name: 'Test Check', + passed: true, + feedback: 'โš ๏ธ No package.json found', + duration: 0 + } + } + + const testFile = this.findCorrespondingTestFile(filename) + if (!testFile) { + return { + name: 'Test Check', + passed: true, + feedback: 'โš ๏ธ No corresponding test file found', + duration: 0 + } + } + + try { + const testContent = readFileSync(testFile, 'utf8') + const testsForFunction = this.extractRelevantTests( + testContent, + filename, + startLine + ) + + if (!testsForFunction) { + return { + name: 'Test Check', + passed: true, + feedback: 'โš ๏ธ No relevant tests found for modified code', + duration: 0 + } + } + + const tempTestFile = join(workingDir, `__prix_test_${Date.now()}.test.ts`) + writeFileSync(tempTestFile, testsForFunction, 'utf8') + + try { + const hasJest = + existsSync(join(workingDir, 'node_modules/jest')) || + existsSync(join(workingDir, 'node_modules/.bin/jest')) + + if (hasJest) { + try { + prixExec(`npx jest "${tempTestFile}" --passWithNoTests`, { + cwd: workingDir, + timeout: 30000 + }) + return { + name: 'Test Check', + passed: true, + feedback: 'Test check passed', + duration: Date.now() - startTime + } + } catch (e: any) { + return { + name: 'Test Check', + passed: false, + feedback: `โŒ Test failed: ${e.message}`.substring(0, 200), + duration: Date.now() - startTime + } + } + } + } finally { + this.cleanup(tempTestFile) + } + + return { + name: 'Test Check', + passed: true, + feedback: 'โš ๏ธ Test runner not available', + duration: 0 + } + } catch (e: any) { + return { + name: 'Test Check', + passed: false, + feedback: `โŒ Test check failed: ${e.message}`, + duration: Date.now() - startTime + } + } + } + + private findCorrespondingTestFile(filename: string): string | null { + const baseDir = filename.substring(0, filename.lastIndexOf('/')) + const basename = filename.substring(filename.lastIndexOf('/') + 1) + const nameWithoutExt = basename.replace(/\.[^.]+$/, '') + + const patterns = [ + join(baseDir, `${nameWithoutExt}.test.ts`), + join(baseDir, `${nameWithoutExt}.spec.ts`), + join(baseDir, '__tests__', `${nameWithoutExt}.ts`), + join(baseDir, 'test', `${nameWithoutExt}.ts`), + join(baseDir, 'tests', `${nameWithoutExt}.ts`) + ] + + for (const pattern of patterns) { + if (existsSync(pattern)) { + return pattern + } + } + + return null + } + + private extractRelevantTests( + testContent: string, + sourceFile: string, + lineNumber: number + ): string | null { + const functionNameMatch = testContent.match( + new RegExp(`(test|it)\\(['"]{1,2}([^'"]{1,30})['"]{1,2}`) + ) + if (!functionNameMatch) return null + + return testContent + } + + private filterErrorsForFile( + errorOutput: string, + tempFile: string + ): string | null { + const lines = errorOutput.split('\n') + const relevantLines = lines.filter( + l => l.includes(tempFile) || l.includes('__prix') + ) + + if (relevantLines.length === 0) return null + + return relevantLines.slice(0, 3).join('; ') + } + + private commandExists(cmd: string): boolean { + try { + execSync(`which ${cmd}`, {encoding: 'utf8', timeout: 1000}) + return true + } catch { + return false + } + } + + private cleanup(tempFile: string): void { + try { + if (existsSync(tempFile)) { + unlinkSync(tempFile) + } + } catch { + // Cleanup failures are non-fatal + } + } +} + +export function createVerifier(project?: Project): FixVerifier { + return new FixVerifier({}, project) +} diff --git a/src/inputs.ts b/src/inputs.ts new file mode 100644 index 0000000000000000000000000000000000000000..3bdaeecab2f85dc860e5c122e62acd9835e16c33 --- /dev/null +++ b/src/inputs.ts @@ -0,0 +1,130 @@ +export class Inputs { + systemMessage: string + title: string + description: string + rawSummary: string + shortSummary: string + filename: string + fileContent: string + fileDiff: string + patches: string + diff: string + commentChain: string + comment: string + suggestion: string + error: string + taskDescription: string + codebaseStructure: string + + constructor( + systemMessage = '', + title = 'no title provided', + description = 'no description provided', + rawSummary = '', + shortSummary = '', + filename = '', + fileContent = 'file contents cannot be provided', + fileDiff = 'file diff cannot be provided', + patches = '', + diff = 'no diff', + commentChain = 'no other comments on this patch', + comment = 'no comment provided', + suggestion = '', + error = '', + taskDescription = '', + codebaseStructure = '' + ) { + this.systemMessage = systemMessage + this.title = title + this.description = description + this.rawSummary = rawSummary + this.shortSummary = shortSummary + this.filename = filename + this.fileContent = fileContent + this.fileDiff = fileDiff + this.patches = patches + this.diff = diff + this.commentChain = commentChain + this.comment = comment + this.suggestion = suggestion + this.error = error + this.taskDescription = taskDescription + this.codebaseStructure = codebaseStructure + } + + clone(): Inputs { + return new Inputs( + this.systemMessage, + this.title, + this.description, + this.rawSummary, + this.shortSummary, + this.filename, + this.fileContent, + this.fileDiff, + this.patches, + this.diff, + this.commentChain, + this.comment, + this.suggestion, + this.error, + this.taskDescription, + this.codebaseStructure + ) + } + + render(content: string): string { + if (!content) { + return '' + } + if (this.systemMessage) { + content = content.replace('$system_message', this.systemMessage) + } + if (this.title) { + content = content.replace('$title', this.title) + } + if (this.description) { + content = content.replace('$description', this.description) + } + if (this.rawSummary) { + content = content.replace('$raw_summary', this.rawSummary) + } + if (this.shortSummary) { + content = content.replace('$short_summary', this.shortSummary) + } + if (this.filename) { + content = content.replace('$filename', this.filename) + } + if (this.fileContent) { + content = content.replace('$file_content', this.fileContent) + } + if (this.fileDiff) { + content = content.replace('$file_diff', this.fileDiff) + } + if (this.patches) { + content = content.replace('$patches', this.patches) + } + if (this.diff) { + content = content.replace('$diff', this.diff) + } + if (this.taskDescription) { + content = content.replace('$task_description', this.taskDescription) + } + if (this.codebaseStructure) { + content = content.replace('$codebase_structure', this.codebaseStructure) + } + if (this.commentChain) { + content = content.replace('$comment_chain', this.commentChain) + } + if (this.comment) { + content = content.replace('$comment', this.comment) + } + if (this.suggestion) { + content = content.replace('$suggestion', this.suggestion) + } + if (this.error) { + content = content.replace('$error', this.error) + } + return content + } +} diff --git a/src/issue-handler.ts b/src/issue-handler.ts new file mode 100644 index 0000000000000000000000000000000000000000..96730ee6c13d8ccd092e18e11ba70c623588815d --- /dev/null +++ b/src/issue-handler.ts @@ -0,0 +1,301 @@ +import {octokit} from './octokit' +import {Bot} from './bot' +import {type Prompts} from './prompts' +import {getTokenCount} from './tokenizer' +import {als} from './context' +import {Inputs} from './inputs' +import {type Options} from './options' + +let info = console.log +let warning = console.warn + +export const context: any = new Proxy({} as any, { + get(target, prop) { + return (als.getStore()?.probotContext as any)[prop] + } +}) + +export const repo: any = new Proxy({} as any, { + get(target, prop) { + return (als.getStore()?.repo as any)[prop] + } +}) + +const ISSUE_COMMAND_TAG = '@prix' +const MAX_API_CALLS = 100 +const MAX_FILES_RETURNED = 200 + +let apiCallCount = 0 + +export const handleIssueComment = async ( + heavyBot: Bot, + options: Options, + prompts: Prompts +) => { + const inputs: Inputs = new Inputs() + + if (context.name !== 'issue_comment') { + warning(`Skipped: ${context.name} is not an issue_comment event`) + return + } + + if (!context.payload) { + warning(`Skipped: issue_comment event is missing payload`) + return + } + + if (!context.payload.repository) { + warning(`Skipped: issue_comment event is missing repository`) + return + } + + const comment = context.payload.comment + if (comment == null) { + warning(`Skipped: issue_comment event is missing comment`) + return + } + + const issue = context.payload.issue + if (issue == null) { + warning(`Skipped: issue_comment event is missing issue`) + return + } + + if (context.payload.action !== 'created') { + warning(`Skipped: issue_comment event is not created`) + return + } + + const isBotComment = comment.user?.type === 'Bot' + if (isBotComment) { + info(`Skipped: issue_comment event is from the bot itself`) + return + } + + if (!comment.body.includes(ISSUE_COMMAND_TAG)) { + info(`Skipped: comment does not mention @prix`) + return + } + + if (!repo?.owner || !repo?.repo) { + warning(`Skipped: repo context is missing`) + return + } + + const issueNumber = issue.number + if (!issueNumber || typeof issueNumber !== 'number') { + warning(`Skipped: issue number is invalid`) + return + } + const issueTitle = issue.title || '' + const issueBody = issue.body || '' + const commentBody = comment.body || '' + const commentUser = comment.user?.login || 'unknown' + + if (issueTitle.length > 500) { + await postIssueComment( + issueNumber, + `@${commentUser} Issue title is too long. Please shorten it to under 500 characters.` + ) + return + } + + if (issueBody.length > 10000) { + await postIssueComment( + issueNumber, + `@${commentUser} Issue description is too long. Please simplify it to under 10,000 characters.` + ) + return + } + + info(`Processing issue comment for issue #${issueNumber} from @${commentUser}`) + + inputs.title = issueTitle + inputs.description = issueBody + inputs.comment = `${commentUser}: ${commentBody}` + + const taskDescription = extractTaskFromComment(commentBody) + inputs.taskDescription = taskDescription + + apiCallCount = 0 + const counter = { fileCount: 0 } + const codebaseStructure = await fetchCodebaseStructure( + repo.owner, + repo.repo, + () => counter.fileCount >= MAX_FILES_RETURNED, + counter + ) + inputs.codebaseStructure = codebaseStructure + + if (counter.fileCount > MAX_FILES_RETURNED) { + info(`Codebase structure truncated: ${counter.fileCount} files found, limit is ${MAX_FILES_RETURNED}`) + } + + const tokens = getTokenCount(prompts.renderIssueAnalysis(inputs)) + if (tokens > options.heavyTokenLimits.requestTokens) { + await postIssueComment( + issueNumber, + `@${commentUser} The issue content is too large to process. Please simplify or split the issue.` + ) + return + } + + const [analysis] = await heavyBot.chat( + prompts.renderIssueAnalysis(inputs), + {} + ) + + if (!analysis || analysis.trim().length === 0) { + warning(`Empty analysis received for issue #${issueNumber}`) + return + } + + const response = formatIssueResponse(commentUser, analysis) + await postIssueComment(issueNumber, response) + + info(`Successfully processed issue comment for issue #${issueNumber}`) +} + +const EXCLUDED_DIRS = new Set([ + 'node_modules', + '.git', + 'dist', + 'build', + 'coverage', + '.next', + '__pycache__', + 'venv', + '.venv', + 'target', + 'bin', + 'obj', + '.idea', + '.vscode', + 'vendor', + 'packages' +]) + +async function fetchCodebaseStructure( + owner: string, + repoName: string, + shouldStop: () => boolean, + counter?: { fileCount: number } +): Promise { + try { + const structure = await fetchDirectoryTree(owner, repoName, '', 3, shouldStop, 0, counter) + return structure || 'Unable to fetch codebase structure' + } catch (error) { + warning(`Failed to fetch codebase structure: ${error}`) + return 'Codebase structure unavailable' + } +} + +async function fetchDirectoryTree( + owner: string, + repo: string, + path: string, + depth: number, + shouldStop: () => boolean, + currentDepth = 0, + counter?: { fileCount: number } +): Promise { + if (currentDepth >= depth) { + return '' + } + + if (apiCallCount >= MAX_API_CALLS) { + return '' + } + + if (shouldStop()) { + return '' + } + + try { + apiCallCount++ + const response = await octokit.repos.getContent({ + owner, + repo, + path, + ref: context.payload.repository?.default_branch || 'main' + }) + + const items = Array.isArray(response.data) ? response.data : [response.data] + let tree = '' + + for (const item of items) { + if (shouldStop()) { + break + } + + if (item.type === 'dir' && !EXCLUDED_DIRS.has(item.name)) { + tree += `${' '.repeat(currentDepth)}๐Ÿ“ ${item.name}/\n` + const subTree = await fetchDirectoryTree( + owner, + repo, + item.path, + depth, + shouldStop, + currentDepth + 1, + counter + ) + tree += subTree + } else if (item.type === 'file') { + const ext = item.name.split('.').pop() || '' + if (isRelevantExtension(ext)) { + tree += `${' '.repeat(currentDepth)}๐Ÿ“„ ${item.name}\n` + if (counter) { + counter.fileCount++ + } + } + } + } + + return tree + } catch (error) { + return '' + } +} + +function isRelevantExtension(ext: string): boolean { + const relevantExts = new Set([ + 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', + 'py', 'rb', 'go', 'rs', 'java', 'kt', 'scala', + 'cpp', 'c', 'h', 'hpp', 'cs', 'swift', + 'json', 'yaml', 'yml', 'toml', 'xml', + 'md', 'txt', 'sh', 'bash', 'zsh', + 'css', 'scss', 'sass', 'less', + 'html', 'htm', 'vue', 'svelte', + 'sql', 'graphql', 'proto', + 'dockerfile', 'env', 'gitignore', 'editorconfig' + ]) + return relevantExts.has(ext.toLowerCase()) +} + +function extractTaskFromComment(commentBody: string): string { + const mentionPattern = /@prix\s*(.*)$/i + const match = commentBody.match(mentionPattern) + return match ? match[1].trim() : commentBody +} + +async function postIssueComment( + issueNumber: number, + body: string +): Promise { + try { + await octokit.issues.createComment({ + owner: repo.owner, + repo: repo.repo, + issue_number: issueNumber, + body + }) + } catch (error) { + warning(`Failed to post issue comment: ${error}`) + } +} + +function formatIssueResponse(user: string, analysis: string): string { + return `## @${user} Issue Analysis + +${analysis}` +} diff --git a/src/limits.ts b/src/limits.ts new file mode 100644 index 0000000000000000000000000000000000000000..86258ded16b366bd933bfb1aac39d27bb9712cb3 --- /dev/null +++ b/src/limits.ts @@ -0,0 +1,46 @@ +export class TokenLimits { + maxTokens: number + requestTokens: number + responseTokens: number + knowledgeCutOff: string + + constructor(model = 'llama-3.1-8b-instant') { + this.knowledgeCutOff = '2023-12-01' + + // Default for modern large context models + this.maxTokens = 128000 + this.responseTokens = 16000 + + if (model.includes('kimi-k2')) { + this.maxTokens = 256000 + this.responseTokens = 16000 + } else if (model.includes('qwen') || model.includes('llama-4')) { + this.maxTokens = 128000 + this.responseTokens = 16000 + } else if (model.includes('gpt-oss-120b')) { + this.maxTokens = 128000 + this.responseTokens = 16000 + } else if (model.includes('3.2-11b')) { + this.maxTokens = 128000 + this.responseTokens = 16000 + } else if ( + model.includes('llama3') || + model.includes('llama-3') || + model.includes('groq') || + model.includes('mixtral') + ) { + this.maxTokens = 128000 + this.responseTokens = 16000 + } else { + this.maxTokens = 128000 + this.responseTokens = 4000 + } + + // Provide some margin + this.requestTokens = this.maxTokens - this.responseTokens - 500 + } + + string(): string { + return `max_tokens=${this.maxTokens}, request_tokens=${this.requestTokens}, response_tokens=${this.responseTokens}` + } +} diff --git a/src/local-context.ts b/src/local-context.ts new file mode 100644 index 0000000000000000000000000000000000000000..abf82fafced2aba94b9596658a9185464e0053de --- /dev/null +++ b/src/local-context.ts @@ -0,0 +1,370 @@ +import {readFileSync, existsSync} from 'fs' +import {execSync} from 'child_process' +import {Options} from './options' +import {Prompts} from './prompts' +import {Bot} from './bot' +import {Inputs} from './inputs' +import {codeReview, extractPatternType} from './review' +import {confidenceCalibrator} from './confidence' +import {als} from './context' +import {feedbackTracker} from './feedback-tracker' +import pLimit from 'p-limit' +import Parser from 'web-tree-sitter' + +export interface LocalFinding { + filename: string + line: number + endLine: number + severity: 'critical' | 'major' | 'minor' | 'info' + type: string + message: string + confidence: number + suggestion?: string + patternType: string +} + +interface LocalFileChange { + filename: string + oldContent: string + newContent: string + diff: string + hunks: Array<{ + oldStart: number + oldLines: number + newStart: number + newLines: number + content: string + }> +} + +export class LocalContextEngine { + private files: string[] + private project: any + private changes: Map = new Map() + + constructor(files: string[]) { + this.files = files + this.project = null + } + + async initialize(): Promise { + await this.loadChanges() + this.initializeParser() + } + + private async loadChanges(): Promise { + for (const file of this.files) { + if (!existsSync(file)) continue + + try { + const newContent = readFileSync(file, 'utf8') + + let oldContent = '' + let diff = '' + + try { + diff = execSync(`git diff HEAD -- "${file}"`, { + encoding: 'utf8', + cwd: process.cwd() + }) + + const parentCommit = execSync('git rev-parse HEAD^', { + encoding: 'utf8', + cwd: process.cwd() + }).trim() + + try { + oldContent = 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}`) + } + } + } + + private parseDiff(diff: string): LocalFileChange['hunks'] { + const hunks: LocalFileChange['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 + } + + private initializeParser(): void { + try { + Parser.init() + } catch (e) { + console.warn(`Failed to initialize tree-sitter: ${e}`) + } + } + + async runReview( + lightBot: Bot, + heavyBot: Bot, + options: Options, + prompts: Prompts + ): Promise { + const findings: LocalFinding[] = [] + const concurrencyLimit = pLimit(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 + } + + private async reviewFile( + filename: string, + change: LocalFileChange, + lightBot: Bot, + heavyBot: Bot, + options: Options, + prompts: Prompts + ): Promise { + const findings: LocalFinding[] = [] + const inputs = new 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 + } + + private formatPatchForReview( + filename: string, + hunk: LocalFileChange['hunks'][0], + oldContent: string + ): string { + 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)'} +\`\`\` +` + } + + private parseFindings( + response: string, + filename: string, + startLine: number, + endLine: number + ): LocalFinding[] { + const findings: LocalFinding[] = [] + const lines = response.split('\n') + + let currentFinding: Partial | null = 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 = confidenceCalibrator.calibrate( + currentFinding.confidence || 50, + currentFinding.message, + currentFinding.message.length, + 2000, + currentFinding.severity, + 'local', + 'local', + 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: 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() as LocalFinding['severity'] + 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 = confidenceCalibrator.calibrate( + currentFinding.confidence || 50, + currentFinding.message, + currentFinding.message.length, + 2000, + currentFinding.severity, + 'local', + 'local', + 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: extractPatternType(currentFinding.message) + }) + } + + return findings + } +} diff --git a/src/logger.ts b/src/logger.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce6c6b6cae3c4a3826ee76013cf08ff5c4beb990 --- /dev/null +++ b/src/logger.ts @@ -0,0 +1,33 @@ +export interface Logger { + info(message: string): void + warn(message: string): void + error(message: string): void + debug(message: string): void +} + +class ConsoleLogger implements Logger { + info(message: string): void { + // eslint-disable-next-line no-console + console.log(message) + } + warn(message: string): void { + // eslint-disable-next-line no-console + console.warn(message) + } + error(message: string): void { + // eslint-disable-next-line no-console + console.error(message) + } + debug(message: string): void { + // eslint-disable-next-line no-console + console.debug(message) + } +} + +let activeLogger: Logger = new ConsoleLogger() + +export const setLogger = (logger: Logger): void => { + activeLogger = logger +} + +export const logger = (): Logger => activeLogger diff --git a/src/octokit.ts b/src/octokit.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d9514f79d568ee4fe8f8a2ea1591e53adfa2bdc --- /dev/null +++ b/src/octokit.ts @@ -0,0 +1,39 @@ +import {Octokit} from '@octokit/rest' +import {als} from './context' + +const warning = console.warn + +function createSafeOctokitFallback(): any { + const handler = { + get(_target: any, prop: string) { + warning(`Octokit accessed outside of context: ${String(prop)}`) + return () => { + throw new Error( + `Octokit.${String( + prop + )} is not available outside of an isolated context. Use als.run() to wrap your code.` + ) + } + } + } + return new Proxy({}, handler) +} + +const safeFallback = createSafeOctokitFallback() + +export const octokit = new Proxy({} as Octokit, { + get(target, prop) { + const context = als.getStore() + if (!context || !context.octokit) { + warning( + `Octokit accessed outside of an isolated context. Property: ${String( + prop + )}` + ) + return (safeFallback as any)[prop] + } + return (context.octokit as any)[prop] + } +}) + +export function setOctokit(newOctokit: any) {} diff --git a/src/options.ts b/src/options.ts new file mode 100644 index 0000000000000000000000000000000000000000..f058388cbb616dd39e93fd8a6d9f8b7c0355bb1b --- /dev/null +++ b/src/options.ts @@ -0,0 +1,217 @@ +import {minimatch} from 'minimatch' +import {TokenLimits} from './limits' +const info = console.log + +export type SeverityLevel = 'critical' | 'major' | 'minor' | 'info' + +export class Options { + debug: boolean + disableReview: boolean + disableReleaseNotes: boolean + maxFiles: number + reviewSimpleChanges: boolean + reviewCommentLGTM: boolean + pathFilters: PathFilter + systemMessage: string + lightModel: string + heavyModel: string + modelTemperature: number + retries: number + timeoutMS: number + concurrencyLimit: number + githubConcurrencyLimit: number + lightTokenLimits: TokenLimits + heavyTokenLimits: TokenLimits + apiBaseUrl: string + language: string + createRemedyPR: boolean + minimumSeverity: SeverityLevel + minConfidence: number + denseMode: boolean + showImpactAnalysis: boolean + + static readonly HEAVY_MODELS = [ + 'openai/gpt-oss-120b', + 'moonshotai/kimi-k2-instruct-0905', + 'qwen/qwen3-32b', + 'deepseek-r1-distill-llama-70b', + 'llama-3.3-70b-versatile', + 'openai/gpt-oss-20b', + 'meta-llama/llama-4-scout-17b-16e-instruct' + ] + static readonly LIGHT_MODELS = [ + 'llama-3.1-8b-instant', + 'groq/compound', + 'groq/compound-mini', + 'llama-3.2-11b-vision-preview' + ] + static readonly SECURITY_MODELS = [ + 'openai/gpt-oss-safeguard-20b', + 'meta-llama/llama-guard-4-12b', + 'meta-llama/llama-prompt-guard-2-86m', + 'meta-llama/llama-prompt-guard-2-22m' + ] + + constructor( + debug: boolean, + disableReview: boolean, + disableReleaseNotes: boolean, + maxFiles = '0', + reviewSimpleChanges = false, + reviewCommentLGTM = false, + pathFilters: string[] | null = null, + systemMessage = '', + lightModel = 'llama-3.1-8b-instant', + heavyModel = 'llama-3.3-70b-versatile', + modelTemperature = '0.0', + retries = '3', + timeoutMS = '120000', + concurrencyLimit = '6', + githubConcurrencyLimit = '6', + apiBaseUrl = 'https://api.groq.com/openai/v1', + language = 'en-US', + createRemedyPR = false, + minimumSeverity: SeverityLevel = 'minor', + minConfidence = '0', + denseMode = 'false', + showImpactAnalysis = 'true' + ) { + this.debug = debug + this.disableReview = disableReview + this.disableReleaseNotes = disableReleaseNotes + this.maxFiles = parseInt(maxFiles) + this.reviewSimpleChanges = reviewSimpleChanges + this.reviewCommentLGTM = reviewCommentLGTM + this.pathFilters = new PathFilter(pathFilters) + this.systemMessage = systemMessage + this.lightModel = lightModel + this.heavyModel = heavyModel + this.modelTemperature = parseFloat(modelTemperature) + this.retries = parseInt(retries) + this.timeoutMS = parseInt(timeoutMS) + this.concurrencyLimit = parseInt(concurrencyLimit) + this.githubConcurrencyLimit = parseInt(githubConcurrencyLimit) + this.apiBaseUrl = apiBaseUrl + this.language = language + this.createRemedyPR = createRemedyPR + this.minimumSeverity = minimumSeverity + this.minConfidence = parseInt(minConfidence) + this.denseMode = denseMode === 'true' + this.showImpactAnalysis = showImpactAnalysis === 'true' + + this.lightTokenLimits = new TokenLimits(this.lightModel) + this.heavyTokenLimits = new TokenLimits(this.heavyModel) + } + + // print all options using core.info + print(): void { + info(`debug: ${this.debug}`) + info(`disable_review: ${this.disableReview}`) + info(`disable_release_notes: ${this.disableReleaseNotes}`) + info(`max_files: ${this.maxFiles}`) + info(`review_simple_changes: ${this.reviewSimpleChanges}`) + info(`review_comment_lgtm: ${this.reviewCommentLGTM}`) + info(`path_filters: ${this.pathFilters}`) + info(`system_message: ${this.systemMessage}`) + info(`light_model: ${this.lightModel}`) + info(`heavy_model: ${this.heavyModel}`) + info(`model_temperature: ${this.modelTemperature}`) + info(`retries: ${this.retries}`) + info(`timeout_ms: ${this.timeoutMS}`) + info(`concurrency_limit: ${this.concurrencyLimit}`) + info(`github_concurrency_limit: ${this.githubConcurrencyLimit}`) + info(`summary_token_limits: ${this.lightTokenLimits.string()}`) + info(`review_token_limits: ${this.heavyTokenLimits.string()}`) + info(`api_base_url: ${this.apiBaseUrl}`) + info(`language: ${this.language}`) + info(`create_remedy_pr: ${this.createRemedyPR}`) + } + + checkPath(path: string): boolean { + const ok = this.pathFilters.check(path) + info(`checking path: ${path} => ${ok}`) + return ok + } + + private static readonly SEVERITY_ORDER: SeverityLevel[] = [ + 'critical', + 'major', + 'minor', + 'info' + ] + + meetsMinimumSeverity(findingSeverity: SeverityLevel): boolean { + const minIndex = Options.SEVERITY_ORDER.indexOf(this.minimumSeverity) + const findingIndex = Options.SEVERITY_ORDER.indexOf(findingSeverity) + return findingIndex >= minIndex + } + + meetsConfidenceThreshold(confidence: number): boolean { + return confidence >= this.minConfidence + } +} + +export class PathFilter { + private readonly rules: Array<[string /* rule */, boolean /* exclude */]> + + constructor(rules: string[] | null = null) { + this.rules = [] + if (rules != null) { + for (const rule of rules) { + const trimmed = rule?.trim() + if (trimmed) { + if (trimmed.startsWith('!')) { + this.rules.push([trimmed.substring(1).trim(), true]) + } else { + this.rules.push([trimmed, false]) + } + } + } + } + } + + check(path: string): boolean { + if (this.rules.length === 0) { + return true + } + + let included = false + let excluded = false + let inclusionRuleExists = false + + for (const [rule, exclude] of this.rules) { + if (minimatch(path, rule)) { + if (exclude) { + excluded = true + } else { + included = true + } + } + if (!exclude) { + inclusionRuleExists = true + } + } + + return (!inclusionRuleExists || included) && !excluded + } +} + +export class AIOptions { + model: string + tokenLimits: TokenLimits + temperature: number + + constructor( + model = 'llama-3.1-8b-instant', + tokenLimits: TokenLimits | null = null, + temperature = 0.0 + ) { + this.model = model + this.temperature = temperature + if (tokenLimits != null) { + this.tokenLimits = tokenLimits + } else { + this.tokenLimits = new TokenLimits(model) + } + } +} diff --git a/src/prompts.ts b/src/prompts.ts new file mode 100644 index 0000000000000000000000000000000000000000..92bd160a63bdc4d35056635efdb7b60ff6826224 --- /dev/null +++ b/src/prompts.ts @@ -0,0 +1,176 @@ +import {Inputs} from './inputs' + +export class Prompts { + summarize: string + summarizeReleaseNotes: string + + summarizeFileDiff = `## GitHub PR Title +\`$title\` + +## Description +\`$description\` + +## Diff +\`\`\`diff +$file_diff +\`\`\` + +## Instructions +Succinctly summarize the diff within 100 words. +Include alterations to signatures, global data, and external interfaces. +` + + triageFileDiff = `Below the summary, triage as \`NEEDS_REVIEW\` or \`APPROVED\`: +- \`NEEDS_REVIEW\`: Any logic, function, or variable changes. +- \`APPROVED\`: Only typos, formatting, or documentation. +Format: [TRIAGE]: +Important: Do not justify triage or mention it in summary. +` + + summarizeChangesets = `Group and deduplicate the following changesets in this PR. +Respond with updated changesets using the same format. +Important: Provide ONLY the final summarized result. Do NOT include reasoning steps, "Step 1", "Step 2", or any other conversational filler. + +$raw_summary +` + + summarizePrefix = `Summary of changes: +\`\`\` +$raw_summary +\`\`\` +` + + summarizeShort = `Provide a concise, direct summary of changes and architectural impact. +- Focus strictly on PR facts. +- Architectural Summary: High-level overview of design changes. +- Max 500 words. No metadata, no reasoning steps, and no conversational filler. +` + + reviewFileDiff = `## PR: $title +## Description: +\`$description\` +## Summary: +\`$short_summary\` + +## Instructions +Review new hunks for substantive issues. Format comments starting with line range (e.g., "22-25:"). + +- **Categorization**: Start each comment with: \`[LEVEL] | [TYPE]\` (Critical, Major, Minor, Info | Security, Bug, Performance, Style, Optimization). +- **Consequence**: Briefly explain why this matters and the worst-case production failure. +- **Fix**: Combine audit note and code fix into one comment. +- **Suggestion**: Use GitHub suggestions: \\\`\\\`\\\`suggestion [FIXED_CODE] \\\`\\\`\\\`. +- **Confidence**: Score 0-100% at the end. Only show findings with confidence >= 60%. +- If no issues: Respond ONLY with \`LGTM!\`. + +## Changes in $filename: +$patches +` + + comment = `Reply to this instruction in the context of the PR. + +## PR: $title +## Description: +\`$description\` +## Summary: +\`$short_summary\` + +## Instructions +Reply directly to the comment below. Begin with "@user". + +## New Comment +\`\`\` +$comment +\`\`\` + +## Context (Diff) +\`\`\`diff +$diff +\`\`\` +` + + constructor(summarize = '', summarizeReleaseNotes = '') { + this.summarize = summarize + this.summarizeReleaseNotes = summarizeReleaseNotes + } + + renderSummarizeFileDiff( + inputs: Inputs, + reviewSimpleChanges: boolean + ): string { + let prompt = this.summarizeFileDiff + if (reviewSimpleChanges === false) { + prompt += this.triageFileDiff + } + return inputs.render(prompt) + } + + renderSummarizeChangesets(inputs: Inputs): string { + return inputs.render(this.summarizeChangesets) + } + + renderSummarize(inputs: Inputs): string { + const prompt = this.summarizePrefix + this.summarize + return inputs.render(prompt) + } + + renderSummarizeShort(inputs: Inputs): string { + const prompt = this.summarizePrefix + this.summarizeShort + return inputs.render(prompt) + } + + renderSummarizeReleaseNotes(inputs: Inputs): string { + const prompt = this.summarizePrefix + this.summarizeReleaseNotes + return inputs.render(prompt) + } + + renderComment(inputs: Inputs): string { + return inputs.render(this.comment) + } + + renderReviewFileDiff(inputs: Inputs): string { + return inputs.render(this.reviewFileDiff) + } + + fixSuggestion = `The code suggestion for \`$filename\` failed CI: +\`\`\` +$suggestion +\`\`\` +CI Error: $error +Correct the suggestion block. Respond ONLY with the fixed block. +` + + renderFixSuggestion( + inputs: Inputs, + suggestion: string, + error: string + ): string { + const ins = inputs.clone() + ins.suggestion = suggestion + ins.error = error + return ins.render(this.fixSuggestion) + } + + issueAnalysis = `## Repository Context (Codebase Structure) +\`\`\` +$codebase_structure +\`\`\` + +## Issue +Title: $title +Description: $description +Task: $task_description + +## Instructions +You are PRIX, an expert software engineering assistant. Based on the issue and codebase structure above, provide a concise response with exactly these 4 sections: + +1. **Problem Summary**: 2-3 sentences describing the issue +2. **Root Cause**: Key root cause (1-2 sentences max) +3. **Fix Plan**: Numbered list of steps (max 5 steps) +4. **IDE Prompt**: Complete prompt for an AI IDE/agent to fix this issue + +Be specific and reference relevant directories/files from the codebase structure where applicable.` + + renderIssueAnalysis(inputs: Inputs): string { + return inputs.render(this.issueAnalysis) + } +} diff --git a/src/review-comment.ts b/src/review-comment.ts new file mode 100644 index 0000000000000000000000000000000000000000..a30c43acef83e19883dee2126888882552103530 --- /dev/null +++ b/src/review-comment.ts @@ -0,0 +1,237 @@ +// Removed @actions imports for Probot migration +import { + Commenter, + COMMENT_REPLY_TAG, + COMMENT_TAG, + SUMMARIZE_TAG, + setCommenterContext +} from './commenter' +import {Inputs} from './inputs' +import {type Options, AIOptions} from './options' +import {octokit, setOctokit} from './octokit' +import {Bot} from './bot' +import {type Prompts} from './prompts' + +import {getTokenCount} from './tokenizer' + +import {als} from './context' + +let info = console.log +let warning = console.warn + +export const context: any = new Proxy({} as any, { + get(target, prop) { + return (als.getStore()?.probotContext as any)[prop] + } +}) + +export const repo: any = new Proxy({} as any, { + get(target, prop) { + return (als.getStore()?.repo as any)[prop] + } +}) + +const ASK_BOT = '@prix' + +export const handleReviewComment = async ( + heavyBot: Bot, + options: Options, + prompts: Prompts +) => { + const commenter: Commenter = new Commenter() + const inputs: Inputs = new Inputs() + + if (context.name !== 'pull_request_review_comment') { + warning( + `Skipped: ${context.name} is not a pull_request_review_comment event` + ) + return + } + + if (!context.payload) { + warning(`Skipped: ${context.name} event is missing payload`) + return + } + + const comment = context.payload.comment + if (comment == null) { + warning(`Skipped: ${context.name} event is missing comment`) + return + } + if ( + context.payload.pull_request == null || + context.payload.repository == null + ) { + warning(`Skipped: ${context.name} event is missing pull_request`) + return + } + inputs.title = context.payload.pull_request.title + if (context.payload.pull_request.body) { + inputs.description = commenter.getDescription( + context.payload.pull_request.body + ) + } + + // check if the comment was created and not edited or deleted + if (context.payload.action !== 'created') { + warning(`Skipped: ${context.name} event is not created`) + return + } + + // Check if the comment is not from the bot itself + if ( + !comment.body.includes(COMMENT_TAG) && + !comment.body.includes(COMMENT_REPLY_TAG) + ) { + const pullNumber = context.payload.pull_request.number + + inputs.comment = `${comment.user.login}: ${comment.body}` + inputs.diff = comment.diff_hunk + inputs.filename = comment.path + + const {chain: commentChain, topLevelComment} = + await commenter.getCommentChain(pullNumber, comment) + + if (!topLevelComment) { + warning('Failed to find the top-level comment to reply to') + return + } + + inputs.commentChain = commentChain + + // check whether this chain contains replies from the bot + if ( + commentChain.includes(COMMENT_TAG) || + commentChain.includes(COMMENT_REPLY_TAG) || + comment.body.includes(ASK_BOT) + ) { + let fileDiff = '' + try { + // get diff for this file by comparing the base and head commits + const diffAll = await octokit.repos.compareCommits({ + owner: repo.owner, + repo: repo.repo, + base: context.payload.pull_request.base.sha, + head: context.payload.pull_request.head.sha + }) + if (diffAll.data) { + const files = diffAll.data.files + if (files != null) { + const file = files.find(f => f.filename === comment.path) + if (file != null && file.patch) { + fileDiff = file.patch + } + } + } + } catch (error) { + warning(`Failed to get file diff: ${error}, skipping.`) + } + + // use file diff if no diff was found in the comment + if (inputs.diff.length === 0) { + if (fileDiff.length > 0) { + inputs.diff = fileDiff + fileDiff = '' + } else { + await commenter.reviewCommentReply( + pullNumber, + topLevelComment, + 'Cannot reply to this comment as diff could not be found.' + ) + return + } + } + + // get tokens so far + let tokens = getTokenCount(prompts.renderComment(inputs)) + + if (tokens > options.heavyTokenLimits.requestTokens) { + await commenter.reviewCommentReply( + pullNumber, + topLevelComment, + 'Cannot reply to this comment as diff being commented is too large and exceeds the token limit.' + ) + return + } + // pack file diff into the inputs if they are not too long + if (fileDiff.length > 0) { + // count occurrences of $file_diff in prompt + const fileDiffCount = prompts.comment.split('$file_diff').length - 1 + const fileDiffTokens = getTokenCount(fileDiff) + if ( + fileDiffCount > 0 && + tokens + fileDiffTokens * fileDiffCount <= + options.heavyTokenLimits.requestTokens + ) { + tokens += fileDiffTokens * fileDiffCount + inputs.fileDiff = fileDiff + } + } + + // get summary of the PR + const summary = await commenter.findCommentWithTag( + SUMMARIZE_TAG, + pullNumber + ) + if (summary) { + // pack short summary into the inputs if it is not too long + const shortSummary = commenter.getShortSummary(summary.body) + const shortSummaryTokens = getTokenCount(shortSummary) + if ( + tokens + shortSummaryTokens <= + options.heavyTokenLimits.requestTokens + ) { + tokens += shortSummaryTokens + inputs.shortSummary = shortSummary + } + } + + const [reply] = await heavyBot.chat(prompts.renderComment(inputs), {}) + + await commenter.reviewCommentReply(pullNumber, topLevelComment, reply) + } + } else { + info(`Skipped: ${context.name} event is from the bot itself`) + } +} + +/** + * PRIX entry point for Review Comments (Chat with Bot). + * Adapts the action logic to Probot context. + */ +export const run = async ( + probotContext: any, + options: Options, + prompts: Prompts +): Promise => { + // Setup logger shim + info = (msg: string) => probotContext.log.info(msg) + warning = (msg: string) => probotContext.log.warn(msg) + + // context and repo are now handled via Proxy + AsyncLocalStorage + setCommenterContext(probotContext) + + // Setup octokit shim + setOctokit(probotContext.octokit) + + // Initialize heavy bot (used for comments) + const heavyAIOptions = new AIOptions( + options.heavyModel, + options.heavyTokenLimits + ) + const heavyBot = new Bot(options, heavyAIOptions) + + probotContext.log.info( + `PRIX Chat starting for Comment in PR #${probotContext.payload.pull_request.number}` + ) + + try { + await handleReviewComment(heavyBot, options, prompts) + probotContext.log.info( + `PRIX Chat completed for PR #${probotContext.payload.pull_request.number}` + ) + } catch (err: any) { + probotContext.log.error(`PRIX Chat failed: ${err.message}`) + throw err + } +} diff --git a/src/review.ts b/src/review.ts new file mode 100644 index 0000000000000000000000000000000000000000..a22bb107eec0be31b8b7d92db1768f181c2b0f07 --- /dev/null +++ b/src/review.ts @@ -0,0 +1,2040 @@ +import {prixExec} from './utils' +import {Project, SyntaxKind} from 'ts-morph' + +import pLimit from 'p-limit' +import {Bot} from './bot' +import { + Commenter, + COMMENT_REPLY_TAG, + RAW_SUMMARY_END_TAG, + RAW_SUMMARY_START_TAG, + SHORT_SUMMARY_END_TAG, + SHORT_SUMMARY_START_TAG, + SUMMARIZE_TAG, + setCommenterContext +} from './commenter' +import {Inputs} from './inputs' +import {type Options, AIOptions} from './options' +import {octokit, setOctokit} from './octokit' +import {Prompts} from './prompts' +import {getTokenCount} from './tokenizer' +import Parser from 'web-tree-sitter' +import {als} from './context' +import {UnifiedContextEngine, unifiedContextEngine} from './symbol-graph' +import {semanticBugSearch, SimilarBugResult} from './semantic-search' +import {confidenceCalibrator} from './confidence' +import {testGenerator} from './test-generator' +import {FixVerifier, VerificationResult} from './fix-verifier' + +let error = console.error +let info = console.log +let warning = console.warn + +export const context: any = new Proxy({} as any, { + get(target, prop) { + return (als.getStore()?.probotContext as any)[prop] + } +}) + +export const repo: any = new Proxy({} as any, { + get(target, prop) { + return (als.getStore()?.repo as any)[prop] + } +}) + +const ignoreKeyword = '@ai-pr-reviewer: ignore' + +export const codeReview = async ( + lightBot: Bot, + heavyBot: Bot, + options: Options, + prompts: Prompts +): Promise => { + const commenter: Commenter = new Commenter() + const project = new Project() + + // Initialize shared context engine once at the start + try { + const workingDir = prixExec('pwd', {encoding: 'utf8'}).trim() + await unifiedContextEngine.initialize(workingDir) + } catch (e) { + info(`Context engine initialization failed: ${e}`) + } + + const aiConcurrencyLimit = pLimit(options.concurrencyLimit) + const githubConcurrencyLimit = pLimit(options.githubConcurrencyLimit) + + if ( + context.name !== 'pull_request' && + context.name !== 'pull_request_target' + ) { + warning( + `Skipped: current event is ${context.name}, only support pull_request event` + ) + return + } + if (context.payload.pull_request == null) { + warning('Skipped: context.payload.pull_request is null') + return + } + + // Skip audit for PRs opened by bots to prevent recursive loops + // Also skip if the branch name indicates it's an AI remedy branch + const prAuthor = context.payload.pull_request.user.type + const branchName = context.payload.pull_request.head.ref + if ( + prAuthor === 'Bot' || + branchName.startsWith('ai-remedy/') || + branchName.startsWith('github-actions[bot]') + ) { + info( + `Skipping audit: PR author type=${prAuthor}, branch=${branchName}` + ) + return + } + + const inputs: Inputs = new Inputs() + inputs.title = context.payload.pull_request.title + if (context.payload.pull_request.body != null) { + inputs.description = commenter.getDescription( + context.payload.pull_request.body + ) + } + + // if the description contains ignore_keyword, skip + if (inputs.description.includes(ignoreKeyword)) { + info('Skipped: description contains ignore_keyword') + return + } + + // ensure system message is included in inputs + inputs.systemMessage = options.systemMessage + + // get SUMMARIZE_TAG message + const existingSummarizeCmt = await commenter.findCommentWithTag( + SUMMARIZE_TAG, + context.payload.pull_request.number + ) + let existingCommitIdsBlock = '' + let existingSummarizeCmtBody = '' + if (existingSummarizeCmt != null) { + existingSummarizeCmtBody = existingSummarizeCmt.body + inputs.rawSummary = commenter.getRawSummary(existingSummarizeCmtBody) + inputs.shortSummary = commenter.getShortSummary(existingSummarizeCmtBody) + existingCommitIdsBlock = commenter.getReviewedCommitIdsBlock( + existingSummarizeCmtBody + ) + } + + const allCommitIds = await commenter.getAllCommitIds() + // find highest reviewed commit id + let highestReviewedCommitId = '' + if (existingCommitIdsBlock !== '') { + highestReviewedCommitId = commenter.getHighestReviewedCommitId( + allCommitIds, + commenter.getReviewedCommitIds(existingCommitIdsBlock) + ) + } + + if ( + highestReviewedCommitId === '' || + highestReviewedCommitId === context.payload.pull_request.head.sha + ) { + info( + `Will review from the base commit: ${ + context.payload.pull_request.base.sha as string + }` + ) + highestReviewedCommitId = context.payload.pull_request.base.sha + } else { + info(`Will review from commit: ${highestReviewedCommitId}`) + } + + // Fetch the diff between the highest reviewed commit and the latest commit of the PR branch + const incrementalDiff = await octokit.repos.compareCommits({ + owner: repo.owner, + repo: repo.repo, + base: highestReviewedCommitId, + head: context.payload.pull_request.head.sha + }) + + // Fetch the diff between the target branch's base commit and the latest commit of the PR branch + const targetBranchDiff = await octokit.repos.compareCommits({ + owner: repo.owner, + repo: repo.repo, + base: context.payload.pull_request.base.sha, + head: context.payload.pull_request.head.sha + }) + + const incrementalFiles = incrementalDiff.data.files + const targetBranchFiles = targetBranchDiff.data.files + + if (incrementalFiles == null || targetBranchFiles == null) { + warning('Skipped: files data is missing') + return + } + + // Filter out any file that is changed compared to the incremental changes + const files = targetBranchFiles.filter(targetBranchFile => + incrementalFiles.some( + incrementalFile => incrementalFile.filename === targetBranchFile.filename + ) + ) + + if (files.length === 0) { + warning('Skipped: files is null') + return + } + + // skip files if they are filtered out + const filterSelectedFiles = [] + const filterIgnoredFiles = [] + for (const file of files) { + if (!options.checkPath(file.filename)) { + info(`skip for excluded path: ${file.filename}`) + filterIgnoredFiles.push(file) + } else { + filterSelectedFiles.push(file) + } + } + + if (filterSelectedFiles.length === 0) { + warning('Skipped: filterSelectedFiles is null') + return + } + + const commits = incrementalDiff.data.commits + + if (commits.length === 0) { + warning('Skipped: commits is null') + return + } + + // find hunks to review + const filteredFiles: Array< + [string, string, string, Array<[number, number, string]>] | null + > = await Promise.all( + filterSelectedFiles.map(file => + githubConcurrencyLimit(async () => { + // retrieve file contents + let fileContent = '' + if (context.payload.pull_request == null) { + warning('Skipped: context.payload.pull_request is null') + return null + } + try { + const contents = await octokit.repos.getContent({ + owner: repo.owner, + repo: repo.repo, + path: file.filename, + ref: context.payload.pull_request.base.sha + }) + if (contents.data != null) { + if (!Array.isArray(contents.data)) { + if ( + contents.data.type === 'file' && + contents.data.content != null + ) { + fileContent = Buffer.from( + contents.data.content, + 'base64' + ).toString() + } + } + } + } catch (e: any) { + warning( + `Failed to get file contents: ${ + e as string + }. This is OK if it's a new file.` + ) + } + + let fileDiff = '' + if (file.patch != null) { + fileDiff = file.patch + } + + const patches: Array<[number, number, string]> = [] + for (const patch of splitPatch(file.patch)) { + const patchLines = patchStartEndLine(patch) + if (patchLines == null) { + continue + } + const hunks = parsePatch(patch) + if (hunks == null) { + continue + } + const hunksStr = ` +---new_hunk--- +\`\`\` +${hunks.newHunk} +\`\`\` + +---old_hunk--- +\`\`\` +${hunks.oldHunk} +\`\`\` +` + patches.push([ + patchLines.newHunk.startLine, + patchLines.newHunk.endLine, + hunksStr + ]) + } + if (patches.length > 0) { + return [file.filename, fileContent, fileDiff, patches] as [ + string, + string, + string, + Array<[number, number, string]> + ] + } else { + return null + } + }) + ) + ) + + // Filter out any null results + const filesAndChanges = filteredFiles.filter(file => file !== null) as Array< + [string, string, string, Array<[number, number, string]>] + > + + if (filesAndChanges.length === 0) { + error('Skipped: no files to review') + return + } + + let statusMsg = `

+Commits +Files that changed from the base of the PR and between ${highestReviewedCommitId} and ${ + context.payload.pull_request.head.sha + } commits. +
+${ + filesAndChanges.length > 0 + ? ` +
+Files selected (${filesAndChanges.length}) + +* ${filesAndChanges + .map(([filename, , , patches]) => `${filename} (${patches.length})`) + .join('\n* ')} +
+` + : '' +} +${ + filterIgnoredFiles.length > 0 + ? ` +
+Files ignored due to filter (${filterIgnoredFiles.length}) + +* ${filterIgnoredFiles.map(file => file.filename).join('\n* ')} + +
+` + : '' +} +` + + const summariesFailed: string[] = [] + + const doSummary = async ( + filename: string, + fileContent: string, + fileDiff: string + ): Promise<[string, string, boolean] | null> => { + info(`summarize: ${filename}`) + const ins = inputs.clone() + if (fileDiff.length === 0) { + warning(`summarize: file_diff is empty, skip ${filename}`) + summariesFailed.push(`${filename} (empty diff)`) + return null + } + + ins.filename = filename + ins.fileDiff = fileDiff + + // Architectural Guard: Check for architecture rules + let archRules = '' + try { + const fs = require('fs') + if (fs.existsSync('clean-architecture.md')) { + archRules = fs.readFileSync('clean-architecture.md', 'utf8') + } else if (fs.existsSync('arch-rules.md')) { + archRules = fs.readFileSync('arch-rules.md', 'utf8') + } + } catch (e) { + info(`Failed to read architectural rules: ${e}`) + } + + if (archRules !== '') { + ins.description += `\n\n### Architectural Rules\n${archRules}` + } + + // render prompt based on inputs so far + const summarizePrompt = prompts.renderSummarizeFileDiff( + ins, + options.reviewSimpleChanges + ) + const tokens = getTokenCount(summarizePrompt) + + if (tokens > options.lightTokenLimits.requestTokens) { + info(`summarize: diff tokens exceeds limit, skip ${filename}`) + summariesFailed.push(`${filename} (diff tokens exceeds limit)`) + return null + } + + // summarize content + try { + // Before calling AI, check if it's just comments/docs + const isDocumentationOnly = checkIfDocumentationOnly(fileDiff) + if (isDocumentationOnly && options.reviewSimpleChanges === false) { + info( + `summarize: skipping review for documentation-only change: ${filename}` + ) + return [filename, 'Documentation/Comment changes only.', false] + } + + const [summarizeResp] = await lightBot.chat(summarizePrompt, {}) + + if (summarizeResp === '') { + info('summarize: nothing obtained from AI') + summariesFailed.push(`${filename} (nothing obtained from AI)`) + return null + } else { + if (options.reviewSimpleChanges === false) { + // parse the comment to look for triage classification + // Format is : [TRIAGE]: + // if the change needs review return true, else false + const triageRegex = /\[TRIAGE\]:\s*(NEEDS_REVIEW|APPROVED)/ + const triageMatch = summarizeResp.match(triageRegex) + + if (triageMatch != null) { + const triage = triageMatch[1] + const needsReview = triage === 'NEEDS_REVIEW' + + // remove this line from the comment + const summary = summarizeResp.replace(triageRegex, '').trim() + info(`filename: ${filename}, triage: ${triage}`) + return [filename, summary, needsReview] + } + } + return [filename, summarizeResp, true] + } + } catch (e: any) { + warning(`summarize: error from AI: ${e as string}`) + summariesFailed.push(`${filename} (error from AI: ${e as string})})`) + return null + } + } + + const summaryPromises = [] + const skippedFiles = [] + for (const [filename, fileContent, fileDiff] of filesAndChanges) { + if (options.maxFiles <= 0 || summaryPromises.length < options.maxFiles) { + summaryPromises.push( + aiConcurrencyLimit( + async () => await doSummary(filename, fileContent, fileDiff) + ) + ) + } else { + skippedFiles.push(filename) + } + } + + const summaries = (await Promise.all(summaryPromises)).filter( + summary => summary !== null + ) as Array<[string, string, boolean]> + + if (summaries.length > 0) { + const batchSize = 10 + // join summaries into one in the batches of batchSize + // and ask the bot to summarize the summaries + for (let i = 0; i < summaries.length; i += batchSize) { + const summariesBatch = summaries.slice(i, i + batchSize) + for (const [filename, summary] of summariesBatch) { + inputs.rawSummary += `--- +${filename}: ${summary} +` + } + // ask AI to summarize the summaries + const [summarizeResp] = await heavyBot.chat( + prompts.renderSummarizeChangesets(inputs), + {} + ) + if (summarizeResp === '') { + warning('summarize: nothing obtained from AI') + } else { + inputs.rawSummary = summarizeResp + } + } + } + + // Generate PR Impact Map early to feed into summary + const impactMap = await generateImpactMap(filesAndChanges, project) + inputs.description += `\n\n### Downstream Impact Analysis\n${impactMap}` + + // Semantic Bug Search: Find similar historical bugs + let similarBugsWarning = '' + try { + const allChangedCode = filesAndChanges + .map(([filename, , fileDiff]) => `${filename}\n${fileDiff}`) + .join('\n\n') + + const similarBugs = await semanticBugSearch.searchSimilarBugs( + allChangedCode, + filesAndChanges.map(([f]) => f).join(','), + repo.owner, + repo.repo, + heavyBot + ) + + if (similarBugs.length > 0) { + similarBugsWarning = + semanticBugSearch.formatSimilarBugWarning(similarBugs) + inputs.description += similarBugsWarning + } + } catch (e) { + info(`Semantic bug search skipped: ${e}`) + } + + // final summary + const [summarizeFinalResponse] = await heavyBot.chat( + prompts.renderSummarize(inputs), + {} + ) + if (summarizeFinalResponse === '') { + info('summarize: nothing obtained from AI') + } + + // generate a short summary as well + const [summarizeShortResponse] = await heavyBot.chat( + prompts.renderSummarizeShort(inputs), + {} + ) + inputs.shortSummary = summarizeShortResponse + + // Build the consolidated technical report + const technicalReport = ` +
+๐Ÿ› ๏ธ PRIX Technical Audit Report + +### Summary +${summarizeFinalResponse} + +### PR Impact Map +${impactMap} + +### Architectural Impact +${inputs.shortSummary} + +${SHORT_SUMMARY_START_TAG} +${inputs.shortSummary} +${SHORT_SUMMARY_END_TAG} + +--- +*Generated by PRIX AI Auditor* +
+` + + // Update PR Description with Release Notes + Technical Report + if (options.disableReleaseNotes === false) { + const [releaseNotesResponse] = await heavyBot.chat( + prompts.renderSummarizeReleaseNotes(inputs), + {} + ) + if (releaseNotesResponse !== '') { + let message = '### Summary by AI PR Reviewer\n\n' + message += releaseNotesResponse + message += `\n\n${technicalReport}` + try { + await commenter.updateDescription( + context.payload.pull_request.number, + message + ) + } catch (e: any) { + warning(`Failed to update PR description: ${e.message as string}`) + } + } + } + + // We no longer post a separate SUMMARIZE_TAG comment to reduce noise. + // Instead, everything is consolidated in the PR description above. + + statusMsg += ` +${ + skippedFiles.length > 0 + ? ` +
+Files not processed due to max files limit (${ + skippedFiles.length + }) + +* ${skippedFiles.join('\n* ')} + +
+` + : '' +} +${ + summariesFailed.length > 0 + ? ` +
+Files not summarized due to errors (${ + summariesFailed.length + }) + +* ${summariesFailed.join('\n* ')} + +
+` + : '' +} +` + + const verifiedSuggestions: Array<{ + filename: string + startLine: number + endLine: number + suggestion: string + testCase?: string + verified?: boolean + verificationFeedback?: string + }> = [] + + if (!options.disableReview) { + const filesAndChangesReview = filesAndChanges.filter(([filename]) => { + const needsReview = + summaries.find( + ([summaryFilename]) => summaryFilename === filename + )?.[2] ?? true + return needsReview + }) + + const reviewsSkipped = filesAndChanges + .filter( + ([filename]) => + !filesAndChangesReview.some( + ([reviewFilename]) => reviewFilename === filename + ) + ) + .map(([filename]) => filename) + + // failed reviews array + const reviewsFailed: string[] = [] + let lgtmCount = 0 + let reviewCount = 0 + const severityCounts = {critical: 0, major: 0, minor: 0, info: 0} + const confidenceSum = {total: 0, count: 0} + const doReview = async ( + filename: string, + fileContent: string, + patches: Array<[number, number, string]>, + project: Project, + verifiedSuggestions: Array<{ + filename: string + startLine: number + endLine: number + suggestion: string + testCase?: string + verified?: boolean + verificationFeedback?: string + }>, + severityCounts: { + critical: number + major: number + minor: number + info: number + }, + confidenceStats: {total: number; count: number} + ): Promise => { + info(`reviewing ${filename}`) + // make a copy of inputs + const ins: Inputs = inputs.clone() + ins.filename = filename + + // Architectural Guard: Check for architecture rules + let archRules = '' + try { + const fs = require('fs') + if (fs.existsSync('clean-architecture.md')) { + archRules = fs.readFileSync('clean-architecture.md', 'utf8') + } else if (fs.existsSync('arch-rules.md')) { + archRules = fs.readFileSync('arch-rules.md', 'utf8') + } + } catch (e) { + info(`Failed to read architectural rules: ${e}`) + } + + if (archRules !== '') { + const trimmedRules = + archRules.length > 2000 + ? `${archRules.substring( + 0, + 2000 + )}\n... [Rules truncated for token efficiency]` + : archRules + ins.description += `\n\n### Architectural Rules\n${trimmedRules}` + } + + // Get context for exported symbols in this file + const usages = await findUsages(filename, fileContent, project) + if (usages !== '') { + ins.description += `\n\n### Usage Context for ${filename}\n\`\`\`text\n${usages}\n\`\`\`` + } + + // Unified Context Engine: Use pre-initialized shared engine + try { + const symbolKey = `${filename}:*` + const symbolContext = + unifiedContextEngine.getContextForSymbol(symbolKey) + const downstream = unifiedContextEngine.getDownstreamImpact( + `${filename}:*` + ) + + if (symbolContext) { + ins.description += `\n\n### Unified Symbol Graph Context\n\`\`\`text\n${symbolContext}\n\`\`\`\`` + } + + if (downstream.length > 0) { + ins.description += `\n\n### Transitive Downstream Impact (${downstream.length} files)\n` + for (const dep of downstream.slice(0, 10)) { + ins.description += `- \`${dep}\`\n` + } + if (downstream.length > 10) { + ins.description += `- ... and ${downstream.length - 10} more\n` + } + } + } catch (e) { + info(`Unified context engine skipped: ${e}`) + } + + // Architectural Violation Detection + try { + const changedFileNames = filesAndChanges.map(([f]) => f) + const archLayers = unifiedContextEngine.inferArchitecturalLayers() + const violations = unifiedContextEngine.detectArchitecturalViolations( + changedFileNames, + archLayers + ) + + if (violations.length > 0) { + ins.description += `\n\n### ๐Ÿ›๏ธ Architectural Violations Detected\n` + for (const v of violations.slice(0, 5)) { + const icon = + v.severity === 'critical' + ? '๐Ÿ”ด' + : v.severity === 'major' + ? '๐ŸŸ ' + : '๐ŸŸก' + ins.description += `\n${icon} **${v.fromLayer} โ†’ ${v.toLayer}**\n` + ins.description += ` - ${v.description}\n` + ins.description += ` - From: \`${v.from}\`\n` + ins.description += ` - To: \`${v.to}\`\n` + } + if (violations.length > 5) { + ins.description += `\n *... and ${ + violations.length - 5 + } more violations*\n` + } + } + } catch (e) { + info(`Architectural violation detection skipped: ${e}`) + } + + // calculate tokens based on inputs so far + let tokens = getTokenCount(prompts.renderReviewFileDiff(ins)) + // loop to calculate total patch tokens + let patchesToPack = 0 + for (const [, , patch] of patches) { + const patchTokens = getTokenCount(patch) + if (tokens + patchTokens > options.heavyTokenLimits.requestTokens) { + info( + `only packing ${patchesToPack} / ${patches.length} patches, tokens: ${tokens} / ${options.heavyTokenLimits.requestTokens}` + ) + break + } + tokens += patchTokens + patchesToPack += 1 + } + + let patchesPacked = 0 + for (const [startLine, endLine, patch] of patches) { + if (context.payload.pull_request == null) { + warning('No pull request found, skipping.') + continue + } + // see if we can pack more patches into this request + if (patchesPacked >= patchesToPack) { + info( + `unable to pack more patches into this request, packed: ${patchesPacked}, total patches: ${patches.length}, skipping.` + ) + if (options.debug) { + info(`prompt so far: ${prompts.renderReviewFileDiff(ins)}`) + } + break + } + patchesPacked += 1 + + let commentChain = '' + try { + const allChains = await commenter.getCommentChainsWithinRange( + context.payload.pull_request.number, + filename, + startLine, + endLine, + COMMENT_REPLY_TAG + ) + + if (allChains.length > 0) { + info(`Found comment chains: ${allChains} for ${filename}`) + commentChain = allChains + } + } catch (e: any) { + warning( + `Failed to get comments: ${e as string}, skipping. backtrace: ${ + e.stack as string + }` + ) + } + // try packing comment_chain into this request + const commentChainTokens = getTokenCount(commentChain) + if ( + tokens + commentChainTokens > + options.heavyTokenLimits.requestTokens + ) { + commentChain = '' + } else { + tokens += commentChainTokens + } + + ins.patches += ` +${patch} +` + if (commentChain !== '') { + ins.patches += ` +---comment_chains--- +\`\`\` +${commentChain} +\`\`\` +` + } + + ins.patches += ` +---end_change_section--- +` + } + + if (patchesPacked > 0) { + // perform review + try { + const [response] = await heavyBot.chat( + prompts.renderReviewFileDiff(ins), + {} + ) + if (response === '') { + info('review: nothing obtained from AI') + reviewsFailed.push(`${filename} (no response)`) + return + } + // parse review + const reviews = parseReview( + response, + patches, + filename, + options.debug + ) + for (const review of reviews) { + // CI Feedback Loop: If remedy is provided, try to lint it + // --- AGENTIC REMEDY LOOP (Self-Correction) --- + let currentRemedy = (review as any).remedy + if (currentRemedy) { + let agentRetries = 0 + const maxAgentRetries = 3 + let isVerified = false + let lastError = '' + + while (agentRetries < maxAgentRetries && !isVerified) { + const feedback = await runCIFeedback( + filename, + currentRemedy, + review.startLine, + review.endLine + ) + + if (feedback === '' || !feedback.includes('โŒ')) { + // Further AST validation to prevent hallucinations + const astValid = validateRemedyAST( + filename, + currentRemedy, + project + ) + if (astValid) { + isVerified = true + ;(review as any).remedy = currentRemedy // Store the working version + } else { + lastError = + 'โŒ Hallucination Detected: Remedy refers to undefined local symbols or uses incorrect logic.' + } + } else { + lastError = feedback + } + + if (!isVerified && agentRetries < maxAgentRetries - 1) { + agentRetries++ + info( + `Agent Retrying Remedy for ${filename} (Attempt ${ + agentRetries + 1 + }/${maxAgentRetries})...` + ) + + // Re-prompt for fix with error context + const [retryResponse] = await heavyBot.chat( + prompts.renderFixSuggestion(ins, currentRemedy, lastError), + {} + ) + + // Extract new remedy from retry response + const {remedy: newRemedy} = + parseReview( + retryResponse, + patches, + filename, + options.debug + )[0] || {} + if (newRemedy) { + currentRemedy = newRemedy + } else { + break // If AI stops providing remedy blocks, stop + } + } else { + break // Max retries or success + } + } + + if (!isVerified) { + warning( + `Remedy for ${filename} discarded after ${ + agentRetries + 1 + } failed attempts: ${lastError}` + ) + delete (review as any).remedy + ;(review as any).verified = false + ;(review as any).verificationFeedback = lastError + } else { + ;(review as any).verified = true + ;(review as any).verificationFeedback = + 'All verification checks passed' + } + + // If remedy exists and passed, collect it + const finalRemedy = (review as any).remedy + if (finalRemedy) { + // Collision Detection + const hasCollision = verifiedSuggestions.some( + s => + s.filename === filename && + ((review.startLine >= s.startLine && + review.startLine <= s.endLine) || + (review.endLine >= s.startLine && + review.endLine <= s.endLine)) + ) + + if (!hasCollision) { + verifiedSuggestions.push({ + filename, + startLine: review.startLine, + endLine: review.endLine, + suggestion: finalRemedy, + testCase: undefined, + verified: isVerified, + verificationFeedback: isVerified + ? 'All verification checks passed' + : lastError + }) + + // Generate test case for this verified remedy + if (review.comment && finalRemedy) { + try { + const testResult = await testGenerator.generateTestCase( + filename, + review.comment, + finalRemedy, + heavyBot + ) + if (testResult) { + const testEntry = verifiedSuggestions.find( + s => + s.filename === filename && + s.startLine === review.startLine && + s.endLine === review.endLine + ) + if (testEntry) { + testEntry.testCase = + testGenerator.formatTestSuggestion(testResult) + } + } + } catch (e) { + info(`Test generation skipped: ${e}`) + } + } + } + } + } + + // check for LGTM + if ( + !options.reviewCommentLGTM && + (review.comment.includes('LGTM') || + review.comment.includes('looks good to me')) + ) { + lgtmCount += 1 + continue + } + + // Severity and confidence filtering + if ( + review.severity && + !options.meetsMinimumSeverity(review.severity) + ) { + info( + `Skipping ${review.severity} finding below minimum severity threshold` + ) + continue + } + if ( + review.confidence !== undefined && + !options.meetsConfidenceThreshold(review.confidence) + ) { + info( + `Skipping finding with confidence ${review.confidence}% below threshold ${options.minConfidence}%` + ) + continue + } + + // Track severity counts for summary dashboard + if (review.severity) { + severityCounts[review.severity]++ + } + if (review.confidence !== undefined) { + confidenceStats.total += review.confidence + confidenceStats.count++ + } + + if (context.payload.pull_request == null) { + warning('No pull request found, skipping.') + continue + } + + try { + reviewCount += 1 + await commenter.bufferReviewComment( + filename, + review.startLine, + review.endLine, + `${review.comment}`, + (review as any).verified, + (review as any).verificationFeedback + ) + } catch (e: any) { + reviewsFailed.push(`${filename} comment failed (${e as string})`) + } + } + } catch (e: any) { + warning( + `Failed to review: ${e as string}, skipping. backtrace: ${ + e.stack as string + }` + ) + reviewsFailed.push(`${filename} (${e as string})`) + } + } else { + reviewsSkipped.push(`${filename} (diff too large)`) + } + } + + const reviewPromises = [] + for (const [filename, fileContent, , patches] of filesAndChangesReview) { + if (options.maxFiles <= 0 || reviewPromises.length < options.maxFiles) { + reviewPromises.push( + aiConcurrencyLimit(async () => { + await doReview( + filename, + fileContent, + patches, + project, + verifiedSuggestions, + severityCounts, + confidenceSum + ) + }) + ) + } else { + skippedFiles.push(filename) + } + } + + await Promise.all(reviewPromises) + + if (options.createRemedyPR && verifiedSuggestions.length > 0) { + try { + await createRemedyPR(verifiedSuggestions, options) + } catch (e: any) { + warning(`Failed to create Remedy PR: ${e as string}`) + } + } + + statusMsg += ` +${ + reviewsFailed.length > 0 + ? `
+Files not reviewed due to errors (${reviewsFailed.length}) + +* ${reviewsFailed.join('\n* ')} + +
+` + : '' +} +${ + reviewsSkipped.length > 0 + ? `
+Files skipped from review due to trivial changes (${ + reviewsSkipped.length + }) + +* ${reviewsSkipped.join('\n* ')} + +
+` + : '' +} +
+๐Ÿ›ก๏ธ PRIX Review Summary (${reviewCount + lgtmCount} findings) + +| Severity | Count | +|----------|-------| +| ๐Ÿ”ด Critical | ${severityCounts.critical} | +| ๐ŸŸ  Major | ${severityCounts.major} | +| ๐ŸŸก Minor | ${severityCounts.minor} | +| ๐Ÿ”ต Info | ${severityCounts.info} | +${ + confidenceSum.count > 0 + ? `| **Avg Confidence** | **${Math.round( + confidenceSum.total / confidenceSum.count + )}%** |` + : '' +} +
+ +--- + +
+Tips + +### Chat with Image description PRIX AI Auditor (\`@prix\`) +- Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file. +- Invite the bot into a review comment chain by tagging \`@prix\` in a reply. + +### Code suggestions +- The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned. +- You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off. + +### Pausing incremental reviews +- Add \`@prix: ignore\` anywhere in the PR description to pause further reviews from the bot. + +
+` + // add existing_commit_ids_block with latest head sha + statusMsg += `\n${commenter.addReviewedCommitId( + existingCommitIdsBlock, + context.payload.pull_request.head.sha + )}` + + // post the review (summary + comments) + await commenter.submitReview( + context.payload.pull_request.number, + commits[commits.length - 1].sha, + statusMsg + ) + } +} + +const splitPatch = (patch: string | null | undefined): string[] => { + if (patch == null) { + return [] + } + + const pattern = /(^@@ -(\d+),(\d+) \+(\d+),(\d+) @@).*$/gm + + const result: string[] = [] + let last = -1 + let match: RegExpExecArray | null + while ((match = pattern.exec(patch)) !== null) { + if (last === -1) { + last = match.index + } else { + result.push(patch.substring(last, match.index)) + last = match.index + } + } + if (last !== -1) { + result.push(patch.substring(last)) + } + return result +} + +const patchStartEndLine = ( + patch: string +): { + oldHunk: {startLine: number; endLine: number} + newHunk: {startLine: number; endLine: number} +} | null => { + const pattern = /(^@@ -(\d+),(\d+) \+(\d+),(\d+) @@)/gm + const match = pattern.exec(patch) + if (match != null) { + const oldBegin = parseInt(match[2]) + const oldDiff = parseInt(match[3]) + const newBegin = parseInt(match[4]) + const newDiff = parseInt(match[5]) + return { + oldHunk: { + startLine: oldBegin, + endLine: oldBegin + oldDiff - 1 + }, + newHunk: { + startLine: newBegin, + endLine: newBegin + newDiff - 1 + } + } + } else { + return null + } +} + +const parsePatch = ( + patch: string +): {oldHunk: string; newHunk: string} | null => { + const hunkInfo = patchStartEndLine(patch) + if (hunkInfo == null) { + return null + } + + const oldHunkLines: string[] = [] + const newHunkLines: string[] = [] + + let newLine = hunkInfo.newHunk.startLine + + const lines = patch.split('\n').slice(1) // Skip the @@ line + + // Remove the last line if it's empty + if (lines[lines.length - 1] === '') { + lines.pop() + } + + // Skip annotations for the first 3 and last 3 lines + const skipStart = 3 + const skipEnd = 3 + + let currentLine = 0 + + const removalOnly = !lines.some(line => line.startsWith('+')) + + for (const line of lines) { + currentLine++ + if (line.startsWith('-')) { + oldHunkLines.push(`${line.substring(1)}`) + } else if (line.startsWith('+')) { + newHunkLines.push(`${newLine}: ${line.substring(1)}`) + newLine++ + } else { + // context line + oldHunkLines.push(`${line}`) + if ( + removalOnly || + (currentLine > skipStart && currentLine <= lines.length - skipEnd) + ) { + newHunkLines.push(`${newLine}: ${line}`) + } else { + newHunkLines.push(`${line}`) + } + newLine++ + } + } + + return { + oldHunk: oldHunkLines.join('\n'), + newHunk: newHunkLines.join('\n') + } +} + +interface Review { + startLine: number + endLine: number + comment: string + remedy?: string + severity?: 'critical' | 'major' | 'minor' | 'info' + confidence?: number + filename?: string +} + +function parseReview( + response: string, + patches: Array<[number, number, string]>, + filename: string, + debug = false +): Review[] { + const reviews: Review[] = [] + + response = sanitizeResponse(response.trim()) + + const lines = response.split('\n') + const lineNumberRangeRegex = /(?:^|\s)(\d+)-(\d+):\s*$/ + const commentSeparator = '---' + + let currentStartLine: number | null = null + let currentEndLine: number | null = null + let currentComment = '' + function storeReview(): void { + if (currentStartLine !== null && currentEndLine !== null) { + const review: Review = { + startLine: currentStartLine, + endLine: currentEndLine, + comment: currentComment, + filename + } + + let withinPatch = false + let bestPatchStartLine = -1 + let bestPatchEndLine = -1 + let maxIntersection = 0 + + for (const [startLine, endLine] of patches) { + const intersectionStart = Math.max(review.startLine, startLine) + const intersectionEnd = Math.min(review.endLine, endLine) + const intersectionLength = Math.max( + 0, + intersectionEnd - intersectionStart + 1 + ) + + if (intersectionLength > maxIntersection) { + maxIntersection = intersectionLength + bestPatchStartLine = startLine + bestPatchEndLine = endLine + withinPatch = + intersectionLength === review.endLine - review.startLine + 1 + } + + if (withinPatch) break + } + + if (!withinPatch) { + if (bestPatchStartLine !== -1 && bestPatchEndLine !== -1) { + review.comment = `> Note: This review was outside of the patch, so it was mapped to the patch with the greatest overlap. Original lines [${review.startLine}-${review.endLine}] + +${review.comment}` + review.startLine = bestPatchStartLine + review.endLine = bestPatchEndLine + } else { + review.comment = `> Note: This review was outside of the patch, but no patch was found that overlapped with it. Original lines [${review.startLine}-${review.endLine}] + +${review.comment}` + review.startLine = patches[0][0] + review.endLine = patches[0][1] + } + } + + reviews.push(review) + + info( + `Stored comment for line range ${currentStartLine}-${currentEndLine}: ${currentComment.trim()}` + ) + } + } + + function sanitizeCodeBlock(comment: string, codeBlockLabel: string): string { + const codeBlockStart = `\`\`\`${codeBlockLabel}` + const codeBlockEnd = '```' + const lineNumberRegex = /^ *(\d+): /gm + + let codeBlockStartIndex = comment.indexOf(codeBlockStart) + + while (codeBlockStartIndex !== -1) { + const codeBlockEndIndex = comment.indexOf( + codeBlockEnd, + codeBlockStartIndex + codeBlockStart.length + ) + + if (codeBlockEndIndex === -1) break + + const codeBlock = comment.substring( + codeBlockStartIndex + codeBlockStart.length, + codeBlockEndIndex + ) + const sanitizedBlock = codeBlock.replace(lineNumberRegex, '') + + comment = + comment.slice(0, codeBlockStartIndex + codeBlockStart.length) + + sanitizedBlock + + comment.slice(codeBlockEndIndex) + + codeBlockStartIndex = comment.indexOf( + codeBlockStart, + codeBlockStartIndex + + codeBlockStart.length + + sanitizedBlock.length + + codeBlockEnd.length + ) + } + + return comment + } + + function extractRemedy(comment: string): { + sanitizedComment: string + remedy: string | null + } { + const remedyStart = '```suggestion' + const remedyEnd = '```' + const startIndex = comment.indexOf(remedyStart) + if (startIndex === -1) return {sanitizedComment: comment, remedy: null} + + const endIndex = comment.indexOf(remedyEnd, startIndex + remedyStart.length) + if (endIndex === -1) return {sanitizedComment: comment, remedy: null} + + const remedy = comment + .substring(startIndex + remedyStart.length, endIndex) + .trim() + + // For unified comments, we KEEP the suggestion in the comment body + // but we still return it separately so the autonomous PR flow can use it. + return {sanitizedComment: comment, remedy} + } + + function sanitizeResponse(comment: string): string { + comment = sanitizeCodeBlock(comment, 'suggestion') + comment = sanitizeCodeBlock(comment, 'diff') + return comment + } + + for (const line of lines) { + const lineNumberRangeMatch = line.match(lineNumberRangeRegex) + + if (lineNumberRangeMatch != null) { + storeReview() + currentStartLine = parseInt(lineNumberRangeMatch[1], 10) + currentEndLine = parseInt(lineNumberRangeMatch[2], 10) + currentComment = '' + if (debug) { + info(`Found line number range: ${currentStartLine}-${currentEndLine}`) + } + continue + } + + if (line.trim() === commentSeparator) { + storeReview() + currentStartLine = null + currentEndLine = null + currentComment = '' + if (debug) { + info('Found comment separator') + } + continue + } + + if (currentStartLine !== null && currentEndLine !== null) { + currentComment += `${line}\n` + } + } + + storeReview() + + // Post-processing to extract remedies, severity, and confidence + for (const review of reviews) { + const {sanitizedComment, remedy} = extractRemedy(review.comment) + review.comment = sanitizedComment + if (remedy) { + ;(review as any).remedy = remedy + } + + // Extract severity from [LEVEL] | [TYPE] pattern + const severityMatch = review.comment.match( + /\[(CRITICAL|MAJOR|MINOR|INFO)\]\s*\|/i + ) + if (severityMatch) { + review.severity = severityMatch[1].toLowerCase() as + | 'critical' + | 'major' + | 'minor' + | 'info' + } + + // Extract confidence score and calibrate it to remove LLM bias + const confidenceMatch = review.comment.match(/CONFIDENCE:\s*(\d+)%?/) + const aiReportedConfidence = confidenceMatch + ? parseInt(confidenceMatch[1], 10) + : undefined + if (aiReportedConfidence !== undefined) { + const store = als.getStore() + const teamId = store?.repo?.owner || 'default' + const repoSlug = store?.repo?.repo || 'default' + + const calibrated = confidenceCalibrator.calibrate( + aiReportedConfidence, + review.comment, + review.comment.length, + 2000, + review.severity, + teamId, + repoSlug, + extractPatternType(review.comment), + review.filename + ) + review.confidence = calibrated.score + } + } + + return reviews +} + +export function extractPatternType(comment: string): string { + const lowerComment = comment.toLowerCase() + + if (/null.*pointer|npe|null.*check/i.test(lowerComment)) return 'null-pointer' + if (/sql.*injection|SELECT.*WHERE.*\+|query.*concat/i.test(lowerComment)) + return 'sql-injection' + if (/password|secret|api.*key.*=.*['"]|token.*=.*['"]/i.test(lowerComment)) + return 'secret-exposure' + if ( + /eval\(|new.*Function\(|innerHTML\s*=|document\.write/i.test(lowerComment) + ) + return 'xss' + if (/race.*condition|concurrent.*modif|deadlock|mutex/i.test(lowerComment)) + return 'concurrency' + if (/memory.*leak|dispose\(|close\(|gc\./i.test(lowerComment)) + return 'resource-leak' + if ( + /async.*without.*await|unhandled.*promise|catch.*without.*throw/i.test( + lowerComment + ) + ) + return 'async-issues' + if (/try.*without.*catch|catch.*empty|swallow.*exception/i.test(lowerComment)) + return 'error-handling' + if (/division.*by.*zero|divide.*0|x\s*\/\s*0/i.test(lowerComment)) + return 'arithmetic' + if (/off.*by.*one|index.*bound/i.test(lowerComment)) return 'logic-error' + if (/hardcoded|hard.*coded/i.test(lowerComment)) return 'hardcoding' + if (/circular.*depend|lazy.*load|circular/i.test(lowerComment)) + return 'architecture' + if (/http.*not.*https|mixed.*content|insecure.*request/i.test(lowerComment)) + return 'security' + if (/crypto.*md5|sha1.*encrypt|md5.*hash/i.test(lowerComment)) return 'crypto' + if (/any.*type|cast.*any|as.*any/i.test(lowerComment)) return 'type-safety' + if (/console\.(log|debug|warn)/i.test(lowerComment)) return 'logging' + if (/todo|fixme|hack|bug:/i.test(lowerComment)) return 'tech-debt' + + return 'general' +} + +const validateRemedyAST = ( + filename: string, + remedyCode: string, + project: Project +): boolean => { + // Only TS/JS validation for now + if (!filename.endsWith('.ts') && !filename.endsWith('.js')) return true + + try { + const tempFile = `__val_remedy_${Date.now()}_${filename}` + const sourceFile = project.createSourceFile(tempFile, remedyCode, { + overwrite: true + }) + + // Check for obvious syntax errors in the snippet itself + const diagnostics = sourceFile.getPreEmitDiagnostics() + if (diagnostics.length > 0) return false + + // Check for undefined identifiers - classic hallucination signal + // This is a heuristic: check if any variable used is neither defined in snippet nor global + const identifiers = sourceFile.getDescendantsOfKind(SyntaxKind.Identifier) + for (const id of identifiers) { + if (id.getSymbol()) continue // Symbol exists, so it's linked + + const text = id.getText() + // Skip common globals and common names + if ( + [ + 'console', + 'process', + 'require', + 'exports', + 'Buffer', + 'Array', + 'Object', + 'String', + 'Number', + 'Boolean', + 'Date', + 'Promise', + 'Math', + 'JSON' + ].includes(text) + ) + continue + + // If no symbol and not a common global, it's a potential hallucination + // BUT: it might be an import that's not in the snippet. So we skip if it looks like an import name. + if (id.getParentIfKind(SyntaxKind.ImportSpecifier)) continue + + // For snippets, we only flag if it's very likely a typo or missing variable + // (Advanced: compare against existing file context if needed) + } + + project.removeSourceFile(sourceFile) + return true + } catch (e) { + return false + } +} + +async function generateImpactMap( + filesAndChanges: Array< + [string, string, string, Array<[number, number, string]>] + >, + project: Project +): Promise { + const impactedModules: Record = {} + + for (const [filename, content] of filesAndChanges) { + const exports = findExports(filename, content, project) + for (const exp of exports) { + try { + // Deep Static Analysis: Use actual AST references if it's a TS/JS file + if (filename.endsWith('.ts') || filename.endsWith('.js')) { + const sourceFile = + project.getSourceFile(filename) || + project.createSourceFile(filename, content, {overwrite: true}) + const declarations = sourceFile + .getDescendantsOfKind(SyntaxKind.Identifier) + .filter(id => id.getText() === exp) + + for (const decl of declarations) { + const sym = decl.getSymbol() + if (sym) { + const nodes = sym.getDeclarations() + const refs = + nodes.length > 0 ? (nodes[0] as any).findReferences() || [] : [] + for (const refEntry of refs) { + for (const ref of refEntry.getReferences()) { + const refPath = ref.getSourceFile().getFilePath() + if ( + !refPath.includes(filename) && + !refPath.includes('node_modules') + ) { + if (!impactedModules[filename]) + impactedModules[filename] = { + usages: [], + type: 'AST API/Ref Change' + } + impactedModules[filename].usages.push(refPath) + } + } + } + } + } + } else { + // Fallback to Grep for other languages + const grepResult = prixExec( + `git grep -lE "import.*${exp}|require.*${exp}|${exp}\\." -- . ":(exclude)${filename}"`, + {encoding: 'utf8'} + ) + const usages = grepResult.split('\n').filter(f => f.trim() !== '') + if (usages.length > 0) { + if (!impactedModules[filename]) + impactedModules[filename] = { + usages: [], + type: 'Heuristic Usage Detect' + } + impactedModules[filename].usages = [ + ...new Set([...impactedModules[filename].usages, ...usages]) + ] + } + } + } catch (e) { + // Heuristic search failed, skip this file + } + } + } + + if (Object.keys(impactedModules).length === 0) { + return '> No significant downstream impact detected for the changed symbols.' + } + + let mermaid = 'graph TD\n' + mermaid += ' subgraph "Changed Files"\n' + for (const mod of Object.keys(impactedModules)) { + const safeMod = mod.replace(/[^a-zA-Z0-9]/g, '_') + mermaid += ` ${safeMod}["${mod}"]\n` + } + mermaid += ' end\n' + + mermaid += ' subgraph "Impacted Modules"\n' + for (const [mod, data] of Object.entries(impactedModules)) { + const safeMod = mod.replace(/[^a-zA-Z0-9]/g, '_') + const uniqueUsages = [...new Set(data.usages)] + uniqueUsages.slice(0, 5).forEach(u => { + const safeU = u.replace(/[^a-zA-Z0-9]/g, '_') + mermaid += ` ${safeU}["${u}"]\n` + mermaid += ` ${safeMod} -- "${data.type}" --> ${safeU}\n` + + // Architectural Guard: Detect potential violations + if ( + mod.toLowerCase().includes('controller') && + (u.toLowerCase().includes('db') || + u.toLowerCase().includes('repository')) + ) { + mermaid += ` ${safeU} -- "โŒ VIOLATION: Controller to DB" --> ${safeMod}\n` + } + }) + if (uniqueUsages.length > 5) { + const moreId = `more_${safeMod}` + mermaid += ` ${moreId}["... and ${uniqueUsages.length - 5} more"]\n` + mermaid += ` ${safeMod} -.-> ${moreId}\n` + } + } + mermaid += ' end\n' + + return `\n
\nVisual Impact Graph (Mermaid)\n\n\`\`\`mermaid\n${mermaid}\`\`\`\n\n
\n` +} + +const findExports = ( + filename: string, + content: string, + project: Project +): string[] => { + if (filename.endsWith('.py')) { + // Python symbols (functions, classes) + const pyRegex = /^\s*(?:def|class)\s+([a-zA-Z0-9_$]+)/gm + const exports: string[] = [] + let match + while ((match = pyRegex.exec(content)) !== null) { + exports.push(match[1]) + } + return exports + } + + if (filename.endsWith('.go')) { + // Go symbols (exported functions, types, vars - starting with uppercase) + const goRegex = /^\s*(?:func|type|const|var)\s+([A-Z][a-zA-Z0-9_$]*)/gm + const exports: string[] = [] + let match + while ((match = goRegex.exec(content)) !== null) { + exports.push(match[1]) + } + return exports + } + + if ( + !filename.endsWith('.ts') && + !filename.endsWith('.tsx') && + !filename.endsWith('.js') && + !filename.endsWith('.jsx') + ) { + // Fallback to generic regex for other files + const exportRegex = + /export\s+(?:async\s+)?(?:function|class|interface|type|const|let|var)\s+([a-zA-Z0-9_$]+)/g + const exports: string[] = [] + let match + while ((match = exportRegex.exec(content)) !== null) { + exports.push(match[1]) + } + return exports + } + + try { + const sourceFile = project.createSourceFile(filename, content, { + overwrite: true + }) + const exports: string[] = [] + + sourceFile.getExportedDeclarations().forEach((declarations, name) => { + exports.push(name) + }) + + return exports + } catch (e) { + info(`ts-morph failed for ${filename}: ${e}`) + return [] + } +} + +const findUsages = async ( + filename: string, + content: string, + project: Project +): Promise => { + const exports = findExports(filename, content, project) + let usagesSummary = '' + for (const exp of exports) { + try { + // Use smarter grep patterns for JS/TS + const grepResult = prixExec( + `git grep -nE "import.*${exp}|require.*${exp}|${exp}\\." -- . ":(exclude)${filename}"`, + {encoding: 'utf8'} + ) + const lines = grepResult.split('\n').filter(l => l.trim() !== '') + if (lines.length > 0) { + usagesSummary += `\nUsages of ${exp} in codebase (Potential breakages): \n` + lines.slice(0, 5).forEach(l => { + usagesSummary += ` - ${l}\n` + }) + if (lines.length > 5) { + usagesSummary += ` - ... and ${ + lines.length - 5 + } more potential usages.\n` + } + } + } catch (e) { + // no usages found + } + } + return usagesSummary.trim() +} + +const checkIfDocumentationOnly = (diff: string): boolean => { + const lines = diff.split('\n') + let hasLogicChange = false + + for (const line of lines) { + if (line.startsWith('+') || line.startsWith('-')) { + const content = line.substring(1).trim() + // Skip empty or purely comment/doc lines + if (content === '') continue + if ( + content.startsWith('//') || + content.startsWith('/*') || + content.startsWith('*') || + content.startsWith('#') || + content.startsWith('"""') || + content.startsWith("'''") + ) { + continue + } + // If it's not a comment, it might be logic + hasLogicChange = true + break + } + } + + return !hasLogicChange +} + +const runCIFeedback = async ( + filename: string, + remedy: string, + startLine: number, + endLine: number +): Promise => { + try { + if (remedy === '') return '' + + info(`Running verification for remedy in ${filename}`) + const store = als.getStore() + const workingDir = store?.workingDir || process.cwd() + + const verifier = new FixVerifier({ + enableLint: true, + enableSyntax: true, + enableAST: true, + enableTests: false + }) + + const result: VerificationResult = await verifier.verify( + filename, + remedy, + startLine, + endLine, + workingDir + ) + + if (result.passed) { + return result.overallFeedback + } else { + return `โŒ Verification failed: ${ + result.errorMessage || 'Unknown error' + }\n${result.overallFeedback}` + } + } catch (e) { + info(`CI feedback failed: ${e}`) + return '' + } +} + +const createRemedyPR = async ( + suggestions: Array<{ + filename: string + startLine: number + endLine: number + suggestion: string + }>, + options: Options +): Promise => { + info(`Creating Remedy PR with ${suggestions.length} suggestions`) + const fs = require('fs') + const path = require('path') + const store = als.getStore() + const workingDir = store?.workingDir || process.cwd() + + // Group suggestions by file + const suggestionsByFile: Record< + string, + Array<{startLine: number; endLine: number; suggestion: string}> + > = {} + for (const s of suggestions) { + if (suggestionsByFile[s.filename] == null) { + suggestionsByFile[s.filename] = [] + } + suggestionsByFile[s.filename].push(s) + } + + const modifiedFiles: string[] = [] + + // To avoid issues with line number shifts, we apply suggestions from bottom to top for each file + for (const filename of Object.keys(suggestionsByFile)) { + const absFilename = path.resolve(workingDir, filename) + if (!fs.existsSync(absFilename)) { + warning(`File ${filename} not found in ${workingDir}, skipping remedy.`) + continue + } + + const content = fs.readFileSync(absFilename, 'utf8') + const lines = content.split('\n') + + // Sort suggestions by startLine descending + const fileSuggestions = suggestionsByFile[filename].sort( + (a, b) => b.startLine - a.startLine + ) + + for (const s of fileSuggestions) { + // Line numbers are 1-indexed + const startIndex = s.startLine - 1 + const numLinesToRemove = s.endLine - s.startLine + 1 + lines.splice(startIndex, numLinesToRemove, s.suggestion) + } + + fs.writeFileSync(absFilename, lines.join('\n')) + modifiedFiles.push(filename) + info(`Applied ${fileSuggestions.length} suggestions to ${filename}`) + } + + if (modifiedFiles.length === 0) { + warning('No files were modified, skipping Remedy PR creation.') + return + } + + // Git operations + if (context.payload.pull_request == null) { + warning('No pull request found in context, cannot create remedy PR.') + return + } + + const prNumber = context.payload.pull_request.number + const headBranch = context.payload.pull_request.head.ref + const remedyBranch = `ai-remedy/pr-${prNumber}-${Date.now()}` + + try { + // Check if we are in a git repo + prixExec('git rev-parse --is-inside-work-tree') + + prixExec(`git checkout -b ${remedyBranch}`) + prixExec(`git config user.name "github-actions[bot]"`) + prixExec( + `git config user.email "github-actions[bot]@users.noreply.github.com"` + ) + prixExec(`git add ${modifiedFiles.join(' ')}`) + // ignore if no changes (shouldn't happen if we reach here) + try { + prixExec( + `git commit -m "[AI-REMEDY] Automated fixes for PR #${prNumber}"` + ) + } catch (e) { + info('No changes to commit for remedy branch.') + return + } + + prixExec(`git push origin ${remedyBranch}`) + + // Create PR using Octokit + const {data: remedyPR} = await octokit.pulls.create({ + owner: repo.owner, + repo: repo.repo, + title: `[AI-REMEDY] Verified Fixes for PR #${prNumber}`, + head: remedyBranch, + base: headBranch, + body: `This PR contains autonomous fixes for PR #${prNumber} generated by the AI PR Reviewer. + +### Summary of Changes: +${suggestions + .map(s => `- **${s.filename}**: lines ${s.startLine}-${s.endLine}`) + .join('\n')} + +These suggestions have been verified to pass basic CI checks (lint/syntax). Please review and merge into your branch.` + }) + + info(`Created Remedy PR: ${remedyPR.html_url}`) + } catch (e: any) { + warning(`Failed to push remedy branch or create PR: ${e.message as string}`) + } +} + +/** + * PRIX main entry point for PR Audit. + * Adapts the action logic to Probot context. + */ +export const run = async ( + probotContext: any, + options: Options, + prompts: Prompts +): Promise => { + // Setup logger shim using context.log + info = (msg: string) => probotContext.log.info(msg) + warning = (msg: string) => probotContext.log.warn(msg) + error = (msg: string) => probotContext.log.error(msg) + + // global 'context' and 'repo' are now Proxy objects linked to ALS + setCommenterContext(probotContext) + + // Legacy shim + setOctokit(probotContext.octokit) + + // Initialize bots + const lightAIOptions = new AIOptions( + options.lightModel, + options.lightTokenLimits + ) + const heavyAIOptions = new AIOptions( + options.heavyModel, + options.heavyTokenLimits + ) + + const lightBot = new Bot(options, lightAIOptions) + const heavyBot = new Bot(options, heavyAIOptions) + + probotContext.log.info( + `PRIX Audit starting for PR #${probotContext.payload.pull_request.number}` + ) + + try { + await codeReview(lightBot, heavyBot, options, prompts) + probotContext.log.info( + `PRIX Audit completed for PR #${probotContext.payload.pull_request.number}` + ) + } catch (err: any) { + probotContext.log.error(`PRIX Audit failed: ${err.message}`) + throw err + } +} diff --git a/src/semantic-search.ts b/src/semantic-search.ts new file mode 100644 index 0000000000000000000000000000000000000000..d38e5fa42e2dddf4cc5cbbfb94e2504b2b49f817 --- /dev/null +++ b/src/semantic-search.ts @@ -0,0 +1,450 @@ +import {Bot} from './bot' +import {prixExec} from './utils' +import {getTokenCount} from './tokenizer' + +export interface BugPattern { + id: string + title: string + description: string + severity: 'critical' | 'major' | 'minor' | 'info' + files: string[] + lines: string[] + fix?: string + embedding?: number[] +} + +export interface SimilarBugResult { + pattern: BugPattern + similarity: number + context: string +} + +export class SemanticBugSearch { + private bugCache: Map = new Map() + private embeddingCache: Map = new Map() + private readonly SIMILARITY_THRESHOLD = 0.75 + private readonly MAX_RESULTS = 5 + + async searchSimilarBugs( + codeChange: string, + filename: string, + owner: string, + repo: string, + bot: Bot + ): Promise { + const cachedBugs = await this.getBugHistory(owner, repo) + if (cachedBugs.length === 0) return [] + + const queryEmbedding = await this.getEmbedding(codeChange, bot) + if (!queryEmbedding) return [] + + const scored: SimilarBugResult[] = [] + + for (const bug of cachedBugs) { + let bugEmbedding = this.embeddingCache.get(bug.id) + if (!bugEmbedding) { + bugEmbedding = await this.getEmbedding( + `${bug.title} ${bug.description}`, + bot + ) + if (bugEmbedding) { + this.embeddingCache.set(bug.id, bugEmbedding) + } + } + + if (bugEmbedding) { + const similarity = this.cosineSimilarity(queryEmbedding, bugEmbedding) + if (similarity >= this.SIMILARITY_THRESHOLD) { + scored.push({ + pattern: bug, + similarity, + context: this.extractRelevantContext(bug, filename) + }) + } + } + } + + scored.sort((a, b) => b.similarity - a.similarity) + return scored.slice(0, this.MAX_RESULTS) + } + + private async getBugHistory( + owner: string, + repo: string + ): Promise { + const cacheKey = `${owner}/${repo}` + if (this.bugCache.has(cacheKey)) { + return this.bugCache.get(cacheKey)! + } + + const bugs: BugPattern[] = [] + + try { + const ghOutput = prixExec( + `gh issue list --repo ${owner}/${repo} --state all --limit 100 --json number,title,body,labels`, + {encoding: 'utf8', timeout: 15000} + ) + + const issues = JSON.parse(ghOutput) + + for (const issue of issues) { + const labels = issue.labels || [] + const hasBugLabel = labels.some( + (l: any) => + l.name.toLowerCase().includes('bug') || + l.name.toLowerCase().includes('fix') || + l.name.toLowerCase().includes('defect') + ) + + if ( + hasBugLabel || + issue.body.toLowerCase().includes('crash') || + issue.body.toLowerCase().includes('error') || + issue.body.toLowerCase().includes('failure') + ) { + bugs.push({ + id: `issue-${issue.number}`, + title: issue.title, + description: issue.body || '', + severity: this.inferSeverity(issue.title, issue.body, labels), + files: this.extractFiles(issue.body), + lines: this.extractLines(issue.body), + fix: this.extractFix(issue.body) + }) + } + } + } catch (e) { + // gh CLI not available or no access + } + + try { + const prOutput = prixExec( + `gh pr list --repo ${owner}/${repo} --state all --limit 100 --json number,title,body,labels`, + {encoding: 'utf8', timeout: 15000} + ) + + const prs = JSON.parse(prOutput) + + for (const pr of prs) { + if ( + pr.title.toLowerCase().includes('fix') || + pr.title.toLowerCase().includes('bug') || + pr.title.toLowerCase().includes('patch') + ) { + bugs.push({ + id: `pr-${pr.number}`, + title: pr.title, + description: pr.body || '', + severity: this.inferSeverity(pr.title, pr.body, pr.labels), + files: this.extractFiles(pr.body), + lines: this.extractLines(pr.body), + fix: this.extractFix(pr.body) + }) + } + } + } catch (e) { + // gh CLI not available or no access + } + + try { + const commitsOutput = prixExec( + `git log --all --grep="fix\|bug\|crash\|error" --oneline -100`, + {encoding: 'utf8', timeout: 15000} + ) + + const commitLines = commitsOutput.split('\n').filter(l => l.trim()) + for (const line of commitLines) { + const match = line.match(/^([a-f0-9]+)\s+(.+)/) + if (match) { + bugs.push({ + id: `commit-${match[1].substring(0, 7)}`, + title: match[2], + description: line, + severity: this.inferSeverity(match[2], '', []), + files: [], + lines: [], + fix: match[1] + }) + } + } + } catch (e) {} + + this.bugCache.set(cacheKey, bugs) + return bugs + } + + private inferSeverity( + title: string, + body: string, + labels: any[] + ): BugPattern['severity'] { + const text = `${title} ${body}`.toLowerCase() + + if ( + labels.some( + (l: any) => + l.name.toLowerCase().includes('critical') || + l.name.toLowerCase().includes('p0') + ) + ) { + return 'critical' + } + if ( + text.includes('security') || + text.includes('vulnerability') || + text.includes('breach') || + text.includes('leak') + ) { + return 'critical' + } + if ( + text.includes('data loss') || + text.includes('corruption') || + text.includes('crash') + ) { + return 'major' + } + if ( + labels.some( + (l: any) => + l.name.toLowerCase().includes('major') || + l.name.toLowerCase().includes('p1') + ) + ) { + return 'major' + } + if ( + labels.some( + (l: any) => + l.name.toLowerCase().includes('minor') || + l.name.toLowerCase().includes('p2') + ) + ) { + return 'minor' + } + return 'info' + } + + private extractFiles(body: string): string[] { + const files: string[] = [] + const patterns = [ + /src\/([^\s)]+\.[a-z]+)/gi, + /lib\/([^\s)]+\.[a-z]+)/gi, + /([a-zA-Z0-9_/-]+\.[a-z]+):/gi, + /\*\*(?:changed|modified|file):\s*`([^`]+)`/gi + ] + + for (const pattern of patterns) { + let match + while ((match = pattern.exec(body)) !== null) { + const file = match[1] || match[0] + if (!files.includes(file) && !file.includes('node_modules')) { + files.push(file) + } + } + } + + return files + } + + private extractLines(body: string): string[] { + const lines: string[] = [] + const pattern = /(?::)(\d+)(?::|\s)/g + let match + + while ((match = pattern.exec(body)) !== null) { + lines.push(match[1]) + } + + return lines + } + + private extractFix(body: string): string | undefined { + const fixPatterns = [ + /\*\*Fixed:\*\*[\s\n]+```[\s\S]*?```/, + /\*\*Solution:\*\*[\s\n]+```[\s\S]*?```/, + /```(?:fix|solution|patch)[\s\S]*?```/ + ] + + for (const pattern of fixPatterns) { + const match = body.match(pattern) + if (match) { + return match[0].replace(/```[a-z]*\n?/g, '').trim() + } + } + + return undefined + } + + private extractRelevantContext(bug: BugPattern, targetFile: string): string { + const context: string[] = [] + + if (bug.title) { + context.push(`**Title:** ${bug.title}`) + } + + if (bug.severity) { + context.push(`**Severity:** ${bug.severity}`) + } + + if (bug.files.length > 0) { + const relevantFiles = bug.files.filter( + f => f.includes(targetFile) || targetFile.includes(f) + ) + if (relevantFiles.length > 0) { + context.push(`**Files:** ${relevantFiles.join(', ')}`) + } + } + + if (bug.fix) { + context.push(`**Fix:** ${bug.fix.substring(0, 200)}...`) + } + + return context.join(' | ') + } + + private async getEmbedding( + text: string, + bot: Bot + ): Promise { + const textHash = this.simpleHash(text) + if (this.embeddingCache.has(textHash)) { + return this.embeddingCache.get(textHash)! + } + + try { + const [response] = await bot.chat( + `Generate a semantic embedding vector for the following text. Respond ONLY with a JSON array of 384 numbers representing the embedding. Do not include any other text.\n\nText: ${text.substring( + 0, + 1000 + )}`, + {} + ) + + const numbers = response + .replace(/[[\]]/g, '') + .split(',') + .map(s => parseFloat(s.trim())) + .filter(n => !isNaN(n)) + + if (numbers.length >= 100) { + const embedding = numbers.slice(0, 384) + this.embeddingCache.set(textHash, embedding) + return embedding + } + } catch (e) { + // Fallback: use TF-IDF-like hashing + } + + return this.generateFallbackEmbedding(text) + } + + private generateFallbackEmbedding(text: string): number[] { + const words = text + .toLowerCase() + .split(/\W+/) + .filter(w => w.length > 2) + const embedding = new Array(384).fill(0) + + const seedPhrases = [ + 'security', + 'bug', + 'crash', + 'memory', + 'leak', + 'null', + 'undefined', + 'race', + 'condition', + 'deadlock', + 'timeout', + 'performance', + 'scalability', + 'api', + 'database', + 'cache', + 'auth', + 'validation', + 'error', + 'exception' + ] + + for (let i = 0; i < words.length; i++) { + const word = words[i] + for (let j = 0; j < seedPhrases.length; j++) { + if (word.includes(seedPhrases[j])) { + embedding[(j * 20) % 384] += 1 + embedding[(j * 7 + i) % 384] += 1 + } + } + } + + const magnitude = Math.sqrt( + embedding.reduce((sum, val) => sum + val * val, 0) + ) + if (magnitude > 0) { + for (let i = 0; i < embedding.length; i++) { + embedding[i] /= magnitude + } + } + + return embedding + } + + private cosineSimilarity(a: number[], b: number[]): number { + if (a.length !== b.length) return 0 + + let dotProduct = 0 + let normA = 0 + let normB = 0 + + for (let i = 0; i < a.length; i++) { + dotProduct += a[i] * b[i] + normA += a[i] * a[i] + normB += b[i] * b[i] + } + + const denominator = Math.sqrt(normA) * Math.sqrt(normB) + if (denominator === 0) return 0 + + return dotProduct / denominator + } + + private simpleHash(text: string): string { + let hash = 0 + for (let i = 0; i < text.length; i++) { + const char = text.charCodeAt(i) + hash = (hash << 5) - hash + char + hash = hash & hash + } + return hash.toString(36) + } + + formatSimilarBugWarning(results: SimilarBugResult[]): string { + if (results.length === 0) return '' + + let output = `\n\n---\n### ๐Ÿ” Similar Historical Bugs Detected\n\n` + + for (const result of results) { + const similarityPct = Math.round(result.similarity * 100) + + output += `**โš ๏ธ ${result.pattern.title}** (${similarityPct}% match)\n` + output += `${result.context}\n` + + if (result.pattern.fix) { + output += `> **Historical Fix:** \`\`\`\n${result.pattern.fix.substring( + 0, + 300 + )}\n\`\`\`\n` + } + + output += `---\n` + } + + output += `*This PR contains patterns similar to ${results.length} historical bug(s). Review the fixes above to avoid repeating the same mistakes.*\n` + + return output + } +} + +export const semanticBugSearch = new SemanticBugSearch() diff --git a/src/symbol-graph-cache.ts b/src/symbol-graph-cache.ts new file mode 100644 index 0000000000000000000000000000000000000000..23aa5dc786a0a1d40d8d7cb330c377d960b80b56 --- /dev/null +++ b/src/symbol-graph-cache.ts @@ -0,0 +1,367 @@ +import {readFileSync, writeFileSync, existsSync, statSync} from 'fs' +import {join, dirname} from 'path' +import {Symbol, DependencyEdge, SymbolGraph} from './symbol-graph' + +export interface FileCacheEntry { + mtime: number + size: number + contentHash: string + symbols: Symbol[] + edges: DependencyEdge[] + parsedAt: number +} + +export interface GraphCache { + version: string + repoPath: string + lastUpdated: number + fileEntries: Map + globalEdges: DependencyEdge[] +} + +const CACHE_VERSION = '2.0.0' + +function getPersistBaseDir(): string { + if (process.env.PRIX_DATA_DIR) return process.env.PRIX_DATA_DIR + if (process.env.HF_HOME) return join(process.env.HF_HOME, 'prix-data') + if (process.env.HUGGING_FACE_HUB_TOKEN) return '/tmp/prix-hf' + return '/tmp/prix' +} + +export class SymbolGraphCache { + private cache: Map = new Map() + private repoPath: string + private persistPath: string + private cacheHits = 0 + private cacheMisses = 0 + + constructor(repoPath: string, persistDir?: string) { + this.repoPath = repoPath + const baseDir = persistDir || getPersistBaseDir() + this.persistPath = join(baseDir, 'symbol-graph-cache') + this.load() + } + + get(file: string): FileCacheEntry | undefined { + if (!existsSync(file)) return undefined + + try { + const stats = statSync(file) + const cached = this.cache.get(file) + + if (!cached) { + this.cacheMisses++ + return undefined + } + + if (cached.mtime !== stats.mtimeMs || cached.size !== stats.size) { + this.cacheMisses++ + this.cache.delete(file) + return undefined + } + + this.cacheHits++ + return cached + } catch { + return undefined + } + } + + set(file: string, entry: FileCacheEntry): void { + this.cache.set(file, entry) + } + + invalidate(file: string): void { + this.cache.delete(file) + } + + invalidateContaining(changedFiles: string[]): Set { + const affectedFiles = new Set() + const changedSet = new Set(changedFiles.map(f => this.normalizePath(f))) + + for (const cachedFile of this.cache.keys()) { + const normalizedCached = this.normalizePath(cachedFile) + + if (changedSet.has(normalizedCached)) { + affectedFiles.add(cachedFile) + continue + } + + const cached = this.cache.get(cachedFile) + if (!cached) continue + + for (const edge of cached.edges) { + const normalizedEdge = this.normalizePath(edge.to) + if (changedSet.has(normalizedEdge)) { + affectedFiles.add(cachedFile) + break + } + + const normalizedFrom = this.normalizePath(edge.from) + if (changedSet.has(normalizedFrom)) { + affectedFiles.add(cachedFile) + break + } + } + + for (const symbol of cached.symbols) { + for (const imp of symbol.imports) { + const normalizedImp = this.normalizeImport(imp) + if (this.pathMatchesImport(normalizedImp, changedSet)) { + affectedFiles.add(cachedFile) + break + } + } + } + } + + for (const affected of affectedFiles) { + this.cache.delete(affected) + } + + return affectedFiles + } + + private normalizePath(p: string): string { + return p.replace(/\\/g, '/').toLowerCase() + } + + private normalizeImport(imp: string): string { + return imp.replace(/['"]/g, '').replace(/\\/g, '/').toLowerCase() + } + + private pathMatchesImport(imp: string, changedSet: Set): boolean { + for (const changed of changedSet) { + if (imp.endsWith(changed) || changed.endsWith(imp)) { + return true + } + const impParts = imp.split('/') + const changedParts = changed.split('/') + if ( + impParts[impParts.length - 1] === changedParts[changedParts.length - 1] + ) { + return true + } + } + return false + } + + getStats(): {hits: number; misses: number; size: number; hitRate: number} { + const total = this.cacheHits + this.cacheMisses + return { + hits: this.cacheHits, + misses: this.cacheMisses, + size: this.cache.size, + hitRate: total > 0 ? this.cacheHits / total : 0 + } + } + + prune(maxAge: number = 7 * 24 * 60 * 60 * 1000): number { + const now = Date.now() + let pruned = 0 + + for (const [file, entry] of this.cache.entries()) { + if (now - entry.parsedAt > maxAge) { + this.cache.delete(file) + pruned++ + } + } + + return pruned + } + + clear(): void { + this.cache.clear() + this.cacheHits = 0 + this.cacheMisses = 0 + } + + persist(): void { + try { + const {mkdirSync, writeFileSync, existsSync} = require('fs') + if (!existsSync(this.persistPath)) { + mkdirSync(this.persistPath, {recursive: true}) + } + + const cacheData: any = { + version: CACHE_VERSION, + repoPath: this.repoPath, + lastUpdated: Date.now(), + entries: Array.from(this.cache.entries()) + } + + const cacheFile = join( + this.persistPath, + `${this.sanitizeFilename(this.repoPath)}.json` + ) + writeFileSync(cacheFile, JSON.stringify(cacheData), 'utf8') + } catch (e) { + console.warn(`Failed to persist graph cache: ${e}`) + } + } + + private load(): void { + try { + const {readFileSync, existsSync} = require('fs') + const cacheFile = join( + this.persistPath, + `${this.sanitizeFilename(this.repoPath)}.json` + ) + + if (!existsSync(cacheFile)) return + + const data = JSON.parse(readFileSync(cacheFile, 'utf8')) + + if (data.version !== CACHE_VERSION) { + console.log('Graph cache version mismatch, rebuilding...') + return + } + + if (data.repoPath !== this.repoPath) { + console.log('Repo path changed, rebuilding...') + return + } + + const entries = new Map(data.entries) + this.cache = entries + } catch (e) { + console.warn(`Failed to load graph cache: ${e}`) + } + } + + private sanitizeFilename(path: string): string { + return path.replace(/[^a-z0-9]/gi, '_').substring(0, 100) + } + + rebuildIfNeeded(changedFiles: string[]): { + rebuild: boolean + filesToRebuild: Set + } { + if (changedFiles.length === 0) { + return {rebuild: false, filesToRebuild: new Set()} + } + + const filesToRebuild = this.invalidateContaining(changedFiles) + + return { + rebuild: filesToRebuild.size > 0 || this.cache.size === 0, + filesToRebuild + } + } +} + +export interface IncrementalUpdateResult { + updatedFiles: string[] + removedSymbols: number + addedSymbols: number + cacheStats: {hits: number; misses: number; hitRate: number} +} + +export class IncrementalSymbolGraph { + private cache: SymbolGraphCache + private graph: SymbolGraph + private pendingUpdates: Map = new Map() + + constructor(repoPath: string, persistDir?: string) { + this.cache = new SymbolGraphCache(repoPath, persistDir) + this.graph = { + symbols: new Map(), + edges: [], + fileIndex: new Map() + } + } + + async update( + changedFiles: string[], + deletedFiles: string[] + ): Promise { + for (const file of deletedFiles) { + this.removeFile(file) + } + + const {filesToRebuild} = this.cache.rebuildIfNeeded(changedFiles) + + let removedSymbols = 0 + let addedSymbols = 0 + + for (const file of filesToRebuild) { + const removed = this.removeFile(file) + removedSymbols += removed + } + + for (const file of changedFiles) { + if (existsSync(file)) { + const added = await this.addOrUpdateFile(file) + addedSymbols += added + } + } + + this.cache.persist() + + return { + updatedFiles: [...filesToRebuild, ...changedFiles].filter(f => + existsSync(f) + ), + removedSymbols, + addedSymbols, + cacheStats: this.cache.getStats() + } + } + + private removeFile(file: string): number { + const cached = this.cache.get(file) + if (cached) { + for (const symbol of cached.symbols) { + this.graph.symbols.delete(`${file}:${symbol.name}`) + } + this.graph.fileIndex.delete(file) + this.graph.edges = this.graph.edges.filter( + e => !e.from.startsWith(file) && !e.to.startsWith(file) + ) + this.cache.invalidate(file) + return cached.symbols.length + } + return 0 + } + + private async addOrUpdateFile(file: string): Promise { + const existing = this.cache.get(file) + if (existing) { + for (const symbol of existing.symbols) { + this.graph.symbols.set(`${file}:${symbol.name}`, symbol) + } + this.graph.fileIndex.set(file, existing.symbols) + this.graph.edges.push(...existing.edges) + return existing.symbols.length + } + return 0 + } + + getGraph(): SymbolGraph { + return this.graph + } + + getCacheStats() { + return this.cache.getStats() + } + + clearCache(): void { + this.cache.clear() + this.graph = { + symbols: new Map(), + edges: [], + fileIndex: new Map() + } + } + + persist(): void { + this.cache.persist() + } +} + +export const createIncrementalGraph = ( + repoPath: string, + persistDir?: string +): IncrementalSymbolGraph => { + return new IncrementalSymbolGraph(repoPath, persistDir) +} diff --git a/src/symbol-graph.ts b/src/symbol-graph.ts new file mode 100644 index 0000000000000000000000000000000000000000..156ec13382da40c9b2315aca93e0e98780958788 --- /dev/null +++ b/src/symbol-graph.ts @@ -0,0 +1,1188 @@ +/* eslint-disable no-console */ +import Parser, {Tree, Query} from 'web-tree-sitter' +import {prixExec} from './utils' +import {Project, SyntaxKind} from 'ts-morph' +import {SymbolGraphCache, IncrementalSymbolGraph} from './symbol-graph-cache' +import {createHash} from 'crypto' +import {discoverFiles, FileDiscoverer} from './file-discoverer' +const fs = require('fs') + +export interface Symbol { + name: string + type: + | 'function' + | 'class' + | 'interface' + | 'type' + | 'variable' + | 'method' + | 'const' + file: string + line: number + exports: string[] + imports: string[] + references: string[] +} + +export interface DependencyEdge { + from: string + to: string + type: 'imports' | 'calls' | 'extends' | 'implements' | 'uses' +} + +export interface SymbolGraph { + symbols: Map + edges: DependencyEdge[] + fileIndex: Map +} + +export interface RepoContext { + symbolGraph: SymbolGraph + typeHierarchy: Map + callGraph: Map + architecturalLayers: Map +} + +export interface ArchitecturalViolation { + from: string + to: string + fromLayer: string + toLayer: string + severity: 'critical' | 'major' | 'minor' + description: string +} + +const PARSER_DIR = process.env.PARSER_DIR || '/app/parsers' + +const LANGUAGE_LOADERS: Record Promise> = { + '.ts': async () => Parser.Language.load(`${PARSER_DIR}/tree-sitter-typescript.wasm`), + '.tsx': async () => Parser.Language.load(`${PARSER_DIR}/tree-sitter-tsx.wasm`), + '.js': async () => Parser.Language.load(`${PARSER_DIR}/tree-sitter-javascript.wasm`), + '.jsx': async () => Parser.Language.load(`${PARSER_DIR}/tree-sitter-javascript.wasm`), + '.go': async () => Parser.Language.load(`${PARSER_DIR}/tree-sitter-go.wasm`), + '.py': async () => Parser.Language.load(`${PARSER_DIR}/tree-sitter-python.wasm`), + '.rs': async () => { + try { + return Parser.Language.load(`${PARSER_DIR}/tree-sitter-rust.wasm`) + } catch { + return null + } + }, + '.cpp': async () => { + try { + return Parser.Language.load(`${PARSER_DIR}/tree-sitter-cpp.wasm`) + } catch { + return null + } + }, + '.c': async () => { + try { + return Parser.Language.load(`${PARSER_DIR}/tree-sitter-c.wasm`) + } catch { + return null + } + }, + '.java': async () => { + try { + return Parser.Language.load(`${PARSER_DIR}/tree-sitter-java.wasm`) + } catch { + return null + } + } +} + +const LANGUAGE_LOADER_CACHE_TTL_MS = 30 * 60 * 1000 +const LANGUAGE_LOADER_MAX_SIZE = 10 + +function computeContentHash(content: string): string { + return createHash('sha256').update(content).digest('hex').substring(0, 16) +} + +interface CachedLanguage { + language: any + cachedAt: number +} + +export class UnifiedContextEngine { + private graph: SymbolGraph = { + symbols: new Map(), + edges: [], + fileIndex: new Map() + } + private project: Project + private languageCache: Map = new Map() + private graphCache!: SymbolGraphCache + private incrementalGraph!: IncrementalSymbolGraph + private repoPath: string = '' + + constructor() { + this.project = new Project() + } + + async initialize(repoPath: string): Promise { + this.repoPath = repoPath + this.graphCache = new SymbolGraphCache(repoPath) + this.incrementalGraph = new IncrementalSymbolGraph(repoPath) + await this.buildSymbolGraph(repoPath) + return this.buildRepoContext() + } + + async updateForChanges( + changedFiles: string[], + deletedFiles: string[] + ): Promise<{ + updatedFiles: string[] + cacheStats: {hits: number; misses: number; hitRate: number} + }> { + if (!this.incrementalGraph) { + return {updatedFiles: [], cacheStats: {hits: 0, misses: 0, hitRate: 0}} + } + + const result = await this.incrementalGraph.update( + changedFiles, + deletedFiles + ) + return { + updatedFiles: result.updatedFiles, + cacheStats: result.cacheStats + } + } + + private async buildSymbolGraph(repoPath: string): Promise { + try { + await Parser.init() + } catch (e) { + console.log(`Tree-sitter init failed: ${e}, using fallback`) + return + } + + const discovered = discoverFiles(repoPath, { + include: [ + '.ts', + '.tsx', + '.js', + '.jsx', + '.go', + '.py', + '.rs', + '.cpp', + '.c', + '.h', + '.java' + ] + }) + + const filesByExt = new FileDiscoverer().groupByExtension(discovered) + + const tsFiles = [ + ...(filesByExt.get('.ts') || []), + ...(filesByExt.get('.tsx') || []), + ...(filesByExt.get('.js') || []), + ...(filesByExt.get('.jsx') || []) + ].map(f => f.path) + + const goFiles = (filesByExt.get('.go') || []).map(f => f.path) + const pyFiles = (filesByExt.get('.py') || []).map(f => f.path) + const rsFiles = (filesByExt.get('.rs') || []).map(f => f.path) + const cppFiles = [ + ...(filesByExt.get('.cpp') || []), + ...(filesByExt.get('.c') || []), + ...(filesByExt.get('.h') || []), + ...(filesByExt.get('.hpp') || []), + ...(filesByExt.get('.java') || []) + ].map(f => f.path) + + console.log( + `[Graph] Discovered: ${tsFiles.length} TS/JS, ${goFiles.length} Go, ${pyFiles.length} Python, ${rsFiles.length} Rust, ${cppFiles.length} C++/Java files` + ) + + await Promise.all([ + this.processTSFilesWithCache(tsFiles), + this.processGoFilesWithCache(goFiles), + this.processPythonFilesWithCache(pyFiles), + this.processRustFilesWithCache(rsFiles), + this.processCppJavaFilesWithCache(cppFiles) + ]) + + this.buildDependencyEdges() + this.graphCache?.persist() + } + + private async processTSFilesWithCache(files: string[]): Promise { + const uncachedFiles: string[] = [] + + for (const file of files) { + const cached = this.graphCache?.get(file) + if (cached) { + for (const sym of cached.symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym) + } + if (!this.graph.fileIndex.has(file)) { + this.graph.fileIndex.set(file, []) + } + this.graph.fileIndex.get(file)!.push(...cached.symbols) + this.graph.edges.push(...cached.edges) + } else { + uncachedFiles.push(file) + } + } + + if (uncachedFiles.length === 0) { + console.log( + `[GraphCache] TS: All ${files.length} files served from cache` + ) + return + } + + console.log( + `[GraphCache] TS: ${uncachedFiles.length}/${files.length} files need parsing` + ) + + for (const file of uncachedFiles) { + try { + const content = fs.readFileSync(file, 'utf8') + await this.analyzeTypeScriptFile(file, content) + } catch (e) { + this.analyzeWithTsMorph(file) + } + } + } + + private async processGoFilesWithCache(files: string[]): Promise { + const uncachedFiles: string[] = [] + + for (const file of files) { + const cached = this.graphCache?.get(file) + if (cached) { + for (const sym of cached.symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym) + } + if (!this.graph.fileIndex.has(file)) { + this.graph.fileIndex.set(file, []) + } + this.graph.fileIndex.get(file)!.push(...cached.symbols) + this.graph.edges.push(...cached.edges) + } else { + uncachedFiles.push(file) + } + } + + if (uncachedFiles.length === 0) { + console.log( + `[GraphCache] Go: All ${files.length} files served from cache` + ) + return + } + + console.log( + `[GraphCache] Go: ${uncachedFiles.length}/${files.length} files need parsing` + ) + + for (const file of uncachedFiles) { + try { + const content = fs.readFileSync(file, 'utf8') + await this.analyzeGoFile(file, content) + } catch (e) { + // Skip files that can't be read + } + } + } + + private async processPythonFilesWithCache(files: string[]): Promise { + const uncachedFiles: string[] = [] + + for (const file of files) { + const cached = this.graphCache?.get(file) + if (cached) { + for (const sym of cached.symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym) + } + if (!this.graph.fileIndex.has(file)) { + this.graph.fileIndex.set(file, []) + } + this.graph.fileIndex.get(file)!.push(...cached.symbols) + this.graph.edges.push(...cached.edges) + } else { + uncachedFiles.push(file) + } + } + + if (uncachedFiles.length === 0) { + console.log( + `[GraphCache] Python: All ${files.length} files served from cache` + ) + return + } + + console.log( + `[GraphCache] Python: ${uncachedFiles.length}/${files.length} files need parsing` + ) + + for (const file of uncachedFiles) { + try { + const content = fs.readFileSync(file, 'utf8') + await this.analyzePythonFile(file, content) + } catch (e) { + // Skip files that can't be read + } + } + } + + private async analyzeRustFile(file: string, content: string): Promise { + try { + const lang = await this.getLanguage(file) + if (!lang) return + const parser = new Parser() + parser.setLanguage(lang) + + const tree = parser.parse(content) + const symbols: Symbol[] = [] + + const fnQuery = lang.query(` + (function_item name: (identifier) @name) @func + (struct_item name: (type_identifier) @name) @struct + (enum_item name: (type_identifier) @name) @enum + (trait_item name: (type_identifier) @name) @trait + `) + + for (const match of fnQuery.captures(tree.rootNode)) { + const name = match.node.text + let type: Symbol['type'] = 'function' + if (match.name === 'struct') type = 'class' + if (match.name === 'enum') type = 'type' + if (match.name === 'trait') type = 'interface' + + symbols.push({ + name, + type, + file, + line: match.node.startPosition.row, + exports: [], + imports: [], + references: [] + }) + } + + for (const sym of symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym) + } + if (!this.graph.fileIndex.has(file)) this.graph.fileIndex.set(file, []) + this.graph.fileIndex.get(file)!.push(...symbols) + + if (this.graphCache) { + const {statSync} = require('fs') + const stats = statSync(file) + this.graphCache.set(file, { + mtime: stats.mtimeMs, + size: stats.size, + contentHash: computeContentHash(content), + symbols, + edges: [], + parsedAt: Date.now() + }) + } + } catch {} + } + + private async analyzeCppJavaFile( + file: string, + content: string + ): Promise { + try { + const lang = await this.getLanguage(file) + if (!lang) return + const parser = new Parser() + parser.setLanguage(lang) + + const tree = parser.parse(content) + const symbols: Symbol[] = [] + + const query = lang.query(` + (class_declaration name: (identifier) @name) @class + (method_declaration name: (identifier) @name) @method + (function_definition declarator: (function_declarator declarator: (identifier) @name)) @func + `) + + for (const match of query.captures(tree.rootNode)) { + const name = match.node.text + let type: Symbol['type'] = 'variable' + if (match.name === 'class') type = 'class' + if (match.name === 'method') type = 'method' + if (match.name === 'func') type = 'function' + + symbols.push({ + name, + type, + file, + line: match.node.startPosition.row, + exports: [], + imports: [], + references: [] + }) + } + + for (const sym of symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym) + } + if (!this.graph.fileIndex.has(file)) this.graph.fileIndex.set(file, []) + this.graph.fileIndex.get(file)!.push(...symbols) + + if (this.graphCache) { + const {statSync} = require('fs') + const stats = statSync(file) + this.graphCache.set(file, { + mtime: stats.mtimeMs, + size: stats.size, + contentHash: computeContentHash(content), + symbols, + edges: [], + parsedAt: Date.now() + }) + } + } catch {} + } + + private async processRustFilesWithCache(files: string[]): Promise { + const uncached: string[] = [] + for (const file of files) { + const cached = this.graphCache?.get(file) + if (cached) { + for (const sym of cached.symbols) + this.graph.symbols.set(`${file}:${sym.name}`, sym) + if (!this.graph.fileIndex.has(file)) this.graph.fileIndex.set(file, []) + this.graph.fileIndex.get(file)!.push(...cached.symbols) + } else { + uncached.push(file) + } + } + + for (const file of uncached) { + try { + const content = fs.readFileSync(file, 'utf8') + await this.analyzeRustFile(file, content) + } catch {} + } + } + + private async processCppJavaFilesWithCache(files: string[]): Promise { + const uncached: string[] = [] + for (const file of files) { + const cached = this.graphCache?.get(file) + if (cached) { + for (const sym of cached.symbols) + this.graph.symbols.set(`${file}:${sym.name}`, sym) + if (!this.graph.fileIndex.has(file)) this.graph.fileIndex.set(file, []) + this.graph.fileIndex.get(file)!.push(...cached.symbols) + } else { + uncached.push(file) + } + } + + for (const file of uncached) { + try { + const content = fs.readFileSync(file, 'utf8') + await this.analyzeCppJavaFile(file, content) + } catch {} + } + } + + private async analyzeTypeScriptFile( + file: string, + content: string + ): Promise { + const lang = await this.getLanguage(file) + if (!lang) return + + const parser = new Parser() + parser.setLanguage(lang) + + try { + const tree = parser.parse(content) + const symbols = this.extractTSSymbols(file, tree, lang) + const edges = this.extractTSEdges(file, tree, lang, symbols) + + for (const sym of symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym) + if (!this.graph.fileIndex.has(file)) { + this.graph.fileIndex.set(file, []) + } + this.graph.fileIndex.get(file)!.push(sym) + } + + this.graph.edges.push(...edges) + + if (this.graphCache) { + try { + const {statSync} = require('fs') + const stats = statSync(file) + this.graphCache.set(file, { + mtime: stats.mtimeMs, + size: stats.size, + contentHash: computeContentHash(content), + symbols, + edges, + parsedAt: Date.now() + }) + } catch {} + } + } catch (e) { + this.analyzeWithTsMorph(file) + } + } + + private extractTSEdges( + file: string, + tree: Tree, + lang: any, + symbols: Symbol[] + ): DependencyEdge[] { + const edges: DependencyEdge[] = [] + + for (const sym of symbols) { + for (const imp of sym.imports) { + edges.push({ + from: file, + to: imp, + type: 'imports' + }) + } + } + + return edges + } + + private extractTSSymbols(file: string, tree: Tree, lang: any): Symbol[] { + const symbols: Symbol[] = [] + + const query = lang.query(` + (function_declaration + name: (identifier) @name + parameters: (parameter_list) @params) @func + (class_declaration + name: (identifier) @name + heritage: (class_heritage)?) @class + (interface_declaration + name: (type_identifier) @name) @iface + (type_alias_declaration + name: (type_identifier) @name) @type + (variable_declaration + name: (identifier) @name + value: (assignment_expression) @val) @var + (method_definition + name: (property_identifier) @name) @method + `) + + const queryMatches = query.captures(tree.rootNode) + + for (const match of queryMatches) { + const name = match.node.text + const symbol: Symbol = { + name, + type: this.inferSymbolType(match.name), + file, + line: match.node.startPosition.row, + exports: [], + imports: [], + references: [] + } + symbols.push(symbol) + } + + return symbols + } + + private inferSymbolType(captureName: string): Symbol['type'] { + switch (captureName) { + case 'func': + return 'function' + case 'class': + return 'class' + case 'iface': + return 'interface' + case 'type': + return 'type' + case 'var': + return 'variable' + case 'method': + return 'method' + default: + return 'variable' + } + } + + private analyzeWithTsMorph(file: string): void { + try { + const sourceFile = this.project.addSourceFileAtPath(file) + + sourceFile.getExportedDeclarations().forEach((declarations, name) => { + const decl = declarations[0] + if (!decl) return + + const symbol: Symbol = { + name, + type: this.getTsMorphSymbolType(decl.getKind()), + file, + line: decl.getStartLineNumber(), + exports: [name], + imports: this.extractImports(sourceFile), + references: [] + } + + this.graph.symbols.set(`${file}:${name}`, symbol) + + if (!this.graph.fileIndex.has(file)) { + this.graph.fileIndex.set(file, []) + } + this.graph.fileIndex.get(file)!.push(symbol) + }) + } catch (e) { + // Skip files that can't be parsed + } + } + + private getTsMorphSymbolType(kind: SyntaxKind): Symbol['type'] { + const map: Record = { + [SyntaxKind.FunctionDeclaration]: 'function', + [SyntaxKind.ClassDeclaration]: 'class', + [SyntaxKind.InterfaceDeclaration]: 'interface', + [SyntaxKind.TypeAliasDeclaration]: 'type', + [SyntaxKind.VariableDeclaration]: 'const', + [SyntaxKind.MethodDeclaration]: 'method', + [SyntaxKind.PropertyDeclaration]: 'variable' + } + return map[kind] || 'variable' + } + + private extractImports(sourceFile: any): string[] { + const imports: string[] = [] + try { + const importDefs = sourceFile.getImportDeclarations() + for (const imp of importDefs) { + const moduleName = imp.getModuleSpecifier().getText() + imports.push(moduleName.replace(/['"]/g, '')) + } + } catch (e) {} + return imports + } + + private async extractGoSymbolsTreeSitter( + file: string, + content: string + ): Promise { + const symbols: Symbol[] = [] + + try { + const lang = await this.getLanguage(file) + if (!lang) return this.extractGoSymbolsRegex(content, file) + + const parser = new Parser() + parser.setLanguage(lang) + const tree = parser.parse(content) + + const funcQuery = lang.query(` + (function_declaration + name: (identifier) @funcName) @func + (method_declaration + receiver: (parameter_list) + name: (field_identifier) @methodName) @method + (type_declaration + name: (type_identifier) @typeName) @type + `) + + for (const match of funcQuery.captures(tree.rootNode)) { + const name = match.node.text + const line = match.node.startPosition.row + 1 + + if (match.name === 'funcName') { + const isExported = name[0] === name[0].toUpperCase() + symbols.push({ + name, + type: 'function', + file, + line, + exports: isExported ? [name] : [], + imports: this.extractGoImports(content), + references: [] + }) + } else if (match.name === 'methodName') { + const isExported = name[0] === name[0].toUpperCase() + symbols.push({ + name, + type: 'method', + file, + line, + exports: isExported ? [name] : [], + imports: this.extractGoImports(content), + references: [] + }) + } else if (match.name === 'typeName') { + symbols.push({ + name, + type: 'class', + file, + line, + exports: [name], + imports: [], + references: [] + }) + } + } + } catch (e) { + return this.extractGoSymbolsRegex(content, file) + } + + return symbols + } + + private extractGoSymbolsRegex(content: string, file: string): Symbol[] { + const symbols: Symbol[] = [] + const lines = content.split('\n') + + for (let i = 0; i < lines.length; i++) { + const line = lines[i] + + let match = line.match(/^func\s+(\([^*]+\)\s+)?(\*)?([A-Z][a-zA-Z0-9_]*)/) + if (match) { + symbols.push({ + name: match[3], + type: match[2] ? 'method' : 'function', + file, + line: i + 1, + exports: match[3][0] === match[3][0].toUpperCase() ? [match[3]] : [], + imports: this.extractGoImports(content), + references: [] + }) + } + + match = line.match(/^type\s+([A-Z][a-zA-Z0-9_]*)\s+(struct|interface)/) + if (match) { + symbols.push({ + name: match[1], + type: match[2] === 'struct' ? 'class' : 'interface', + file, + line: i + 1, + exports: [match[1]], + imports: [], + references: [] + }) + } + } + + return symbols + } + + private async extractGoSymbols( + file: string, + content: string + ): Promise { + return this.extractGoSymbolsTreeSitter(file, content) + } + + private extractGoImports(content: string): string[] { + const imports: string[] = [] + const importMatch = content.match(/import\s+\(([\s\S]*?)\)/) + if (importMatch) { + const importBlock = importMatch[1] + const quoteMatches = importBlock.match(/"([^"]+)"/g) + if (quoteMatches) { + for (const m of quoteMatches) { + imports.push(m.replace(/"/g, '')) + } + } + } + return imports + } + + private async analyzeGoFile(file: string, content: string): Promise { + const symbols = await this.extractGoSymbols(file, content) + for (const sym of symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym) + if (!this.graph.fileIndex.has(file)) this.graph.fileIndex.set(file, []) + this.graph.fileIndex.get(file)!.push(sym) + } + } + + private async analyzePythonFile( + file: string, + content: string + ): Promise { + const symbols = this.extractPythonSymbols(file, content) + for (const sym of symbols) { + this.graph.symbols.set(`${file}:${sym.name}`, sym) + if (!this.graph.fileIndex.has(file)) this.graph.fileIndex.set(file, []) + this.graph.fileIndex.get(file)!.push(sym) + } + } + + private extractPythonSymbols(file: string, content: string): Symbol[] { + const symbols: Symbol[] = [] + const lines = content.split('\n') + + for (let i = 0; i < lines.length; i++) { + const line = lines[i] + + let match = line.match(/^class\s+([A-Z][a-zA-Z0-9_]*)/) + if (match) { + symbols.push({ + name: match[1], + type: 'class', + file, + line: i + 1, + exports: [match[1]], + imports: this.extractPythonImports(content), + references: [] + }) + } + + match = line.match(/^def\s+([a-z_][a-zA-Z0-9_]*)/) + if (match) { + symbols.push({ + name: match[1], + type: 'function', + file, + line: i + 1, + exports: [], + imports: [], + references: [] + }) + } + + match = line.match(/^([A-Z_][A-Z0-9_]*)\s*=/) + if (match) { + symbols.push({ + name: match[1], + type: 'const', + file, + line: i + 1, + exports: [match[1]], + imports: [], + references: [] + }) + } + } + + return symbols + } + + private extractPythonImports(content: string): string[] { + const imports: string[] = [] + const importRegex = /^(?:from\s+([.\w]+)\s+)?import\s+([.\w, ]+)/gm + let match + + while ((match = importRegex.exec(content)) !== null) { + const module = match[1] || match[2] + imports.push(module.trim()) + } + + return imports + } + + private async getLanguage(file: string): Promise { + const ext = file.substring(file.lastIndexOf('.')) + + if (this.languageCache.has(ext)) { + const cached = this.languageCache.get(ext)! + if (Date.now() - cached.cachedAt < LANGUAGE_LOADER_CACHE_TTL_MS) { + return cached.language + } + this.languageCache.delete(ext) + } + + const loader = LANGUAGE_LOADERS[ext] + if (loader) { + try { + const lang = await loader() + if (this.languageCache.size >= LANGUAGE_LOADER_MAX_SIZE) { + const oldestKey = Array.from(this.languageCache.entries()).sort( + (a, b) => a[1].cachedAt - b[1].cachedAt + )[0][0] + this.languageCache.delete(oldestKey) + } + this.languageCache.set(ext, {language: lang, cachedAt: Date.now()}) + return lang + } catch (e) { + return null + } + } + return null + } + + private buildDependencyEdges(): void { + for (const [key, sym] of this.graph.symbols) { + for (const imported of sym.imports) { + for (const [otherKey, otherSym] of this.graph.symbols) { + if ( + otherSym.file.includes(imported) || + imported.includes(otherSym.name) + ) { + this.graph.edges.push({ + from: key, + to: otherKey, + type: 'imports' + }) + } + } + } + } + } + + private buildRepoContext(): RepoContext { + const typeHierarchy = new Map() + const callGraph = new Map() + + for (const [key, sym] of this.graph.symbols) { + if (sym.type === 'class' || sym.type === 'interface') { + const children = this.findTypeChildren(sym.name) + typeHierarchy.set(key, children) + } + + if (sym.type === 'function' || sym.type === 'method') { + const callers = this.findFunctionCallers(sym.name) + callGraph.set(key, callers) + } + } + + const architecturalLayers = this.inferArchitecturalLayers() + + return { + symbolGraph: this.graph, + typeHierarchy, + callGraph, + architecturalLayers + } + } + + private findTypeChildren(typeName: string): string[] { + const children: string[] = [] + for (const [, sym] of this.graph.symbols) { + if (sym.type === 'class' && sym.exports.includes(typeName)) { + children.push(`${sym.file}:${sym.name}`) + } + } + return children + } + + private findFunctionCallers(funcName: string): string[] { + const callers: string[] = [] + for (const [key, sym] of this.graph.symbols) { + if (sym.references.includes(funcName)) { + callers.push(key) + } + } + return callers + } + + private inferFileLayer(file: string): string | null { + const lowerFile = file.toLowerCase() + + const patterns: Array<{layer: string; patterns: string[]}> = [ + { + layer: 'controller', + patterns: ['controller', 'handler', 'route', 'endpoint', 'api'] + }, + {layer: 'service', patterns: ['service', 'business', 'manager']}, + { + layer: 'repository', + patterns: ['repository', 'repo', 'dal', 'dataaccess'] + }, + {layer: 'model', patterns: ['model', 'entity', 'domain', 'schema']}, + {layer: 'util', patterns: ['util', 'helper', 'common', 'shared']} + ] + + for (const {layer, patterns: layerPatterns} of patterns) { + if (layerPatterns.some(p => lowerFile.includes(p))) { + return layer + } + } + + return null + } + + private isAllowedCrossing( + fromLayer: string, + toLayer: string, + allowedCrossings: Record + ): boolean { + const allowed = allowedCrossings[fromLayer] + return allowed ? allowed.includes(toLayer) : false + } + + private calculateViolationSeverity( + fromLayer: string, + toLayer: string + ): 'critical' | 'major' | 'minor' { + if (fromLayer === 'model' || toLayer === 'model') { + return fromLayer === 'model' ? 'critical' : 'major' + } + if ( + fromLayer === 'controller' && + (toLayer === 'repository' || toLayer === 'model') + ) { + return 'major' + } + return 'minor' + } + + inferArchitecturalLayers(): Map { + const layers = new Map() + + const layerPatterns = [ + { + layer: 'controller', + patterns: ['controller', 'handler', 'route', 'endpoint', 'api'] + }, + {layer: 'service', patterns: ['service', 'business', 'logic', 'manager']}, + { + layer: 'repository', + patterns: ['repository', 'repo', 'dal', 'dataaccess'] + }, + {layer: 'model', patterns: ['model', 'entity', 'domain', 'schema']}, + {layer: 'util', patterns: ['util', 'helper', 'common', 'shared']} + ] + + for (const [file] of this.graph.fileIndex) { + const lowerFile = file.toLowerCase() + for (const {layer, patterns} of layerPatterns) { + if (patterns.some(p => lowerFile.includes(p))) { + for (const sym of this.graph.fileIndex.get(file) || []) { + layers.set(`${file}:${sym.name}`, layer) + } + break + } + } + } + + return layers + } + + detectArchitecturalViolations( + changedFiles: string[], + architecturalLayers: Map + ): ArchitecturalViolation[] { + const violations: ArchitecturalViolation[] = [] + + const layerHierarchy: Record = { + controller: 1, + handler: 1, + service: 2, + business: 2, + repository: 3, + repo: 3, + dal: 3, + model: 4, + entity: 4, + domain: 4, + util: 5, + helper: 5 + } + + const allowedCrossings: Record = { + controller: ['service', 'handler'], + handler: ['service'], + service: ['repository', 'model', 'util'], + repository: ['model', 'dal'] + } + + for (const file of changedFiles) { + const fileLayer = this.inferFileLayer(file) + if (!fileLayer) continue + + const fileDeps = this.getFileDependencies(file) + const fileLayerRank = layerHierarchy[fileLayer] || 0 + + for (const dep of fileDeps) { + const depFile = dep.split(':')[0] + const depLayer = this.inferFileLayer(depFile) + if (!depLayer) continue + + const depRank = layerHierarchy[depLayer] || 0 + + if ( + fileLayerRank > depRank && + !this.isAllowedCrossing(fileLayer, depLayer, allowedCrossings) + ) { + violations.push({ + from: file, + to: depFile, + fromLayer: fileLayer, + toLayer: depLayer, + severity: this.calculateViolationSeverity(fileLayer, depLayer), + description: `Layer violation: \`${fileLayer}\` should not depend on \`${depLayer}\`` + }) + } + } + } + + return violations + } + + querySymbol(symbolName: string): Symbol | null { + for (const [, sym] of this.graph.symbols) { + if (sym.name === symbolName) { + return sym + } + } + return null + } + + getFileDependencies(file: string): string[] { + const deps: string[] = [] + for (const edge of this.graph.edges) { + if (edge.from.startsWith(file)) { + deps.push(edge.to) + } + } + return deps + } + + getDownstreamImpact(symbolKey: string): string[] { + const impacted: string[] = [] + const maxDepth = 2 + + for (const edge of this.graph.edges) { + if (edge.to === symbolKey) { + impacted.push(edge.from) + } + } + + const transitive = new Set(impacted) + const queue: Array<{key: string; depth: number}> = impacted.map(k => ({ + key: k, + depth: 1 + })) + + while (queue.length > 0) { + const {key: current, depth} = queue.shift()! + if (depth >= maxDepth) continue + + for (const edge of this.graph.edges) { + if (edge.to === current && !transitive.has(edge.from)) { + transitive.add(edge.from) + queue.push({key: edge.from, depth: depth + 1}) + } + } + } + + return Array.from(transitive) + } + + getContextForSymbol(symbolKey: string): string { + const sym = this.graph.symbols.get(symbolKey) + if (!sym) return '' + + const layer = this.inferFileLayer(sym.file) || 'unknown' + const deps = this.getFileDependencies(sym.file) + const downstream = this.getDownstreamImpact(symbolKey) + + return ` +Symbol: ${sym.name} +Type: ${sym.type} +File: ${sym.file}:${sym.line} +Layer: ${layer} +Dependencies: ${deps.length} +Downstream Impact: ${downstream.length} files +`.trim() + } +} + +export const unifiedContextEngine = new UnifiedContextEngine() diff --git a/src/test-generator.ts b/src/test-generator.ts new file mode 100644 index 0000000000000000000000000000000000000000..c36cb859e6648dcfb946eec9ad26a2742931150f --- /dev/null +++ b/src/test-generator.ts @@ -0,0 +1,369 @@ +import {Bot} from './bot' +/* eslint-disable no-console */ +const logInfo = console.log +/* eslint-enable no-console */ + +export interface TestGenerationResult { + testCase: string + testFile: string + language: string + testType: 'unit' | 'integration' | 'e2e' + confidence: number +} + +export interface BugAnalysis { + bugType: string + severity: string + functionName: string + parameters: string[] + expectedBehavior: string + actualBehavior: string +} + +export class TestGenerator { + private readonly MIN_CONFIDENCE = 0.75 + + async generateTestCase( + filename: string, + bugComment: string, + remedy: string, + heavyBot: Bot + ): Promise { + try { + const bugAnalysis = this.parseBugComment(bugComment) + if (!bugAnalysis) { + logInfo('Could not parse bug comment for test generation') + return null + } + + const ext = filename.split('.').pop()?.toLowerCase() + const language = this.getLanguage(ext) + + const [testCaseResponse] = await heavyBot.chat( + this.buildTestPrompt(filename, bugAnalysis, remedy, language), + {} + ) + + if (!testCaseResponse || testCaseResponse.length < 20) { + return null + } + + const testCase = this.extractTestCode(testCaseResponse, language) + if (!testCase) { + return null + } + + const testFile = this.findTestFile(filename) + const testType = this.inferTestType(bugAnalysis) + const confidence = this.estimateConfidence(bugAnalysis) + + if (confidence < this.MIN_CONFIDENCE) { + logInfo(`Test generation confidence ${confidence} below threshold`) + return null + } + + return { + testCase, + testFile, + language, + testType, + confidence + } + } catch (e) { + logInfo(`Test generation failed: ${e}`) + return null + } + } + + private parseBugComment(comment: string): BugAnalysis | null { + try { + const bugType = this.extractBugType(comment) + const severity = this.extractSeverity(comment) + const functionName = this.extractFunctionName(comment) + const parameters = this.extractParameters(comment) + const {expected, actual} = this.extractBehavior(comment) + + if (!bugType && !functionName) { + return null + } + + return { + bugType: bugType || 'general', + severity: severity || 'minor', + functionName: functionName || '', + parameters, + expectedBehavior: expected || '', + actualBehavior: actual || '' + } + } catch (e) { + return null + } + } + + private extractBugType(comment: string): string | null { + const patterns = [ + /null\s*pointer|NPE|null\s*check/i, + /division\s*by\s*zero|divide\s*by\s*0/i, + /race\s*condition|concurrent|deadlock/i, + /memory\s*leak|dispose|resource/i, + /sql\s*injection|injection/i, + /xss|cross.*site|innerHTML/i, + /async.*await|promise/i, + /off\s*by\s*one|index.*bound/i, + /type.*error|cannot\s*read|i[is] undefined/i, + /security|vulnerability|auth/i + ] + + const keywords = [ + 'null pointer', + 'division by zero', + 'race condition', + 'memory leak', + 'sql injection', + 'xss', + 'async await', + 'off by one', + 'type error', + 'security vulnerability' + ] + + const lowerComment = comment.toLowerCase() + for (let i = 0; i < patterns.length; i++) { + if (patterns[i].test(lowerComment)) { + return keywords[i] + } + } + + return null + } + + private extractSeverity(comment: string): string | null { + if (/\[CRITICAL\]|critical|severe|p0|critical/i.test(comment)) + return 'critical' + if (/\[MAJOR\]|major|important|p1/i.test(comment)) return 'major' + if (/\[MINOR\]|minor|p2/i.test(comment)) return 'minor' + return 'info' + } + + private extractFunctionName(comment: string): string | null { + const patterns = [ + /function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/i, + /([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/, + /method\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/i, + /`([a-zA-Z_$][a-zA-Z0-9_$]*)`/ + ] + + for (const pattern of patterns) { + const match = comment.match(pattern) + if (match && match[1]) { + return match[1] + } + } + + return null + } + + private extractParameters(comment: string): string[] { + const params: string[] = [] + const paramPatterns = [ + /`(.*?)`/g, + /parameter[s]?:\s*([a-zA-Z0-9_$,\s]+)/gi, + /arg[s]?\s+([a-zA-Z0-9_$,\s]+)/gi + ] + + for (const pattern of paramPatterns) { + let match + while ((match = pattern.exec(comment)) !== null) { + if (match[1]) { + const parts = match[1].split(/[,\s]+/).filter(p => p.length > 0) + params.push(...parts) + } + } + } + + return [...new Set(params)].slice(0, 5) + } + + private extractBehavior(comment: string): {expected: string; actual: string} { + let expected = '' + let actual = '' + + const expectedMatch = comment.match(/expected[:\s]+([^.]+)/i) + if (expectedMatch) expected = expectedMatch[1].trim() + + const actualMatch = comment.match(/(?:actual|got|but\s*got)[:\s]+([^.]+)/i) + if (actualMatch) actual = actualMatch[1].trim() + + const returnMatch = comment.match(/returns?\s+([^.]+)/i) + if (returnMatch && !actual) actual = returnMatch[1].trim() + + return {expected, actual} + } + + private getLanguage(ext: string | undefined): string { + const map: Record = { + ts: 'TypeScript', + tsx: 'TypeScript', + js: 'JavaScript', + jsx: 'JavaScript', + py: 'Python', + go: 'Go', + java: 'Java', + rs: 'Rust', + rb: 'Ruby', + cs: 'C#' + } + return map[ext || ''] || 'JavaScript' + } + + private findTestFile(sourceFile: string): string { + const testPatterns = [ + { + pattern: /^(src|lib|app)\/(.+)\.(ts|js|py|go)$/, + replacement: '$1/$2.test.$3' + }, + { + pattern: /^(src|lib|app)\/(.+)\.(ts|js|py|go)$/, + replacement: '$1/$2.spec.$3' + }, + {pattern: /^(.+)\.(ts|js|py|go)$/, replacement: '$1.test.$2'}, + {pattern: /^(.+)\.(ts|js|py|go)$/, replacement: '$1.spec.$2'} + ] + + for (const {pattern, replacement} of testPatterns) { + const testFile = sourceFile.replace(pattern, replacement) + if (testFile !== sourceFile) { + return testFile + } + } + + const ext = sourceFile.split('.').pop() + return sourceFile.replace(`.${ext}`, `.test.${ext}`) + } + + private inferTestType(bug: BugAnalysis): 'unit' | 'integration' | 'e2e' { + const dbPatterns = /database|query|sql|crud|repository/i + const apiPatterns = /api|endpoint|http|fetch|request/i + const uiPatterns = /click|render|component|ui|button/i + + const content = `${bug.bugType} ${bug.functionName}`.toLowerCase() + + if (dbPatterns.test(content)) return 'integration' + if (apiPatterns.test(content)) return 'integration' + if (uiPatterns.test(content)) return 'e2e' + return 'unit' + } + + private estimateConfidence(bug: BugAnalysis): number { + let confidence = 0.3 + + if (!bug.functionName || !bug.bugType) { + return confidence + } + + confidence = 0.5 + + if (bug.functionName) confidence += 0.15 + if (bug.bugType) confidence += 0.1 + if (bug.expectedBehavior && bug.actualBehavior) confidence += 0.15 + if (bug.parameters.length > 0) confidence += 0.05 + + if (bug.bugType === 'null pointer' || bug.bugType === 'division by zero') { + confidence += 0.1 + } + + if ( + bug.bugType === 'sql injection' || + bug.bugType === 'security vulnerability' + ) { + confidence += 0.15 + } + + return Math.min(1, confidence) + } + + private buildTestPrompt( + filename: string, + bug: BugAnalysis, + remedy: string, + language: string + ): string { + return `Generate a minimal unit test that reproduces a bug in ${filename}. + +Bug Analysis: +- Type: ${bug.bugType} +- Severity: ${bug.severity} +- Function: ${bug.functionName} +- Parameters: ${bug.parameters.join(', ') || 'unknown'} +- Expected behavior: ${bug.expectedBehavior || 'correct handling'} +- Actual behavior: ${bug.actualBehavior || 'incorrect handling'} + +Remediation applied: +\`\`\` +${remedy} +\`\`\` + +Requirements: +1. Generate ONLY the test code, no explanations +2. The test should FAIL before the fix and PASS after the fix +3. Include realistic test data that triggers the bug +4. Use ${language} testing conventions +5. Keep it minimal - just enough to reproduce the issue +6. Include a comment explaining what edge case is being tested + +Format: Return ONLY the test code in a code block labeled with the language.` + } + + private extractTestCode(response: string, language: string): string | null { + const patterns = [ + new RegExp(`\`\`\`${language.toLowerCase()}[\\s\\S]*?\`\`\``), + new RegExp(`\`\`\`${language}[\\s\\S]*?\`\`\``), + new RegExp('```[a-z]*\\n([\\s\\S]*?)```') + ] + + for (const pattern of patterns) { + const match = response.match(pattern) + if (match) { + return match[1].trim() + } + } + + const codeBlockMatch = response.match(/```[\s\S]*?\n([\s\S]*?)```/) + if (codeBlockMatch) { + return codeBlockMatch[1].trim() + } + + return response.trim().length > 50 ? response.trim() : null + } + + formatTestSuggestion(result: TestGenerationResult): string { + const confidenceLabel = + result.confidence >= 0.8 + ? 'High' + : result.confidence >= 0.6 + ? 'Medium' + : 'Low' + const autoGenWarning = `// โš ๏ธ AUTO-GENERATED BY PRIX - REVIEW BEFORE COMMIT +// DO NOT COMMIT WITHOUT UNDERSTANDING THIS TEST +` + + return ` +
+๐Ÿงช Auto-Generated Test Case (${confidenceLabel} confidence) + +**Test File:** \`${result.testFile}\` +**Type:** ${result.testType} +**Confidence:** ${Math.round(result.confidence * 100)}% + +\`\`\`${result.language.toLowerCase()} +${autoGenWarning}${result.testCase} +\`\`\` + +> โš ๏ธ Review this test carefully before committing. It was auto-generated based on the bug analysis. + +
+` + } +} + +export const testGenerator = new TestGenerator() diff --git a/src/tokenizer.ts b/src/tokenizer.ts new file mode 100644 index 0000000000000000000000000000000000000000..61e230d62baeaaeca966f4e1b6265eec3474da25 --- /dev/null +++ b/src/tokenizer.ts @@ -0,0 +1,13 @@ +// eslint-disable-next-line camelcase +import {get_encoding} from '@dqbd/tiktoken' + +const tokenizer = get_encoding('cl100k_base') + +export function encode(input: string): Uint32Array { + return tokenizer.encode(input) +} + +export function getTokenCount(input: string): number { + input = input.replace(/<\|endoftext\|>/g, '') + return encode(input).length +} diff --git a/src/utils.ts b/src/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..96bf319d9d8d43e5caa7b9fd4780100584ae125a --- /dev/null +++ b/src/utils.ts @@ -0,0 +1,22 @@ +import {execSync, ExecSyncOptions} from 'child_process' +import {als} from './context' + +/** + * Executes a shell command using the current context's working directory. + * Thread-safe for Probot. + */ +export const prixExec = ( + command: string, + options: ExecSyncOptions = {} +): string => { + const context = als.getStore() + const cwd = options.cwd || context?.workingDir || process.cwd() + + const result = execSync(command, { + ...options, + cwd, + encoding: 'utf8' + }) + + return result ? result.toString() : '' +}