CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
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 | /**
* AI-powered code review using Claude.
*
* Generates inline review comments on pull request diffs.
* Reviews are posted as PR comments with isAiReview=true.
*/
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;
}
/**
* Marker we drop into the AI summary comment body. Used to detect a
* prior review and short-circuit duplicate runs (e.g. when a PR is
* marked draft → ready → draft → ready).
*/
export const AI_REVIEW_MARKER = "<!-- gluecron-ai-review:summary -->";
/** Max bytes of diff we send to Claude. Matches reviewDiff's internal cap. */
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;
}
/**
* Run AI code review on a PR diff.
*/
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 : "";
// Best-effort cost capture. Caller passes "owner/repo" as repoFullName,
// so we can't easily resolve the repo id here; the call site at
// `triggerAiReview` records with a repository_id below.
try {
const usage = extractUsage(message);
await recordAiCost({
model: REVIEW_MODEL,
inputTokens: usage.input,
outputTokens: usage.output,
category: "ai_review",
sourceKind: "pull_request",
});
} catch {
/* never escape — observational only */
}
try {
// Extract JSON from response (may be wrapped in markdown code block)
const jsonMatch = text.match(/\{[\s\S]*\}/);
if (!jsonMatch) {
// FAIL-CLOSED: parsing failure must NOT count as approval. Previously
// this returned approved:true, which silently auto-approved PRs
// whenever Claude's output drifted off the JSON spec — a real auto-
// merge hazard. Surface the failure in the summary instead.
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 : [],
// Require explicit `approved: true` — undefined or any other value
// is treated as not-approved. Same fail-closed principle as above.
approved: parsed.approved === true,
};
} catch (err) {
// FAIL-CLOSED: JSON.parse threw (truncated output, schema-shaped
// garbage, etc.). Echo a short error tail so operators have a
// breadcrumb in the comment body, but never approve.
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,
};
}
}
/**
* Check if AI review is available (API key configured).
*/
export function isAiReviewEnabled(): boolean {
return !!config.anthropicApiKey;
}
/**
* Compute the merge-base diff between two branches in a bare repo.
* Returns "" on any error so callers can no-op cleanly. Uses the
* three-dot `base...head` form so the diff is what changed on `head`
* relative to the common ancestor with `base` (which is the PR
* conventional view, not a literal range diff).
*/
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 "";
}
}
/**
* Resolve a branch name to its current commit SHA via `git rev-parse`.
* Returns "" on any error — callers should treat that as "unknown" and
* carry on; this is only used for audit metadata.
*/
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 "";
}
}
/**
* Has this PR already been reviewed by the AI for the given head SHA?
* Detected by an existing PR comment carrying our summary marker that
* also embeds a SHA marker matching the current head. If the stored SHA
* differs (new commits pushed) we allow a re-review. If no review
* exists yet we also allow it. Cheap LIKE query — if it fails (DB
* hiccup) we fall back to "not yet" and re-review, which is idempotent
* at worst (a duplicate summary), never destructive.
*/
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;
// Extract the SHA embedded in the comment. If it matches the current
// head we skip (same commit reviewed already). If it differs or is
// missing we allow re-review (new commits pushed).
const shaMatch = row.body.match(/<!-- gluecron-ai-review:sha:([0-9a-f]+) -->/);
if (!shaMatch) return false; // Legacy comment without SHA — re-review.
return shaMatch[1] === headSha;
} catch {
return false;
}
}
/**
* Real AI review trigger. Replaces the previous stub. Pipeline:
*
* 1. Idempotency check — bail if a prior review summary exists.
* 2. Compute the base...head diff via the bare repo.
* 3. Call reviewDiff for a structured response (summary + per-file
* comments + approved boolean).
* 4. Persist:
* - one summary comment (isAiReview=true, marker embedded), and
* - one comment per inline finding (isAiReview=true, filePath +
* lineNumber populated).
*
* Always fire-and-forget at the call site (`.catch(...)`); this
* function still never throws so the catch is belt-and-braces. AI
* comments are authored by the PR author so the existing comment
* rendering can group them naturally — there is no synthetic bot user
* yet (tracked alongside H2 app-bot identity work).
*/
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;
// Resolve the current head SHA early — needed for SHA-based idempotency
// on both the single-Claude and trio paths.
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;
// Per-repo automation gate — 'off' skips AI review entirely. The loader
// fails open to the defaults ('suggest' = current behavior), so a broken
// settings lookup can never disable reviews.
const automation = await (options.loadSettings ?? getAutomationSettings)(
pr.repositoryId
);
if (automation.aiReviewMode === "off") return;
// Hard quota gate — post a comment and bail if the user's AI budget is
// exhausted. This runs after loading the PR so we have authorId for the
// comment insert.
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;
}
// Any other error from assertAiQuota is unexpected — log and proceed
// (fail open so a billing glitch never silently kills reviews).
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);
}
// Trio path — replaces the single-Claude review when enabled. The
// trio helper owns its own persistence + audit; we bail after it.
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;
}
// Resolve the bot user id once; fall back to the PR author so that
// comment insertion never fails even before migration 0078 has run.
const commentAuthorId = await getBotUserIdOrFallback(pr.authorId);
let result: ReviewResult;
try {
result = await reviewDiff(
`${ownerName}/${repoName}`,
title,
body || null,
baseBranch,
headBranch,
diffText
);
} catch (err) {
// Anthropic API failure — degrade to a single advisory comment so
// PR authors see the attempt rather than silence.
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) => {
// Was a silent .catch(() => {}) — DB blips here meant the user
// saw no review comment AND no diagnostic. Log so operators
// can investigate, but don't re-throw (caller is fire-and-forget).
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) {
// Belt-and-braces: never escape into the request path.
if (process.env.DEBUG_AI_REVIEW === "1") {
console.error("[ai-review] crashed:", err);
}
}
}
/**
* Merge-gate signal: did AI review clear this PR?
*
* The single source of truth for "no blocking issues" is the literal
* verdict line `triggerAiReview` writes (`"no blocking issues found"` vs.
* `"flagged N item(s) for human attention"`) -- three call sites
* (mcp-tools.ts's merge tool, pulls.tsx's PR-page gate preview, and
* pulls.tsx's actual merge handler) had each grown their own ad-hoc
* heuristic, checking for strings like "**Approved**" / "approved: true"
* / "lgtm" that the real generator never produces. Left alone, that meant
* a genuinely clean review could still hard-block a merge depending on
* which code path ran it.
*
* Also treats a degraded review ("AI review skipped" on quota exhaustion,
* "AI review unavailable" on a provider error -- e.g. the Anthropic
* account running out of credit) as non-blocking, same fail-open
* precedent already applied to the security-scan gate: a review that
* never ran is not the same signal as a review that ran and found real
* problems, and treating them identically means any Anthropic-side
* hiccup silently blocks every merge platform-wide.
*
* No comment at all (review disabled, or hasn't posted yet) also
* approves -- gating on AI review's mere presence isn't this function's
* job, `runAllGateChecks`'s `runAiReview`/settings check already covers
* "should this gate even run".
*/
export async function isAiReviewApproved(prId: string): Promise<boolean> {
const aiComments = await db
.select({ body: prComments.body, createdAt: prComments.createdAt })
.from(prComments)
.where(
and(eq(prComments.pullRequestId, prId), eq(prComments.isAiReview, true))
);
return computeAiReviewApproval(aiComments);
}
/**
* Pure decision logic behind `isAiReviewApproved`, split out so it's
* directly unit-testable without a DB connection. Takes the PR's
* isAiReview=true comments (any order) and picks the most recent one
* carrying the summary marker.
*/
export function computeAiReviewApproval(
aiComments: Array<{ body: string; createdAt: string | Date }>
): boolean {
const summaryComments = aiComments
.filter((c) => c.body.includes(AI_REVIEW_MARKER))
.sort((a, b) => +new Date(b.createdAt) - +new Date(a.createdAt));
const latest = summaryComments[0];
if (!latest) return true;
if (
latest.body.includes("AI review skipped") ||
latest.body.includes("AI review unavailable")
) {
return true;
}
return latest.body.includes("no blocking issues found");
}
/**
* Test-only export: the internal helpers. Not part of the public API.
*/
export const __test = {
diffBetweenBranches,
alreadyReviewed,
};
|