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
|
import Anthropic from "@anthropic-ai/sdk";
import { eq, and, like } from "drizzle-orm";
import { db } from "../db";
import { pullRequests, prComments } from "../db/schema";
import { getRepoPath } from "../git/repository";
import { config } from "./config";
import { recordAiCost, extractUsage } from "./ai-cost-tracker";
import {
isTrioReviewEnabled,
alreadyTrioReviewed,
runTrioReview,
} from "./ai-review-trio";
import { assertAiQuota, AiQuotaExceededError } from "./billing";
import { getBotUserIdOrFallback } from "./bot-user";
import {
getAutomationSettings,
type AutomationSettingsLoader,
} from "./automation-settings";
interface ReviewComment {
filePath: string;
lineNumber: number | null;
body: string;
}
interface ReviewResult {
summary: string;
comments: ReviewComment[];
approved: boolean;
}
export const AI_REVIEW_MARKER = "<!-- gluecron-ai-review:summary -->";
const DIFF_BYTE_CAP = 100_000;
let _client: Anthropic | null = null;
function getClient(): Anthropic {
if (!_client) {
if (!config.anthropicApiKey) {
throw new Error("ANTHROPIC_API_KEY is not set");
}
_client = new Anthropic({ apiKey: config.anthropicApiKey });
}
return _client;
}
export async function reviewDiff(
repoFullName: string,
prTitle: string,
prBody: string | null,
baseBranch: string,
headBranch: string,
diffText: string
): Promise<ReviewResult> {
const client = getClient();
const REVIEW_MODEL = "claude-sonnet-4-6";
const message = await client.messages.create({
model: REVIEW_MODEL,
max_tokens: 4096,
messages: [
{
role: "user",
content: `You are reviewing a pull request on the repository "${repoFullName}".
**PR Title:** ${prTitle}
**PR Description:** ${prBody || "(none)"}
**Base branch:** ${baseBranch}
**Head branch:** ${headBranch}
Review the following diff. Look for:
- Bugs, logic errors, or potential runtime failures
- Security vulnerabilities (injection, XSS, auth bypasses, secrets in code)
- Performance issues (N+1 queries, unnecessary allocations, blocking I/O)
- Missing error handling at system boundaries
- Breaking changes or API contract violations
Do NOT comment on style, formatting, naming, missing docs, or minor nitpicks. Only flag issues that could cause real problems.
Respond in JSON format:
{
"summary": "1-3 sentence overall assessment",
"approved": true/false,
"comments": [
{
"filePath": "path/to/file.ts",
"lineNumber": 42,
"body": "Explain the issue and suggest a fix"
}
]
}
If the diff looks clean, return approved: true with an empty comments array.
\`\`\`diff
${diffText.slice(0, 100000)}
\`\`\``,
},
],
});
const text =
message.content[0].type === "text" ? message.content[0].text : "";
try {
const usage = extractUsage(message);
await recordAiCost({
model: REVIEW_MODEL,
inputTokens: usage.input,
outputTokens: usage.output,
category: "ai_review",
sourceKind: "pull_request",
});
} catch {
}
try {
const jsonMatch = text.match(/\{[\s\S]*\}/);
if (!jsonMatch) {
return {
summary:
"AI review failed: model returned output that could not be parsed as JSON. Treating as not-approved; a human reviewer should look at this PR.",
comments: [],
approved: false,
};
}
const parsed = JSON.parse(jsonMatch[0]);
return {
summary: parsed.summary || "Review complete.",
comments: Array.isArray(parsed.comments) ? parsed.comments : [],
approved: parsed.approved === true,
};
} catch (err) {
const tail = err instanceof Error ? err.message.slice(0, 200) : String(err);
return {
summary: `AI review failed to parse model output (${tail}). Treating as not-approved; a human reviewer should look at this PR.`,
comments: [],
approved: false,
};
}
}
export function isAiReviewEnabled(): boolean {
return !!config.anthropicApiKey;
}
async function diffBetweenBranches(
ownerName: string,
repoName: string,
baseBranch: string,
headBranch: string
): Promise<string> {
try {
const cwd = getRepoPath(ownerName, repoName);
const proc = Bun.spawn(
[
"git",
"diff",
`${baseBranch}...${headBranch}`,
"--",
],
{ cwd, stdout: "pipe", stderr: "pipe" }
);
const text = await new Response(proc.stdout).text();
await proc.exited;
return text;
} catch {
return "";
}
}
async function resolveHeadSha(
ownerName: string,
repoName: string,
branch: string
): Promise<string> {
try {
const cwd = getRepoPath(ownerName, repoName);
const proc = Bun.spawn(["git", "rev-parse", branch], {
cwd,
stdout: "pipe",
stderr: "pipe",
});
const text = await new Response(proc.stdout).text();
await proc.exited;
return text.trim();
} catch {
return "";
}
}
async function alreadyReviewed(prId: string, headSha: string): Promise<boolean> {
try {
const [row] = await db
.select({ body: prComments.body })
.from(prComments)
.where(
and(
eq(prComments.pullRequestId, prId),
eq(prComments.isAiReview, true),
like(prComments.body, `%${AI_REVIEW_MARKER}%`)
)
)
.limit(1);
if (!row) return false;
const shaMatch = row.body.match(/<!-- gluecron-ai-review:sha:([0-9a-f]+) -->/);
if (!shaMatch) return false;
return shaMatch[1] === headSha;
} catch {
return false;
}
}
export async function triggerAiReview(
ownerName: string,
repoName: string,
prId: string,
title: string,
body: string,
baseBranch: string,
headBranch: string,
options: { force?: boolean; loadSettings?: AutomationSettingsLoader } = {}
): Promise<void> {
try {
if (!isAiReviewEnabled()) return;
const headSha = await resolveHeadSha(ownerName, repoName, headBranch);
const useTrio = isTrioReviewEnabled();
if (
!options.force &&
(useTrio
? await alreadyTrioReviewed(prId)
: await alreadyReviewed(prId, headSha))
)
return;
const [pr] = await db
.select({
id: pullRequests.id,
authorId: pullRequests.authorId,
repositoryId: pullRequests.repositoryId,
})
.from(pullRequests)
.where(eq(pullRequests.id, prId))
.limit(1);
if (!pr) return;
const automation = await (options.loadSettings ?? getAutomationSettings)(
pr.repositoryId
);
if (automation.aiReviewMode === "off") return;
try {
await assertAiQuota(pr.authorId);
} catch (err) {
if (err instanceof AiQuotaExceededError) {
await db
.insert(prComments)
.values({
pullRequestId: prId,
authorId: pr.authorId,
isAiReview: true,
body: `${AI_REVIEW_MARKER}\n## AI review skipped\n\nYour monthly AI token budget has been reached. Upgrade at [/settings/billing](/settings/billing) to re-enable AI code review.`,
})
.catch(() => {});
return;
}
console.warn("[ai-review] assertAiQuota failed unexpectedly:", err);
}
let diffText = await diffBetweenBranches(
ownerName,
repoName,
baseBranch,
headBranch
);
if (!diffText.trim()) return;
if (diffText.length > DIFF_BYTE_CAP) {
diffText = diffText.slice(0, DIFF_BYTE_CAP);
}
if (useTrio) {
try {
await runTrioReview({
pullRequestId: prId,
headSha,
diff: diffText,
repositoryId: pr.repositoryId,
});
} catch (err) {
if (process.env.DEBUG_AI_REVIEW === "1") {
console.error("[ai-review] trio crashed:", err);
}
}
return;
}
const commentAuthorId = await getBotUserIdOrFallback(pr.authorId);
let result: ReviewResult;
try {
result = await reviewDiff(
`${ownerName}/${repoName}`,
title,
body || null,
baseBranch,
headBranch,
diffText
);
} catch (err) {
const reason = err instanceof Error ? err.message : "unknown error";
await db
.insert(prComments)
.values({
pullRequestId: prId,
authorId: commentAuthorId,
isAiReview: true,
body: `${AI_REVIEW_MARKER}\n## AI review unavailable\n\nThe AI review attempt failed: ${reason}. The PR is otherwise unchanged.`,
})
.catch((err) => {
console.error(
`[ai-review] failed to insert API-failure advisory comment for PR ${prId}:`,
err instanceof Error ? err.message : err
);
});
return;
}
const verdict = result.approved
? "**AI review:** no blocking issues found."
: `**AI review:** flagged ${result.comments.length} item(s) for human attention.`;
const shaMarker = headSha ? `<!-- gluecron-ai-review:sha:${headSha} -->` : "";
const summaryBody = `${AI_REVIEW_MARKER}${shaMarker ? `\n${shaMarker}` : ""}\n## AI Code Review\n\n${verdict}\n\n${result.summary}`;
await db
.insert(prComments)
.values({
pullRequestId: prId,
authorId: commentAuthorId,
isAiReview: true,
body: summaryBody,
})
.catch((err) => {
console.error(
`[ai-review] failed to insert summary comment for PR ${prId}:`,
err instanceof Error ? err.message : err
);
});
for (const c of result.comments) {
if (!c || !c.body) continue;
const filePath =
typeof c.filePath === "string" && c.filePath ? c.filePath : null;
const lineNumber =
Number.isInteger(c.lineNumber) && (c.lineNumber as number) > 0
? (c.lineNumber as number)
: null;
await db
.insert(prComments)
.values({
pullRequestId: prId,
authorId: commentAuthorId,
isAiReview: true,
body: c.body,
filePath,
lineNumber,
})
.catch((err) => {
console.error(
`[ai-review] failed to insert inline comment for PR ${prId} (${filePath}:${lineNumber}):`,
err instanceof Error ? err.message : err
);
});
}
if (process.env.DEBUG_AI_REVIEW === "1") {
console.log(
"[ai-review] reviewed",
ownerName,
repoName,
prId,
`comments=${result.comments.length}`,
`approved=${result.approved}`
);
}
} catch (err) {
if (process.env.DEBUG_AI_REVIEW === "1") {
console.error("[ai-review] crashed:", err);
}
}
}
export const __test = {
diffBetweenBranches,
alreadyReviewed,
};
|