forked from DGouron/review-flow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitlab.controller.ts
More file actions
647 lines (589 loc) · 25.5 KB
/
gitlab.controller.ts
File metadata and controls
647 lines (589 loc) · 25.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
import type { FastifyRequest, FastifyReply } from 'fastify';
import type { Logger } from 'pino';
import { verifyGitLabSignature, getGitLabEventType } from '@/security/verifier.js';
import { gitLabMergeRequestEventGuard } from '@/entities/gitlab/gitlabMergeRequestEvent.guard.js';
import { filterGitLabEvent, filterGitLabMrUpdate, filterGitLabMrClose, filterGitLabMrMerge, filterGitLabMrApprove } from '@/interface-adapters/controllers/webhook/eventFilter.js';
import { findRepositoryByProjectPath } from '@/config/loader.js';
import {
enqueueReview,
createJobId,
updateJobProgress,
cancelJob,
type ReviewJob,
} from '@/frameworks/queue/pQueueAdapter.js';
import { invokeClaudeReview, sendNotification } from '@/claude/invoker.js';
import type { ReviewRequestTrackingGateway } from '@/interface-adapters/gateways/reviewRequestTracking.gateway.js';
import type { TrackAssignmentUseCase } from '@/usecases/tracking/trackAssignment.usecase.js';
import type { RecordReviewCompletionUseCase } from '@/usecases/tracking/recordReviewCompletion.usecase.js';
import type { RecordPushUseCase } from '@/usecases/tracking/recordPush.usecase.js';
import type { TransitionStateUseCase } from '@/usecases/tracking/transitionState.usecase.js';
import type { CheckFollowupNeededUseCase } from '@/usecases/tracking/checkFollowupNeeded.usecase.js';
import type { SyncThreadsUseCase } from '@/usecases/tracking/syncThreads.usecase.js';
import { loadProjectConfig, getProjectAgents, getFollowupAgents, getProjectLanguage } from '@/config/projectConfig.js';
import { DEFAULT_AGENTS, DEFAULT_FOLLOWUP_AGENTS } from '@/entities/progress/agentDefinition.type.js';
import { parseReviewOutput } from '@/services/statsService.js';
import { parseThreadActions } from '@/services/threadActionsParser.js';
import { executeThreadActions, defaultCommandExecutor } from '@/services/threadActionsExecutor.js';
import { executeActionsFromContext } from '@/services/contextActionsExecutor.js';
import { startWatchingReviewContext, stopWatchingReviewContext } from '@/main/websocket.js';
import type { ReviewContextGateway } from '@/entities/reviewContext/reviewContext.gateway.js';
import type { ThreadFetchGateway } from '@/entities/threadFetch/threadFetch.gateway.js';
import type { DiffMetadataFetchGateway } from '@/entities/diffMetadata/diffMetadata.gateway.js';
function extractBaseUrl(remoteUrl: string): string | undefined {
try {
// Handle HTTPS URLs: https://gitlab.example.com/group/project.git
if (remoteUrl.startsWith('http')) {
const url = new URL(remoteUrl)
return `${url.protocol}//${url.host}`
}
// Handle SSH URLs: git@gitlab.example.com:group/project.git
const sshMatch = remoteUrl.match(/@([^:]+):/)
if (sshMatch) {
return `https://${sshMatch[1]}`
}
} catch {
// Invalid URL — return undefined
}
return undefined
}
export interface GitLabWebhookDependencies {
reviewContextGateway: ReviewContextGateway;
threadFetchGateway: ThreadFetchGateway;
diffMetadataFetchGateway: DiffMetadataFetchGateway;
trackAssignment: TrackAssignmentUseCase;
recordCompletion: RecordReviewCompletionUseCase;
recordPush: RecordPushUseCase;
transitionState: TransitionStateUseCase;
checkFollowupNeeded: CheckFollowupNeededUseCase;
syncThreads: SyncThreadsUseCase;
}
export async function handleGitLabWebhook(
request: FastifyRequest,
reply: FastifyReply,
logger: Logger,
trackingGateway: ReviewRequestTrackingGateway,
deps: GitLabWebhookDependencies
): Promise<void> {
const { trackAssignment, recordCompletion, recordPush, transitionState, checkFollowupNeeded, syncThreads } = deps;
// 1. Verify signature
const verification = verifyGitLabSignature(request);
if (!verification.valid) {
logger.warn({ error: verification.error }, 'GitLab signature verification failed');
reply.status(401).send({ error: verification.error });
return;
}
// 2. Check event type
const eventType = getGitLabEventType(request);
if (eventType !== 'Merge Request Hook') {
logger.debug({ eventType }, 'Ignoring non-MR event');
reply.status(200).send({ status: 'ignored', reason: 'Not a MR event' });
return;
}
// 3. Parse and validate event
const parseResult = gitLabMergeRequestEventGuard.safeParse(request.body);
if (!parseResult.success) {
logger.warn({ errors: parseResult.error }, 'Invalid GitLab webhook payload');
reply.status(400).send({ error: 'Invalid webhook payload' });
return;
}
const event = parseResult.data;
// 3a. Check if MR was closed - clean up tracking and cancel any running job
const closeResult = filterGitLabMrClose(event);
if (closeResult.shouldProcess) {
const projectPath = closeResult.projectPath;
const mrNumber = closeResult.mergeRequestNumber;
const mrId = `gitlab-${projectPath}-${mrNumber}`;
// Find repo config
const repoConfig = findRepositoryByProjectPath(projectPath);
if (repoConfig) {
// Cancel any running job for this MR
const jobId = createJobId('gitlab', projectPath, mrNumber);
const cancelled = cancelJob(jobId);
// Archive the MR from tracking
const archived = trackingGateway.archive(repoConfig.localPath, mrId);
// Delete review context file
const contextGateway = deps.reviewContextGateway;
const contextDeleted = contextGateway.delete(repoConfig.localPath, mrId);
logger.info(
{
mrNumber,
project: projectPath,
jobCancelled: cancelled,
trackingArchived: archived,
contextDeleted: contextDeleted.deleted,
},
'MR closed - cleaned up tracking and cancelled job'
);
reply.status(200).send({
status: 'cleaned',
mrNumber,
jobCancelled: cancelled,
trackingArchived: archived,
});
return;
}
// No repo config, just acknowledge
logger.info({ mrNumber, project: projectPath }, 'MR closed but repo not configured');
reply.status(200).send({ status: 'ignored', reason: 'MR closed, repo not configured' });
return;
}
// 3b. Check if MR was merged - update tracking state
const mergeResult = filterGitLabMrMerge(event);
if (mergeResult.shouldProcess) {
const repoConfig = findRepositoryByProjectPath(mergeResult.projectPath);
if (repoConfig) {
const mrId = `gitlab-${mergeResult.projectPath}-${mergeResult.mergeRequestNumber}`;
transitionState.execute({ projectPath: repoConfig.localPath, mrId, targetState: 'merged' });
logger.info({ mrNumber: mergeResult.mergeRequestNumber }, 'MR marked as merged');
reply.status(200).send({ status: 'merged', mrNumber: mergeResult.mergeRequestNumber });
return;
}
}
// 3c. Check if MR was approved - update tracking state
const approveResult = filterGitLabMrApprove(event);
if (approveResult.shouldProcess) {
const repoConfig = findRepositoryByProjectPath(approveResult.projectPath);
if (repoConfig) {
const mrId = `gitlab-${approveResult.projectPath}-${approveResult.mergeRequestNumber}`;
transitionState.execute({ projectPath: repoConfig.localPath, mrId, targetState: 'approved' });
logger.info({ mrNumber: approveResult.mergeRequestNumber }, 'MR marked as approved');
reply.status(200).send({ status: 'approved', mrNumber: approveResult.mergeRequestNumber });
return;
}
}
// 3d. Filter for review assignment
const filterResult = filterGitLabEvent(event);
// Debug: log reviewers data
logger.info(
{
project: event.project?.path_with_namespace,
mrIid: event.object_attributes?.iid,
action: event.object_attributes?.action,
reviewers: event.reviewers?.map(r => r.username) || 'NONE',
changesReviewers: event.changes?.reviewers ? 'YES' : 'NO',
shouldProcess: filterResult.shouldProcess,
reason: filterResult.reason,
},
'GitLab MR event received'
);
if (!filterResult.shouldProcess) {
// Check if this is an MR update that might need a followup review
const updateResult = filterGitLabMrUpdate(event);
logger.debug(
{ updateResult, action: event.object_attributes?.action },
'Checking for followup review'
);
if (updateResult.shouldProcess && updateResult.isFollowup) {
// Find repo config to get local path
const updateRepoConfig = findRepositoryByProjectPath(updateResult.projectPath);
if (updateRepoConfig) {
// Record the push event
const mr = recordPush.execute({ projectPath: updateRepoConfig.localPath, mrNumber: updateResult.mergeRequestNumber, platform: 'gitlab' });
logger.info(
{
mrNumber: updateResult.mergeRequestNumber,
mrFound: !!mr,
mrState: mr?.state,
lastPushAt: mr?.lastPushAt,
lastReviewAt: mr?.lastReviewAt,
},
'Push event recorded'
);
// Check if this MR needs a followup (has open threads and was pushed since last review)
const needsFollowup = mr && checkFollowupNeeded.execute({ projectPath: updateRepoConfig.localPath, mrNumber: updateResult.mergeRequestNumber, platform: 'gitlab' });
logger.info({ needsFollowup, mrState: mr?.state }, 'Followup check result');
if (needsFollowup) {
if (mr.autoFollowup === false) {
logger.info(
{ mrNumber: updateResult.mergeRequestNumber, project: updateResult.projectPath },
'Auto-followup disabled for this MR, skipping'
);
reply.status(200).send({ status: 'ignored', reason: 'Auto-followup disabled' });
return;
}
logger.info(
{ mrNumber: updateResult.mergeRequestNumber, project: updateResult.projectPath },
'Auto-triggering followup review after push'
);
const projectConfig = loadProjectConfig(updateRepoConfig.localPath);
const skill = projectConfig?.reviewFollowupSkill || 'review-followup';
const followupJobId = createJobId('gitlab-followup', updateResult.projectPath, updateResult.mergeRequestNumber);
const followupJob: ReviewJob = {
id: followupJobId,
platform: 'gitlab',
projectPath: updateResult.projectPath,
localPath: updateRepoConfig.localPath,
mrNumber: updateResult.mergeRequestNumber,
skill,
mrUrl: updateResult.mergeRequestUrl,
sourceBranch: updateResult.sourceBranch,
targetBranch: updateResult.targetBranch,
jobType: 'followup',
};
enqueueReview(followupJob, async (j, signal) => {
sendNotification('Review followup démarrée', `MR !${j.mrNumber} - ${j.projectPath}`, logger);
// Create review context file with pre-fetched threads and diff metadata
const mergeRequestId = `gitlab-${j.projectPath}-${j.mrNumber}`;
const contextGateway = deps.reviewContextGateway;
const threadFetchGw = deps.threadFetchGateway;
const diffMetadataFetchGw = deps.diffMetadataFetchGateway;
try {
const threads = threadFetchGw.fetchThreads(j.projectPath, j.mrNumber);
let diffMetadata: import('../../../entities/reviewContext/reviewContext.js').DiffMetadata | undefined;
try {
diffMetadata = diffMetadataFetchGw.fetchDiffMetadata(j.projectPath, j.mrNumber);
} catch (error) {
logger.warn(
{ mrNumber: j.mrNumber, error: error instanceof Error ? error.message : String(error) },
'Failed to fetch diff metadata for followup, inline comments will be skipped'
);
}
const followupAgentsList = getFollowupAgents(j.localPath) ?? DEFAULT_FOLLOWUP_AGENTS;
contextGateway.create({
localPath: j.localPath,
mergeRequestId,
platform: 'gitlab',
projectPath: j.projectPath,
mergeRequestNumber: j.mrNumber,
threads,
agents: followupAgentsList,
diffMetadata,
});
logger.info(
{ mrNumber: j.mrNumber, threadsCount: threads.length, hasDiffMetadata: !!diffMetadata },
'Review context file created with threads for followup'
);
startWatchingReviewContext(j.id, j.localPath, mergeRequestId);
logger.info({ mrNumber: j.mrNumber }, 'Started watching review context for live progress');
} catch (error) {
logger.warn(
{ mrNumber: j.mrNumber, error: error instanceof Error ? error.message : String(error) },
'Failed to create review context file for followup, continuing without it'
);
}
const result = await invokeClaudeReview(j, logger, (progress, progressEvent) => {
updateJobProgress(j.id, progress, progressEvent);
// Also update the review context file for file-based progress tracking
const runningAgent = progress.agents.find(a => a.status === 'running');
const completedAgents = progress.agents
.filter(a => a.status === 'completed')
.map(a => a.name);
contextGateway.updateProgress(j.localPath, mergeRequestId, {
phase: progress.currentPhase,
currentStep: runningAgent?.name ?? null,
stepsCompleted: completedAgents,
});
}, signal);
stopWatchingReviewContext(mergeRequestId);
if (result.success) {
// Parse review output for stats
const parsed = parseReviewOutput(result.stdout);
let threadResolveCount = 0;
// PRIMARY: Execute actions from context file (agent writes actions here)
const reviewContext = contextGateway.read(j.localPath, mergeRequestId);
if (reviewContext && reviewContext.actions.length > 0) {
threadResolveCount = reviewContext.actions.filter(a => a.type === 'THREAD_RESOLVE').length;
const followupBaseUrl = extractBaseUrl(updateRepoConfig.remoteUrl);
const contextActionResult = await executeActionsFromContext(
reviewContext,
j.localPath,
logger,
defaultCommandExecutor,
followupBaseUrl,
);
logger.info(
{ ...contextActionResult, threadResolveCount, mrNumber: j.mrNumber },
'Actions executed from context file for followup'
);
} else {
// FALLBACK: Execute thread actions from stdout markers (backward compatibility)
const threadActions = parseThreadActions(result.stdout);
if (threadActions.length > 0) {
threadResolveCount = threadActions.filter(a => a.type === 'THREAD_RESOLVE').length;
const actionResult = await executeThreadActions(
threadActions,
{
platform: 'gitlab',
projectPath: j.projectPath,
mrNumber: j.mrNumber,
localPath: j.localPath,
},
logger,
defaultCommandExecutor
);
logger.info(
{ ...actionResult, threadResolveCount, mrNumber: j.mrNumber },
'Thread actions executed from stdout markers for followup (fallback)'
);
}
}
// Sync threads from GitLab FIRST to get real state after followup resolves threads
const mrId = `gitlab-${j.projectPath}-${j.mrNumber}`;
const updatedMr = syncThreads.execute({ projectPath: j.localPath, mrId });
// Record followup completion with parsed stats
// threadsClosed comes from THREAD_RESOLVE markers parsed from output
recordCompletion.execute({
projectPath: j.localPath,
mrId,
reviewData: {
type: 'followup',
durationMs: result.durationMs,
score: parsed.score,
blocking: parsed.blocking,
warnings: parsed.warnings,
suggestions: parsed.suggestions,
threadsOpened: 0,
threadsClosed: threadResolveCount,
},
});
logger.info(
{
mrNumber: j.mrNumber,
score: parsed.score,
blocking: parsed.blocking,
warnings: parsed.warnings,
suggestions: parsed.suggestions,
durationMs: result.durationMs,
openThreads: updatedMr?.openThreads,
state: updatedMr?.state,
},
'Followup stats recorded and threads synced'
);
sendNotification('Review followup terminée', `MR !${j.mrNumber} - ${j.projectPath}`, logger);
} else if (!result.cancelled) {
sendNotification('Review followup échouée', `MR !${j.mrNumber} - Code ${result.exitCode}`, logger);
throw new Error(`Followup review failed with exit code ${result.exitCode}`);
}
});
reply.status(202).send({
status: 'followup-queued',
jobId: followupJobId,
mrNumber: updateResult.mergeRequestNumber,
});
return;
}
}
}
reply.status(200).send({ status: 'ignored', reason: filterResult.reason });
return;
}
// 4. Find repository configuration
const repoConfig = findRepositoryByProjectPath(filterResult.projectPath);
if (!repoConfig) {
logger.warn(
{ projectPath: filterResult.projectPath },
'Projet non configuré'
);
reply.status(200).send({
status: 'ignored',
reason: 'Repository not configured',
});
return;
}
// 5. Track MR assignment with user info
// Use MR assignee (actual owner), not webhook trigger (who added the reviewer)
const mrTitle = event.object_attributes?.title || `MR !${filterResult.mergeRequestNumber}`;
const mrAssignee = event.assignees?.[0];
const assignedBy = {
username: mrAssignee?.username || event.user?.username || 'unknown',
displayName: mrAssignee?.name || event.user?.name,
};
trackAssignment.execute({
projectPath: repoConfig.localPath,
mrInfo: {
mrNumber: filterResult.mergeRequestNumber,
title: mrTitle,
url: filterResult.mergeRequestUrl,
project: filterResult.projectPath,
platform: 'gitlab',
sourceBranch: filterResult.sourceBranch,
targetBranch: filterResult.targetBranch,
},
assignedBy,
});
logger.info(
{ mrNumber: filterResult.mergeRequestNumber, assignedBy: assignedBy.username },
'MR tracked for review'
);
// 6. Create and enqueue job
const jobId = createJobId('gitlab', filterResult.projectPath, filterResult.mergeRequestNumber);
const job: ReviewJob = {
id: jobId,
platform: 'gitlab',
projectPath: filterResult.projectPath,
localPath: repoConfig.localPath,
mrNumber: filterResult.mergeRequestNumber,
skill: repoConfig.skill,
mrUrl: filterResult.mergeRequestUrl,
sourceBranch: filterResult.sourceBranch,
targetBranch: filterResult.targetBranch,
jobType: 'review',
language: getProjectLanguage(repoConfig.localPath),
// MR metadata for dashboard
title: mrTitle,
description: event.object_attributes?.description,
assignedBy,
};
const enqueued = await enqueueReview(job, async (j, signal) => {
// Send start notification
sendNotification(
'Review démarrée',
`MR !${j.mrNumber} - ${j.projectPath}`,
logger
);
// Create review context file with pre-fetched threads and diff metadata
const mergeRequestId = `gitlab-${j.projectPath}-${j.mrNumber}`;
const contextGateway = deps.reviewContextGateway;
const threadFetchGw = deps.threadFetchGateway;
const diffMetadataFetchGw = deps.diffMetadataFetchGateway;
try {
const threads = threadFetchGw.fetchThreads(j.projectPath, j.mrNumber);
let diffMetadata: import('../../../entities/reviewContext/reviewContext.js').DiffMetadata | undefined;
try {
diffMetadata = diffMetadataFetchGw.fetchDiffMetadata(j.projectPath, j.mrNumber);
} catch (error) {
logger.warn(
{ mrNumber: j.mrNumber, error: error instanceof Error ? error.message : String(error) },
'Failed to fetch diff metadata, inline comments will be skipped'
);
}
const reviewAgentsList = getProjectAgents(j.localPath) ?? DEFAULT_AGENTS;
contextGateway.create({
localPath: j.localPath,
mergeRequestId,
platform: 'gitlab',
projectPath: j.projectPath,
mergeRequestNumber: j.mrNumber,
threads,
agents: reviewAgentsList,
diffMetadata,
});
logger.info(
{ mrNumber: j.mrNumber, threadsCount: threads.length, hasDiffMetadata: !!diffMetadata },
'Review context file created with threads'
);
startWatchingReviewContext(j.id, j.localPath, mergeRequestId);
logger.info({ mrNumber: j.mrNumber }, 'Started watching review context for live progress');
} catch (error) {
logger.warn(
{ mrNumber: j.mrNumber, error: error instanceof Error ? error.message : String(error) },
'Failed to create review context file, continuing without it'
);
}
// Invoke Claude with progress tracking and cancellation support
const result = await invokeClaudeReview(j, logger, (progress, progressEvent) => {
updateJobProgress(j.id, progress, progressEvent);
// Also update the review context file for file-based progress tracking
const runningAgent = progress.agents.find(a => a.status === 'running');
const completedAgents = progress.agents
.filter(a => a.status === 'completed')
.map(a => a.name);
contextGateway.updateProgress(j.localPath, mergeRequestId, {
phase: progress.currentPhase,
currentStep: runningAgent?.name ?? null,
stepsCompleted: completedAgents,
});
}, signal);
// Stop watching context file (auto-stops on completion, but explicit stop for error cases)
stopWatchingReviewContext(mergeRequestId);
// Send completion notification and record stats
if (result.cancelled) {
sendNotification(
'Review annulée',
`MR !${j.mrNumber} - ${j.projectPath}`,
logger
);
} else if (result.success) {
// Parse review output for stats
const parsed = parseReviewOutput(result.stdout);
// PRIMARY: Execute actions from context file (agent writes actions here)
const reviewContext = contextGateway.read(j.localPath, mergeRequestId);
if (reviewContext && reviewContext.actions.length > 0) {
const reviewBaseUrl = extractBaseUrl(repoConfig.remoteUrl);
const contextActionResult = await executeActionsFromContext(
reviewContext,
j.localPath,
logger,
defaultCommandExecutor,
reviewBaseUrl,
);
logger.info(
{ ...contextActionResult, mrNumber: j.mrNumber },
'Actions executed from context file'
);
} else {
// FALLBACK: Execute thread actions from stdout markers (backward compatibility)
const threadActions = parseThreadActions(result.stdout);
if (threadActions.length > 0) {
const actionResult = await executeThreadActions(
threadActions,
{
platform: 'gitlab',
projectPath: j.projectPath,
mrNumber: j.mrNumber,
localPath: j.localPath,
},
logger,
defaultCommandExecutor
);
logger.info(
{ ...actionResult, mrNumber: j.mrNumber },
'Thread actions executed from stdout markers (fallback)'
);
}
}
// Record review completion with parsed stats
// Only blocking issues count as open threads - warnings are informational
recordCompletion.execute({
projectPath: j.localPath,
mrId: `gitlab-${j.projectPath}-${j.mrNumber}`,
reviewData: {
type: 'review',
durationMs: result.durationMs,
score: parsed.score,
blocking: parsed.blocking,
warnings: parsed.warnings,
suggestions: parsed.suggestions,
threadsOpened: parsed.blocking, // Only blocking issues open threads
},
});
logger.info(
{
mrNumber: j.mrNumber,
score: parsed.score,
blocking: parsed.blocking,
warnings: parsed.warnings,
suggestions: parsed.suggestions,
durationMs: result.durationMs,
},
'Review stats recorded'
);
sendNotification(
'Review terminée',
`MR !${j.mrNumber} - ${j.projectPath}`,
logger
);
} else {
sendNotification(
'Review échouée',
`MR !${j.mrNumber} - Code ${result.exitCode}`,
logger
);
// Throw to mark job as failed (allows retry)
throw new Error(`Review failed with exit code ${result.exitCode}`);
}
});
if (enqueued) {
reply.status(202).send({
status: 'queued',
jobId,
mrNumber: filterResult.mergeRequestNumber,
});
} else {
reply.status(200).send({
status: 'deduplicated',
jobId,
reason: 'Review already in progress or recently completed',
});
}
}