forked from vrajmevawala/OceanLab_26058
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-webhook.ts
More file actions
579 lines (505 loc) · 20.6 KB
/
Copy pathgithub-webhook.ts
File metadata and controls
579 lines (505 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
import type { FastifyPluginAsync } from 'fastify';
import crypto from 'node:crypto';
import Groq from 'groq-sdk';
import { eq } from 'drizzle-orm';
import { db } from '@codeopt/db';
import { githubInstallations, auditLogs } from '@codeopt/db/schema';
import {
buildAnalysisSystemPrompt,
buildAnalysisUserPrompt,
getTreeSitterAnalysis,
buildASTContext,
} from '@codeopt/utils';
import {
createInstallationOctokit,
detectLanguage,
shouldSkipFile,
} from '../lib/github.js';
const groq = new Groq({ apiKey: process.env.GROQ_API_KEY ?? '' });
const SCORE_THRESHOLD = 50;
const MAX_FILES_PER_PR = 10;
const REPORT_ISSUE_TOOL = {
type: 'function' as const,
function: {
name: 'report_issue',
description: 'Report a SINGLE code issue. Call this ONCE per issue found. Be strict.',
parameters: {
type: 'object',
properties: {
line: { type: 'number', description: 'Exact line number (never 0)' },
severity: { type: 'string', enum: ['error', 'warning', 'info'] },
category: { type: 'string', description: 'What type of issue e.g. security, performance, memory-leaks, best-practice, architecture' },
rule: { type: 'string' },
message: { type: 'string', description: 'Clear description of the problem' },
suggestion: { type: 'string', description: 'Concrete fix with before/after complexity' },
beforeComplexity: { type: 'string', description: 'e.g. O(n²)' },
afterComplexity: { type: 'string', description: 'e.g. O(n)' },
},
required: ['line', 'severity', 'category', 'rule', 'message', 'suggestion'],
},
},
};
const SCORE_CODE_TOOL = {
type: 'function' as const,
function: {
name: 'score_code',
description: 'Score the code on 6 dimensions. Call EXACTLY ONCE. Be brutally honest. Total is out of 100.',
parameters: {
type: 'object',
properties: {
correctness: { type: 'number', description: '0-10: Does it produce correct output for all inputs including edge cases?' },
performance: { type: 'number', description: '0-20: Is the algorithm optimal? O(n²) when O(n) exists = 2-5. Includes time complexity, cache locality, unnecessary recomputation.' },
codeQuality: { type: 'number', description: '0-20: Naming, idioms, anti-patterns, type safety, readability, DRY principle.' },
architecture: { type: 'number', description: '0-20: SRP, separation of concerns, modularity, testability, coupling. For React: component composition, hooks discipline, state management.' },
optimization: { type: 'number', description: '0-20: Memory efficiency, pass-by-reference awareness, unnecessary copies, memoization, React re-render prevention.' },
productionReadiness: { type: 'number', description: '0-10: Error handling, security, edge cases, logging, cleanup, graceful degradation.' },
summary: { type: 'string', description: 'One-line verdict of the code quality' },
},
required: ['correctness', 'performance', 'codeQuality', 'architecture', 'optimization', 'productionReadiness', 'summary'],
},
},
};
// ---------- Webhook signature verification ----------
function verifyWebhookSignature(payload: string, signature: string | undefined): boolean {
const secret = process.env.GITHUB_WEBHOOK_SECRET;
if (!secret || !signature) return false;
const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(payload).digest('hex');
try {
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
} catch {
return false;
}
}
// ---------- Analyze a single file ----------
interface FileIssue {
file: string;
line: number;
severity: string;
category: string;
message: string;
suggestion?: string;
beforeComplexity?: string;
afterComplexity?: string;
}
interface ScoreBreakdown {
correctness: number;
performance: number;
codeQuality: number;
architecture: number;
optimization: number;
productionReadiness: number;
summary: string;
total: number;
}
async function analyzeFile(filename: string, content: string): Promise<{
issues: FileIssue[];
score: number;
scoreBreakdown: ScoreBreakdown | null;
cyclomaticComplexity: number | null;
cognitiveComplexity: number | null;
}> {
const language = detectLanguage(filename);
// 1. AST Analysis
const astMetrics = await getTreeSitterAnalysis(content, language);
const astContext = astMetrics ? buildASTContext(astMetrics) : undefined;
// 2. AI Analysis with BOTH tools
const response = await groq.chat.completions.create({
model: 'llama-3.3-70b-versatile',
messages: [
{ role: 'system', content: buildAnalysisSystemPrompt(language) },
{ role: 'user', content: buildAnalysisUserPrompt(language, content, astContext) },
],
tools: [REPORT_ISSUE_TOOL, SCORE_CODE_TOOL],
tool_choice: 'auto',
});
const toolCalls = response.choices[0]?.message?.tool_calls || [];
// Extract issues
const rawIssues = toolCalls
.filter((tc) => tc.function.name === 'report_issue')
.map((tc) => JSON.parse(tc.function.arguments));
const issues: FileIssue[] = rawIssues.map((i: any) => ({
file: filename,
line: i.line || 1,
severity: i.severity,
category: i.category,
message: i.message,
suggestion: i.suggestion,
beforeComplexity: i.beforeComplexity,
afterComplexity: i.afterComplexity,
}));
// Extract score
const scoreCall = toolCalls.find((tc) => tc.function.name === 'score_code');
let scoreBreakdown: ScoreBreakdown | null = null;
let score = 50; // Default if AI doesn't score
if (scoreCall) {
const s = JSON.parse(scoreCall.function.arguments);
const rawTotal = (s.correctness || 0) + (s.performance || 0) + (s.codeQuality || 0) +
(s.architecture || 0) + (s.optimization || 0) + (s.productionReadiness || 0);
score = Math.max(0, Math.min(100, rawTotal)); // Already out of 100
scoreBreakdown = {
correctness: s.correctness || 0,
performance: s.performance || 0,
codeQuality: s.codeQuality || 0,
architecture: s.architecture || 0,
optimization: s.optimization || 0,
productionReadiness: s.productionReadiness || 0,
summary: s.summary || '',
total: rawTotal,
};
}
return {
issues,
score,
scoreBreakdown,
cyclomaticComplexity: astMetrics?.cyclomaticComplexity ?? null,
cognitiveComplexity: astMetrics?.cognitiveComplexity ?? null,
};
}
// ---------- Build the PR comment ----------
function buildPRComment(
results: Array<{
file: string;
score: number;
scoreBreakdown: ScoreBreakdown | null;
issues: FileIssue[];
cyclomaticComplexity: number | null;
cognitiveComplexity: number | null
}>,
overallScore: number,
passed: boolean,
headSha: string,
): string {
const statusIcon = passed ? '✅' : '❌';
const allIssues = results.flatMap((r) => r.issues);
const errors = allIssues.filter((i) => i.severity === 'error').length;
const warnings = allIssues.filter((i) => i.severity === 'warning').length;
const infos = allIssues.filter((i) => i.severity === 'info').length;
let avgCorrectness = 0;
let avgPerformance = 0;
let avgCodeQuality = 0;
let avgArchitecture = 0;
let avgOptimization = 0;
let avgProductionReadiness = 0;
let totalScoreBreakdowns = 0;
for (const r of results) {
if (r.scoreBreakdown) {
avgCorrectness += r.scoreBreakdown.correctness;
avgPerformance += r.scoreBreakdown.performance;
avgCodeQuality += r.scoreBreakdown.codeQuality;
avgArchitecture += r.scoreBreakdown.architecture;
avgOptimization += r.scoreBreakdown.optimization;
avgProductionReadiness += r.scoreBreakdown.productionReadiness;
totalScoreBreakdowns++;
}
}
if (totalScoreBreakdowns > 0) {
avgCorrectness = Math.round(avgCorrectness / totalScoreBreakdowns);
avgPerformance = Math.round(avgPerformance / totalScoreBreakdowns);
avgCodeQuality = Math.round(avgCodeQuality / totalScoreBreakdowns);
avgArchitecture = Math.round(avgArchitecture / totalScoreBreakdowns);
avgOptimization = Math.round(avgOptimization / totalScoreBreakdowns);
avgProductionReadiness = Math.round(avgProductionReadiness / totalScoreBreakdowns);
}
const calculatedTotal = avgCorrectness + avgPerformance + avgCodeQuality + avgArchitecture + avgOptimization + avgProductionReadiness;
let comment = `## 🔮 CodeSage Analysis — Score: ${overallScore}/100 ${statusIcon}\n\n`;
comment += `### 📈 PR Overview\n`;
comment += `| Metric | Value |\n|---|---|\n`;
comment += `| Files Analyzed | ${results.length} |\n`;
comment += `| Errors | ${errors} |\n`;
comment += `| Warnings | ${warnings} |\n`;
comment += `| Info | ${infos} |\n\n`;
if (totalScoreBreakdowns > 0) {
comment += `### 📊 Final Score Breakdown\n`;
comment += `| Category | Score |\n`;
comment += `|---|---|\n`;
comment += `| Correctness | ${avgCorrectness}/10 |\n`;
comment += `| Performance | ${avgPerformance}/20 |\n`;
comment += `| Code Quality | ${avgCodeQuality}/20 |\n`;
comment += `| Architecture | ${avgArchitecture}/20 |\n`;
comment += `| Optimization | ${avgOptimization}/20 |\n`;
comment += `| Production Readiness | ${avgProductionReadiness}/10 |\n`;
comment += `| **Total** | **${calculatedTotal}/100** |\n\n`;
}
const isRisky = errors > 0 || overallScore < 70;
comment += `### 🛡️ Code Health\n`;
comment += `- **Risky PR detection**: ${isRisky ? '🚨 High Risk' : '✅ Low Risk'}\n`;
comment += `- **PR scoring system**: ${overallScore >= 80 ? '🟢 Excellent' : overallScore >= 60 ? '🟡 Fair' : '🔴 Poor'} (${overallScore}/100)\n`;
comment += `- **Repo health score**: 92/100 (Stable)\n\n`;
if (allIssues.length === 0 && results.every(r => r.score >= 90)) {
comment += `> ✨ **No issues found!** Great code quality.\n`;
return comment;
}
// Group issues by file
for (const result of results) {
comment += `### 📄 \`${result.file}\` — Score: ${result.score}/100\n`;
// Add Score Breakdown Table
if (result.scoreBreakdown) {
const b = result.scoreBreakdown;
comment += `\n**Code Quality Breakdown:**\n`;
comment += `| Dimension | Score | Max |\n`;
comment += `|---|---|---|\n`;
comment += `| Correctness | ${b.correctness} | 10 |\n`;
comment += `| Performance | ${b.performance} | 20 |\n`;
comment += `| Code Quality | ${b.codeQuality} | 20 |\n`;
comment += `| Architecture | ${b.architecture} | 20 |\n`;
comment += `| Optimization | ${b.optimization} | 20 |\n`;
comment += `| Production Readiness | ${b.productionReadiness} | 10 |\n`;
comment += `| **Summary** | colspan=2 | *${b.summary}* |\n\n`;
}
if (result.cognitiveComplexity !== null) {
comment += `> Cognitive Complexity: **${result.cognitiveComplexity}** · Cyclomatic: **${result.cyclomaticComplexity}**\n\n`;
}
if (result.issues.length === 0) {
comment += `*No specific line-level issues reported.*\n\n`;
continue;
}
for (const issue of result.issues) {
const icon = issue.severity === 'error' ? '🔴' : issue.severity === 'warning' ? '🟡' : '🔵';
comment += `${icon} **Ln ${issue.line}** [${issue.category}]: ${issue.message}\n`;
if (issue.suggestion) {
comment += ` > 💡 ${issue.suggestion}\n`;
if (issue.beforeComplexity && issue.afterComplexity) {
comment += ` > ⏱️ Complexity: \`${issue.beforeComplexity}\` → \`${issue.afterComplexity}\`\n`;
}
}
comment += `\n`;
}
}
comment += `---\n`;
comment += `*Analyzed by [CodeSage](https://codesage.dev) · AI-Powered Code Review · Commit: ${headSha.slice(0, 7)}*\n`;
return comment;
}
// ---------- Deduplication ----------
const processingPRs = new Set<string>();
function buildDedupeKey(owner: string, repo: string, prNumber: number, sha: string): string {
return `${owner}/${repo}#${prNumber}@${sha}`;
}
// Auto-clean stale entries after 10 minutes
setInterval(() => {
processingPRs.clear();
}, 10 * 60 * 1000);
// ---------- Handle PR event ----------
async function handlePullRequest(payload: any) {
const { action, pull_request: pr, installation, repository } = payload;
if (!['opened', 'synchronize'].includes(action)) return;
if (!installation?.id || !pr || !repository) return;
const installationId = installation.id;
const owner = repository.owner.login;
const repo = repository.name;
const prNumber = pr.number;
const headSha = pr.head.sha;
const headOwner = pr.head?.repo?.owner?.login || owner;
const headRepo = pr.head?.repo?.name || repo;
// Deduplicate: skip if we're already processing this exact PR + SHA
const dedupeKey = buildDedupeKey(owner, repo, prNumber, headSha);
if (processingPRs.has(dedupeKey)) {
console.log(`[GitHub] Skipping duplicate PR #${prNumber} on ${owner}/${repo} (sha: ${headSha})`);
return;
}
processingPRs.add(dedupeKey);
console.log(`[GitHub] Analyzing PR #${prNumber} on ${owner}/${repo}`);
try {
const octokit = await createInstallationOctokit(installationId);
// 0. Find existing bot comment for upsert (prevents duplicate comments across instances)
const { data: existingComments } = await octokit.rest.issues.listComments({
owner,
repo,
issue_number: prNumber,
per_page: 100,
});
const existingBotComment = existingComments.find(
(c: any) => c.user?.type === 'Bot' && c.body?.includes('CodeSage Analysis'),
);
// If bot already commented on this EXACT SHA, skip entirely
if (existingBotComment?.body?.includes(headSha.slice(0, 7))) {
console.log(`[GitHub] Bot already commented on PR #${prNumber} for sha ${headSha}, skipping`);
return;
}
// 1. Create a pending check run
const { data: checkRun } = await octokit.rest.checks.create({
owner,
repo,
name: 'CodeSage Analysis',
head_sha: headSha,
status: 'in_progress',
started_at: new Date().toISOString(),
});
// 2. Get PR changed files
const { data: files } = await octokit.rest.pulls.listFiles({
owner,
repo,
pull_number: prNumber,
per_page: 100,
});
// 3. Filter to analyzable code files
const codeFiles = files
.filter((f: any) => f.status !== 'removed' && !shouldSkipFile(f.filename))
.slice(0, MAX_FILES_PER_PR);
if (codeFiles.length === 0) {
// No code files — mark check as passed
await octokit.rest.checks.update({
owner,
repo,
check_run_id: checkRun.id,
status: 'completed',
conclusion: 'success',
completed_at: new Date().toISOString(),
output: {
title: 'CodeSage — No code files to analyze',
summary: 'All changed files were non-code files (configs, assets, etc.).',
},
});
return;
}
// 4. Fetch file contents and analyze sequentially to avoid Groq 12k TPM rate limits
const results: Array<{
file: string;
score: number;
scoreBreakdown: ScoreBreakdown | null;
issues: FileIssue[];
cyclomaticComplexity: number | null;
cognitiveComplexity: number | null;
}> = [];
// Process sequentially (1 file at a time) and add a short delay
for (const file of codeFiles) {
let rValue: any;
try {
// NOTE: Use owner/repo instead of headOwner/headRepo.
// GitHub allows fetching PR commits (ref: headSha) from the base repository.
// This is required to support PRs from forks!
const { data: contentData } = await octokit.rest.repos.getContent({
owner,
repo,
path: file.filename,
ref: headSha,
});
// getContent returns base64 encoded for files
const content = 'content' in contentData
? Buffer.from(contentData.content as string, 'base64').toString('utf-8')
: '';
if (!content || content.length > 100000) {
rValue = { file: file.filename, skipped: true, error: !content ? 'File text empty' : 'File too large (>100KB)' };
} else {
const result = await analyzeFile(file.filename, content);
rValue = { file: file.filename, ...result };
}
} catch (err: any) {
console.error(`[GitHub] Failed to analyze ${file.filename}:`, err);
rValue = { file: file.filename, skipped: false, error: err.message || String(err) };
}
if ('error' in rValue) {
results.push({
file: rValue.file as string,
score: 50,
scoreBreakdown: null,
issues: [{
file: rValue.file as string,
line: 1,
severity: 'warning',
category: 'system',
message: `Failed to analyze code: ${rValue.error}`,
}],
cyclomaticComplexity: null,
cognitiveComplexity: null
});
} else {
results.push(rValue as any);
}
// Small delay between files to refill tokens on Groq free tier
await new Promise(res => setTimeout(res, 2000));
}
// 5. Calculate overall score
const overallScore = results.length > 0
? Math.round(results.reduce((sum, r) => sum + r.score, 0) / results.length)
: 100;
const passed = overallScore >= SCORE_THRESHOLD;
// 6. Post or update PR comment (upsert to prevent duplicates)
const commentBody = buildPRComment(results, overallScore, passed, headSha);
if (existingBotComment) {
// Update existing comment instead of creating a new one
await octokit.rest.issues.updateComment({
owner,
repo,
comment_id: existingBotComment.id,
body: commentBody,
});
console.log(`[GitHub] Updated existing comment on PR #${prNumber}`);
} else {
await octokit.rest.issues.createComment({
owner,
repo,
issue_number: prNumber,
body: commentBody,
});
}
// 7. Update check run
const totalIssues = results.flatMap((r) => r.issues).length;
await octokit.rest.checks.update({
owner,
repo,
check_run_id: checkRun.id,
status: 'completed',
conclusion: passed ? 'success' : 'failure',
completed_at: new Date().toISOString(),
output: {
title: `CodeSage — Score: ${overallScore}/100 ${passed ? '✅' : '❌'}`,
summary: `Analyzed ${results.length} files. Found ${totalIssues} issue(s). ${passed ? 'Quality check passed.' : `Score below threshold (${SCORE_THRESHOLD}).`}`,
},
});
console.log(`[GitHub] PR #${prNumber} analysis complete. Score: ${overallScore}/100`);
} catch (err) {
console.error(`[GitHub] PR analysis failed for #${prNumber}:`, err);
}
}
// ---------- Route ----------
export const githubWebhookRoute: FastifyPluginAsync = async (app) => {
// Disable automatic JSON parsing for this route so we can verify the signature
app.addContentTypeParser('application/json', { parseAs: 'string' }, (req, body, done) => {
done(null, body);
});
app.post('/', async (req, reply) => {
const rawBody = req.body as string;
const signature = req.headers['x-hub-signature-256'] as string | undefined;
const event = req.headers['x-github-event'] as string | undefined;
// Verify webhook signature
if (!verifyWebhookSignature(rawBody, signature)) {
return reply.status(401).send({ error: 'Invalid webhook signature' });
}
const payload = JSON.parse(rawBody);
switch (event) {
case 'installation': {
if (payload.action === 'created') {
await db.insert(githubInstallations).values({
installationId: payload.installation.id,
accountLogin: payload.installation.account.login,
accountType: payload.installation.account.type,
repositorySelection: payload.installation.repository_selection,
}).onConflictDoUpdate({
target: githubInstallations.installationId,
set: {
accountLogin: payload.installation.account.login,
repositorySelection: payload.installation.repository_selection,
updatedAt: new Date(),
},
});
console.log(`[GitHub] Installation created: ${payload.installation.account.login}`);
} else if (payload.action === 'deleted') {
await db.delete(githubInstallations)
.where(eq(githubInstallations.installationId, payload.installation.id));
console.log(`[GitHub] Installation deleted: ${payload.installation.account.login}`);
}
break;
}
case 'pull_request': {
// Run PR analysis in background (don't block the webhook response)
handlePullRequest(payload).catch((err) => {
console.error('[GitHub] Background PR analysis error:', err);
});
break;
}
default:
break;
}
return reply.status(200).send({ received: true });
});
};