plugin-git-manager 1.2.10 → 1.2.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1221 +1,1263 @@
1
- import { Context } from '@nocobase/actions';
2
- import type { Application } from '@nocobase/server';
3
- import { parseGitLabProject } from '../utils/gitlab-url';
4
- import { redactPat } from '../utils/redact';
5
-
6
- export const WORKER_JOB_GIT_REVIEW_PROCESS = 'git-review:process';
7
- const REVIEW_QUEUE_CHANNEL = 'plugin-git-manager.review';
8
- const REVIEW_WORKER_ALIASES = [REVIEW_QUEUE_CHANNEL, 'plugin-git-manager:review:queue'];
9
- const REVIEW_QUEUE_CONCURRENCY = Math.max(
10
- 1,
11
- Number.parseInt(process.env.GIT_REVIEW_QUEUE_CONCURRENCY || process.env.GIT_REVIEW_MAX_CONCURRENCY || '3', 10) || 3,
12
- );
13
- const REVIEW_QUEUE_TIMEOUT_MS = Math.max(
14
- 60_000,
15
- Number.parseInt(process.env.GIT_REVIEW_QUEUE_TIMEOUT_MS || '', 10) || 10 * 60 * 1000,
16
- );
17
- const REVIEW_QUEUE_POLL_INTERVAL_MS = Math.max(
18
- 1000,
19
- Number.parseInt(process.env.GIT_REVIEW_QUEUE_POLL_INTERVAL_MS || '', 10) || 5000,
20
- );
21
- const REVIEW_PROCESS_LOCK_TTL_MS = Math.max(REVIEW_QUEUE_TIMEOUT_MS + 60_000, 11 * 60 * 1000);
22
- const REVIEW_QUEUE_WAKE_CHANNEL = 'plugin-git-manager.review.wake';
23
- const REVIEW_QUEUE_REDIS_CONNECTION = 'plugin-git-manager.review.queue';
24
-
25
- interface TriggerArgs {
26
- flowId?: number | null;
27
- repositoryId: number;
28
- targetType: 'mr' | 'commit' | 'branch';
29
- mrIid?: number | null;
30
- commitSha?: string | null;
31
- branch?: string | null;
32
- headSha?: string | null;
33
- extraInstructions?: string;
34
- triggeredBy?: 'manual' | 'poll';
35
- userId?: number | string | null;
36
- }
37
-
38
- interface ReviewFlowSnapshot {
39
- id: number;
40
- name?: string;
41
- postMode?: string;
42
- llmService?: string | null;
43
- model?: string | null;
44
- instructions?: string | null;
45
- }
46
-
47
- interface ReviewQueueMessage {
48
- reviewId: number;
49
- repositoryId: number;
50
- targetType: 'mr' | 'commit' | 'branch';
51
- mrIid?: number | null;
52
- commitSha?: string | null;
53
- branch?: string | null;
54
- headSha?: string | null;
55
- aiEmployeeUsername: string;
56
- extraInstructions?: string;
57
- userId?: number | string | null;
58
- flowSnapshot?: ReviewFlowSnapshot;
59
- }
60
-
61
- interface QueuedReviewMetadata {
62
- queuedAt?: string;
63
- aiEmployeeUsername?: string;
64
- extraInstructions?: string | null;
65
- userId?: number | string | null;
66
- flowSnapshot?: ReviewFlowSnapshot;
67
- }
68
-
69
- let reviewQueueTimer: NodeJS.Timeout | null = null;
70
- let reviewQueueKickTimer: NodeJS.Timeout | null = null;
71
- let reviewQueueProcessing = false;
72
- let reviewWakeHandler: ((message?: any) => Promise<void>) | null = null;
73
-
74
- function getActionParams(ctx: Context) {
75
- return { ...ctx.action.params, ...ctx.action.params?.values, ...((ctx as any).request?.body || {}) };
76
- }
77
-
78
- /**
79
- * Per-target mutex to prevent two concurrent calls to
80
- * `triggerReviewInternal` for the same MR / commit / branch from racing
81
- * `findOne` → `create` and producing two duplicate review rows or
82
- * scheduling two `runReview`s.
83
- *
84
- * Uses `app.lockManager` so the same code path covers both single-node
85
- * (in-memory `async-mutex`) and HA cluster (Redis-backed Redlock when
86
- * `plugin-cluster-manager` is active and `LOCK_ADAPTER_DEFAULT=redis`).
87
- * The locked region only does an upsert + queue publish (a few ms), so a 30s
88
- * TTL is generous and auto-releases if the process crashes.
89
- */
90
- function targetKey(args: TriggerArgs): string {
91
- if (args.targetType === 'mr') return `${args.repositoryId}:mr:${args.mrIid}`;
92
- if (args.targetType === 'commit') return `${args.repositoryId}:commit:${args.commitSha}`;
93
- return `${args.repositoryId}:branch:${args.branch}`;
94
- }
95
-
96
- const TRIGGER_LOCK_TTL_MS = 30_000;
97
-
98
- async function withTriggerLock<T>(app: Application, key: string, fn: () => Promise<T>): Promise<T> {
99
- const lockKey = `git-review:trigger:${key}`;
100
- return app.lockManager.runExclusive(lockKey, fn, TRIGGER_LOCK_TTL_MS);
101
- }
102
-
103
- /**
104
- * Trigger an AI-driven code review for an MR / commit / branch.
105
- * The review record is upserted synchronously, then queued for an available
106
- * git-review worker. The action returns immediately with the reviewId.
107
- */
108
- export async function triggerReview(ctx: Context, next: () => Promise<void>) {
109
- const params = getActionParams(ctx);
110
- const { flowId, repositoryId, targetType, mrIid, commitSha, branch, extraInstructions } = params;
111
-
112
- if (!repositoryId) ctx.throw(400, 'repositoryId is required');
113
- if (!targetType) ctx.throw(400, 'targetType is required');
114
- if (!['mr', 'commit', 'branch'].includes(targetType)) ctx.throw(400, 'invalid targetType');
115
- if (targetType === 'mr' && !mrIid) ctx.throw(400, 'mrIid is required for MR review');
116
- if (targetType === 'commit' && !commitSha) ctx.throw(400, 'commitSha is required for commit review');
117
- if (targetType === 'branch' && !branch) ctx.throw(400, 'branch is required for branch review');
118
-
119
- const userId = (ctx as any).state?.currentUser?.id;
120
- try {
121
- const reviewId = await triggerReviewInternal(ctx.app, {
122
- flowId,
123
- repositoryId: Number(repositoryId),
124
- targetType,
125
- mrIid: mrIid != null ? Number(mrIid) : null,
126
- commitSha: commitSha || null,
127
- branch: branch || null,
128
- extraInstructions,
129
- triggeredBy: 'manual',
130
- userId,
131
- });
132
- ctx.body = { success: true, data: { reviewId } };
133
- } catch (err: any) {
134
- ctx.throw(err.status || 400, err.message || 'Failed to trigger review');
135
- }
136
- await next();
137
- }
138
-
139
- /**
140
- * Programmatic entry point — used by manual action and by the poller.
141
- * Returns the reviewId of the upserted record.
142
- */
143
- export async function triggerReviewInternal(app: Application, args: TriggerArgs): Promise<number> {
144
- return withTriggerLock(app, targetKey(args), () => triggerReviewInternalLocked(app, args));
145
- }
146
-
147
- async function triggerReviewInternalLocked(app: Application, args: TriggerArgs): Promise<number> {
148
- const db = app.db;
149
- const flowsRepo = db.getRepository('gitReviewFlows');
150
-
151
- // Resolve flow
152
- let flow: any = null;
153
- if (args.flowId) {
154
- flow = await flowsRepo.findOne({ filterByTk: args.flowId });
155
- if (!flow) throwHttp(404, 'Review flow not found');
156
- if (!flow.get('enabled')) throwHttp(400, 'Review flow is disabled');
157
- } else {
158
- // Find flows scoped to repo or global, prefer repo-specific
159
- const candidates = await flowsRepo.find({
160
- filter: {
161
- enabled: true,
162
- $or: [{ repositoryId: args.repositoryId }, { repositoryId: null }],
163
- },
164
- sort: ['-repositoryId'],
165
- });
166
- flow = pickFlowMatchingBranch(candidates, args.branch || undefined);
167
- if (!flow) throwHttp(400, 'No enabled review flow found for this repository');
168
- }
169
-
170
- // Apply branchFilter even when flow is explicitly given (consistency)
171
- if (args.branch && !branchMatches(flow, args.branch)) {
172
- throwHttp(400, `Branch '${args.branch}' does not match flow's branchFilter`);
173
- }
174
-
175
- const aiEmployeeUsername = flow.get('aiEmployeeUsername') as string;
176
- if (!aiEmployeeUsername) throwHttp(400, 'Flow has no AI employee configured');
177
-
178
- const repo = await db.getRepository('gitRepositories').findOne({ filterByTk: args.repositoryId });
179
- if (!repo) throwHttp(404, 'Repository not found');
180
-
181
- // For MR targets, ensure we know the head SHA so the "new commits" indicator
182
- // works regardless of whether the trigger came from poller or manual UI.
183
- let headSha = args.headSha || null;
184
- if (args.targetType === 'mr' && !headSha && args.mrIid) {
185
- headSha = await fetchMrHeadSha(repo, args.mrIid).catch(() => null);
186
- }
187
-
188
- // Upsert review record (1 per MR/commit/branch target)
189
- const reviewsRepo = db.getRepository('gitCodeReviews');
190
- const targetFilter: any = {
191
- repositoryId: args.repositoryId,
192
- targetType: args.targetType,
193
- };
194
- if (args.targetType === 'mr') targetFilter.mrIid = args.mrIid;
195
- else if (args.targetType === 'commit') targetFilter.commitSha = args.commitSha;
196
- else if (args.targetType === 'branch') targetFilter.branch = args.branch;
197
-
198
- const existing = await reviewsRepo.findOne({ filter: targetFilter });
199
- // Preserve a poller-tracked latestSha if we don't have a fresher one.
200
- const existingLatestSha = existing?.get('latestSha') as string | null | undefined;
201
- const baseValues: any = {
202
- flowId: flow.get('id'),
203
- repositoryId: args.repositoryId,
204
- targetType: args.targetType,
205
- mrIid: args.targetType === 'mr' ? args.mrIid : null,
206
- commitSha: args.targetType === 'commit' ? args.commitSha : null,
207
- branch: args.branch || null,
208
- headSha: headSha,
209
- latestSha: headSha || existingLatestSha || null,
210
- triggeredBy: args.triggeredBy || 'manual',
211
- status: 'pending',
212
- // `startedAt` is stamped by the queue worker when execution actually
213
- // starts. Pending rows are durable queue items for worker polling.
214
- startedAt: null,
215
- finishedAt: null,
216
- durationMs: null,
217
- postStatus: getInitialPostStatus(flow, args.targetType),
218
- error: null,
219
- metadata: {
220
- queuedAt: new Date().toISOString(),
221
- aiEmployeeUsername,
222
- extraInstructions: args.extraInstructions || null,
223
- userId: args.userId ?? null,
224
- flowSnapshot: createFlowSnapshot(flow),
225
- },
226
- };
227
-
228
- let reviewId: number;
229
- if (existing) {
230
- const st = existing.get('status');
231
- // Treat `pending` the same as `running`: between this fn returning and
232
- // the scheduled `runReview` flipping the row to `running`, a second
233
- // caller would otherwise slip past and schedule a duplicate runReview.
234
- // Stuck `pending` rows (process died before runReview ran) are swept
235
- // by `recoverStuckReviews` on next startup.
236
- if (st === 'running' || st === 'pending') {
237
- return existing.get('id') as number;
238
- }
239
- await reviewsRepo.update({
240
- filterByTk: existing.get('id'),
241
- values: baseValues,
242
- });
243
- reviewId = existing.get('id') as number;
244
- } else {
245
- const review = await reviewsRepo.create({ values: baseValues });
246
- reviewId = review.get('id') as number;
247
- }
248
-
249
- // Queue for background workers; the action returns as soon as the message is published.
250
- await enqueueReview(app, {
251
- reviewId,
252
- repositoryId: args.repositoryId,
253
- targetType: args.targetType,
254
- mrIid: args.targetType === 'mr' ? args.mrIid : null,
255
- commitSha: args.targetType === 'commit' ? args.commitSha : null,
256
- branch: args.branch || undefined,
257
- headSha,
258
- aiEmployeeUsername,
259
- extraInstructions: args.extraInstructions,
260
- userId: args.userId ?? null,
261
- flowSnapshot: createFlowSnapshot(flow),
262
- });
263
-
264
- return reviewId;
265
- }
266
-
267
- export function registerReviewQueue(app: Application) {
268
- app.eventQueue.subscribe(REVIEW_QUEUE_CHANNEL, {
269
- concurrency: REVIEW_QUEUE_CONCURRENCY,
270
- idle: () => isGitReviewWorker(app),
271
- process: async (message: ReviewQueueMessage) => {
272
- await processQueuedReview(app, message);
273
- },
274
- });
275
- if (!isGitReviewWorker(app)) {
276
- app.on('afterStart', () => clearLocalReviewMemoryQueue(app));
277
- }
278
- startReviewQueueProcessor(app);
279
- }
280
-
281
- export function unregisterReviewQueue(app: Application) {
282
- app.eventQueue.unsubscribe(REVIEW_QUEUE_CHANNEL);
283
- stopReviewQueueProcessor(app);
284
- }
285
-
286
- function createFlowSnapshot(flow: any): ReviewFlowSnapshot {
287
- return {
288
- id: Number(flow.get('id')),
289
- name: flow.get('name') as string,
290
- postMode: flow.get('postMode') as string,
291
- llmService: flow.get('llmService') as string | null,
292
- model: flow.get('model') as string | null,
293
- instructions: flow.get('instructions') as string | null,
294
- };
295
- }
296
-
297
- function createFlowFromSnapshot(snapshot: ReviewFlowSnapshot | undefined, fallback?: any) {
298
- return {
299
- get(name: string) {
300
- if (snapshot && Object.prototype.hasOwnProperty.call(snapshot, name)) {
301
- return (snapshot as any)[name];
302
- }
303
- return fallback?.get?.(name);
304
- },
305
- };
306
- }
307
-
308
- function isGitReviewWorker(app: Application): boolean {
309
- return app.serving(WORKER_JOB_GIT_REVIEW_PROCESS) || workerModeServesGitReview();
310
- }
311
-
312
- function workerModeServesGitReview(): boolean {
313
- const workerMode = process.env.WORKER_MODE || '';
314
- const workerModes = workerMode
315
- .split(',')
316
- .map((mode) => mode.trim())
317
- .filter(Boolean);
318
-
319
- return workerModes.some((mode) => {
320
- if (mode === '*' || mode === 'worker' || mode === 'task' || mode === WORKER_JOB_GIT_REVIEW_PROCESS) {
321
- return true;
322
- }
323
- return REVIEW_WORKER_ALIASES.some((alias) => mode === alias || mode.endsWith(`:${alias}`));
324
- });
325
- }
326
-
327
- function clearLocalReviewMemoryQueue(app: Application) {
328
- const eventQueue = (app as any).eventQueue;
329
- const adapter = eventQueue?.adapter;
330
- const fullChannel = eventQueue?.getFullChannel?.(REVIEW_QUEUE_CHANNEL);
331
- const queue = fullChannel ? adapter?.queues?.get?.(fullChannel) : null;
332
- if (!queue?.length) return;
333
-
334
- adapter.queues.set(fullChannel, []);
335
- app.log?.warn?.(
336
- `git review queue: cleared ${queue.length} stale local memory message(s) on non-worker node; pending DB rows will be picked up by workers`,
337
- );
338
- }
339
-
340
- function getReviewQueueRedisKey(app: Application): string {
341
- const appName = (app as any).name || process.env.APP_NAME || 'main';
342
- return `${appName}:plugin-git-manager:review:queue`;
343
- }
344
-
345
- async function getReviewQueueRedis(app: Application): Promise<any | null> {
346
- const manager = (app as any).redisConnectionManager;
347
- if (!manager?.getConnectionSync) {
348
- return null;
349
- }
350
-
351
- try {
352
- const connectionString = process.env.QUEUE_ADAPTER_REDIS_URL || process.env.REDIS_URL;
353
- return await manager.getConnectionSync(
354
- REVIEW_QUEUE_REDIS_CONNECTION,
355
- connectionString ? { connectionString } : undefined,
356
- );
357
- } catch (err: any) {
358
- app.log?.debug?.(`git review queue: Redis queue unavailable, falling back to DB polling: ${err?.message || err}`);
359
- return null;
360
- }
361
- }
362
-
363
- async function enqueueReviewToRedis(app: Application, message: ReviewQueueMessage): Promise<boolean> {
364
- const redis = await getReviewQueueRedis(app);
365
- if (!redis) return false;
366
-
367
- await redis.sendCommand(['RPUSH', getReviewQueueRedisKey(app), JSON.stringify(message)]);
368
- app.log?.debug?.(`git review queue: enqueued review ${message.reviewId} to Redis`);
369
- return true;
370
- }
371
-
372
- async function publishReviewQueueWake(app: Application, reviewId?: number) {
373
- try {
374
- await (app as any).pubSubManager?.publish?.(
375
- REVIEW_QUEUE_WAKE_CHANNEL,
376
- { reviewId },
377
- { skipSelf: !isGitReviewWorker(app) },
378
- );
379
- } catch (err: any) {
380
- app.log?.debug?.(`git review queue: wake publish skipped: ${err?.message || err}`);
381
- }
382
- }
383
-
384
- function startReviewQueueProcessor(app: Application) {
385
- if (!isGitReviewWorker(app)) {
386
- app.log?.debug?.('plugin-git-manager: review queue processor disabled on non-worker node');
387
- return;
388
- }
389
- if (reviewQueueTimer) return;
390
-
391
- reviewWakeHandler = async () => {
392
- scheduleReviewQueueTick(app, 0);
393
- };
394
-
395
- const subscribe = (app as any).pubSubManager?.subscribe?.(REVIEW_QUEUE_WAKE_CHANNEL, reviewWakeHandler);
396
- if (subscribe?.catch) {
397
- subscribe.catch((err: any) => app.log?.debug?.(`git review queue: wake subscribe skipped: ${err?.message || err}`));
398
- }
399
-
400
- reviewQueueTimer = setInterval(() => scheduleReviewQueueTick(app, 0), REVIEW_QUEUE_POLL_INTERVAL_MS);
401
- (reviewQueueTimer as any).unref?.();
402
- scheduleReviewQueueTick(app, 1000);
403
- app.log?.info?.(`plugin-git-manager: review queue processor started (interval ${REVIEW_QUEUE_POLL_INTERVAL_MS}ms)`);
404
- }
405
-
406
- function stopReviewQueueProcessor(app: Application) {
407
- if (reviewQueueTimer) {
408
- clearInterval(reviewQueueTimer);
409
- reviewQueueTimer = null;
410
- }
411
- if (reviewQueueKickTimer) {
412
- clearTimeout(reviewQueueKickTimer);
413
- reviewQueueKickTimer = null;
414
- }
415
- if (reviewWakeHandler) {
416
- const unsubscribe = (app as any).pubSubManager?.unsubscribe?.(REVIEW_QUEUE_WAKE_CHANNEL, reviewWakeHandler);
417
- if (unsubscribe?.catch) {
418
- unsubscribe.catch(() => undefined);
419
- }
420
- reviewWakeHandler = null;
421
- }
422
- reviewQueueProcessing = false;
423
- }
424
-
425
- function scheduleReviewQueueTick(app: Application, delayMs: number) {
426
- if (reviewQueueKickTimer) return;
427
- reviewQueueKickTimer = setTimeout(() => {
428
- reviewQueueKickTimer = null;
429
- runReviewQueueTick(app).catch((err) => app.log?.error?.('git review queue: processor tick failed', err));
430
- }, delayMs);
431
- (reviewQueueKickTimer as any).unref?.();
432
- }
433
-
434
- async function runReviewQueueTick(app: Application) {
435
- if (reviewQueueProcessing || !isGitReviewWorker(app)) return;
436
-
437
- reviewQueueProcessing = true;
438
- try {
439
- const redisMessages = await drainRedisReviewQueue(app, REVIEW_QUEUE_CONCURRENCY);
440
- await processReviewQueueMessages(app, redisMessages);
441
-
442
- const remaining = Math.max(1, REVIEW_QUEUE_CONCURRENCY - redisMessages.length);
443
- await processPendingReviews(app, remaining);
444
- } finally {
445
- reviewQueueProcessing = false;
446
- }
447
- }
448
-
449
- async function drainRedisReviewQueue(app: Application, count: number): Promise<ReviewQueueMessage[]> {
450
- const redis = await getReviewQueueRedis(app);
451
- if (!redis) return [];
452
-
453
- const key = getReviewQueueRedisKey(app);
454
- const messages: ReviewQueueMessage[] = [];
455
- for (let i = 0; i < count; i += 1) {
456
- const raw = await redis.sendCommand(['LPOP', key]);
457
- if (!raw) break;
458
- try {
459
- messages.push(JSON.parse(String(raw)));
460
- } catch (err: any) {
461
- app.log?.warn?.(`git review queue: dropped invalid Redis message: ${err?.message || err}`);
462
- }
463
- }
464
- return messages;
465
- }
466
-
467
- function getQueuedReviewMetadata(review: any): QueuedReviewMetadata {
468
- const raw = review?.get?.('metadata');
469
- if (!raw) return {};
470
- if (typeof raw === 'string') {
471
- try {
472
- return JSON.parse(raw) || {};
473
- } catch {
474
- return {};
475
- }
476
- }
477
- return typeof raw === 'object' ? raw : {};
478
- }
479
-
480
- function toNullableNumber(value: any): number | null {
481
- if (value === null || value === undefined || value === '') return null;
482
- const parsed = Number(value);
483
- return Number.isFinite(parsed) ? parsed : null;
484
- }
485
-
486
- function createReviewQueueMessageFromReview(review: any): ReviewQueueMessage {
487
- const metadata = getQueuedReviewMetadata(review);
488
- const targetType = review.get('targetType') as 'mr' | 'commit' | 'branch';
489
- return {
490
- reviewId: Number(review.get('id')),
491
- repositoryId: Number(review.get('repositoryId')),
492
- targetType,
493
- mrIid: targetType === 'mr' ? toNullableNumber(review.get('mrIid')) : null,
494
- commitSha: targetType === 'commit' ? (review.get('commitSha') as string | null) : null,
495
- branch: targetType === 'branch' ? (review.get('branch') as string | null) : null,
496
- headSha: review.get('headSha') as string | null,
497
- aiEmployeeUsername: metadata.aiEmployeeUsername || '',
498
- extraInstructions: metadata.extraInstructions || undefined,
499
- userId: metadata.userId ?? null,
500
- flowSnapshot: metadata.flowSnapshot,
501
- };
502
- }
503
-
504
- async function processPendingReviews(app: Application, count: number) {
505
- const pending = await app.db.getRepository('gitCodeReviews').find({
506
- filter: { status: 'pending' },
507
- sort: ['createdAt'],
508
- limit: count,
509
- });
510
- if (!pending?.length) return;
511
- await processReviewQueueMessages(app, pending.map(createReviewQueueMessageFromReview));
512
- }
513
-
514
- async function processReviewQueueMessages(app: Application, messages: ReviewQueueMessage[]) {
515
- if (!messages.length) return;
516
- await Promise.all(messages.map((message) => processQueuedReview(app, message)));
517
- }
518
-
519
- async function withReviewProcessLock<T>(app: Application, reviewId: number, fn: () => Promise<T>): Promise<T> {
520
- const lockKey = `git-review:process:${reviewId}`;
521
- return app.lockManager.runExclusive(lockKey, fn, REVIEW_PROCESS_LOCK_TTL_MS);
522
- }
523
-
524
- async function enqueueReview(app: Application, message: ReviewQueueMessage) {
525
- try {
526
- const queuedInRedis = await enqueueReviewToRedis(app, message);
527
- if (queuedInRedis) {
528
- await publishReviewQueueWake(app, message.reviewId);
529
- return;
530
- }
531
-
532
- await publishReviewQueueWake(app, message.reviewId);
533
-
534
- if (isGitReviewWorker(app)) {
535
- await app.eventQueue.publish(REVIEW_QUEUE_CHANNEL, message, {
536
- timeout: REVIEW_QUEUE_TIMEOUT_MS,
537
- maxRetries: 1,
538
- });
539
- return;
540
- }
541
-
542
- app.log?.warn?.(
543
- `git review queue: Redis queue is unavailable; review ${message.reviewId} will remain pending until a worker DB poller picks it up`,
544
- );
545
- } catch (err: any) {
546
- const safeMessage = redactPat(err?.message || String(err));
547
- await app.db.getRepository('gitCodeReviews').update({
548
- filterByTk: message.reviewId,
549
- values: {
550
- status: 'failed',
551
- error: `Failed to enqueue review: ${safeMessage}`,
552
- finishedAt: new Date(),
553
- },
554
- });
555
- throw err;
556
- }
557
- }
558
-
559
- async function failQueuedReview(app: Application, reviewId: number, err: any) {
560
- const safeMessage = redactPat(err?.message || String(err));
561
- await app.db.getRepository('gitCodeReviews').update({
562
- filterByTk: reviewId,
563
- values: {
564
- status: 'failed',
565
- error: safeMessage,
566
- finishedAt: new Date(),
567
- },
568
- });
569
- }
570
-
571
- async function processQueuedReview(app: Application, message: ReviewQueueMessage) {
572
- await withReviewProcessLock(app, message.reviewId, async () => {
573
- const db = app.db;
574
- const reviewsRepo = db.getRepository('gitCodeReviews');
575
- const review = await reviewsRepo.findOne({ filterByTk: message.reviewId });
576
- if (!review) {
577
- app.log?.warn?.(`git review queue: review ${message.reviewId} not found, skipping`);
578
- return;
579
- }
580
-
581
- if (review.get('status') !== 'pending') {
582
- app.log?.info?.(`git review queue: review ${message.reviewId} is ${review.get('status')}, skipping`);
583
- return;
584
- }
585
-
586
- const metadata = getQueuedReviewMetadata(review);
587
- const targetType = (message.targetType || review.get('targetType')) as 'mr' | 'commit' | 'branch';
588
-
589
- try {
590
- const repo = await db.getRepository('gitRepositories').findOne({
591
- filterByTk: message.repositoryId || review.get('repositoryId'),
592
- });
593
- if (!repo) throw new Error('Repository not found');
594
-
595
- const flowSnapshot = message.flowSnapshot || metadata.flowSnapshot;
596
- const storedFlow = await db.getRepository('gitReviewFlows').findOne({
597
- filterByTk: flowSnapshot?.id || review.get('flowId'),
598
- });
599
- const flow = createFlowFromSnapshot(flowSnapshot, storedFlow);
600
- const aiEmployeeUsername =
601
- message.aiEmployeeUsername || metadata.aiEmployeeUsername || (flow.get('aiEmployeeUsername') as string);
602
- if (!aiEmployeeUsername) throw new Error('Flow has no AI employee configured');
603
-
604
- await runReview(app, {
605
- reviewId: message.reviewId,
606
- flow,
607
- repo,
608
- targetType,
609
- mrIid: targetType === 'mr' ? message.mrIid ?? toNullableNumber(review.get('mrIid')) : null,
610
- commitSha: targetType === 'commit' ? message.commitSha || (review.get('commitSha') as string) : null,
611
- branch: message.branch || (review.get('branch') as string | undefined),
612
- headSha: message.headSha || (review.get('headSha') as string | null),
613
- aiEmployeeUsername,
614
- extraInstructions: message.extraInstructions ?? metadata.extraInstructions ?? undefined,
615
- userId: message.userId ?? metadata.userId ?? null,
616
- });
617
- } catch (err) {
618
- app.log?.error?.('git review queue: failed before review execution', err);
619
- await failQueuedReview(app, message.reviewId, err);
620
- }
621
- });
622
- }
623
-
624
- /**
625
- * Mark a review as approved and post its content to GitLab as an MR note.
626
- */
627
- export async function reviewApprovePost(ctx: Context, next: () => Promise<void>) {
628
- const params = getActionParams(ctx);
629
- const { reviewId, editedMarkdown } = params;
630
- if (!reviewId) ctx.throw(400, 'reviewId is required');
631
-
632
- const reviewsRepo = ctx.db.getRepository('gitCodeReviews');
633
- const review = await reviewsRepo.findOne({ filterByTk: reviewId });
634
- if (!review) ctx.throw(404, 'Review not found');
635
- if (review.get('status') !== 'completed') ctx.throw(400, 'Review is not completed');
636
- if (review.get('targetType') !== 'mr') ctx.throw(400, 'Only MR reviews can be posted');
637
-
638
- const markdown = (editedMarkdown ?? review.get('reviewMarkdown')) as string;
639
- if (!markdown) ctx.throw(400, 'No review content to post');
640
-
641
- const repo = await ctx.db.getRepository('gitRepositories').findOne({
642
- filterByTk: review.get('repositoryId'),
643
- });
644
- if (!repo) ctx.throw(404, 'Repository not found');
645
-
646
- const noteId = await postNoteToGitLab(repo, Number(review.get('mrIid')), markdown);
647
-
648
- const userId = (ctx as any).state?.currentUser?.id;
649
- await reviewsRepo.update({
650
- filterByTk: reviewId,
651
- values: {
652
- reviewMarkdown: markdown,
653
- postStatus: 'posted',
654
- postedNoteId: String(noteId),
655
- approvedBy: userId ? String(userId) : null,
656
- approvedAt: new Date(),
657
- error: null,
658
- },
659
- });
660
-
661
- ctx.body = { success: true, data: { reviewId, postedNoteId: noteId } };
662
- await next();
663
- }
664
-
665
- /**
666
- * Reject a pending review (do not post to GitLab).
667
- */
668
- export async function reviewReject(ctx: Context, next: () => Promise<void>) {
669
- const params = getActionParams(ctx);
670
- const { reviewId, reason } = params;
671
- if (!reviewId) ctx.throw(400, 'reviewId is required');
672
-
673
- const reviewsRepo = ctx.db.getRepository('gitCodeReviews');
674
- const review = await reviewsRepo.findOne({ filterByTk: reviewId });
675
- if (!review) ctx.throw(404, 'Review not found');
676
-
677
- const userId = (ctx as any).state?.currentUser?.id;
678
- await reviewsRepo.update({
679
- filterByTk: reviewId,
680
- values: {
681
- postStatus: 'rejected',
682
- approvedBy: userId ? String(userId) : null,
683
- approvedAt: new Date(),
684
- error: reason ? `Rejected: ${reason}` : 'Rejected',
685
- },
686
- });
687
-
688
- ctx.body = { success: true, data: { reviewId } };
689
- await next();
690
- }
691
-
692
- /* ───────── Helpers ───────── */
693
-
694
- interface RunReviewArgs {
695
- reviewId: number;
696
- flow: any;
697
- repo: any;
698
- targetType: string;
699
- mrIid: number | null;
700
- commitSha: string | null;
701
- branch?: string;
702
- headSha?: string | null;
703
- aiEmployeeUsername: string;
704
- extraInstructions?: string;
705
- userId?: number | string | null;
706
- }
707
-
708
- async function runReview(app: Application, args: RunReviewArgs) {
709
- const db = app.db;
710
- const reviewsRepo = db.getRepository('gitCodeReviews');
711
- const startedAt = new Date();
712
- let sessionId: string | null = null;
713
-
714
- try {
715
- await reviewsRepo.update({
716
- filterByTk: args.reviewId,
717
- values: { status: 'running', startedAt },
718
- });
719
-
720
- const employeeRecord = await db.getRepository('aiEmployees').findOne({
721
- filter: { username: args.aiEmployeeUsername },
722
- });
723
- if (!employeeRecord) {
724
- throw new Error(`AI employee '${args.aiEmployeeUsername}' not found`);
725
- }
726
-
727
- const conversation = await db.getRepository('aiConversations').create({
728
- values: {
729
- userId: args.userId ?? null,
730
- aiEmployee: { username: args.aiEmployeeUsername },
731
- options: {},
732
- thread: 1,
733
- },
734
- });
735
- // aiConversations uses sessionId (uuid) as primary key — no `id` field exists.
736
- sessionId = (conversation.get('sessionId') as string) || null;
737
- if (!sessionId) {
738
- throw new Error('Failed to resolve sessionId from created aiConversation');
739
- }
740
-
741
- await reviewsRepo.update({
742
- filterByTk: args.reviewId,
743
- values: { sessionId },
744
- });
745
-
746
- const prompt = buildReviewPrompt(args);
747
-
748
- // Synthesize a minimal ctx-shaped object that AIEmployee accepts.
749
- // It needs `app`, `db`, `state.currentUser`, `get(headerName)`, `req.headers`,
750
- // `action.params.values` (used in getSystemPrompt), and `res.write` (used by
751
- // ChatStreamProtocol). All stubs are no-ops since we use `invoke` (not stream).
752
- const syntheticCtx: any = {
753
- app,
754
- db,
755
- isBackgroundReview: true,
756
- reviewTargetRepositoryId: args.repo.get('id'),
757
- state: { currentUser: args.userId ? { id: args.userId } : null },
758
- auth: { user: args.userId ? { id: args.userId } : { id: null } },
759
- req: { headers: { 'x-timezone': '+00:00', 'x-locale': 'en-US' } },
760
- // AIEmployee.getSystemPrompt reads ctx.action.params.values.important
761
- action: { params: { values: {} } },
762
- // ChatStreamProtocol.write calls ctx.res.write — stub for non-stream invoke
763
- res: {
764
- write() {},
765
- end() {},
766
- writableEnded: false,
767
- },
768
- log: app.logger || console,
769
- logger: app.logger || console,
770
- get(name: string) {
771
- return this.req.headers[String(name).toLowerCase()];
772
- },
773
- getCurrentLocale() {
774
- return 'en-US';
775
- },
776
- t(key: string) {
777
- return key;
778
- },
779
- i18n: {
780
- t(key: string) {
781
- return key;
782
- },
783
- },
784
- };
785
-
786
- // H-3 fix: try multiple import paths for resilience against plugin-ai restructuring
787
- let AIEmployee: any;
788
- for (const importPath of [
789
- '@nocobase/plugin-ai/dist/server/ai-employees/ai-employee.js',
790
- '@nocobase/plugin-ai/dist/server/ai-employees/ai-employee',
791
- '@nocobase/plugin-ai/server',
792
- ]) {
793
- try {
794
- const mod = await import(/* webpackIgnore: true */ importPath as any);
795
- AIEmployee = (mod as any).AIEmployee || (mod as any).default?.AIEmployee;
796
- if (AIEmployee) break;
797
- } catch {
798
- // try next path
799
- }
800
- }
801
- if (!AIEmployee)
802
- throw new Error('AIEmployee class not found — plugin-ai may not be installed or its exports changed');
803
-
804
- const llmService = args.flow.get('llmService') as string | null;
805
- const model = args.flow.get('model') as string | null;
806
- const modelRef = llmService && model ? { llmService, model } : undefined;
807
-
808
- const aiEmployee = new AIEmployee(
809
- syntheticCtx,
810
- employeeRecord,
811
- sessionId,
812
- undefined,
813
- undefined,
814
- false,
815
- modelRef,
816
- false,
817
- );
818
-
819
- // H-4 fix: enforce a timeout on AI review execution to prevent stuck reviews
820
- const REVIEW_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
821
- const result = await Promise.race([
822
- aiEmployee.invoke({
823
- userMessages: [
824
- {
825
- role: 'user',
826
- content: { type: 'text', content: prompt },
827
- },
828
- ],
829
- }),
830
- new Promise<never>((_resolve, reject) =>
831
- setTimeout(() => reject(new Error('AI review timed out after 5 minutes')), REVIEW_TIMEOUT_MS),
832
- ),
833
- ]);
834
-
835
- const content = extractLastAiMessageContent(result);
836
- if (!content) {
837
- throw new Error('AI employee returned empty review content');
838
- }
839
-
840
- const finishedAt = new Date();
841
- const durationMs = finishedAt.getTime() - startedAt.getTime();
842
-
843
- const postMode = getFlowPostMode(args.flow);
844
- let postStatus = getInitialPostStatus(args.flow, args.targetType);
845
- let postedNoteId: string | null = null;
846
- let autoPostError: string | null = null;
847
-
848
- if (postMode === 'disabled') {
849
- postStatus = 'skipped';
850
- } else if (postMode === 'auto' && args.targetType === 'mr' && args.mrIid) {
851
- try {
852
- postedNoteId = String(await postNoteToGitLab(args.repo, args.mrIid, content));
853
- postStatus = 'posted';
854
- } catch (err: any) {
855
- autoPostError = redactPat(err?.message || String(err));
856
- postStatus = 'post_failed';
857
- app.log?.error?.('Auto-post review note failed', err);
858
- }
859
- }
860
-
861
- await reviewsRepo.update({
862
- filterByTk: args.reviewId,
863
- values: {
864
- status: 'completed',
865
- reviewMarkdown: content,
866
- rawOutput: JSON.stringify({
867
- messageCount: result?.messages?.length ?? 0,
868
- llmService: llmService || 'default',
869
- model: model || 'default',
870
- }),
871
- durationMs,
872
- finishedAt,
873
- postStatus,
874
- postedNoteId,
875
- error: autoPostError ? `Auto-post failed: ${autoPostError}` : null,
876
- metadata: {
877
- flowName: args.flow.get('name'),
878
- aiEmployeeUsername: args.aiEmployeeUsername,
879
- llmService,
880
- model,
881
- postMode,
882
- autoPostError,
883
- },
884
- },
885
- });
886
-
887
- if (sessionId) {
888
- db.getRepository('aiConversations')
889
- .destroy({ filterByTk: sessionId })
890
- .catch(() => undefined);
891
- }
892
- } catch (err: any) {
893
- const finishedAt = new Date();
894
- // Redact PAT before persisting the error — simple-git / fetch errors
895
- // can echo back the authenticated remote URL in their messages.
896
- const safeMessage = redactPat(err?.message || String(err));
897
- await reviewsRepo.update({
898
- filterByTk: args.reviewId,
899
- values: {
900
- status: 'failed',
901
- error: safeMessage,
902
- finishedAt,
903
- durationMs: finishedAt.getTime() - startedAt.getTime(),
904
- },
905
- });
906
- if (sessionId) {
907
- db.getRepository('aiConversations')
908
- .destroy({ filterByTk: sessionId })
909
- .catch(() => undefined);
910
- }
911
- }
912
- }
913
-
914
- function buildReviewPrompt(args: RunReviewArgs): string {
915
- const lines: string[] = [];
916
- lines.push(`You are performing a code review on repository "${args.repo.get('name')}" (id=${args.repo.get('id')}).`);
917
- lines.push('');
918
-
919
- if (args.targetType === 'mr') {
920
- lines.push(`Target: Merge Request !${args.mrIid}.`);
921
- lines.push(
922
- `Use the \`git_get_merge_request\` tool with repositoryId=${args.repo.get('id')} and mrIid=${
923
- args.mrIid
924
- } to fetch the diff and metadata.`,
925
- );
926
- lines.push('Optionally call `git_get_merge_request_notes` to avoid duplicating prior comments.');
927
- } else if (args.targetType === 'commit') {
928
- lines.push(`Target: Commit ${args.commitSha}.`);
929
- lines.push(
930
- `Use the \`git_get_commit\` tool with repositoryId=${args.repo.get('id')} and commitHash=${
931
- args.commitSha
932
- } to fetch the diff.`,
933
- );
934
- } else {
935
- lines.push(`Target: Branch ${args.branch}.`);
936
- lines.push(
937
- `Use \`git_list_commits\`, \`git_get_diff\`, and \`git_get_file_content\` (with repositoryId=${args.repo.get(
938
- 'id',
939
- )}) to inspect recent changes on this branch.`,
940
- );
941
- }
942
-
943
- lines.push('');
944
- lines.push('Produce a thorough but concise code review report in Markdown. Required sections:');
945
- lines.push('1. **Summary** — overall assessment.');
946
- lines.push(
947
- '2. **Findings** — issues grouped by severity (`Critical`, `High`, `Medium`, `Low`, `Info`). For each finding include the file path, line/range when possible, the problem, and a suggested fix.',
948
- );
949
- lines.push('3. **Suggestions** — non-blocking improvements.');
950
- lines.push('4. **Verdict** — one of: `LGTM`, `Approve with comments`, `Request changes`, `Block`.');
951
- lines.push('');
952
- lines.push('Cite code snippets in fenced code blocks. Do not output anything outside the Markdown report.');
953
-
954
- const flowInstructions = args.flow.get('instructions') as string;
955
- if (flowInstructions) {
956
- lines.push('');
957
- lines.push('---');
958
- lines.push('Additional instructions from the review flow:');
959
- lines.push(flowInstructions);
960
- }
961
- if (args.extraInstructions) {
962
- lines.push('');
963
- lines.push('---');
964
- lines.push('Additional instructions for this run:');
965
- lines.push(args.extraInstructions);
966
- }
967
-
968
- return lines.join('\n');
969
- }
970
-
971
- /**
972
- * Pick the AI's final reply out of a LangChain-style message list.
973
- *
974
- * The previous implementation relied solely on `constructor.name`, which is
975
- * unsafe under bundling/minification (class names can be mangled to single
976
- * letters) and after JSON serialisation (instances become plain objects).
977
- * The new logic checks several signals in order: LangChain's `_getType()`,
978
- * an explicit `role` field, then the constructor name as a last resort.
979
- */
980
- function extractLastAiMessageContent(result: any): string {
981
- const messages = result?.messages;
982
- if (!Array.isArray(messages)) return '';
983
-
984
- const isAiMessage = (msg: any): boolean => {
985
- if (!msg) return false;
986
- if (typeof msg._getType === 'function') {
987
- try {
988
- return msg._getType() === 'ai';
989
- } catch {
990
- // fall through to other signals
991
- }
992
- }
993
- if (typeof msg.role === 'string') {
994
- const r = msg.role.toLowerCase();
995
- return r === 'assistant' || r === 'ai';
996
- }
997
- if (typeof msg.type === 'string' && msg.type.toLowerCase() === 'ai') return true;
998
- const name = msg?.constructor?.name;
999
- if (name === 'AIMessage' || name === 'AIMessageChunk') return true;
1000
- return false;
1001
- };
1002
-
1003
- const getContent = (msg: any): string => {
1004
- if (typeof msg.content === 'string') return msg.content;
1005
- if (Array.isArray(msg.content)) {
1006
- const textBlock = msg.content.find((c: any) => c?.type === 'text');
1007
- if (typeof textBlock?.text === 'string') return textBlock.text;
1008
- }
1009
- return '';
1010
- };
1011
-
1012
- for (let i = messages.length - 1; i >= 0; i--) {
1013
- const msg = messages[i];
1014
- if (!isAiMessage(msg)) continue;
1015
- const content = getContent(msg);
1016
- if (content) return content;
1017
- }
1018
- return '';
1019
- }
1020
-
1021
- async function fetchMrHeadSha(repo: any, mrIid: number): Promise<string | null> {
1022
- const repoUrl = repo.get('repoUrl') as string;
1023
- const pat = repo.get('pat') as string;
1024
- if (!pat) return null;
1025
- const isGitHub = repoUrl.includes('github.com');
1026
-
1027
- try {
1028
- if (isGitHub) {
1029
- const { projectPath } = parseGitLabProject(repoUrl);
1030
- const response = await fetch(`https://api.github.com/repos/${projectPath}/pulls/${mrIid}`, {
1031
- headers: { Authorization: `Bearer ${pat}`, Accept: 'application/vnd.github.v3+json' },
1032
- });
1033
- if (!response.ok) return null;
1034
- const data = await response.json();
1035
- return data?.head?.sha || null;
1036
- } else {
1037
- const { apiBase, encodedProject } = parseGitLabProject(repoUrl);
1038
- const response = await fetch(`${apiBase}/projects/${encodedProject}/merge_requests/${mrIid}`, {
1039
- headers: { 'PRIVATE-TOKEN': pat, Accept: 'application/json' },
1040
- });
1041
- if (!response.ok) return null;
1042
- const data = await response.json();
1043
- return (data?.sha as string) || (data?.diff_refs?.head_sha as string) || null;
1044
- }
1045
- } catch {
1046
- return null;
1047
- }
1048
- }
1049
-
1050
- async function postNoteToGitLab(repo: any, mrIid: number, body: string): Promise<number | string> {
1051
- const repoUrl = repo.get('repoUrl') as string;
1052
- const pat = repo.get('pat') as string;
1053
- const isGitHub = repoUrl.includes('github.com');
1054
-
1055
- if (isGitHub) {
1056
- if (!pat) throw new Error('Repository has no PAT configured');
1057
- const { projectPath } = parseGitLabProject(repoUrl);
1058
-
1059
- const response = await fetch(`https://api.github.com/repos/${projectPath}/issues/${mrIid}/comments`, {
1060
- method: 'POST',
1061
- headers: {
1062
- Authorization: `Bearer ${pat}`,
1063
- 'Content-Type': 'application/json',
1064
- Accept: 'application/vnd.github.v3+json',
1065
- },
1066
- body: JSON.stringify({ body }),
1067
- });
1068
-
1069
- if (!response.ok) {
1070
- const text = await response.text().catch(() => '');
1071
- throw new Error(`GitHub note post failed ${response.status}: ${text}`);
1072
- }
1073
- const data = await response.json();
1074
- return data?.id;
1075
- } else {
1076
- if (!pat) throw new Error('Repository has no PAT configured');
1077
-
1078
- const { apiBase, encodedProject } = parseGitLabProject(repoUrl);
1079
-
1080
- const response = await fetch(`${apiBase}/projects/${encodedProject}/merge_requests/${mrIid}/notes`, {
1081
- method: 'POST',
1082
- headers: {
1083
- 'PRIVATE-TOKEN': pat,
1084
- 'Content-Type': 'application/json',
1085
- Accept: 'application/json',
1086
- },
1087
- body: JSON.stringify({ body }),
1088
- });
1089
- if (!response.ok) {
1090
- const text = await response.text().catch(() => '');
1091
- throw new Error(`GitLab note post failed ${response.status}: ${text}`);
1092
- }
1093
- const data = await response.json();
1094
- return data?.id;
1095
- }
1096
- }
1097
-
1098
- /* ───────── Flow matching helpers ───────── */
1099
-
1100
- /**
1101
- * H-1 fix: guard against ReDoS by limiting regex length and wrapping
1102
- * execution in a try-catch.
1103
- *
1104
- * Fail-closed: an invalid or oversized pattern means "no branch matches".
1105
- * Reviewing all branches when a user explicitly configured a filter is more
1106
- * dangerous (auto-posts to GitLab, consumes LLM credits) than skipping a
1107
- * malformed flow. The poller logs once per process so misconfiguration is
1108
- * still observable.
1109
- */
1110
- const MAX_BRANCH_FILTER_LENGTH = 200;
1111
- const loggedBadFilters = new Set<string>();
1112
-
1113
- type ReviewPostMode = 'auto' | 'manual' | 'disabled';
1114
-
1115
- function getFlowPostMode(flow: any): ReviewPostMode {
1116
- const rawValue = flow?.get?.('postMode');
1117
- const value = rawValue && typeof rawValue === 'object' && 'value' in rawValue ? rawValue.value : rawValue;
1118
- const normalized = String(value || 'manual')
1119
- .trim()
1120
- .toLowerCase()
1121
- .replace(/[\s-]+/g, '_');
1122
-
1123
- if (['auto', 'auto_post', 'autopost', 'auto_post_to_mr'].includes(normalized)) return 'auto';
1124
- if (['disabled', 'disable', 'do_not_post', 'dont_post', 'none', 'skip', 'skipped'].includes(normalized)) {
1125
- return 'disabled';
1126
- }
1127
- return 'manual';
1128
- }
1129
-
1130
- function getInitialPostStatus(flow: any, targetType: string): string {
1131
- const postMode = getFlowPostMode(flow);
1132
- if (postMode === 'disabled') return 'skipped';
1133
- if (postMode === 'auto' && targetType !== 'mr') return 'skipped';
1134
- return 'pending_approval';
1135
- }
1136
-
1137
- function warnInvalidBranchFilter(filter: string, reason: string) {
1138
- if (loggedBadFilters.has(filter)) return;
1139
- loggedBadFilters.add(filter);
1140
- console.warn(
1141
- `[plugin-git-manager] branchFilter rejected (${reason}): ${JSON.stringify(
1142
- filter,
1143
- )}. Flow will not match any branch.`,
1144
- );
1145
- }
1146
-
1147
- export function branchMatches(flow: any, branch: string): boolean {
1148
- const filter = flow.get('branchFilter') as string | null;
1149
- if (!filter) return true;
1150
- if (filter.length > MAX_BRANCH_FILTER_LENGTH) {
1151
- warnInvalidBranchFilter(filter, `too long (>${MAX_BRANCH_FILTER_LENGTH} chars)`);
1152
- return false;
1153
- }
1154
- try {
1155
- return new RegExp(filter).test(branch);
1156
- } catch (err: any) {
1157
- warnInvalidBranchFilter(filter, `invalid regex: ${err?.message || err}`);
1158
- return false;
1159
- }
1160
- }
1161
-
1162
- export function pickFlowMatchingBranch(flows: any[], branch?: string): any | null {
1163
- if (!flows?.length) return null;
1164
- if (!branch) return flows[0];
1165
- for (const f of flows) {
1166
- if (branchMatches(f, branch)) return f;
1167
- }
1168
- return null;
1169
- }
1170
-
1171
- function throwHttp(status: number, message: string): never {
1172
- const err: any = new Error(message);
1173
- err.status = status;
1174
- throw err;
1175
- }
1176
-
1177
- /**
1178
- * Review execution is delegated to worker queue processing. When a worker
1179
- * restarts mid-run, the DB record can stay in `status='running'` indefinitely.
1180
- * On startup we sweep any `running` review whose `startedAt` is older than the
1181
- * in-process timeout (5 min) plus a safety margin and mark it as failed.
1182
- *
1183
- * The cutoff is intentionally larger than the runtime timeout so concurrent
1184
- * reviews running on a *different* node in an HA cluster aren't clobbered.
1185
- */
1186
- const STUCK_REVIEW_CUTOFF_MS = 10 * 60 * 1000; // 10 minutes
1187
-
1188
- export async function recoverStuckReviews(app: Application): Promise<number> {
1189
- try {
1190
- const reviewsRepo = app.db.getRepository('gitCodeReviews');
1191
- const cutoff = new Date(Date.now() - STUCK_REVIEW_CUTOFF_MS);
1192
- // Pending rows are the durable queue source of truth and are picked up by
1193
- // worker DB polling, so only sweep reviews that were actually claimed.
1194
- const stuck = await reviewsRepo.find({
1195
- filter: {
1196
- status: 'running',
1197
- startedAt: { $lt: cutoff },
1198
- },
1199
- });
1200
- if (!stuck?.length) return 0;
1201
- const finishedAt = new Date();
1202
- for (const review of stuck) {
1203
- const startedAt = review.get('startedAt') as Date | null;
1204
- const durationMs = startedAt ? finishedAt.getTime() - new Date(startedAt).getTime() : null;
1205
- await reviewsRepo.update({
1206
- filterByTk: review.get('id'),
1207
- values: {
1208
- status: 'failed',
1209
- error: 'Review interrupted by application restart',
1210
- finishedAt,
1211
- durationMs,
1212
- },
1213
- });
1214
- }
1215
- app.log?.info?.(`plugin-git-manager: marked ${stuck.length} stuck review(s) as failed after restart`);
1216
- return stuck.length;
1217
- } catch (err: any) {
1218
- app.log?.error?.(`plugin-git-manager: recoverStuckReviews failed: ${err?.message}`);
1219
- return 0;
1220
- }
1221
- }
1
+ import { Context } from '@nocobase/actions';
2
+ import type { Application } from '@nocobase/server';
3
+ import { parseGitLabProject } from '../utils/gitlab-url';
4
+ import { redactPat } from '../utils/redact';
5
+
6
+ export const WORKER_JOB_GIT_REVIEW_PROCESS = 'git-review:process';
7
+ const REVIEW_QUEUE_CHANNEL = 'plugin-git-manager.review';
8
+ const REVIEW_WORKER_ALIASES = [REVIEW_QUEUE_CHANNEL, 'plugin-git-manager:review:queue'];
9
+ const REVIEW_QUEUE_CONCURRENCY = Math.max(
10
+ 1,
11
+ Number.parseInt(process.env.GIT_REVIEW_QUEUE_CONCURRENCY || process.env.GIT_REVIEW_MAX_CONCURRENCY || '3', 10) || 3,
12
+ );
13
+ const REVIEW_QUEUE_TIMEOUT_MS = Math.max(
14
+ 60_000,
15
+ Number.parseInt(process.env.GIT_REVIEW_QUEUE_TIMEOUT_MS || '', 10) || 10 * 60 * 1000,
16
+ );
17
+ const REVIEW_QUEUE_POLL_INTERVAL_MS = Math.max(
18
+ 1000,
19
+ Number.parseInt(process.env.GIT_REVIEW_QUEUE_POLL_INTERVAL_MS || '', 10) || 5000,
20
+ );
21
+ const REVIEW_PROCESS_LOCK_TTL_MS = Math.max(REVIEW_QUEUE_TIMEOUT_MS + 60_000, 11 * 60 * 1000);
22
+ const REVIEW_QUEUE_WAKE_CHANNEL = 'plugin-git-manager.review.wake';
23
+ const REVIEW_QUEUE_REDIS_CONNECTION = 'plugin-git-manager.review.queue';
24
+
25
+ interface TriggerArgs {
26
+ flowId?: number | null;
27
+ repositoryId: number;
28
+ targetType: 'mr' | 'commit' | 'branch';
29
+ mrIid?: number | null;
30
+ commitSha?: string | null;
31
+ branch?: string | null;
32
+ headSha?: string | null;
33
+ extraInstructions?: string;
34
+ triggeredBy?: 'manual' | 'poll';
35
+ userId?: number | string | null;
36
+ }
37
+
38
+ interface ReviewFlowSnapshot {
39
+ id: number;
40
+ name?: string;
41
+ postMode?: string;
42
+ llmService?: string | null;
43
+ model?: string | null;
44
+ instructions?: string | null;
45
+ }
46
+
47
+ interface ReviewQueueMessage {
48
+ reviewId: number;
49
+ repositoryId: number;
50
+ targetType: 'mr' | 'commit' | 'branch';
51
+ mrIid?: number | null;
52
+ commitSha?: string | null;
53
+ branch?: string | null;
54
+ headSha?: string | null;
55
+ aiEmployeeUsername: string;
56
+ extraInstructions?: string;
57
+ userId?: number | string | null;
58
+ flowSnapshot?: ReviewFlowSnapshot;
59
+ }
60
+
61
+ interface QueuedReviewMetadata {
62
+ queuedAt?: string;
63
+ aiEmployeeUsername?: string;
64
+ extraInstructions?: string | null;
65
+ userId?: number | string | null;
66
+ flowSnapshot?: ReviewFlowSnapshot;
67
+ }
68
+
69
+ let reviewQueueTimer: NodeJS.Timeout | null = null;
70
+ let reviewQueueKickTimer: NodeJS.Timeout | null = null;
71
+ let reviewQueueProcessing = false;
72
+ let reviewWakeHandler: ((message?: any) => Promise<void>) | null = null;
73
+
74
+ function getActionParams(ctx: Context) {
75
+ return { ...ctx.action.params, ...ctx.action.params?.values, ...((ctx as any).request?.body || {}) };
76
+ }
77
+
78
+ /**
79
+ * Per-target mutex to prevent two concurrent calls to
80
+ * `triggerReviewInternal` for the same MR / commit / branch from racing
81
+ * `findOne` → `create` and producing two duplicate review rows or
82
+ * scheduling two `runReview`s.
83
+ *
84
+ * Uses `app.lockManager` so the same code path covers both single-node
85
+ * (in-memory `async-mutex`) and HA cluster (Redis-backed Redlock when
86
+ * `plugin-cluster-manager` is active and `LOCK_ADAPTER_DEFAULT=redis`).
87
+ * The locked region only does an upsert + queue publish (a few ms), so a 30s
88
+ * TTL is generous and auto-releases if the process crashes.
89
+ */
90
+ function targetKey(args: TriggerArgs): string {
91
+ if (args.targetType === 'mr') return `${args.repositoryId}:mr:${args.mrIid}`;
92
+ if (args.targetType === 'commit') return `${args.repositoryId}:commit:${args.commitSha}`;
93
+ return `${args.repositoryId}:branch:${args.branch}`;
94
+ }
95
+
96
+ const TRIGGER_LOCK_TTL_MS = 30_000;
97
+
98
+ async function withTriggerLock<T>(app: Application, key: string, fn: () => Promise<T>): Promise<T> {
99
+ const lockKey = `git-review:trigger:${key}`;
100
+ return app.lockManager.runExclusive(lockKey, fn, TRIGGER_LOCK_TTL_MS);
101
+ }
102
+
103
+ /**
104
+ * Trigger an AI-driven code review for an MR / commit / branch.
105
+ * The review record is upserted synchronously, then queued for an available
106
+ * git-review worker. The action returns immediately with the reviewId.
107
+ */
108
+ export async function triggerReview(ctx: Context, next: () => Promise<void>) {
109
+ const params = getActionParams(ctx);
110
+ const { flowId, repositoryId, targetType, mrIid, commitSha, branch, extraInstructions } = params;
111
+
112
+ if (!repositoryId) ctx.throw(400, 'repositoryId is required');
113
+ if (!targetType) ctx.throw(400, 'targetType is required');
114
+ if (!['mr', 'commit', 'branch'].includes(targetType)) ctx.throw(400, 'invalid targetType');
115
+ if (targetType === 'mr' && !mrIid) ctx.throw(400, 'mrIid is required for MR review');
116
+ if (targetType === 'commit' && !commitSha) ctx.throw(400, 'commitSha is required for commit review');
117
+ if (targetType === 'branch' && !branch) ctx.throw(400, 'branch is required for branch review');
118
+
119
+ const userId = (ctx as any).state?.currentUser?.id;
120
+ try {
121
+ const reviewId = await triggerReviewInternal(ctx.app, {
122
+ flowId,
123
+ repositoryId: Number(repositoryId),
124
+ targetType,
125
+ mrIid: mrIid != null ? Number(mrIid) : null,
126
+ commitSha: commitSha || null,
127
+ branch: branch || null,
128
+ extraInstructions,
129
+ triggeredBy: 'manual',
130
+ userId,
131
+ });
132
+ ctx.body = { success: true, data: { reviewId } };
133
+ } catch (err: any) {
134
+ ctx.throw(err.status || 400, err.message || 'Failed to trigger review');
135
+ }
136
+ await next();
137
+ }
138
+
139
+ /**
140
+ * Programmatic entry point — used by manual action and by the poller.
141
+ * Returns the reviewId of the upserted record.
142
+ */
143
+ export async function triggerReviewInternal(app: Application, args: TriggerArgs): Promise<number> {
144
+ return withTriggerLock(app, targetKey(args), () => triggerReviewInternalLocked(app, args));
145
+ }
146
+
147
+ async function triggerReviewInternalLocked(app: Application, args: TriggerArgs): Promise<number> {
148
+ const db = app.db;
149
+ const flowsRepo = db.getRepository('gitReviewFlows');
150
+
151
+ // Resolve flow
152
+ let flow: any = null;
153
+ if (args.flowId) {
154
+ flow = await flowsRepo.findOne({ filterByTk: args.flowId });
155
+ if (!flow) throwHttp(404, 'Review flow not found');
156
+ if (!flow.get('enabled')) throwHttp(400, 'Review flow is disabled');
157
+ } else {
158
+ // Find flows scoped to repo or global, prefer repo-specific
159
+ const candidates = await flowsRepo.find({
160
+ filter: {
161
+ enabled: true,
162
+ $or: [{ repositoryId: args.repositoryId }, { repositoryId: null }],
163
+ },
164
+ sort: ['-repositoryId'],
165
+ });
166
+ flow = pickFlowMatchingBranch(candidates, args.branch || undefined);
167
+ if (!flow) throwHttp(400, 'No enabled review flow found for this repository');
168
+ }
169
+
170
+ // Apply branchFilter even when flow is explicitly given (consistency)
171
+ if (args.branch && !branchMatches(flow, args.branch)) {
172
+ throwHttp(400, `Branch '${args.branch}' does not match flow's branchFilter`);
173
+ }
174
+
175
+ const aiEmployeeUsername = flow.get('aiEmployeeUsername') as string;
176
+ if (!aiEmployeeUsername) throwHttp(400, 'Flow has no AI employee configured');
177
+
178
+ const repo = await db.getRepository('gitRepositories').findOne({ filterByTk: args.repositoryId });
179
+ if (!repo) throwHttp(404, 'Repository not found');
180
+
181
+ // For MR targets, ensure we know the head SHA so the "new commits" indicator
182
+ // works regardless of whether the trigger came from poller or manual UI.
183
+ let headSha = args.headSha || null;
184
+ if (args.targetType === 'mr' && !headSha && args.mrIid) {
185
+ headSha = await fetchMrHeadSha(repo, args.mrIid).catch(() => null);
186
+ }
187
+
188
+ // Upsert review record (1 per MR/commit/branch target)
189
+ const reviewsRepo = db.getRepository('gitCodeReviews');
190
+ const targetFilter: any = {
191
+ repositoryId: args.repositoryId,
192
+ targetType: args.targetType,
193
+ };
194
+ if (args.targetType === 'mr') targetFilter.mrIid = args.mrIid;
195
+ else if (args.targetType === 'commit') targetFilter.commitSha = args.commitSha;
196
+ else if (args.targetType === 'branch') targetFilter.branch = args.branch;
197
+
198
+ const existing = await reviewsRepo.findOne({ filter: targetFilter });
199
+ // Preserve a poller-tracked latestSha if we don't have a fresher one.
200
+ const existingLatestSha = existing?.get('latestSha') as string | null | undefined;
201
+ const baseValues: any = {
202
+ flowId: flow.get('id'),
203
+ repositoryId: args.repositoryId,
204
+ targetType: args.targetType,
205
+ mrIid: args.targetType === 'mr' ? args.mrIid : null,
206
+ commitSha: args.targetType === 'commit' ? args.commitSha : null,
207
+ branch: args.branch || null,
208
+ headSha: headSha,
209
+ latestSha: headSha || existingLatestSha || null,
210
+ triggeredBy: args.triggeredBy || 'manual',
211
+ status: 'pending',
212
+ // `startedAt` is stamped by the queue worker when execution actually
213
+ // starts. Pending rows are durable queue items for worker polling.
214
+ startedAt: null,
215
+ finishedAt: null,
216
+ durationMs: null,
217
+ postStatus: getInitialPostStatus(flow, args.targetType),
218
+ error: null,
219
+ metadata: {
220
+ queuedAt: new Date().toISOString(),
221
+ aiEmployeeUsername,
222
+ extraInstructions: args.extraInstructions || null,
223
+ userId: args.userId ?? null,
224
+ flowSnapshot: createFlowSnapshot(flow),
225
+ },
226
+ };
227
+
228
+ let reviewId: number;
229
+ if (existing) {
230
+ const st = existing.get('status');
231
+ // Treat `pending` the same as `running`: between this fn returning and
232
+ // the scheduled `runReview` flipping the row to `running`, a second
233
+ // caller would otherwise slip past and schedule a duplicate runReview.
234
+ // Stuck `pending` rows (process died before runReview ran) are swept
235
+ // by `recoverStuckReviews` on next startup.
236
+ if (st === 'running' || st === 'pending') {
237
+ return existing.get('id') as number;
238
+ }
239
+ await reviewsRepo.update({
240
+ filterByTk: existing.get('id'),
241
+ values: baseValues,
242
+ });
243
+ reviewId = existing.get('id') as number;
244
+ } else {
245
+ const review = await reviewsRepo.create({ values: baseValues });
246
+ reviewId = review.get('id') as number;
247
+ }
248
+
249
+ // Queue for background workers; the action returns as soon as the message is published.
250
+ await enqueueReview(app, {
251
+ reviewId,
252
+ repositoryId: args.repositoryId,
253
+ targetType: args.targetType,
254
+ mrIid: args.targetType === 'mr' ? args.mrIid : null,
255
+ commitSha: args.targetType === 'commit' ? args.commitSha : null,
256
+ branch: args.branch || undefined,
257
+ headSha,
258
+ aiEmployeeUsername,
259
+ extraInstructions: args.extraInstructions,
260
+ userId: args.userId ?? null,
261
+ flowSnapshot: createFlowSnapshot(flow),
262
+ });
263
+
264
+ return reviewId;
265
+ }
266
+
267
+ export function registerReviewQueue(app: Application) {
268
+ app.eventQueue.subscribe(REVIEW_QUEUE_CHANNEL, {
269
+ concurrency: REVIEW_QUEUE_CONCURRENCY,
270
+ idle: () => isGitReviewWorker(app),
271
+ process: async (message: ReviewQueueMessage) => {
272
+ await processQueuedReview(app, message);
273
+ },
274
+ });
275
+ if (!isGitReviewWorker(app)) {
276
+ app.on('afterStart', () => clearLocalReviewMemoryQueue(app));
277
+ }
278
+ startReviewQueueProcessor(app);
279
+ }
280
+
281
+ export function unregisterReviewQueue(app: Application) {
282
+ app.eventQueue.unsubscribe(REVIEW_QUEUE_CHANNEL);
283
+ stopReviewQueueProcessor(app);
284
+ }
285
+
286
+ function createFlowSnapshot(flow: any): ReviewFlowSnapshot {
287
+ return {
288
+ id: Number(flow.get('id')),
289
+ name: flow.get('name') as string,
290
+ postMode: flow.get('postMode') as string,
291
+ llmService: flow.get('llmService') as string | null,
292
+ model: flow.get('model') as string | null,
293
+ instructions: flow.get('instructions') as string | null,
294
+ };
295
+ }
296
+
297
+ function createFlowFromSnapshot(snapshot: ReviewFlowSnapshot | undefined, fallback?: any) {
298
+ return {
299
+ get(name: string) {
300
+ if (snapshot && Object.prototype.hasOwnProperty.call(snapshot, name)) {
301
+ return (snapshot as any)[name];
302
+ }
303
+ return fallback?.get?.(name);
304
+ },
305
+ };
306
+ }
307
+
308
+ function isGitReviewWorker(app: Application): boolean {
309
+ return app.serving(WORKER_JOB_GIT_REVIEW_PROCESS) || workerModeServesGitReview();
310
+ }
311
+
312
+ function workerModeServesGitReview(): boolean {
313
+ const workerMode = process.env.WORKER_MODE || '';
314
+ const workerModes = workerMode
315
+ .split(',')
316
+ .map((mode) => mode.trim())
317
+ .filter(Boolean);
318
+
319
+ return workerModes.some((mode) => {
320
+ if (mode === '*' || mode === 'worker' || mode === 'task' || mode === WORKER_JOB_GIT_REVIEW_PROCESS) {
321
+ return true;
322
+ }
323
+ return REVIEW_WORKER_ALIASES.some((alias) => mode === alias || mode.endsWith(`:${alias}`));
324
+ });
325
+ }
326
+
327
+ function clearLocalReviewMemoryQueue(app: Application) {
328
+ const eventQueue = (app as any).eventQueue;
329
+ const adapter = eventQueue?.adapter;
330
+ const fullChannel = eventQueue?.getFullChannel?.(REVIEW_QUEUE_CHANNEL);
331
+ const queue = fullChannel ? adapter?.queues?.get?.(fullChannel) : null;
332
+ if (!queue?.length) return;
333
+
334
+ adapter.queues.set(fullChannel, []);
335
+ app.log?.warn?.(
336
+ `git review queue: cleared ${queue.length} stale local memory message(s) on non-worker node; pending DB rows will be picked up by workers`,
337
+ );
338
+ }
339
+
340
+ function getReviewQueueRedisKey(app: Application): string {
341
+ const appName = (app as any).name || process.env.APP_NAME || 'main';
342
+ return `${appName}:plugin-git-manager:review:queue`;
343
+ }
344
+
345
+ async function getReviewQueueRedis(app: Application): Promise<any | null> {
346
+ const manager = (app as any).redisConnectionManager;
347
+ if (!manager?.getConnectionSync) {
348
+ return null;
349
+ }
350
+
351
+ try {
352
+ const connectionString = process.env.QUEUE_ADAPTER_REDIS_URL || process.env.REDIS_URL;
353
+ return await manager.getConnectionSync(
354
+ REVIEW_QUEUE_REDIS_CONNECTION,
355
+ connectionString ? { connectionString } : undefined,
356
+ );
357
+ } catch (err: any) {
358
+ app.log?.debug?.(`git review queue: Redis queue unavailable, falling back to DB polling: ${err?.message || err}`);
359
+ return null;
360
+ }
361
+ }
362
+
363
+ async function enqueueReviewToRedis(app: Application, message: ReviewQueueMessage): Promise<boolean> {
364
+ const redis = await getReviewQueueRedis(app);
365
+ if (!redis) return false;
366
+
367
+ await redis.sendCommand(['RPUSH', getReviewQueueRedisKey(app), JSON.stringify(message)]);
368
+ app.log?.debug?.(`git review queue: enqueued review ${message.reviewId} to Redis`);
369
+ return true;
370
+ }
371
+
372
+ async function publishReviewQueueWake(app: Application, reviewId?: number) {
373
+ try {
374
+ await (app as any).pubSubManager?.publish?.(
375
+ REVIEW_QUEUE_WAKE_CHANNEL,
376
+ { reviewId },
377
+ { skipSelf: !isGitReviewWorker(app) },
378
+ );
379
+ } catch (err: any) {
380
+ app.log?.debug?.(`git review queue: wake publish skipped: ${err?.message || err}`);
381
+ }
382
+ }
383
+
384
+ function startReviewQueueProcessor(app: Application) {
385
+ if (!isGitReviewWorker(app)) {
386
+ app.log?.debug?.('plugin-git-manager: review queue processor disabled on non-worker node');
387
+ return;
388
+ }
389
+ if (reviewQueueTimer) return;
390
+
391
+ reviewWakeHandler = async () => {
392
+ scheduleReviewQueueTick(app, 0);
393
+ };
394
+
395
+ const subscribe = (app as any).pubSubManager?.subscribe?.(REVIEW_QUEUE_WAKE_CHANNEL, reviewWakeHandler);
396
+ if (subscribe?.catch) {
397
+ subscribe.catch((err: any) => app.log?.debug?.(`git review queue: wake subscribe skipped: ${err?.message || err}`));
398
+ }
399
+
400
+ reviewQueueTimer = setInterval(() => scheduleReviewQueueTick(app, 0), REVIEW_QUEUE_POLL_INTERVAL_MS);
401
+ (reviewQueueTimer as any).unref?.();
402
+ scheduleReviewQueueTick(app, 1000);
403
+ app.log?.info?.(`plugin-git-manager: review queue processor started (interval ${REVIEW_QUEUE_POLL_INTERVAL_MS}ms)`);
404
+ }
405
+
406
+ function stopReviewQueueProcessor(app: Application) {
407
+ if (reviewQueueTimer) {
408
+ clearInterval(reviewQueueTimer);
409
+ reviewQueueTimer = null;
410
+ }
411
+ if (reviewQueueKickTimer) {
412
+ clearTimeout(reviewQueueKickTimer);
413
+ reviewQueueKickTimer = null;
414
+ }
415
+ if (reviewWakeHandler) {
416
+ const unsubscribe = (app as any).pubSubManager?.unsubscribe?.(REVIEW_QUEUE_WAKE_CHANNEL, reviewWakeHandler);
417
+ if (unsubscribe?.catch) {
418
+ unsubscribe.catch(() => undefined);
419
+ }
420
+ reviewWakeHandler = null;
421
+ }
422
+ reviewQueueProcessing = false;
423
+ }
424
+
425
+ function scheduleReviewQueueTick(app: Application, delayMs: number) {
426
+ if (reviewQueueKickTimer) return;
427
+ reviewQueueKickTimer = setTimeout(() => {
428
+ reviewQueueKickTimer = null;
429
+ runReviewQueueTick(app).catch((err) => app.log?.error?.('git review queue: processor tick failed', err));
430
+ }, delayMs);
431
+ (reviewQueueKickTimer as any).unref?.();
432
+ }
433
+
434
+ async function runReviewQueueTick(app: Application) {
435
+ if (reviewQueueProcessing || !isGitReviewWorker(app)) return;
436
+
437
+ reviewQueueProcessing = true;
438
+ try {
439
+ const redisMessages = await drainRedisReviewQueue(app, REVIEW_QUEUE_CONCURRENCY);
440
+ await processReviewQueueMessages(app, redisMessages);
441
+
442
+ const remaining = Math.max(1, REVIEW_QUEUE_CONCURRENCY - redisMessages.length);
443
+ await processPendingReviews(app, remaining);
444
+ } finally {
445
+ reviewQueueProcessing = false;
446
+ }
447
+ }
448
+
449
+ async function drainRedisReviewQueue(app: Application, count: number): Promise<ReviewQueueMessage[]> {
450
+ const redis = await getReviewQueueRedis(app);
451
+ if (!redis) return [];
452
+
453
+ const key = getReviewQueueRedisKey(app);
454
+ const messages: ReviewQueueMessage[] = [];
455
+ for (let i = 0; i < count; i += 1) {
456
+ const raw = await redis.sendCommand(['LPOP', key]);
457
+ if (!raw) break;
458
+ try {
459
+ messages.push(JSON.parse(String(raw)));
460
+ } catch (err: any) {
461
+ app.log?.warn?.(`git review queue: dropped invalid Redis message: ${err?.message || err}`);
462
+ }
463
+ }
464
+ return messages;
465
+ }
466
+
467
+ function getQueuedReviewMetadata(review: any): QueuedReviewMetadata {
468
+ const raw = review?.get?.('metadata');
469
+ if (!raw) return {};
470
+ if (typeof raw === 'string') {
471
+ try {
472
+ return JSON.parse(raw) || {};
473
+ } catch {
474
+ return {};
475
+ }
476
+ }
477
+ return typeof raw === 'object' ? raw : {};
478
+ }
479
+
480
+ function toNullableNumber(value: any): number | null {
481
+ if (value === null || value === undefined || value === '') return null;
482
+ const parsed = Number(value);
483
+ return Number.isFinite(parsed) ? parsed : null;
484
+ }
485
+
486
+ function createReviewQueueMessageFromReview(review: any): ReviewQueueMessage {
487
+ const metadata = getQueuedReviewMetadata(review);
488
+ const targetType = review.get('targetType') as 'mr' | 'commit' | 'branch';
489
+ return {
490
+ reviewId: Number(review.get('id')),
491
+ repositoryId: Number(review.get('repositoryId')),
492
+ targetType,
493
+ mrIid: targetType === 'mr' ? toNullableNumber(review.get('mrIid')) : null,
494
+ commitSha: targetType === 'commit' ? (review.get('commitSha') as string | null) : null,
495
+ branch: targetType === 'branch' ? (review.get('branch') as string | null) : null,
496
+ headSha: review.get('headSha') as string | null,
497
+ aiEmployeeUsername: metadata.aiEmployeeUsername || '',
498
+ extraInstructions: metadata.extraInstructions || undefined,
499
+ userId: metadata.userId ?? null,
500
+ flowSnapshot: metadata.flowSnapshot,
501
+ };
502
+ }
503
+
504
+ async function processPendingReviews(app: Application, count: number) {
505
+ const pending = await app.db.getRepository('gitCodeReviews').find({
506
+ filter: { status: 'pending' },
507
+ sort: ['createdAt'],
508
+ limit: count,
509
+ });
510
+ if (!pending?.length) return;
511
+ await processReviewQueueMessages(app, pending.map(createReviewQueueMessageFromReview));
512
+ }
513
+
514
+ async function processReviewQueueMessages(app: Application, messages: ReviewQueueMessage[]) {
515
+ if (!messages.length) return;
516
+ await Promise.all(messages.map((message) => processQueuedReview(app, message)));
517
+ }
518
+
519
+ async function withReviewProcessLock<T>(app: Application, reviewId: number, fn: () => Promise<T>): Promise<T> {
520
+ const lockKey = `git-review:process:${reviewId}`;
521
+ return app.lockManager.runExclusive(lockKey, fn, REVIEW_PROCESS_LOCK_TTL_MS);
522
+ }
523
+
524
+ async function enqueueReview(app: Application, message: ReviewQueueMessage) {
525
+ try {
526
+ const queuedInRedis = await enqueueReviewToRedis(app, message);
527
+ if (queuedInRedis) {
528
+ await publishReviewQueueWake(app, message.reviewId);
529
+ return;
530
+ }
531
+
532
+ await publishReviewQueueWake(app, message.reviewId);
533
+
534
+ if (isGitReviewWorker(app)) {
535
+ await app.eventQueue.publish(REVIEW_QUEUE_CHANNEL, message, {
536
+ timeout: REVIEW_QUEUE_TIMEOUT_MS,
537
+ maxRetries: 1,
538
+ });
539
+ return;
540
+ }
541
+
542
+ app.log?.warn?.(
543
+ `git review queue: Redis queue is unavailable; review ${message.reviewId} will remain pending until a worker DB poller picks it up`,
544
+ );
545
+ } catch (err: any) {
546
+ const safeMessage = redactPat(err?.message || String(err));
547
+ await app.db.getRepository('gitCodeReviews').update({
548
+ filterByTk: message.reviewId,
549
+ values: {
550
+ status: 'failed',
551
+ error: `Failed to enqueue review: ${safeMessage}`,
552
+ finishedAt: new Date(),
553
+ },
554
+ });
555
+ throw err;
556
+ }
557
+ }
558
+
559
+ async function failQueuedReview(app: Application, reviewId: number, err: any) {
560
+ const safeMessage = redactPat(err?.message || String(err));
561
+ await app.db.getRepository('gitCodeReviews').update({
562
+ filterByTk: reviewId,
563
+ values: {
564
+ status: 'failed',
565
+ error: safeMessage,
566
+ finishedAt: new Date(),
567
+ },
568
+ });
569
+ }
570
+
571
+ async function processQueuedReview(app: Application, message: ReviewQueueMessage) {
572
+ await withReviewProcessLock(app, message.reviewId, async () => {
573
+ const db = app.db;
574
+ const reviewsRepo = db.getRepository('gitCodeReviews');
575
+ const review = await reviewsRepo.findOne({ filterByTk: message.reviewId });
576
+ if (!review) {
577
+ app.log?.warn?.(`git review queue: review ${message.reviewId} not found, skipping`);
578
+ return;
579
+ }
580
+
581
+ if (review.get('status') !== 'pending') {
582
+ app.log?.info?.(`git review queue: review ${message.reviewId} is ${review.get('status')}, skipping`);
583
+ return;
584
+ }
585
+
586
+ const metadata = getQueuedReviewMetadata(review);
587
+ const targetType = (message.targetType || review.get('targetType')) as 'mr' | 'commit' | 'branch';
588
+
589
+ try {
590
+ const repo = await db.getRepository('gitRepositories').findOne({
591
+ filterByTk: message.repositoryId || review.get('repositoryId'),
592
+ });
593
+ if (!repo) throw new Error('Repository not found');
594
+
595
+ const flowSnapshot = message.flowSnapshot || metadata.flowSnapshot;
596
+ const storedFlow = await db.getRepository('gitReviewFlows').findOne({
597
+ filterByTk: flowSnapshot?.id || review.get('flowId'),
598
+ });
599
+ const flow = createFlowFromSnapshot(flowSnapshot, storedFlow);
600
+ const aiEmployeeUsername =
601
+ message.aiEmployeeUsername || metadata.aiEmployeeUsername || (flow.get('aiEmployeeUsername') as string);
602
+ if (!aiEmployeeUsername) throw new Error('Flow has no AI employee configured');
603
+
604
+ await runReview(app, {
605
+ reviewId: message.reviewId,
606
+ flow,
607
+ repo,
608
+ targetType,
609
+ mrIid: targetType === 'mr' ? message.mrIid ?? toNullableNumber(review.get('mrIid')) : null,
610
+ commitSha: targetType === 'commit' ? message.commitSha || (review.get('commitSha') as string) : null,
611
+ branch: message.branch || (review.get('branch') as string | undefined),
612
+ headSha: message.headSha || (review.get('headSha') as string | null),
613
+ aiEmployeeUsername,
614
+ extraInstructions: message.extraInstructions ?? metadata.extraInstructions ?? undefined,
615
+ userId: message.userId ?? metadata.userId ?? null,
616
+ });
617
+ } catch (err) {
618
+ app.log?.error?.('git review queue: failed before review execution', err);
619
+ await failQueuedReview(app, message.reviewId, err);
620
+ }
621
+ });
622
+ }
623
+
624
+ /**
625
+ * Mark a review as approved and post its content to GitLab as an MR note.
626
+ */
627
+ export async function reviewApprovePost(ctx: Context, next: () => Promise<void>) {
628
+ const params = getActionParams(ctx);
629
+ const { reviewId, editedMarkdown } = params;
630
+ if (!reviewId) ctx.throw(400, 'reviewId is required');
631
+
632
+ const reviewsRepo = ctx.db.getRepository('gitCodeReviews');
633
+ const review = await reviewsRepo.findOne({ filterByTk: reviewId });
634
+ if (!review) ctx.throw(404, 'Review not found');
635
+ if (review.get('status') !== 'completed') ctx.throw(400, 'Review is not completed');
636
+ if (review.get('targetType') !== 'mr') ctx.throw(400, 'Only MR reviews can be posted');
637
+
638
+ const markdown = (editedMarkdown ?? review.get('reviewMarkdown')) as string;
639
+ if (!markdown) ctx.throw(400, 'No review content to post');
640
+
641
+ const repo = await ctx.db.getRepository('gitRepositories').findOne({
642
+ filterByTk: review.get('repositoryId'),
643
+ });
644
+ if (!repo) ctx.throw(404, 'Repository not found');
645
+
646
+ const noteId = await postNoteToGitLab(repo, Number(review.get('mrIid')), markdown);
647
+
648
+ const userId = (ctx as any).state?.currentUser?.id;
649
+ await reviewsRepo.update({
650
+ filterByTk: reviewId,
651
+ values: {
652
+ reviewMarkdown: markdown,
653
+ postStatus: 'posted',
654
+ postedNoteId: String(noteId),
655
+ approvedBy: userId ? String(userId) : null,
656
+ approvedAt: new Date(),
657
+ error: null,
658
+ },
659
+ });
660
+
661
+ ctx.body = { success: true, data: { reviewId, postedNoteId: noteId } };
662
+ await next();
663
+ }
664
+
665
+ /**
666
+ * Reject a pending review (do not post to GitLab).
667
+ */
668
+ export async function reviewReject(ctx: Context, next: () => Promise<void>) {
669
+ const params = getActionParams(ctx);
670
+ const { reviewId, reason } = params;
671
+ if (!reviewId) ctx.throw(400, 'reviewId is required');
672
+
673
+ const reviewsRepo = ctx.db.getRepository('gitCodeReviews');
674
+ const review = await reviewsRepo.findOne({ filterByTk: reviewId });
675
+ if (!review) ctx.throw(404, 'Review not found');
676
+
677
+ const userId = (ctx as any).state?.currentUser?.id;
678
+ await reviewsRepo.update({
679
+ filterByTk: reviewId,
680
+ values: {
681
+ postStatus: 'rejected',
682
+ approvedBy: userId ? String(userId) : null,
683
+ approvedAt: new Date(),
684
+ error: reason ? `Rejected: ${reason}` : 'Rejected',
685
+ },
686
+ });
687
+
688
+ ctx.body = { success: true, data: { reviewId } };
689
+ await next();
690
+ }
691
+
692
+ /* ───────── Helpers ───────── */
693
+
694
+ interface RunReviewArgs {
695
+ reviewId: number;
696
+ flow: any;
697
+ repo: any;
698
+ targetType: string;
699
+ mrIid: number | null;
700
+ commitSha: string | null;
701
+ branch?: string;
702
+ headSha?: string | null;
703
+ aiEmployeeUsername: string;
704
+ extraInstructions?: string;
705
+ userId?: number | string | null;
706
+ }
707
+
708
+ async function runReview(app: Application, args: RunReviewArgs) {
709
+ const db = app.db;
710
+ const reviewsRepo = db.getRepository('gitCodeReviews');
711
+ const startedAt = new Date();
712
+ let sessionId: string | null = null;
713
+
714
+ try {
715
+ await reviewsRepo.update({
716
+ filterByTk: args.reviewId,
717
+ values: { status: 'running', startedAt },
718
+ });
719
+
720
+ const employeeRecord = await db.getRepository('aiEmployees').findOne({
721
+ filter: { username: args.aiEmployeeUsername },
722
+ });
723
+ if (!employeeRecord) {
724
+ throw new Error(`AI employee '${args.aiEmployeeUsername}' not found`);
725
+ }
726
+
727
+ const conversation = await db.getRepository('aiConversations').create({
728
+ values: {
729
+ userId: args.userId ?? null,
730
+ aiEmployee: { username: args.aiEmployeeUsername },
731
+ options: {},
732
+ thread: 1,
733
+ },
734
+ });
735
+ // aiConversations uses sessionId (uuid) as primary key — no `id` field exists.
736
+ sessionId = (conversation.get('sessionId') as string) || null;
737
+ if (!sessionId) {
738
+ throw new Error('Failed to resolve sessionId from created aiConversation');
739
+ }
740
+
741
+ await reviewsRepo.update({
742
+ filterByTk: args.reviewId,
743
+ values: { sessionId },
744
+ });
745
+
746
+ const prompt = buildReviewPrompt(args);
747
+ const currentRoles = await resolveBackgroundReviewRoles(db, args.userId);
748
+ const currentUser = args.userId
749
+ ? {
750
+ id: args.userId,
751
+ roles: currentRoles.map((name) => ({ name })),
752
+ }
753
+ : null;
754
+
755
+ // Synthesize a minimal ctx-shaped object that AIEmployee accepts.
756
+ // It needs `app`, `db`, `state.currentUser`, `get(headerName)`, `req.headers`,
757
+ // `action.params.values` (used in getSystemPrompt), and `res.write` (used by
758
+ // ChatStreamProtocol). All stubs are no-ops since we use `invoke` (not stream).
759
+ const syntheticCtx: any = {
760
+ app,
761
+ db,
762
+ isBackgroundReview: true,
763
+ reviewTargetRepositoryId: args.repo.get('id'),
764
+ state: {
765
+ currentUser,
766
+ currentRole: currentRoles[0],
767
+ currentRoles,
768
+ },
769
+ auth: { user: currentUser || { id: null } },
770
+ req: { headers: { 'x-timezone': '+00:00', 'x-locale': 'en-US' } },
771
+ // AIEmployee.getSystemPrompt reads ctx.action.params.values.important
772
+ action: { params: { values: {} } },
773
+ // ChatStreamProtocol.write calls ctx.res.write — stub for non-stream invoke
774
+ res: {
775
+ write() {},
776
+ end() {},
777
+ writableEnded: false,
778
+ },
779
+ log: app.logger || console,
780
+ logger: app.logger || console,
781
+ get(name: string) {
782
+ return this.req.headers[String(name).toLowerCase()];
783
+ },
784
+ getCurrentLocale() {
785
+ return 'en-US';
786
+ },
787
+ t(key: string) {
788
+ return key;
789
+ },
790
+ i18n: {
791
+ t(key: string) {
792
+ return key;
793
+ },
794
+ },
795
+ };
796
+
797
+ // H-3 fix: try multiple import paths for resilience against plugin-ai restructuring
798
+ let AIEmployee: any;
799
+ for (const importPath of [
800
+ '@nocobase/plugin-ai/dist/server/ai-employees/ai-employee.js',
801
+ '@nocobase/plugin-ai/dist/server/ai-employees/ai-employee',
802
+ '@nocobase/plugin-ai/server',
803
+ ]) {
804
+ try {
805
+ const mod = await import(/* webpackIgnore: true */ importPath as any);
806
+ AIEmployee = (mod as any).AIEmployee || (mod as any).default?.AIEmployee;
807
+ if (AIEmployee) break;
808
+ } catch {
809
+ // try next path
810
+ }
811
+ }
812
+ if (!AIEmployee)
813
+ throw new Error('AIEmployee class not found — plugin-ai may not be installed or its exports changed');
814
+
815
+ const llmService = args.flow.get('llmService') as string | null;
816
+ const model = args.flow.get('model') as string | null;
817
+ const modelRef = llmService && model ? { llmService, model } : undefined;
818
+
819
+ const aiEmployee = new AIEmployee({
820
+ ctx: syntheticCtx,
821
+ employee: employeeRecord,
822
+ sessionId,
823
+ systemMessage: undefined,
824
+ skillSettings: undefined,
825
+ webSearch: false,
826
+ model: modelRef,
827
+ legacy: false,
828
+ });
829
+
830
+ // H-4 fix: enforce a timeout on AI review execution to prevent stuck reviews
831
+ const REVIEW_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
832
+ const result = await Promise.race([
833
+ aiEmployee.invoke({
834
+ userMessages: [
835
+ {
836
+ role: 'user',
837
+ content: { type: 'text', content: prompt },
838
+ },
839
+ ],
840
+ }),
841
+ new Promise<never>((_resolve, reject) =>
842
+ setTimeout(() => reject(new Error('AI review timed out after 5 minutes')), REVIEW_TIMEOUT_MS),
843
+ ),
844
+ ]);
845
+
846
+ const content = extractLastAiMessageContent(result);
847
+ if (!content) {
848
+ throw new Error('AI employee returned empty review content');
849
+ }
850
+
851
+ const finishedAt = new Date();
852
+ const durationMs = finishedAt.getTime() - startedAt.getTime();
853
+
854
+ const postMode = getFlowPostMode(args.flow);
855
+ let postStatus = getInitialPostStatus(args.flow, args.targetType);
856
+ let postedNoteId: string | null = null;
857
+ let autoPostError: string | null = null;
858
+
859
+ if (postMode === 'disabled') {
860
+ postStatus = 'skipped';
861
+ } else if (postMode === 'auto' && args.targetType === 'mr' && args.mrIid) {
862
+ try {
863
+ postedNoteId = String(await postNoteToGitLab(args.repo, args.mrIid, content));
864
+ postStatus = 'posted';
865
+ } catch (err: any) {
866
+ autoPostError = redactPat(err?.message || String(err));
867
+ postStatus = 'post_failed';
868
+ app.log?.error?.('Auto-post review note failed', err);
869
+ }
870
+ }
871
+
872
+ await reviewsRepo.update({
873
+ filterByTk: args.reviewId,
874
+ values: {
875
+ status: 'completed',
876
+ reviewMarkdown: content,
877
+ rawOutput: JSON.stringify({
878
+ messageCount: result?.messages?.length ?? 0,
879
+ llmService: llmService || 'default',
880
+ model: model || 'default',
881
+ }),
882
+ durationMs,
883
+ finishedAt,
884
+ postStatus,
885
+ postedNoteId,
886
+ error: autoPostError ? `Auto-post failed: ${autoPostError}` : null,
887
+ metadata: {
888
+ flowName: args.flow.get('name'),
889
+ aiEmployeeUsername: args.aiEmployeeUsername,
890
+ llmService,
891
+ model,
892
+ postMode,
893
+ autoPostError,
894
+ },
895
+ },
896
+ });
897
+
898
+ if (sessionId) {
899
+ db.getRepository('aiConversations')
900
+ .destroy({ filterByTk: sessionId })
901
+ .catch(() => undefined);
902
+ }
903
+ } catch (err: any) {
904
+ const finishedAt = new Date();
905
+ // Redact PAT before persisting the error — simple-git / fetch errors
906
+ // can echo back the authenticated remote URL in their messages.
907
+ const safeMessage = redactPat(err?.message || String(err));
908
+ app.log?.error?.(`git review ${args.reviewId} failed: ${safeMessage}`, err);
909
+ await reviewsRepo.update({
910
+ filterByTk: args.reviewId,
911
+ values: {
912
+ status: 'failed',
913
+ error: safeMessage,
914
+ finishedAt,
915
+ durationMs: finishedAt.getTime() - startedAt.getTime(),
916
+ },
917
+ });
918
+ if (sessionId) {
919
+ db.getRepository('aiConversations')
920
+ .destroy({ filterByTk: sessionId })
921
+ .catch(() => undefined);
922
+ }
923
+ }
924
+ }
925
+
926
+ async function resolveBackgroundReviewRoles(db: any, userId?: number | string | null): Promise<string[]> {
927
+ if (!userId) return ['admin'];
928
+
929
+ try {
930
+ const roles = await db.getRepository('users.roles', userId).find({ raw: true });
931
+ const roleNames = (Array.isArray(roles) ? roles : [])
932
+ .map((role: any) => role?.name)
933
+ .filter((name: unknown): name is string => typeof name === 'string' && !!name);
934
+ if (roleNames.length) return roleNames;
935
+ } catch {
936
+ // Fall back to the through table below for apps where the association
937
+ // repository is unavailable in a background worker context.
938
+ }
939
+
940
+ try {
941
+ const mappings = await db.getRepository('rolesUsers').find({
942
+ filter: { userId },
943
+ raw: true,
944
+ });
945
+ const roleNames = (Array.isArray(mappings) ? mappings : [])
946
+ .map((mapping: any) => mapping?.roleName)
947
+ .filter((name: unknown): name is string => typeof name === 'string' && !!name);
948
+ if (roleNames.length) return roleNames;
949
+ } catch {
950
+ // Keep the synthetic ctx valid even if role lookup is unavailable.
951
+ }
952
+
953
+ return ['admin'];
954
+ }
955
+
956
+ function buildReviewPrompt(args: RunReviewArgs): string {
957
+ const lines: string[] = [];
958
+ lines.push(`You are performing a code review on repository "${args.repo.get('name')}" (id=${args.repo.get('id')}).`);
959
+ lines.push('');
960
+
961
+ if (args.targetType === 'mr') {
962
+ lines.push(`Target: Merge Request !${args.mrIid}.`);
963
+ lines.push(
964
+ `Use the \`git_get_merge_request\` tool with repositoryId=${args.repo.get('id')} and mrIid=${
965
+ args.mrIid
966
+ } to fetch the diff and metadata.`,
967
+ );
968
+ lines.push('Optionally call `git_get_merge_request_notes` to avoid duplicating prior comments.');
969
+ } else if (args.targetType === 'commit') {
970
+ lines.push(`Target: Commit ${args.commitSha}.`);
971
+ lines.push(
972
+ `Use the \`git_get_commit\` tool with repositoryId=${args.repo.get('id')} and commitHash=${
973
+ args.commitSha
974
+ } to fetch the diff.`,
975
+ );
976
+ } else {
977
+ lines.push(`Target: Branch ${args.branch}.`);
978
+ lines.push(
979
+ `Use \`git_list_commits\`, \`git_get_diff\`, and \`git_get_file_content\` (with repositoryId=${args.repo.get(
980
+ 'id',
981
+ )}) to inspect recent changes on this branch.`,
982
+ );
983
+ }
984
+
985
+ lines.push('');
986
+ lines.push('Produce a thorough but concise code review report in Markdown. Required sections:');
987
+ lines.push('1. **Summary** — overall assessment.');
988
+ lines.push(
989
+ '2. **Findings** — issues grouped by severity (`Critical`, `High`, `Medium`, `Low`, `Info`). For each finding include the file path, line/range when possible, the problem, and a suggested fix.',
990
+ );
991
+ lines.push('3. **Suggestions** — non-blocking improvements.');
992
+ lines.push('4. **Verdict** — one of: `LGTM`, `Approve with comments`, `Request changes`, `Block`.');
993
+ lines.push('');
994
+ lines.push('Cite code snippets in fenced code blocks. Do not output anything outside the Markdown report.');
995
+
996
+ const flowInstructions = args.flow.get('instructions') as string;
997
+ if (flowInstructions) {
998
+ lines.push('');
999
+ lines.push('---');
1000
+ lines.push('Additional instructions from the review flow:');
1001
+ lines.push(flowInstructions);
1002
+ }
1003
+ if (args.extraInstructions) {
1004
+ lines.push('');
1005
+ lines.push('---');
1006
+ lines.push('Additional instructions for this run:');
1007
+ lines.push(args.extraInstructions);
1008
+ }
1009
+
1010
+ return lines.join('\n');
1011
+ }
1012
+
1013
+ /**
1014
+ * Pick the AI's final reply out of a LangChain-style message list.
1015
+ *
1016
+ * The previous implementation relied solely on `constructor.name`, which is
1017
+ * unsafe under bundling/minification (class names can be mangled to single
1018
+ * letters) and after JSON serialisation (instances become plain objects).
1019
+ * The new logic checks several signals in order: LangChain's `_getType()`,
1020
+ * an explicit `role` field, then the constructor name as a last resort.
1021
+ */
1022
+ function extractLastAiMessageContent(result: any): string {
1023
+ const messages = result?.messages;
1024
+ if (!Array.isArray(messages)) return '';
1025
+
1026
+ const isAiMessage = (msg: any): boolean => {
1027
+ if (!msg) return false;
1028
+ if (typeof msg._getType === 'function') {
1029
+ try {
1030
+ return msg._getType() === 'ai';
1031
+ } catch {
1032
+ // fall through to other signals
1033
+ }
1034
+ }
1035
+ if (typeof msg.role === 'string') {
1036
+ const r = msg.role.toLowerCase();
1037
+ return r === 'assistant' || r === 'ai';
1038
+ }
1039
+ if (typeof msg.type === 'string' && msg.type.toLowerCase() === 'ai') return true;
1040
+ const name = msg?.constructor?.name;
1041
+ if (name === 'AIMessage' || name === 'AIMessageChunk') return true;
1042
+ return false;
1043
+ };
1044
+
1045
+ const getContent = (msg: any): string => {
1046
+ if (typeof msg.content === 'string') return msg.content;
1047
+ if (Array.isArray(msg.content)) {
1048
+ const textBlock = msg.content.find((c: any) => c?.type === 'text');
1049
+ if (typeof textBlock?.text === 'string') return textBlock.text;
1050
+ }
1051
+ return '';
1052
+ };
1053
+
1054
+ for (let i = messages.length - 1; i >= 0; i--) {
1055
+ const msg = messages[i];
1056
+ if (!isAiMessage(msg)) continue;
1057
+ const content = getContent(msg);
1058
+ if (content) return content;
1059
+ }
1060
+ return '';
1061
+ }
1062
+
1063
+ async function fetchMrHeadSha(repo: any, mrIid: number): Promise<string | null> {
1064
+ const repoUrl = repo.get('repoUrl') as string;
1065
+ const pat = repo.get('pat') as string;
1066
+ if (!pat) return null;
1067
+ const isGitHub = repoUrl.includes('github.com');
1068
+
1069
+ try {
1070
+ if (isGitHub) {
1071
+ const { projectPath } = parseGitLabProject(repoUrl);
1072
+ const response = await fetch(`https://api.github.com/repos/${projectPath}/pulls/${mrIid}`, {
1073
+ headers: { Authorization: `Bearer ${pat}`, Accept: 'application/vnd.github.v3+json' },
1074
+ });
1075
+ if (!response.ok) return null;
1076
+ const data = await response.json();
1077
+ return data?.head?.sha || null;
1078
+ } else {
1079
+ const { apiBase, encodedProject } = parseGitLabProject(repoUrl);
1080
+ const response = await fetch(`${apiBase}/projects/${encodedProject}/merge_requests/${mrIid}`, {
1081
+ headers: { 'PRIVATE-TOKEN': pat, Accept: 'application/json' },
1082
+ });
1083
+ if (!response.ok) return null;
1084
+ const data = await response.json();
1085
+ return (data?.sha as string) || (data?.diff_refs?.head_sha as string) || null;
1086
+ }
1087
+ } catch {
1088
+ return null;
1089
+ }
1090
+ }
1091
+
1092
+ async function postNoteToGitLab(repo: any, mrIid: number, body: string): Promise<number | string> {
1093
+ const repoUrl = repo.get('repoUrl') as string;
1094
+ const pat = repo.get('pat') as string;
1095
+ const isGitHub = repoUrl.includes('github.com');
1096
+
1097
+ if (isGitHub) {
1098
+ if (!pat) throw new Error('Repository has no PAT configured');
1099
+ const { projectPath } = parseGitLabProject(repoUrl);
1100
+
1101
+ const response = await fetch(`https://api.github.com/repos/${projectPath}/issues/${mrIid}/comments`, {
1102
+ method: 'POST',
1103
+ headers: {
1104
+ Authorization: `Bearer ${pat}`,
1105
+ 'Content-Type': 'application/json',
1106
+ Accept: 'application/vnd.github.v3+json',
1107
+ },
1108
+ body: JSON.stringify({ body }),
1109
+ });
1110
+
1111
+ if (!response.ok) {
1112
+ const text = await response.text().catch(() => '');
1113
+ throw new Error(`GitHub note post failed ${response.status}: ${text}`);
1114
+ }
1115
+ const data = await response.json();
1116
+ return data?.id;
1117
+ } else {
1118
+ if (!pat) throw new Error('Repository has no PAT configured');
1119
+
1120
+ const { apiBase, encodedProject } = parseGitLabProject(repoUrl);
1121
+
1122
+ const response = await fetch(`${apiBase}/projects/${encodedProject}/merge_requests/${mrIid}/notes`, {
1123
+ method: 'POST',
1124
+ headers: {
1125
+ 'PRIVATE-TOKEN': pat,
1126
+ 'Content-Type': 'application/json',
1127
+ Accept: 'application/json',
1128
+ },
1129
+ body: JSON.stringify({ body }),
1130
+ });
1131
+ if (!response.ok) {
1132
+ const text = await response.text().catch(() => '');
1133
+ throw new Error(`GitLab note post failed ${response.status}: ${text}`);
1134
+ }
1135
+ const data = await response.json();
1136
+ return data?.id;
1137
+ }
1138
+ }
1139
+
1140
+ /* ───────── Flow matching helpers ───────── */
1141
+
1142
+ /**
1143
+ * H-1 fix: guard against ReDoS by limiting regex length and wrapping
1144
+ * execution in a try-catch.
1145
+ *
1146
+ * Fail-closed: an invalid or oversized pattern means "no branch matches".
1147
+ * Reviewing all branches when a user explicitly configured a filter is more
1148
+ * dangerous (auto-posts to GitLab, consumes LLM credits) than skipping a
1149
+ * malformed flow. The poller logs once per process so misconfiguration is
1150
+ * still observable.
1151
+ */
1152
+ const MAX_BRANCH_FILTER_LENGTH = 200;
1153
+ const loggedBadFilters = new Set<string>();
1154
+
1155
+ type ReviewPostMode = 'auto' | 'manual' | 'disabled';
1156
+
1157
+ function getFlowPostMode(flow: any): ReviewPostMode {
1158
+ const rawValue = flow?.get?.('postMode');
1159
+ const value = rawValue && typeof rawValue === 'object' && 'value' in rawValue ? rawValue.value : rawValue;
1160
+ const normalized = String(value || 'manual')
1161
+ .trim()
1162
+ .toLowerCase()
1163
+ .replace(/[\s-]+/g, '_');
1164
+
1165
+ if (['auto', 'auto_post', 'autopost', 'auto_post_to_mr'].includes(normalized)) return 'auto';
1166
+ if (['disabled', 'disable', 'do_not_post', 'dont_post', 'none', 'skip', 'skipped'].includes(normalized)) {
1167
+ return 'disabled';
1168
+ }
1169
+ return 'manual';
1170
+ }
1171
+
1172
+ function getInitialPostStatus(flow: any, targetType: string): string {
1173
+ const postMode = getFlowPostMode(flow);
1174
+ if (postMode === 'disabled') return 'skipped';
1175
+ if (postMode === 'auto' && targetType !== 'mr') return 'skipped';
1176
+ return 'pending_approval';
1177
+ }
1178
+
1179
+ function warnInvalidBranchFilter(filter: string, reason: string) {
1180
+ if (loggedBadFilters.has(filter)) return;
1181
+ loggedBadFilters.add(filter);
1182
+ console.warn(
1183
+ `[plugin-git-manager] branchFilter rejected (${reason}): ${JSON.stringify(
1184
+ filter,
1185
+ )}. Flow will not match any branch.`,
1186
+ );
1187
+ }
1188
+
1189
+ export function branchMatches(flow: any, branch: string): boolean {
1190
+ const filter = flow.get('branchFilter') as string | null;
1191
+ if (!filter) return true;
1192
+ if (filter.length > MAX_BRANCH_FILTER_LENGTH) {
1193
+ warnInvalidBranchFilter(filter, `too long (>${MAX_BRANCH_FILTER_LENGTH} chars)`);
1194
+ return false;
1195
+ }
1196
+ try {
1197
+ return new RegExp(filter).test(branch);
1198
+ } catch (err: any) {
1199
+ warnInvalidBranchFilter(filter, `invalid regex: ${err?.message || err}`);
1200
+ return false;
1201
+ }
1202
+ }
1203
+
1204
+ export function pickFlowMatchingBranch(flows: any[], branch?: string): any | null {
1205
+ if (!flows?.length) return null;
1206
+ if (!branch) return flows[0];
1207
+ for (const f of flows) {
1208
+ if (branchMatches(f, branch)) return f;
1209
+ }
1210
+ return null;
1211
+ }
1212
+
1213
+ function throwHttp(status: number, message: string): never {
1214
+ const err: any = new Error(message);
1215
+ err.status = status;
1216
+ throw err;
1217
+ }
1218
+
1219
+ /**
1220
+ * Review execution is delegated to worker queue processing. When a worker
1221
+ * restarts mid-run, the DB record can stay in `status='running'` indefinitely.
1222
+ * On startup we sweep any `running` review whose `startedAt` is older than the
1223
+ * in-process timeout (5 min) plus a safety margin and mark it as failed.
1224
+ *
1225
+ * The cutoff is intentionally larger than the runtime timeout so concurrent
1226
+ * reviews running on a *different* node in an HA cluster aren't clobbered.
1227
+ */
1228
+ const STUCK_REVIEW_CUTOFF_MS = 10 * 60 * 1000; // 10 minutes
1229
+
1230
+ export async function recoverStuckReviews(app: Application): Promise<number> {
1231
+ try {
1232
+ const reviewsRepo = app.db.getRepository('gitCodeReviews');
1233
+ const cutoff = new Date(Date.now() - STUCK_REVIEW_CUTOFF_MS);
1234
+ // Pending rows are the durable queue source of truth and are picked up by
1235
+ // worker DB polling, so only sweep reviews that were actually claimed.
1236
+ const stuck = await reviewsRepo.find({
1237
+ filter: {
1238
+ status: 'running',
1239
+ startedAt: { $lt: cutoff },
1240
+ },
1241
+ });
1242
+ if (!stuck?.length) return 0;
1243
+ const finishedAt = new Date();
1244
+ for (const review of stuck) {
1245
+ const startedAt = review.get('startedAt') as Date | null;
1246
+ const durationMs = startedAt ? finishedAt.getTime() - new Date(startedAt).getTime() : null;
1247
+ await reviewsRepo.update({
1248
+ filterByTk: review.get('id'),
1249
+ values: {
1250
+ status: 'failed',
1251
+ error: 'Review interrupted by application restart',
1252
+ finishedAt,
1253
+ durationMs,
1254
+ },
1255
+ });
1256
+ }
1257
+ app.log?.info?.(`plugin-git-manager: marked ${stuck.length} stuck review(s) as failed after restart`);
1258
+ return stuck.length;
1259
+ } catch (err: any) {
1260
+ app.log?.error?.(`plugin-git-manager: recoverStuckReviews failed: ${err?.message}`);
1261
+ return 0;
1262
+ }
1263
+ }