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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
|
import { eq, and, like } from "drizzle-orm";
import { db } from "../db";
import { pullRequests, prComments } from "../db/schema";
import { getAnthropic, MODEL_SONNET, parseJsonResponse } from "./ai-client";
import { audit } from "./notify";
import { recordAiCost, extractUsage } from "./ai-cost-tracker";
export type TrioPersona = "security" | "correctness" | "style";
export type Verdict = "pass" | "fail";
export interface TrioFinding {
severity: "low" | "medium" | "high" | "critical" | string;
file: string | null;
line: number | null;
issue: string;
fix: string;
}
export interface TrioVerdict {
persona: TrioPersona;
verdict: Verdict;
findings: TrioFinding[];
rawText: string;
latencyMs: number;
failed: boolean;
}
export interface TrioDisagreement {
file: string;
line: number | null;
failingPersonas: TrioPersona[];
passingPersonas: TrioPersona[];
}
export interface TrioReviewResult {
securityVerdict: TrioVerdict;
correctnessVerdict: TrioVerdict;
styleVerdict: TrioVerdict;
disagreements: TrioDisagreement[];
}
export interface RunTrioReviewOpts {
pullRequestId: string;
headSha: string;
diff: string;
repositoryId?: string | null;
model?: string;
}
export const TRIO_COMMENT_MARKER: Record<TrioPersona, string> = {
security: "<!-- ai-trio:security -->",
correctness: "<!-- ai-trio:correctness -->",
style: "<!-- ai-trio:style -->",
};
export const TRIO_SUMMARY_MARKER = "<!-- ai-trio:summary -->";
const DIFF_BYTE_CAP = 100_000;
const MAX_TOKENS = 3072;
const SYSTEM_PROMPT_BASE = `You are a focused code reviewer on a pull request. Respond with ONLY valid JSON matching this exact shape:
{
"verdict": "pass" | "fail",
"findings": [
{
"severity": "low" | "medium" | "high" | "critical",
"file": "path/to/file.ts",
"line": 42,
"issue": "short description of the problem",
"fix": "concrete suggested fix"
}
]
}
Rules:
- Return "verdict": "fail" if you found ANY finding worth flagging at your remit. Otherwise "pass" with an empty findings array.
- "line" is the line number in the NEW file (right side of the diff), or null when you can't pin it.
- Stay strictly inside your remit — do not flag issues that belong to another reviewer.
- No prose outside the JSON. No code fences.`;
const PERSONA_PROMPT: Record<TrioPersona, string> = {
security: `You are the SECURITY reviewer. Be paranoid. Find security issues:
- SQL/NoSQL injection, command injection, path traversal
- XSS (reflected, stored, DOM-based) and HTML-escaping gaps
- Broken auth: missing session/token checks, IDOR, privilege escalation
- Secret leaks (API keys, tokens, passwords committed to source)
- Unsafe deserialization (eval, Function, untrusted JSON.parse into prototypes)
- Crypto misuse (weak hashes, missing HMAC verification, IV reuse)
- CSRF / SSRF / open redirects
Do NOT flag style, naming, or non-security bugs.
${SYSTEM_PROMPT_BASE}`,
correctness: `You are the CORRECTNESS reviewer. Find logic bugs:
- Null/undefined dereference risks where input may not be guaranteed
- Race conditions, missing await, unhandled promise rejection
- Off-by-one errors in loops, slices, range checks
- Missing error handling at system boundaries (fs, network, DB)
- Wrong operator (== vs ===, & vs &&), inverted conditions
- Resource leaks (unclosed handles, missing cleanup on error)
- Type coercion bugs, NaN propagation, integer overflow
Do NOT flag style, naming, security, or readability.
${SYSTEM_PROMPT_BASE}`,
style: `You are the STYLE reviewer. Find readability + maintainability issues:
- Inconsistent or unclear naming (vars, functions, types)
- Missing JSDoc / docstring on newly-added public APIs
- Functions over ~80 lines or cyclomatic complexity hotspots
- Magic numbers without named constants
- Duplicated code blocks that should be extracted
- Deeply nested conditionals that hurt readability
Do NOT flag security, correctness bugs, or trivial formatting (let the linter do that).
${SYSTEM_PROMPT_BASE}`,
};
export type PersonaRunner = (args: {
persona: TrioPersona;
diff: string;
model: string;
}) => Promise<{ text: string; inputTokens: number; outputTokens: number }>;
let _runnerOverride: PersonaRunner | null = null;
export function __setPersonaRunnerForTests(fn: PersonaRunner | null): void {
_runnerOverride = fn;
}
export function isTrioReviewEnabled(): boolean {
return process.env.AI_TRIO_REVIEW_ENABLED === "1";
}
export async function alreadyTrioReviewed(prId: string): Promise<boolean> {
try {
const [row] = await db
.select({ id: prComments.id })
.from(prComments)
.where(
and(
eq(prComments.pullRequestId, prId),
eq(prComments.isAiReview, true),
like(prComments.body, `%${TRIO_SUMMARY_MARKER}%`)
)
)
.limit(1);
return !!row;
} catch {
return false;
}
}
export async function runTrioReview(
opts: RunTrioReviewOpts
): Promise<TrioReviewResult> {
const model = opts.model || MODEL_SONNET;
const diff =
opts.diff.length > DIFF_BYTE_CAP
? opts.diff.slice(0, DIFF_BYTE_CAP)
: opts.diff;
const personas: TrioPersona[] = ["security", "correctness", "style"];
const [securityVerdict, correctnessVerdict, styleVerdict] = await Promise.all(
personas.map((p) => runOnePersona({ persona: p, diff, model }))
);
const disagreements = computeDisagreements({
securityVerdict,
correctnessVerdict,
styleVerdict,
});
const result: TrioReviewResult = {
securityVerdict,
correctnessVerdict,
styleVerdict,
disagreements,
};
await persistTrioComments({
pullRequestId: opts.pullRequestId,
result,
});
try {
await audit({
action: "ai.review.trio",
targetType: "pull_request",
targetId: opts.pullRequestId,
repositoryId: opts.repositoryId ?? null,
metadata: {
headSha: opts.headSha,
security: securityVerdict.verdict,
correctness: correctnessVerdict.verdict,
style: styleVerdict.verdict,
disagreements: disagreements.length,
failed: [
securityVerdict.failed ? "security" : null,
correctnessVerdict.failed ? "correctness" : null,
styleVerdict.failed ? "style" : null,
].filter(Boolean),
},
});
} catch {
}
return result;
}
async function runOnePersona(args: {
persona: TrioPersona;
diff: string;
model: string;
}): Promise<TrioVerdict> {
const t0 = Date.now();
let text = "";
let inputTokens = 0;
let outputTokens = 0;
let failed = false;
try {
if (_runnerOverride) {
const out = await _runnerOverride({
persona: args.persona,
diff: args.diff,
model: args.model,
});
text = out.text || "";
inputTokens = out.inputTokens || 0;
outputTokens = out.outputTokens || 0;
} else {
const client = getAnthropic();
const message = await client.messages.create({
model: args.model,
max_tokens: MAX_TOKENS,
system: PERSONA_PROMPT[args.persona],
messages: [
{
role: "user",
content: `Review this diff at your remit (${args.persona}). Return JSON only.\n\n\`\`\`diff\n${args.diff}\n\`\`\``,
},
],
});
text =
message.content[0]?.type === "text" ? message.content[0].text : "";
const usage = extractUsage(message);
inputTokens = usage.input;
outputTokens = usage.output;
}
} catch (err) {
failed = true;
text = `__error__:${err instanceof Error ? err.message : String(err)}`;
}
if (!failed && (inputTokens || outputTokens)) {
try {
await recordAiCost({
model: args.model,
inputTokens,
outputTokens,
category: "ai_review",
sourceKind: "pull_request",
});
} catch {
}
}
const parsed = parseJsonResponse<{
verdict?: unknown;
findings?: unknown;
}>(text);
let verdict: Verdict = "fail";
let findings: TrioFinding[] = [];
if (parsed && typeof parsed === "object") {
if (parsed.verdict === "pass") verdict = "pass";
else if (parsed.verdict === "fail") verdict = "fail";
if (Array.isArray(parsed.findings)) {
findings = parsed.findings
.map((f) => normaliseFinding(f))
.filter((f): f is TrioFinding => !!f);
}
} else if (!failed) {
failed = true;
}
return {
persona: args.persona,
verdict,
findings,
rawText: text,
latencyMs: Date.now() - t0,
failed,
};
}
function normaliseFinding(raw: unknown): TrioFinding | null {
if (!raw || typeof raw !== "object") return null;
const r = raw as Record<string, unknown>;
const issue =
typeof r.issue === "string"
? r.issue
: typeof r.description === "string"
? r.description
: "";
if (!issue) return null;
return {
severity:
typeof r.severity === "string" && r.severity.length > 0
? r.severity
: "medium",
file: typeof r.file === "string" && r.file.length > 0 ? r.file : null,
line:
typeof r.line === "number" && Number.isInteger(r.line) && r.line > 0
? r.line
: null,
issue,
fix: typeof r.fix === "string" ? r.fix : "",
};
}
export function computeDisagreements(args: {
securityVerdict: TrioVerdict;
correctnessVerdict: TrioVerdict;
styleVerdict: TrioVerdict;
}): TrioDisagreement[] {
const verdicts: TrioVerdict[] = [
args.securityVerdict,
args.correctnessVerdict,
args.styleVerdict,
];
const byKey = new Map<
string,
{
file: string;
line: number | null;
failingPersonas: Set<TrioPersona>;
}
>();
for (const v of verdicts) {
for (const f of v.findings) {
const file = f.file;
if (!file) continue;
const key = `${file}::${f.line ?? ""}`;
let bucket = byKey.get(key);
if (!bucket) {
bucket = { file, line: f.line, failingPersonas: new Set() };
byKey.set(key, bucket);
}
bucket.failingPersonas.add(v.persona);
}
}
const allPersonas: TrioPersona[] = ["security", "correctness", "style"];
const disagreements: TrioDisagreement[] = [];
for (const bucket of byKey.values()) {
if (
bucket.failingPersonas.size === 0 ||
bucket.failingPersonas.size === allPersonas.length
) {
continue;
}
disagreements.push({
file: bucket.file,
line: bucket.line,
failingPersonas: Array.from(bucket.failingPersonas).sort() as TrioPersona[],
passingPersonas: allPersonas.filter(
(p) => !bucket.failingPersonas.has(p)
),
});
}
disagreements.sort((a, b) => {
if (a.file !== b.file) return a.file < b.file ? -1 : 1;
return (a.line ?? 0) - (b.line ?? 0);
});
return disagreements;
}
async function persistTrioComments(args: {
pullRequestId: string;
result: TrioReviewResult;
}): Promise<void> {
let authorId: string | null = null;
try {
const [pr] = await db
.select({ authorId: pullRequests.authorId })
.from(pullRequests)
.where(eq(pullRequests.id, args.pullRequestId))
.limit(1);
if (pr) authorId = pr.authorId;
} catch {
}
if (!authorId) return;
const verdicts: TrioVerdict[] = [
args.result.securityVerdict,
args.result.correctnessVerdict,
args.result.styleVerdict,
];
for (const v of verdicts) {
const body = renderPersonaCommentBody(v);
try {
await db.insert(prComments).values({
pullRequestId: args.pullRequestId,
authorId,
isAiReview: true,
body,
});
} catch (err) {
console.error(
`[ai-review-trio] persona ${v.persona} comment insert failed for PR ${args.pullRequestId}:`,
err instanceof Error ? err.message : err
);
}
}
try {
await db.insert(prComments).values({
pullRequestId: args.pullRequestId,
authorId,
isAiReview: true,
body: renderSummaryCommentBody(args.result),
});
} catch (err) {
console.error(
`[ai-review-trio] summary insert failed for PR ${args.pullRequestId}:`,
err instanceof Error ? err.message : err
);
}
}
function renderPersonaCommentBody(v: TrioVerdict): string {
const marker = TRIO_COMMENT_MARKER[v.persona];
const heading = `${marker}\n## AI ${v.persona[0].toUpperCase() + v.persona.slice(1)} Review — ${v.verdict === "pass" ? "Pass" : "Fail"}`;
if (v.failed) {
return `${heading}\n\n_AI review call failed; treating as fail-closed. A human reviewer should look at this PR._`;
}
if (v.findings.length === 0) {
return `${heading}\n\nNo ${v.persona} issues detected.`;
}
const lines = v.findings.map((f) => {
const loc = f.file
? `\`${f.file}${f.line ? `:${f.line}` : ""}\``
: "_(unattributed)_";
return `- **${f.severity}** ${loc} — ${f.issue}${f.fix ? ` _Fix: ${f.fix}_` : ""}`;
});
return `${heading}\n\n${lines.join("\n")}`;
}
function renderSummaryCommentBody(r: TrioReviewResult): string {
const verdictLine = (v: TrioVerdict): string =>
`- **${v.persona}**: ${v.verdict === "pass" ? "✓ pass" : "✗ fail"}${v.failed ? " _(call failed)_" : ""} — ${v.findings.length} finding(s)`;
const disagreementLines =
r.disagreements.length === 0
? "_All three reviewers agree on every flagged location._"
: r.disagreements
.map((d) => {
const loc = `\`${d.file}${d.line ? `:${d.line}` : ""}\``;
return `- ${loc} — ${d.failingPersonas.join(", ")} say ✗, ${d.passingPersonas.join(", ")} say ✓`;
})
.join("\n");
return [
TRIO_SUMMARY_MARKER,
"## AI Trio Review",
"",
"Three independent reviewers ran in parallel — security, correctness, style.",
"",
"### Verdicts",
verdictLine(r.securityVerdict),
verdictLine(r.correctnessVerdict),
verdictLine(r.styleVerdict),
"",
"### Disagreements",
disagreementLines,
].join("\n");
}
export const __test = {
PERSONA_PROMPT,
normaliseFinding,
renderPersonaCommentBody,
renderSummaryCommentBody,
DIFF_BYTE_CAP,
};
|