plugin-git-manager 1.2.28 → 1.3.1

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.
Files changed (67) hide show
  1. package/README.md +58 -40
  2. package/dist/client/941.1793e67472872992.js +10 -0
  3. package/dist/client/index.js +1 -1
  4. package/dist/client-v2/941.b0d55429cd053f32.js +10 -0
  5. package/dist/client-v2/index.js +1 -1
  6. package/dist/locale/en-US.json +90 -1
  7. package/dist/locale/vi-VN.json +90 -1
  8. package/dist/locale/zh-CN.json +90 -1
  9. package/dist/node_modules/simple-git/package.json +1 -1
  10. package/dist/node_modules/zod/package.json +1 -1
  11. package/dist/server/actions/review-cutover.js +137 -0
  12. package/dist/server/actions/review.js +132 -43
  13. package/dist/server/actions/role-permissions.js +1 -0
  14. package/dist/server/ai-tools.js +8 -9
  15. package/dist/server/collections/gitCodeReviews.js +10 -0
  16. package/dist/server/collections/gitReviewCutover.js +44 -0
  17. package/dist/server/collections/gitReviewFlows.js +3 -0
  18. package/dist/server/collections/gitReviewInbox.js +51 -0
  19. package/dist/server/collections/gitReviewProjects.js +43 -0
  20. package/dist/server/collections/gitReviewRequests.js +56 -0
  21. package/dist/server/index.js +8 -2
  22. package/dist/server/plugin.js +51 -16
  23. package/dist/server/poller.js +54 -34
  24. package/dist/server/repository-access.js +23 -5
  25. package/dist/server/request-method-policy.js +2 -1
  26. package/dist/server/review-control-access.js +79 -0
  27. package/dist/server/services/legacy-post-service.js +412 -0
  28. package/dist/server/services/review-service.js +1451 -0
  29. package/dist/server/services/review-source.js +325 -0
  30. package/package.json +2 -2
  31. package/src/client/__tests__/CommitHistory.test.tsx +79 -0
  32. package/src/client/__tests__/ReviewHistory.test.tsx +126 -0
  33. package/src/client/__tests__/RunReviewButton.test.tsx +46 -35
  34. package/src/client/__tests__/workflowRoutes.test.ts +65 -0
  35. package/src/client/components/CommitHistory.tsx +61 -6
  36. package/src/client/components/ReviewFlows.tsx +90 -41
  37. package/src/client/components/ReviewHistory.tsx +245 -15
  38. package/src/client/components/RunReviewButton.tsx +12 -136
  39. package/src/client/workflowRoutes.ts +42 -0
  40. package/src/locale/en-US.json +90 -1
  41. package/src/locale/vi-VN.json +90 -1
  42. package/src/locale/zh-CN.json +90 -1
  43. package/src/server/__tests__/repository-access.test.ts +11 -3
  44. package/src/server/__tests__/review-service.integration.test.ts +1263 -0
  45. package/src/server/__tests__/review.test.ts +37 -98
  46. package/src/server/actions/review-cutover.ts +121 -0
  47. package/src/server/actions/review.ts +148 -38
  48. package/src/server/actions/role-permissions.ts +10 -0
  49. package/src/server/ai-tools.ts +23 -8
  50. package/src/server/collections/gitCodeReviews.ts +19 -0
  51. package/src/server/collections/gitReviewCutover.ts +23 -0
  52. package/src/server/collections/gitReviewFlows.ts +12 -0
  53. package/src/server/collections/gitReviewInbox.ts +30 -0
  54. package/src/server/collections/gitReviewProjects.ts +22 -0
  55. package/src/server/collections/gitReviewRequests.ts +35 -0
  56. package/src/server/index.ts +12 -0
  57. package/src/server/plugin.ts +43 -6
  58. package/src/server/poller.ts +54 -40
  59. package/src/server/repository-access.ts +32 -2
  60. package/src/server/request-method-policy.ts +1 -0
  61. package/src/server/review-control-access.ts +71 -0
  62. package/src/server/services/__tests__/review-source.test.ts +226 -0
  63. package/src/server/services/legacy-post-service.ts +550 -0
  64. package/src/server/services/review-service.ts +1899 -0
  65. package/src/server/services/review-source.ts +359 -0
  66. package/dist/client/900.a48beac7e2ebee7d.js +0 -10
  67. package/dist/client-v2/900.e6155002a9c97e7f.js +0 -10
@@ -0,0 +1,550 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import { createHash, randomUUID } from 'crypto';
11
+ import type { Application } from '@nocobase/server';
12
+ import { Transaction } from 'sequelize';
13
+ import { resolveBackgroundReviewRoles } from '../actions/review';
14
+ import { hasRepositoryAccess } from '../repository-access';
15
+ import {
16
+ assertCurrentMrHead,
17
+ findLegacyPublishedReview,
18
+ PinnedReviewSource,
19
+ publishPinnedReview,
20
+ resolveReviewProjectKey,
21
+ resolveReviewSource,
22
+ } from './review-source';
23
+
24
+ type Id = number | string;
25
+ type Getter = { get(name: string): unknown };
26
+ type LegacyStatus = 'posted' | 'unknown' | 'observed';
27
+
28
+ export interface LegacyPostResult {
29
+ status: LegacyStatus;
30
+ attemptId: string | null;
31
+ canRetry: boolean;
32
+ baseUnverified: true;
33
+ baseAcknowledged: boolean;
34
+ holdActive: boolean;
35
+ postedNoteId?: string;
36
+ }
37
+
38
+ function value<T>(record: Getter, name: string): T {
39
+ return record.get(name) as T;
40
+ }
41
+
42
+ function conflict(message: string): never {
43
+ const error = new Error(message) as Error & { status: number };
44
+ error.status = 409;
45
+ throw error;
46
+ }
47
+
48
+ function hash(markdown: string): string {
49
+ return createHash('sha256').update(markdown).digest('hex');
50
+ }
51
+
52
+ function sourceOf(record: Getter): PinnedReviewSource | null {
53
+ const source = value<unknown>(record, 'legacyPostSource');
54
+ if (source == null) return null;
55
+ if (!source || typeof source !== 'object' || Array.isArray(source)) conflict('Legacy review source is invalid');
56
+ const candidate = source as Partial<PinnedReviewSource>;
57
+ if (
58
+ candidate.targetType !== 'mr' ||
59
+ typeof candidate.projectKey !== 'string' ||
60
+ !candidate.projectKey ||
61
+ !candidate.mrIid ||
62
+ typeof candidate.headSha !== 'string' ||
63
+ typeof candidate.baseSha !== 'string' ||
64
+ String(candidate.repositoryId) !== String(value<Id>(record, 'repositoryId')) ||
65
+ String(candidate.mrIid) !== String(value<Id>(record, 'mrIid')) ||
66
+ candidate.headSha !== value<string>(record, 'headSha')
67
+ )
68
+ conflict('Legacy review source is invalid');
69
+ const projectKey = value<string | null>(record, 'legacyPostProjectKey');
70
+ if (projectKey && projectKey !== candidate.projectKey) conflict('Legacy review source is invalid');
71
+ return candidate as PinnedReviewSource;
72
+ }
73
+
74
+ function baseAcknowledged(record: Getter): boolean {
75
+ return (
76
+ value<string | null>(record, 'legacyBaseProvenance') === 'unverified_legacy' &&
77
+ !!value<string | null>(record, 'legacyBaseAcknowledgedBy') &&
78
+ !!value<Date | null>(record, 'legacyBaseAcknowledgedAt')
79
+ );
80
+ }
81
+
82
+ /** Handles old review records without restarting their AI or treating an uncertain remote POST as a failure. */
83
+ export class LegacyPostService {
84
+ constructor(private readonly app: Application) {}
85
+
86
+ private async load(reviewId: Id, actor: Id, roles: string[]) {
87
+ const db = this.app.db;
88
+ const review = await db.getRepository('gitCodeReviews').findOne({ filterByTk: reviewId });
89
+ if (!review) conflict('Review not found');
90
+ if (
91
+ value<{ workflowManaged?: boolean } | null>(review, 'metadata')?.workflowManaged ||
92
+ (await db.getRepository('gitReviewInbox').findOne({ filter: { reviewId } }))
93
+ ) {
94
+ conflict('Use the workflow approval task for this review');
95
+ }
96
+ if (value<string>(review, 'status') !== 'completed' || value<string>(review, 'targetType') !== 'mr') {
97
+ conflict('Only completed legacy merge request reviews can be published');
98
+ }
99
+ const repositoryId = value<Id>(review, 'repositoryId');
100
+ const currentRoles = await resolveBackgroundReviewRoles(db, actor);
101
+ if (
102
+ !roles.length ||
103
+ roles.some((role) => !currentRoles.includes(role)) ||
104
+ !(await hasRepositoryAccess({ acl: this.app.acl, roles, repositoryId, action: 'reviewApprovePost' }))
105
+ ) {
106
+ const error = new Error('Permission denied') as Error & { status: number };
107
+ error.status = 403;
108
+ throw error;
109
+ }
110
+ const repo = await db.getRepository('gitRepositories').findOne({ filterByTk: repositoryId });
111
+ if (!repo) conflict('Repository not found');
112
+ return { review, repo, repositoryId };
113
+ }
114
+
115
+ private async lookupSource(review: Getter, repo: Getter): Promise<PinnedReviewSource> {
116
+ const snapshot = sourceOf(review);
117
+ if (snapshot) return snapshot;
118
+ const mrIid = Number(value<Id>(review, 'mrIid'));
119
+ if (!Number.isSafeInteger(mrIid) || mrIid < 1) conflict('Invalid merge request');
120
+ return {
121
+ projectKey:
122
+ value<string | null>(review, 'legacyPostProjectKey') || (await resolveReviewProjectKey(this.app.db, repo)),
123
+ repositoryId: Number(value<Id>(review, 'repositoryId')),
124
+ targetType: 'mr',
125
+ mrIid,
126
+ branch: null,
127
+ folderPath: null,
128
+ headSha: value<string | null>(review, 'headSha') || '',
129
+ baseSha: null,
130
+ };
131
+ }
132
+
133
+ async status(reviewId: Id, actor: Id, roles: string[]): Promise<LegacyPostResult> {
134
+ const db = this.app.db;
135
+ const { review, repo } = await this.load(reviewId, actor, roles);
136
+ const postStatus = value<string>(review, 'postStatus');
137
+ if (!['posting', 'post_unknown', 'post_failed', 'posted'].includes(postStatus)) {
138
+ conflict('Legacy review is not awaiting publication recovery');
139
+ }
140
+ const markdown = value<string>(review, 'reviewMarkdown');
141
+ if (!markdown) conflict('No review content to post');
142
+ const fingerprint = hash(markdown);
143
+ const stored = value<string | null>(review, 'legacyPostFingerprint');
144
+ if (stored && stored !== fingerprint) conflict('Approved review content changed');
145
+ const source = await this.lookupSource(review, repo);
146
+ const project = await db.getRepository('gitReviewProjects').findOne({ filter: { projectKey: source.projectKey } });
147
+ const attemptId = value<string | null>(review, 'legacyPostClaim') ?? null;
148
+ const result: LegacyPostResult = {
149
+ status: postStatus === 'posted' ? 'posted' : 'unknown',
150
+ attemptId,
151
+ canRetry: postStatus !== 'posted',
152
+ baseUnverified: true,
153
+ baseAcknowledged: baseAcknowledged(review),
154
+ holdActive: !!project && String(value<Id | null>(project, 'legacyPostReviewId')) === String(reviewId),
155
+ };
156
+ if (postStatus === 'posted') {
157
+ const noteId = value<Id | null>(review, 'postedNoteId');
158
+ if (noteId != null) result.postedNoteId = String(noteId);
159
+ return result;
160
+ }
161
+ const marker = `<!-- git-review:legacy:${String(reviewId)}:${fingerprint} -->`;
162
+ const found = await findLegacyPublishedReview(db, repo, source, markdown, marker);
163
+ if (!found) return result;
164
+ result.status = 'observed';
165
+ result.canRetry = found.kind === 'marked' && attemptId != null;
166
+ result.postedNoteId = found.noteId;
167
+ if (found.kind !== 'marked' || attemptId) return result;
168
+ await db.sequelize.transaction(async (transaction) => {
169
+ const current = await db
170
+ .getCollection('gitCodeReviews')
171
+ .model.findOne({ where: { id: reviewId }, transaction, lock: transaction.LOCK.UPDATE });
172
+ if (
173
+ !current ||
174
+ value<string | null>(current, 'legacyPostClaim') ||
175
+ value<string>(current, 'reviewMarkdown') !== markdown ||
176
+ !['posting', 'post_unknown', 'post_failed'].includes(value<string>(current, 'postStatus'))
177
+ )
178
+ return;
179
+ const oldFingerprint = value<string | null>(current, 'legacyPostFingerprint');
180
+ if (oldFingerprint && oldFingerprint !== fingerprint) return;
181
+ await current.update(
182
+ { postStatus: 'posted', postedNoteId: found.noteId, legacyPostFingerprint: fingerprint, error: null },
183
+ { transaction },
184
+ );
185
+ await db
186
+ .getCollection('gitReviewProjects')
187
+ .model.update(
188
+ { legacyPostReviewId: null },
189
+ { where: { projectKey: source.projectKey, legacyPostReviewId: reviewId }, transaction },
190
+ );
191
+ result.status = 'posted';
192
+ result.holdActive = false;
193
+ });
194
+ return result;
195
+ }
196
+
197
+ async approve(
198
+ reviewId: Id,
199
+ actor: Id,
200
+ roles: string[],
201
+ editedMarkdown: unknown,
202
+ baseConfirmation: unknown,
203
+ ): Promise<LegacyPostResult> {
204
+ return this.post(reviewId, actor, roles, { kind: 'approve', editedMarkdown, baseConfirmation });
205
+ }
206
+
207
+ async retry(
208
+ reviewId: Id,
209
+ actor: Id,
210
+ roles: string[],
211
+ expectedAttempt: string | null,
212
+ baseConfirmation: unknown,
213
+ ): Promise<LegacyPostResult> {
214
+ return this.post(reviewId, actor, roles, { kind: 'retry', expectedAttempt, baseConfirmation });
215
+ }
216
+
217
+ private async post(
218
+ reviewId: Id,
219
+ actor: Id,
220
+ roles: string[],
221
+ input:
222
+ | { kind: 'approve'; editedMarkdown: unknown; baseConfirmation: unknown }
223
+ | { kind: 'retry'; expectedAttempt: string | null; baseConfirmation: unknown },
224
+ ): Promise<LegacyPostResult> {
225
+ const db = this.app.db;
226
+ const owner = (this.app.pm.get('plugin-git-manager') || this.app.pm.get('git-manager')) as unknown as {
227
+ reviewService?: {
228
+ cutoverStatus(): Promise<{ state: string }>;
229
+ ensureReviewProject(key: string): Promise<void>;
230
+ reconcile(): Promise<void>;
231
+ };
232
+ };
233
+ if (!owner?.reviewService || (await owner.reviewService.cutoverStatus()).state !== 'ready') {
234
+ conflict('Review cutover has not been confirmed');
235
+ }
236
+ const { review, repo, repositoryId } = await this.load(reviewId, actor, roles);
237
+ const previousStatus = value<string>(review, 'postStatus');
238
+ if (input.kind === 'approve' && previousStatus !== 'pending_approval') conflict('Review is not awaiting approval');
239
+ if (input.kind === 'retry' && !['posting', 'post_unknown', 'post_failed'].includes(previousStatus)) {
240
+ conflict('Legacy review is not awaiting publication recovery');
241
+ }
242
+ const oldAttempt = value<string | null>(review, 'legacyPostClaim') ?? null;
243
+ if (input.kind === 'retry' && oldAttempt !== input.expectedAttempt) conflict('Review publication claim changed');
244
+ if (input.kind === 'approve' && oldAttempt) conflict('A publication attempt may still be running');
245
+ const existingMarkdown = value<string>(review, 'reviewMarkdown');
246
+ const markdown = input.kind === 'approve' && input.editedMarkdown != null ? input.editedMarkdown : existingMarkdown;
247
+ if (typeof markdown !== 'string' || !markdown.trim() || Buffer.byteLength(markdown) > 200_000)
248
+ conflict('No review content to post');
249
+ const fingerprint = hash(markdown);
250
+ const previousFingerprint = value<string | null>(review, 'legacyPostFingerprint');
251
+ if (previousFingerprint && previousFingerprint !== fingerprint) conflict('Approved review content changed');
252
+ const marker = `<!-- git-review:legacy:${String(reviewId)}:${fingerprint} -->`;
253
+ let source = sourceOf(review);
254
+ const lookup = source || (await this.lookupSource(review, repo));
255
+ const priorMatch =
256
+ input.kind === 'retry' ? await findLegacyPublishedReview(db, repo, lookup, markdown, marker) : null;
257
+ if (priorMatch?.kind === 'unmarked') {
258
+ const project = await db
259
+ .getRepository('gitReviewProjects')
260
+ .findOne({ filter: { projectKey: lookup.projectKey } });
261
+ return {
262
+ status: 'observed',
263
+ attemptId: oldAttempt,
264
+ canRetry: false,
265
+ baseUnverified: true,
266
+ baseAcknowledged: baseAcknowledged(review),
267
+ holdActive: !!project && String(value<Id | null>(project, 'legacyPostReviewId')) === String(reviewId),
268
+ postedNoteId: priorMatch.noteId,
269
+ };
270
+ }
271
+ let acknowledgedNow = false;
272
+ if (source && !baseAcknowledged(review) && !priorMatch) {
273
+ if (input.baseConfirmation !== 'LEGACY_BASE_UNVERIFIED')
274
+ conflict('Legacy review base requires explicit confirmation');
275
+ acknowledgedNow = true;
276
+ }
277
+ if (!source && !priorMatch) {
278
+ if (input.baseConfirmation !== 'LEGACY_BASE_UNVERIFIED')
279
+ conflict('Legacy review base requires explicit confirmation');
280
+ const headSha = value<string | null>(review, 'headSha');
281
+ if (!headSha) conflict('Reviewed commit is unavailable');
282
+ source = await resolveReviewSource(db, repo, {
283
+ targetType: 'mr',
284
+ mrIid: Number(value<Id>(review, 'mrIid')),
285
+ headSha,
286
+ });
287
+ acknowledgedNow = true;
288
+ }
289
+ const selectedSource = source || lookup;
290
+ await owner.reviewService.ensureReviewProject(selectedSource.projectKey);
291
+ const token = randomUUID();
292
+ await db.sequelize.transaction(async (transaction) => {
293
+ const current = await db
294
+ .getCollection('gitCodeReviews')
295
+ .model.findOne({ where: { id: reviewId }, transaction, lock: transaction.LOCK.UPDATE });
296
+ if (
297
+ !current ||
298
+ value<string>(current, 'status') !== 'completed' ||
299
+ value<string>(current, 'postStatus') !== previousStatus ||
300
+ (value<string | null>(current, 'legacyPostClaim') ?? null) !== oldAttempt ||
301
+ value<string>(current, 'reviewMarkdown') !== existingMarkdown ||
302
+ (value<string | null>(current, 'legacyPostFingerprint') &&
303
+ value<string>(current, 'legacyPostFingerprint') !== fingerprint) ||
304
+ (value<string | null>(current, 'legacyPostProjectKey') &&
305
+ value<string>(current, 'legacyPostProjectKey') !== selectedSource.projectKey)
306
+ ) {
307
+ conflict('Review publication claim changed');
308
+ }
309
+ if (await db.getRepository('gitReviewInbox').findOne({ filter: { reviewId }, transaction }))
310
+ conflict('Use the workflow approval task for this review');
311
+ const project = await db.getCollection('gitReviewProjects').model.findOne({
312
+ where: { projectKey: selectedSource.projectKey },
313
+ transaction,
314
+ lock: transaction.LOCK.UPDATE,
315
+ });
316
+ if (!project || value<Id | null>(project, 'activeInboxId') != null)
317
+ conflict('Another review is active for this project');
318
+ const legacyOwner = value<Id | null>(project, 'legacyPostReviewId');
319
+ if (legacyOwner != null && String(legacyOwner) !== String(reviewId))
320
+ conflict('Another review is active for this project');
321
+ if (legacyOwner == null) {
322
+ const [reserved] = await db.getCollection('gitReviewProjects').model.update(
323
+ { legacyPostReviewId: reviewId },
324
+ {
325
+ where: { projectKey: selectedSource.projectKey, activeInboxId: null, legacyPostReviewId: null },
326
+ transaction,
327
+ },
328
+ );
329
+ if (reserved !== 1) conflict('Another review is active for this project');
330
+ }
331
+ const values: Record<string, unknown> = {
332
+ reviewMarkdown: markdown,
333
+ legacyPostFingerprint: fingerprint,
334
+ legacyPostClaim: token,
335
+ legacyPostProjectKey: selectedSource.projectKey,
336
+ postStatus: 'posting',
337
+ ...(input.kind === 'approve' ? { approvedBy: String(actor), approvedAt: new Date() } : {}),
338
+ ...(source ? { legacyPostSource: source } : {}),
339
+ ...(acknowledgedNow
340
+ ? {
341
+ legacyBaseProvenance: 'unverified_legacy',
342
+ legacyBaseAcknowledgedBy: String(actor),
343
+ legacyBaseAcknowledgedAt: new Date(),
344
+ }
345
+ : {}),
346
+ };
347
+ const [claimed] = await db.getCollection('gitCodeReviews').model.update(values, {
348
+ where: { id: reviewId, status: 'completed', postStatus: previousStatus, legacyPostClaim: oldAttempt },
349
+ transaction,
350
+ });
351
+ if (claimed !== 1) conflict('Review publication claim changed');
352
+ });
353
+ try {
354
+ const found = await findLegacyPublishedReview(db, repo, selectedSource, markdown, marker);
355
+ if (found?.kind === 'unmarked') {
356
+ const nextAttempt = await this.finish(reviewId, selectedSource.projectKey, token, fingerprint, null);
357
+ return {
358
+ status: 'observed',
359
+ attemptId: nextAttempt,
360
+ canRetry: false,
361
+ baseUnverified: true,
362
+ baseAcknowledged: acknowledgedNow || baseAcknowledged(review),
363
+ holdActive: false,
364
+ postedNoteId: found.noteId,
365
+ };
366
+ }
367
+ const noteId =
368
+ found?.noteId ||
369
+ (await publishPinnedReview(db, repo, selectedSource, markdown, marker, async (start) => {
370
+ const freshRepo = await db.getRepository('gitRepositories').findOne({ filterByTk: repositoryId });
371
+ if (!freshRepo) conflict('Repository not found');
372
+ const currentRoles = await resolveBackgroundReviewRoles(db, actor);
373
+ if (
374
+ roles.some((role) => !currentRoles.includes(role)) ||
375
+ !(await hasRepositoryAccess({ acl: this.app.acl, roles, repositoryId, action: 'reviewApprovePost' }))
376
+ )
377
+ conflict('Permission denied');
378
+ await assertCurrentMrHead(db, freshRepo, selectedSource);
379
+ const options = db.sequelize.getDialect() === 'sqlite' ? { type: Transaction.TYPES.IMMEDIATE } : {};
380
+ return db.sequelize.transaction(options, async (transaction) => {
381
+ const current = await db
382
+ .getCollection('gitCodeReviews')
383
+ .model.findOne({ where: { id: reviewId }, transaction, lock: transaction.LOCK.UPDATE });
384
+ const project = await db.getCollection('gitReviewProjects').model.findOne({
385
+ where: { projectKey: selectedSource.projectKey },
386
+ transaction,
387
+ lock: transaction.LOCK.UPDATE,
388
+ });
389
+ const currentSource = current && sourceOf(current);
390
+ if (
391
+ !current ||
392
+ value<string>(current, 'status') !== 'completed' ||
393
+ value<string>(current, 'postStatus') !== 'posting' ||
394
+ value<string | null>(current, 'legacyPostClaim') !== token ||
395
+ value<string>(current, 'legacyPostProjectKey') !== selectedSource.projectKey ||
396
+ value<string>(current, 'legacyPostFingerprint') !== fingerprint ||
397
+ hash(value<string>(current, 'reviewMarkdown') || '') !== fingerprint ||
398
+ !currentSource ||
399
+ String(currentSource.repositoryId) !== String(selectedSource.repositoryId) ||
400
+ String(currentSource.mrIid) !== String(selectedSource.mrIid) ||
401
+ currentSource.headSha !== selectedSource.headSha ||
402
+ currentSource.baseSha !== selectedSource.baseSha ||
403
+ !baseAcknowledged(current) ||
404
+ !project ||
405
+ String(value<Id | null>(project, 'legacyPostReviewId')) !== String(reviewId) ||
406
+ value<Id | null>(project, 'activeInboxId') != null
407
+ )
408
+ conflict('Review publication claim changed');
409
+ const response = start();
410
+ response.catch(() => undefined);
411
+ return { response };
412
+ });
413
+ }));
414
+ await this.finish(reviewId, selectedSource.projectKey, token, fingerprint, noteId);
415
+ await owner.reviewService
416
+ .reconcile()
417
+ .catch((error) => this.app.log?.error?.('Git review dispatch will be retried', error));
418
+ return {
419
+ status: 'posted',
420
+ attemptId: null,
421
+ canRetry: false,
422
+ baseUnverified: true,
423
+ baseAcknowledged: acknowledgedNow || baseAcknowledged(review),
424
+ holdActive: false,
425
+ postedNoteId: noteId,
426
+ };
427
+ } catch (error) {
428
+ await db.getCollection('gitCodeReviews').model.update(
429
+ {
430
+ postStatus: 'post_unknown',
431
+ error: error instanceof Error ? error.message : 'Publication outcome is unknown',
432
+ },
433
+ { where: { id: reviewId, legacyPostClaim: token, postStatus: 'posting' } },
434
+ );
435
+ throw error;
436
+ }
437
+ }
438
+
439
+ private async finish(
440
+ reviewId: Id,
441
+ projectKey: string,
442
+ token: string,
443
+ fingerprint: string,
444
+ noteId: string | null,
445
+ ): Promise<string | null> {
446
+ const db = this.app.db;
447
+ const nextAttempt = noteId ? null : randomUUID();
448
+ await db.sequelize.transaction(async (transaction) => {
449
+ const review = await db
450
+ .getCollection('gitCodeReviews')
451
+ .model.findOne({ where: { id: reviewId }, transaction, lock: transaction.LOCK.UPDATE });
452
+ const project = await db
453
+ .getCollection('gitReviewProjects')
454
+ .model.findOne({ where: { projectKey }, transaction, lock: transaction.LOCK.UPDATE });
455
+ if (
456
+ !review ||
457
+ value<string | null>(review, 'legacyPostClaim') !== token ||
458
+ value<string>(review, 'legacyPostFingerprint') !== fingerprint ||
459
+ hash(value<string>(review, 'reviewMarkdown') || '') !== fingerprint ||
460
+ !project ||
461
+ String(value<Id | null>(project, 'legacyPostReviewId')) !== String(reviewId) ||
462
+ value<Id | null>(project, 'activeInboxId') != null
463
+ )
464
+ conflict('Review publication claim changed');
465
+ const [changed] = await db.getCollection('gitCodeReviews').model.update(
466
+ {
467
+ postStatus: noteId ? 'posted' : 'post_unknown',
468
+ postedNoteId: noteId,
469
+ legacyPostClaim: nextAttempt,
470
+ error: null,
471
+ },
472
+ { where: { id: reviewId, legacyPostClaim: token, legacyPostFingerprint: fingerprint }, transaction },
473
+ );
474
+ if (changed !== 1) conflict('Review publication claim changed');
475
+ const [released] = await db
476
+ .getCollection('gitReviewProjects')
477
+ .model.update(
478
+ { legacyPostReviewId: null },
479
+ { where: { projectKey, legacyPostReviewId: reviewId, activeInboxId: null }, transaction },
480
+ );
481
+ if (released !== 1) conflict('Review project reservation changed');
482
+ });
483
+ return nextAttempt;
484
+ }
485
+
486
+ async releaseHold(reviewId: Id, actor: Id, roles: string[], expectedAttempt: string | null): Promise<void> {
487
+ if (!roles.includes('root')) {
488
+ const error = new Error('Permission denied') as Error & { status: number };
489
+ error.status = 403;
490
+ throw error;
491
+ }
492
+ const currentRoles = await resolveBackgroundReviewRoles(this.app.db, actor);
493
+ if (!currentRoles.includes('root')) {
494
+ const error = new Error('Permission denied') as Error & { status: number };
495
+ error.status = 403;
496
+ throw error;
497
+ }
498
+ const review = await this.app.db.getRepository('gitCodeReviews').findOne({ filterByTk: reviewId });
499
+ if (
500
+ !review ||
501
+ value<string>(review, 'status') !== 'completed' ||
502
+ value<string>(review, 'targetType') !== 'mr' ||
503
+ value<{ workflowManaged?: boolean } | null>(review, 'metadata')?.workflowManaged ||
504
+ (await this.app.db.getRepository('gitReviewInbox').findOne({ filter: { reviewId } }))
505
+ )
506
+ conflict('Legacy review is not available');
507
+ const projectKey = value<string | null>(review, 'legacyPostProjectKey') || sourceOf(review)?.projectKey;
508
+ if (!projectKey) conflict('Legacy review has no publication hold');
509
+ const db = this.app.db;
510
+ await db.sequelize.transaction(async (transaction) => {
511
+ const current = await db
512
+ .getCollection('gitCodeReviews')
513
+ .model.findOne({ where: { id: reviewId }, transaction, lock: transaction.LOCK.UPDATE });
514
+ if (
515
+ !current ||
516
+ (value<string | null>(current, 'legacyPostClaim') ?? null) !== expectedAttempt ||
517
+ !['posting', 'post_unknown', 'post_failed'].includes(value<string>(current, 'postStatus')) ||
518
+ (value<string | null>(current, 'legacyPostProjectKey') || sourceOf(current)?.projectKey) !== projectKey
519
+ )
520
+ conflict('Review publication claim changed');
521
+ const project = await db
522
+ .getCollection('gitReviewProjects')
523
+ .model.findOne({ where: { projectKey }, transaction, lock: transaction.LOCK.UPDATE });
524
+ const [changed] = await db.getCollection('gitCodeReviews').model.update(
525
+ {
526
+ postStatus: 'post_unknown',
527
+ legacyPostClaim: randomUUID(),
528
+ legacyHoldReleasedBy: String(actor),
529
+ legacyHoldReleasedAt: new Date(),
530
+ },
531
+ { where: { id: reviewId, legacyPostClaim: expectedAttempt, status: 'completed' }, transaction },
532
+ );
533
+ if (changed !== 1) conflict('Review publication claim changed');
534
+ if (project)
535
+ await db.getCollection('gitReviewProjects').model.update(
536
+ { legacyPostReviewId: null },
537
+ {
538
+ where: { projectKey, legacyPostReviewId: reviewId, activeInboxId: null },
539
+ transaction,
540
+ },
541
+ );
542
+ });
543
+ const owner = (this.app.pm.get('plugin-git-manager') || this.app.pm.get('git-manager')) as unknown as {
544
+ reviewService?: { reconcile(): Promise<void> };
545
+ };
546
+ await owner.reviewService
547
+ ?.reconcile()
548
+ .catch((error) => this.app.log?.error?.('Git review dispatch will be retried', error));
549
+ }
550
+ }