-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathprepare-review-payload.ts
More file actions
527 lines (484 loc) · 18.5 KB
/
prepare-review-payload.ts
File metadata and controls
527 lines (484 loc) · 18.5 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
/**
* Prepare Code Review Payload
*
* Extracts all preparation logic (DB lookups, token generation, prompt generation)
* Returns complete payload ready for cloud agent
*
* Supports both GitHub and GitLab platforms.
*/
import { captureException } from '@sentry/nextjs';
import { db } from '@/lib/drizzle';
import { kilocode_users } from '@kilocode/db/schema';
import { eq } from 'drizzle-orm';
import { generateApiToken } from '@/lib/tokens';
import {
generateGitHubInstallationToken,
findKiloReviewComment,
fetchPRInlineComments,
getPRHeadCommit,
} from '@/lib/integrations/platforms/github/adapter';
import type { GitHubAppType } from '@/lib/integrations/platforms/github/app-selector';
import {
findKiloReviewNote,
fetchMRInlineComments,
getMRHeadCommit,
getMRDiffRefs,
GitLabProjectAccessTokenPermissionError,
} from '@/lib/integrations/platforms/gitlab/adapter';
import {
getOrCreateProjectAccessToken,
type GitLabIntegrationMetadata,
} from '@/lib/integrations/gitlab-service';
import type {
ExistingReviewState,
PreviousReviewStatus,
GitLabDiffContext,
} from '../prompts/generate-prompt';
import { getIntegrationById } from '@/lib/integrations/db/platform-integrations';
import { getCodeReviewById, findPreviousCompletedReview } from '../db/code-reviews';
import { isFeatureFlagEnabled } from '@/lib/posthog-feature-flags';
import {
DEFAULT_CODE_REVIEW_MODEL,
DEFAULT_CODE_REVIEW_MODE,
FEATURE_FLAG_INCREMENTAL_REVIEW,
} from '../core/constants';
import type { Owner } from '../core';
import { generateReviewPrompt } from '../prompts/generate-prompt';
import type { CodeReviewAgentConfig } from '@/lib/agent-config/core/types';
import { logExceptInTest, errorExceptInTest } from '@/lib/utils.server';
import type { CodeReviewPlatform } from '../core/schemas';
import { PLATFORM } from '@/lib/integrations/core/constants';
export type PreparePayloadParams = {
reviewId: string;
owner: Owner;
agentConfig: {
config: CodeReviewAgentConfig | Record<string, unknown>;
[key: string]: unknown;
};
/** Platform type (defaults to 'github' for backward compatibility) */
platform?: CodeReviewPlatform;
};
export type SessionInput = {
/** GitHub repo in format "owner/repo" (for GitHub platform) */
githubRepo?: string;
/** Full git URL for cloning (for GitLab and other platforms) */
gitUrl?: string;
kilocodeOrganizationId?: string;
prompt: string;
mode: 'code';
model: string;
/** Thinking effort variant name (e.g. "high", "max") — undefined means model default */
variant?: string;
upstreamBranch: string;
/** GitHub installation token (for GitHub platform) */
githubToken?: string;
/** Generic git token for authentication (for GitLab and other platforms) */
gitToken?: string;
/** Git platform type for correct token/env var handling */
platform?: 'github' | 'gitlab';
/** Gate threshold — when not 'off', the agent should report gateResult in its callback */
gateThreshold?: 'off' | 'all' | 'warning' | 'critical';
};
export type CodeReviewPayload = {
reviewId: string;
authToken: string;
sessionInput: SessionInput;
owner: Owner;
skipBalanceCheck?: boolean;
/** Which cloud agent backend to use: 'v1' (cloud-agent SSE) or 'v2' (cloud-agent-next) */
agentVersion?: string;
/** Cloud-agent session ID from a previous completed review, for session continuation */
previousCloudAgentSessionId?: string;
};
/**
* Prepare complete payload for code review
* Does all the heavy lifting: DB queries, token generation, prompt generation
* Supports both GitHub and GitLab platforms.
*/
export async function prepareReviewPayload(
params: PreparePayloadParams
): Promise<CodeReviewPayload> {
const { reviewId, owner, agentConfig, platform = 'github' } = params;
logExceptInTest('[prepareReviewPayload] Starting payload preparation', {
reviewId,
platform,
ownerType: owner.type,
ownerId: owner.id,
});
try {
// 1. Get the review from DB
const review = await getCodeReviewById(reviewId);
if (!review) {
throw new Error(`Review ${reviewId} not found`);
}
logExceptInTest('[prepareReviewPayload] Found review in DB', {
reviewId,
repoFullName: review.repo_full_name,
prNumber: review.pr_number,
platformIntegrationId: review.platform_integration_id,
headRef: review.head_ref,
});
// 2. Get the user by userId
const [user] = await db
.select()
.from(kilocode_users)
.where(eq(kilocode_users.id, owner.userId))
.limit(1);
if (!user) {
throw new Error(`User ${owner.userId} not found`);
}
// 3. Get platform token and build review state based on platform
let githubToken: string | undefined;
let gitlabToken: string | undefined;
let gitlabInstanceUrl: string | undefined;
let existingReviewState: ExistingReviewState | null = null;
let gitlabContext: GitLabDiffContext | undefined;
if (review.platform_integration_id) {
const integration = await getIntegrationById(review.platform_integration_id);
if (platform === 'github' && integration?.platform_installation_id) {
try {
// Use the stored app type (defaults to 'standard' for existing integrations)
const appType: GitHubAppType = integration.github_app_type || 'standard';
// GitHub: Use installation token
const tokenData = await generateGitHubInstallationToken(
integration.platform_installation_id,
appType
);
githubToken = tokenData.token;
// Build complete review state for intelligent update/create decisions
try {
const [repoOwner, repoName] = review.repo_full_name.split('/');
// Fetch all state in parallel for efficiency
const [summaryComment, inlineComments, headCommitSha] = await Promise.all([
findKiloReviewComment(
integration.platform_installation_id,
repoOwner,
repoName,
review.pr_number,
appType
),
fetchPRInlineComments(
integration.platform_installation_id,
repoOwner,
repoName,
review.pr_number,
appType
),
getPRHeadCommit(
integration.platform_installation_id,
repoOwner,
repoName,
review.pr_number,
appType
),
]);
existingReviewState = buildReviewState(summaryComment, inlineComments, headCommitSha);
logExceptInTest('[prepareReviewPayload] Built GitHub review state', {
reviewId,
hasSummary: !!summaryComment,
inlineCount: inlineComments.length,
previousStatus: existingReviewState.previousStatus,
headCommitSha: headCommitSha.substring(0, 8),
});
} catch (stateLookupError) {
// Non-critical - continue without state info
logExceptInTest('[prepareReviewPayload] Failed to build GitHub review state:', {
reviewId,
error: stateLookupError,
});
}
} catch (authError) {
captureException(authError, {
tags: { operation: 'prepareReviewPayload', step: 'get-github-token' },
extra: { reviewId, platformIntegrationId: review.platform_integration_id },
});
// Continue without token - cloud agent may still work with public repos
}
} else if (platform === PLATFORM.GITLAB && integration) {
// GitLab: Use Project Access Token (PrAT) for all operations
// PrAT is required for cloning private repos and for the glab CLI.
// Unlike GitHub, we cannot fall back to no-token for GitLab private repos,
// so auth errors here are hard failures that must propagate.
const metadata = integration.metadata as GitLabIntegrationMetadata | null;
gitlabInstanceUrl = metadata?.gitlab_instance_url || 'https://gitlab.com';
const instanceUrl = gitlabInstanceUrl;
logExceptInTest('[prepareReviewPayload] GitLab integration found', {
integrationId: integration.id,
instanceUrl,
});
// Get or create Project Access Token (PrAT) for all GitLab operations
const projectId = review.platform_project_id;
if (!projectId) {
throw new Error(
`GitLab code review requires platform_project_id. ` +
`Review ${reviewId} for ${review.repo_full_name} is missing this field.`
);
}
try {
gitlabToken = await getOrCreateProjectAccessToken(integration, projectId);
logExceptInTest('[prepareReviewPayload] Using PrAT for code review', {
reviewId,
repoFullName: review.repo_full_name,
projectId,
});
} catch (pratError) {
if (pratError instanceof GitLabProjectAccessTokenPermissionError) {
throw new Error(
`Cannot create Project Access Token for GitLab code review. ` +
`You need Maintainer role or higher on project ${review.repo_full_name}. ` +
`Error: ${pratError.message}`
);
}
throw new Error(
`Failed to create Project Access Token for GitLab code review on ${review.repo_full_name}. ` +
`Error: ${pratError instanceof Error ? pratError.message : String(pratError)}`
);
}
// Build complete review state for GitLab (using PrAT for reading)
try {
const mrIid = review.pr_number;
// Use repo_full_name as the project path for GitLab API calls
const repoPath = review.repo_full_name;
// Fetch all state in parallel for efficiency (using PrAT)
const [summaryNote, inlineComments, headCommitSha, diffRefs] = await Promise.all([
findKiloReviewNote(gitlabToken, repoPath, mrIid, instanceUrl),
fetchMRInlineComments(gitlabToken, repoPath, mrIid, instanceUrl),
getMRHeadCommit(gitlabToken, repoPath, mrIid, instanceUrl),
getMRDiffRefs(gitlabToken, repoPath, mrIid, instanceUrl),
]);
// Convert GitLab note format to common format
const summaryComment = summaryNote
? { commentId: summaryNote.noteId, body: summaryNote.body }
: null;
// Convert GitLab inline comments to common format
const convertedInlineComments = inlineComments.map(c => ({
id: c.id,
path: c.path,
line: c.line,
body: c.body,
isOutdated: c.isOutdated,
}));
existingReviewState = buildReviewState(
summaryComment,
convertedInlineComments,
headCommitSha
);
// Store GitLab diff context for prompt generation
gitlabContext = {
baseSha: diffRefs.baseSha,
startSha: diffRefs.startSha,
headSha: diffRefs.headSha,
};
logExceptInTest('[prepareReviewPayload] Built GitLab review state', {
reviewId,
hasSummary: !!summaryNote,
inlineCount: inlineComments.length,
previousStatus: existingReviewState.previousStatus,
headCommitSha: headCommitSha.substring(0, 8),
});
} catch (stateLookupError) {
// Non-critical - continue without state info
logExceptInTest('[prepareReviewPayload] Failed to build GitLab review state:', {
reviewId,
error: stateLookupError,
});
}
}
}
// 4. Check for previous completed review (incremental review optimization)
// Both previousHeadSha (for diff base) and previousCloudAgentSessionId (for session
// continuation) are derived from the same review row to avoid mismatches.
let previousHeadSha: string | null = null;
let previousCloudAgentSessionId: string | undefined;
const incrementalEnabled = await isFeatureFlagEnabled(
FEATURE_FLAG_INCREMENTAL_REVIEW,
owner.userId
);
logExceptInTest('[prepareReviewPayload] Incremental review flag evaluated', {
reviewId,
incrementalEnabled,
ownerId: owner.userId,
});
if (incrementalEnabled) {
try {
const previousReview = await findPreviousCompletedReview(
review.repo_full_name,
review.pr_number,
existingReviewState?.headCommitSha ?? review.head_sha,
platform
);
previousHeadSha = previousReview?.head_sha ?? null;
previousCloudAgentSessionId = previousReview?.session_id ?? undefined;
if (previousHeadSha) {
logExceptInTest(
'[prepareReviewPayload] Found previous completed review for incremental mode',
{
reviewId,
previousHeadSha: previousHeadSha.substring(0, 8),
currentHeadSha: review.head_sha.substring(0, 8),
previousCloudAgentSessionId,
}
);
} else {
logExceptInTest(
'[prepareReviewPayload] No previous completed review found, using full review',
{ reviewId }
);
}
} catch (error) {
// Non-critical - fall back to full review
logExceptInTest(
'[prepareReviewPayload] Failed to fetch previous review, falling back to full review:',
{
reviewId,
error,
}
);
}
}
// 5. Generate auth token for cloud agent with bot identifier
const authToken = generateApiToken(user, { botId: 'reviewer' });
// 6. Generate dynamic review prompt
const { prompt, version, source } = await generateReviewPrompt(
agentConfig.config as CodeReviewAgentConfig,
review.repo_full_name,
review.pr_number,
{
reviewId,
existingReviewState,
platform,
gitlabContext,
previousHeadSha,
}
);
logExceptInTest('[prepareReviewPayload] Generated prompt:', {
reviewId,
platform,
version,
source,
promptLength: prompt.length,
});
// 7. Prepare session input
// Note: cloud-agent automatically sets GH_TOKEN/GITLAB_TOKEN from token parameters
const config = agentConfig.config as CodeReviewAgentConfig;
// Build platform-specific session input
// GitHub: uses githubRepo (owner/repo format) + githubToken
// GitLab: uses gitUrl (full HTTPS URL) + gitToken
const variant = config.thinking_effort ?? undefined;
// Defense-in-depth: only send gateThreshold to the agent when the PR gate flag is enabled.
// This prevents a stale non-'off' config from activating gating after the flag is turned off.
const isPrGateEnabled =
process.env.NODE_ENV === 'development' ||
(await isFeatureFlagEnabled('code-review-pr-gate', owner.userId));
const gateThreshold = isPrGateEnabled ? (config.gate_threshold ?? 'off') : 'off';
const sessionInput: SessionInput =
platform === PLATFORM.GITLAB
? {
// GitLab: use full git URL for cloning
gitUrl: `${gitlabInstanceUrl || 'https://gitlab.com'}/${review.repo_full_name}.git`,
gitToken: gitlabToken,
platform: 'gitlab',
kilocodeOrganizationId: owner.type === 'org' ? owner.id : undefined,
prompt,
mode: DEFAULT_CODE_REVIEW_MODE as 'code',
model: config.model_slug || DEFAULT_CODE_REVIEW_MODEL,
variant,
upstreamBranch: review.head_ref,
...(gateThreshold !== 'off' ? { gateThreshold } : {}),
}
: {
// GitHub: use owner/repo format
githubRepo: review.repo_full_name,
githubToken,
platform: 'github',
kilocodeOrganizationId: owner.type === 'org' ? owner.id : undefined,
prompt,
mode: DEFAULT_CODE_REVIEW_MODE as 'code',
model: config.model_slug || DEFAULT_CODE_REVIEW_MODEL,
variant,
upstreamBranch: review.head_ref,
...(gateThreshold !== 'off' ? { gateThreshold } : {}),
};
// Log the session input for GitLab
if (platform === PLATFORM.GITLAB) {
logExceptInTest('[prepareReviewPayload] GitLab session input prepared', {
gitUrl: sessionInput.gitUrl,
hasGitToken: !!sessionInput.gitToken,
upstreamBranch: sessionInput.upstreamBranch,
model: sessionInput.model,
});
} else {
logExceptInTest('[prepareReviewPayload] GitHub session input prepared', {
githubRepo: sessionInput.githubRepo,
hasGithubToken: !!sessionInput.githubToken,
upstreamBranch: sessionInput.upstreamBranch,
model: sessionInput.model,
});
}
// 8. Build complete payload
const payload: CodeReviewPayload = {
reviewId,
authToken,
sessionInput,
owner,
previousCloudAgentSessionId,
};
logExceptInTest('[prepareReviewPayload] Prepared payload', {
reviewId,
platform,
owner,
sessionInput: {
...sessionInput,
githubToken: sessionInput.githubToken ? '***' : undefined, // Redact token
gitToken: sessionInput.gitToken ? '***' : undefined, // Redact token
prompt: sessionInput.prompt.substring(0, 200) + '...', // Show first 200 chars
},
});
return payload;
} catch (error) {
errorExceptInTest('[prepareReviewPayload] Error preparing payload:', error);
captureException(error, {
tags: { operation: 'prepareReviewPayload' },
extra: { reviewId, owner, platform },
});
throw error;
}
}
/**
* Build review state from summary comment and inline comments
* Common logic for both GitHub and GitLab
*/
function buildReviewState(
summaryComment: { commentId: number; body: string } | null,
inlineComments: Array<{
id: number;
path: string;
line: number | null;
body: string;
isOutdated: boolean;
}>,
headCommitSha: string
): ExistingReviewState {
// Determine previous status from summary body
let previousStatus: PreviousReviewStatus = 'no-review';
if (summaryComment) {
if (
summaryComment.body.includes('No Issues Found') ||
summaryComment.body.includes('No New Issues')
) {
previousStatus = 'no-issues';
} else if (
summaryComment.body.includes('Issues Found') ||
summaryComment.body.includes('WARNING') ||
summaryComment.body.includes('CRITICAL')
) {
previousStatus = 'issues-found';
}
}
return {
summaryComment,
inlineComments,
previousStatus,
headCommitSha,
};
}