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
@@ -1,3 +1,12 @@
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
+
1
10
  import type { Application } from '@nocobase/server';
2
11
  import { vi } from 'vitest';
3
12
 
@@ -11,82 +20,44 @@ function record(values: Record<string, unknown>) {
11
20
  };
12
21
  }
13
22
 
14
- function createReviewApp(flowRepositoryId: number | null, existingReview: Record<string, unknown> | null = null) {
15
- const flow = record({
16
- id: 8,
17
- enabled: true,
18
- repositoryId: flowRepositoryId,
19
- aiEmployeeUsername: 'reviewer',
20
- name: 'Review flow',
21
- postMode: 'manual',
22
- llmService: null,
23
- model: null,
24
- instructions: null,
25
- branchFilter: null,
26
- });
27
- const flowsRepository = {
28
- findOne: vi.fn().mockResolvedValue(flow),
29
- };
30
- const repositoriesRepository = {
31
- findOne: vi.fn().mockResolvedValue(record({ id: 20 })),
32
- };
33
- const reviewsRepository = {
34
- findOne: vi.fn().mockResolvedValue(existingReview ? record(existingReview) : null),
35
- create: vi.fn().mockResolvedValue(record({ id: 99 })),
36
- update: vi.fn().mockResolvedValue(undefined),
37
- };
38
- const getRepository = vi.fn((name: string) => {
39
- if (name === 'gitReviewFlows') return flowsRepository;
40
- if (name === 'gitRepositories') return repositoriesRepository;
41
- if (name === 'gitCodeReviews') return reviewsRepository;
42
- throw new Error(`Unexpected repository ${name}`);
43
- });
44
- const app = {
45
- db: { getRepository },
46
- lockManager: {
47
- runExclusive: vi.fn(async (_key: string, callback: () => Promise<unknown>) => callback()),
48
- },
49
- serving: vi.fn().mockReturnValue(false),
50
- eventQueue: {
51
- publish: vi.fn().mockResolvedValue(undefined),
23
+ function createApp(enqueue?: (input: Record<string, unknown>) => Promise<number>) {
24
+ const reviewService = enqueue ? { enqueue } : undefined;
25
+ return {
26
+ pm: {
27
+ get: vi.fn((name: string) => (name === 'git-manager' ? { reviewService } : undefined)),
52
28
  },
53
29
  } as unknown as Application;
54
-
55
- return { app, repositoriesRepository, reviewsRepository };
56
30
  }
57
31
 
58
- describe('Git Manager review flows', () => {
59
- it('rejects an explicitly selected flow from another repository', async () => {
60
- const { app, repositoriesRepository } = createReviewApp(10);
32
+ describe('Git Manager review admission adapter', () => {
33
+ it('delegates the selected manual request to the durable review service', async () => {
34
+ const enqueue = vi.fn(async () => 99);
35
+ const app = createApp(enqueue);
36
+ const input = {
37
+ flowId: 8,
38
+ repositoryId: 20,
39
+ targetType: 'commit' as const,
40
+ commitSha: 'a'.repeat(40),
41
+ triggeredBy: 'manual' as const,
42
+ userId: 7,
43
+ actorRoles: ['root'],
44
+ };
45
+
46
+ await expect(triggerReviewInternal(app, input)).resolves.toBe(99);
47
+ expect(app.pm.get).toHaveBeenCalledWith('git-manager');
48
+ expect(enqueue).toHaveBeenCalledWith(input);
49
+ });
61
50
 
51
+ it('fails closed when the durable review service is not registered', async () => {
62
52
  await expect(
63
- triggerReviewInternal(app, {
64
- flowId: 8,
53
+ triggerReviewInternal(createApp(), {
65
54
  repositoryId: 20,
66
55
  targetType: 'branch',
67
56
  branch: 'main',
57
+ userId: 7,
58
+ actorRoles: ['root'],
68
59
  }),
69
- ).rejects.toMatchObject({ status: 400, message: 'Review flow does not belong to this repository' });
70
-
71
- expect(repositoriesRepository.findOne).not.toHaveBeenCalled();
72
- });
73
-
74
- it('allows an explicitly selected global flow', async () => {
75
- const { app, repositoriesRepository, reviewsRepository } = createReviewApp(null);
76
-
77
- const reviewId = await triggerReviewInternal(app, {
78
- flowId: 8,
79
- repositoryId: 20,
80
- targetType: 'branch',
81
- branch: 'main',
82
- userId: 7,
83
- });
84
-
85
- expect(reviewId).toBe(99);
86
- expect(repositoriesRepository.findOne).toHaveBeenCalledWith({ filterByTk: 20 });
87
- expect(reviewsRepository.create).toHaveBeenCalledWith({
88
- values: expect.objectContaining({ flowId: 8, repositoryId: 20, createdById: 7 }),
89
- });
60
+ ).rejects.toThrow('Git review workflow service is unavailable');
90
61
  });
91
62
 
92
63
  it('uses the immutable creator field instead of review metadata for worker identity', () => {
@@ -102,36 +73,4 @@ describe('Git Manager review flows', () => {
102
73
  await expect(resolveBackgroundReviewRoles(db, 7)).rejects.toThrow('Unable to resolve roles for review actor');
103
74
  await expect(resolveBackgroundReviewRoles(db, null)).resolves.toEqual(['admin']);
104
75
  });
105
-
106
- it.each(['completed', 'failed'])(
107
- 'refreshes the immutable actor when a different user requeues a %s review',
108
- async (status) => {
109
- const { app, reviewsRepository } = createReviewApp(null, {
110
- id: 99,
111
- status,
112
- latestSha: null,
113
- createdById: 1,
114
- });
115
-
116
- await triggerReviewInternal(app, {
117
- flowId: 8,
118
- repositoryId: 20,
119
- targetType: 'branch',
120
- branch: 'main',
121
- triggeredBy: 'manual',
122
- userId: 7,
123
- });
124
-
125
- expect(reviewsRepository.update).toHaveBeenCalledWith({
126
- filterByTk: 99,
127
- values: expect.objectContaining({
128
- createdById: 7,
129
- triggeredBy: 'manual',
130
- status: 'pending',
131
- metadata: expect.objectContaining({ userId: 7 }),
132
- }),
133
- });
134
- expect(reviewsRepository.create).not.toHaveBeenCalled();
135
- },
136
- );
137
76
  });
@@ -0,0 +1,121 @@
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 type { Context } from '@nocobase/actions';
11
+ import type { GitReviewService } from '../services/review-service';
12
+ import { getEffectiveActionParams } from '../repository-access';
13
+
14
+ function service(ctx: Context): GitReviewService {
15
+ const roles = ctx.state?.currentRoles;
16
+ if (!Array.isArray(roles) || !roles.includes('root') || !ctx.state?.currentUser?.id)
17
+ ctx.throw(403, 'Permission denied');
18
+ const plugin = (ctx.app.pm.get('plugin-git-manager') || ctx.app.pm.get('git-manager')) as unknown as {
19
+ reviewService?: GitReviewService;
20
+ };
21
+ if (!plugin?.reviewService) ctx.throw(503, 'Git review workflow service is unavailable');
22
+ return plugin.reviewService;
23
+ }
24
+
25
+ export async function reviewCutoverStatus(ctx: Context, next: () => Promise<void>) {
26
+ ctx.body = { success: true, data: await service(ctx).cutoverStatus() };
27
+ await next();
28
+ }
29
+
30
+ export async function reviewConfirmCutover(ctx: Context, next: () => Promise<void>) {
31
+ const reviewService = service(ctx);
32
+ if (getEffectiveActionParams(ctx).confirmation !== 'OLD_WORKERS_AND_AI_STOPPED')
33
+ ctx.throw(400, ctx.t('Worker and AI stop confirmation is required', { ns: 'plugin-git-manager' }));
34
+ await reviewService.confirmCutover(ctx.state.currentUser.id);
35
+ ctx.body = { success: true, data: await reviewService.cutoverStatus() };
36
+ await next();
37
+ }
38
+
39
+ export async function reviewCancelLegacy(ctx: Context, next: () => Promise<void>) {
40
+ const reviewService = service(ctx);
41
+ const { confirmation, legacyReviewId } = getEffectiveActionParams(ctx);
42
+ if (confirmation !== 'CANCEL_LEGACY_REVIEW')
43
+ ctx.throw(400, ctx.t('Legacy review cancellation confirmation is required', { ns: 'plugin-git-manager' }));
44
+ if (typeof legacyReviewId !== 'string' && typeof legacyReviewId !== 'number')
45
+ ctx.throw(400, ctx.t('Legacy review identifier is required', { ns: 'plugin-git-manager' }));
46
+ await reviewService.cancelLegacy(legacyReviewId, ctx.state.currentUser.id);
47
+ ctx.body = { success: true };
48
+ await next();
49
+ }
50
+
51
+ export async function reviewRecover(ctx: Context, next: () => Promise<void>) {
52
+ const reviewService = service(ctx);
53
+ const { confirmation, requestId, executionId, legacyReviewId, inboxId } = getEffectiveActionParams(ctx);
54
+ if (confirmation !== 'AI_STOPPED')
55
+ ctx.throw(400, ctx.t('AI stop confirmation is required', { ns: 'plugin-git-manager' }));
56
+ try {
57
+ if (typeof legacyReviewId === 'string' || typeof legacyReviewId === 'number') {
58
+ await reviewService.recoverLegacy(legacyReviewId, ctx.state.currentUser.id);
59
+ } else if (typeof inboxId === 'string' || typeof inboxId === 'number') {
60
+ await reviewService.recoverOrphaned(inboxId, ctx.state.currentUser.id);
61
+ } else if (
62
+ (typeof requestId === 'string' || typeof requestId === 'number') &&
63
+ (executionId == null || typeof executionId === 'string' || typeof executionId === 'number')
64
+ ) {
65
+ await reviewService.recover(requestId, executionId ?? null, ctx.state.currentUser.id);
66
+ } else {
67
+ ctx.throw(400, 'Review and execution identifiers are required');
68
+ }
69
+ } catch (error) {
70
+ if (
71
+ error instanceof Error &&
72
+ error.message === 'Resolve publication or reset the stopped post attempt before recovery'
73
+ ) {
74
+ ctx.throw(
75
+ 409,
76
+ ctx.t('Resolve publication or reset the stopped post attempt before recovery', { ns: 'plugin-git-manager' }),
77
+ );
78
+ }
79
+ throw error;
80
+ }
81
+ ctx.body = { success: true };
82
+ await next();
83
+ }
84
+
85
+ export async function reviewResetPostClaim(ctx: Context, next: () => Promise<void>) {
86
+ const reviewService = service(ctx);
87
+ const params = getEffectiveActionParams(ctx);
88
+ const { confirmation, reviewId, expectedAttempt } = params;
89
+ if (confirmation !== 'OUTBOUND_POST_STOPPED')
90
+ ctx.throw(400, ctx.t('Outbound post stop confirmation is required', { ns: 'plugin-git-manager' }));
91
+ if (typeof reviewId !== 'string' && typeof reviewId !== 'number') ctx.throw(400, 'reviewId is required');
92
+ if (
93
+ !Object.prototype.hasOwnProperty.call(params, 'expectedAttempt') ||
94
+ (expectedAttempt !== null && typeof expectedAttempt !== 'string')
95
+ ) {
96
+ ctx.throw(400, ctx.t('Refresh publication status before recovery', { ns: 'plugin-git-manager' }));
97
+ }
98
+ try {
99
+ await reviewService.resetPostClaim(reviewId, ctx.state.currentUser.id, expectedAttempt);
100
+ } catch (error) {
101
+ const status =
102
+ error && typeof error === 'object' && 'status' in error && typeof error.status === 'number' ? error.status : 400;
103
+ ctx.throw(
104
+ status,
105
+ ctx.t(error instanceof Error ? error.message : 'Could not reset publication claim', { ns: 'plugin-git-manager' }),
106
+ );
107
+ }
108
+ ctx.body = { success: true };
109
+ await next();
110
+ }
111
+
112
+ export async function reviewCancelQueued(ctx: Context, next: () => Promise<void>) {
113
+ const reviewService = service(ctx);
114
+ const { confirmation, inboxId } = getEffectiveActionParams(ctx);
115
+ if (confirmation !== 'CANCEL_QUEUED_REVIEW')
116
+ ctx.throw(400, ctx.t('Queued review cancellation confirmation is required', { ns: 'plugin-git-manager' }));
117
+ if (typeof inboxId !== 'string' && typeof inboxId !== 'number') ctx.throw(400, 'inboxId is required');
118
+ await reviewService.cancelQueued(inboxId, ctx.state.currentUser.id);
119
+ ctx.body = { success: true };
120
+ await next();
121
+ }
@@ -13,6 +13,7 @@ import { getEffectiveActionParams } from '../repository-access';
13
13
  import { parseGitLabProject } from '../utils/gitlab-url';
14
14
  import { redactPat } from '../utils/redact';
15
15
  import { getRepoAccount } from '../utils/get-repo-account';
16
+ import type { LegacyPostService } from '../services/legacy-post-service';
16
17
 
17
18
  export const WORKER_JOB_GIT_REVIEW_PROCESS = 'git-review:process';
18
19
  const REVIEW_QUEUE_CHANNEL = 'plugin-git-manager.review';
@@ -44,7 +45,9 @@ interface TriggerArgs {
44
45
  headSha?: string | null;
45
46
  extraInstructions?: string;
46
47
  triggeredBy?: 'manual' | 'poll';
48
+ eventType?: 'change_opened' | 'head_changed';
47
49
  userId?: number | string | null;
50
+ actorRoles?: string[];
48
51
  }
49
52
 
50
53
  interface ReviewFlowSnapshot {
@@ -147,10 +150,20 @@ export async function triggerReview(ctx: Context, next: () => Promise<void>) {
147
150
  extraInstructions: typeof extraInstructions === 'string' ? extraInstructions : undefined,
148
151
  triggeredBy: 'manual',
149
152
  userId,
153
+ actorRoles: Array.isArray(ctx.state?.currentRoles)
154
+ ? ctx.state.currentRoles.filter((role: unknown): role is string => typeof role === 'string')
155
+ : [],
150
156
  });
151
157
  ctx.body = { success: true, data: { reviewId } };
152
158
  } catch (err: any) {
153
- ctx.throw(err.status || 400, err.message || 'Failed to trigger review');
159
+ const errorMessage = err.message || 'Failed to trigger review';
160
+ const providerError = /^Git provider request failed \((\d+)\)$/.exec(errorMessage);
161
+ ctx.throw(
162
+ err.status || 400,
163
+ providerError
164
+ ? ctx.t('Git provider request failed ({{status}})', { ns: 'plugin-git-manager', status: providerError[1] })
165
+ : ctx.t(errorMessage, { ns: 'plugin-git-manager' }),
166
+ );
154
167
  }
155
168
  await next();
156
169
  }
@@ -160,7 +173,11 @@ export async function triggerReview(ctx: Context, next: () => Promise<void>) {
160
173
  * Returns the reviewId of the upserted record.
161
174
  */
162
175
  export async function triggerReviewInternal(app: Application, args: TriggerArgs): Promise<number> {
163
- return withTriggerLock(app, targetKey(args), () => triggerReviewInternalLocked(app, args));
176
+ const plugin = (app.pm.get('plugin-git-manager') || app.pm.get('git-manager')) as unknown as {
177
+ reviewService?: { enqueue(input: TriggerArgs): Promise<number> };
178
+ };
179
+ if (!plugin?.reviewService) throw new Error('Git review workflow service is unavailable');
180
+ return plugin.reviewService.enqueue(args);
164
181
  }
165
182
 
166
183
  async function triggerReviewInternalLocked(app: Application, args: TriggerArgs): Promise<number> {
@@ -643,7 +660,7 @@ async function processQueuedReview(app: Application, message: ReviewQueueMessage
643
660
  return;
644
661
  }
645
662
 
646
- if (review.get('status') !== 'pending') {
663
+ if (review.get('status') !== 'pending' || review.get('metadata')?.workflowManaged) {
647
664
  app.log?.info?.(`git review queue: review ${message.reviewId} is ${review.get('status')}, skipping`);
648
665
  return;
649
666
  }
@@ -692,7 +709,9 @@ async function processQueuedReview(app: Application, message: ReviewQueueMessage
692
709
  userId: actorUserId,
693
710
  });
694
711
  } catch (err) {
695
- app.log?.error?.('git review queue: failed before review execution', err);
712
+ app.log?.error?.('git review queue: failed before review execution', {
713
+ error: redactPat(err instanceof Error ? err.message : String(err)),
714
+ });
696
715
  await failQueuedReview(app, message.reviewId, err);
697
716
  }
698
717
  });
@@ -701,43 +720,91 @@ async function processQueuedReview(app: Application, message: ReviewQueueMessage
701
720
  /**
702
721
  * Mark a review as approved and post its content to GitLab as an MR note.
703
722
  */
704
- export async function reviewApprovePost(ctx: Context, next: () => Promise<void>) {
705
- const params = getEffectiveActionParams(ctx);
706
- const { reviewId, editedMarkdown } = params;
707
- if (!reviewId || (typeof reviewId !== 'string' && typeof reviewId !== 'number')) {
708
- ctx.throw(400, 'reviewId is required');
723
+ function legacyPostContext(ctx: Context): { service: LegacyPostService; actor: number | string; roles: string[] } {
724
+ const actor: unknown = ctx.state?.currentUser?.id;
725
+ const roles: unknown = ctx.state?.currentRoles;
726
+ if (
727
+ (typeof actor !== 'string' && typeof actor !== 'number') ||
728
+ !Array.isArray(roles) ||
729
+ !roles.every((role) => typeof role === 'string')
730
+ ) {
731
+ ctx.throw(403, 'Permission denied');
709
732
  }
733
+ const plugin = (ctx.app.pm.get('plugin-git-manager') || ctx.app.pm.get('git-manager')) as unknown as {
734
+ legacyPostService?: LegacyPostService;
735
+ };
736
+ if (!plugin?.legacyPostService) ctx.throw(503, 'Git review workflow service is unavailable');
737
+ return { service: plugin.legacyPostService, actor, roles };
738
+ }
710
739
 
711
- const reviewsRepo = ctx.db.getRepository('gitCodeReviews');
712
- const review = await reviewsRepo.findOne({ filterByTk: reviewId });
713
- if (!review) ctx.throw(404, 'Review not found');
714
- if (review.get('status') !== 'completed') ctx.throw(400, 'Review is not completed');
715
- if (review.get('targetType') !== 'mr') ctx.throw(400, 'Only MR reviews can be posted');
740
+ async function legacyPostAction(ctx: Context, run: () => Promise<unknown>): Promise<void> {
741
+ try {
742
+ ctx.body = { success: true, data: await run() };
743
+ } catch (error) {
744
+ const status =
745
+ error && typeof error === 'object' && 'status' in error && typeof error.status === 'number' ? error.status : 400;
746
+ ctx.throw(
747
+ status,
748
+ ctx.t(error instanceof Error ? error.message : 'Failed to reconcile review publication', {
749
+ ns: 'plugin-git-manager',
750
+ }),
751
+ );
752
+ }
753
+ }
716
754
 
717
- const markdown = (editedMarkdown ?? review.get('reviewMarkdown')) as string;
718
- if (!markdown) ctx.throw(400, 'No review content to post');
755
+ export async function reviewApprovePost(ctx: Context, next: () => Promise<void>) {
756
+ const { reviewId, editedMarkdown, baseConfirmation } = getEffectiveActionParams(ctx);
757
+ if (typeof reviewId !== 'string' && typeof reviewId !== 'number') ctx.throw(400, 'reviewId is required');
758
+ const { service, actor, roles } = legacyPostContext(ctx);
759
+ await legacyPostAction(ctx, () => service.approve(reviewId, actor, roles, editedMarkdown, baseConfirmation));
760
+ await next();
761
+ }
719
762
 
720
- const repo = await ctx.db.getRepository('gitRepositories').findOne({
721
- filterByTk: review.get('repositoryId'),
722
- });
723
- if (!repo) ctx.throw(404, 'Repository not found');
763
+ export async function reviewLegacyPostStatus(ctx: Context, next: () => Promise<void>) {
764
+ const { reviewId } = getEffectiveActionParams(ctx);
765
+ if (typeof reviewId !== 'string' && typeof reviewId !== 'number') ctx.throw(400, 'reviewId is required');
766
+ const { service, actor, roles } = legacyPostContext(ctx);
767
+ await legacyPostAction(ctx, () => service.status(reviewId, actor, roles));
768
+ await next();
769
+ }
724
770
 
725
- const noteId = await postNoteToGitLab(ctx.db, repo, Number(review.get('mrIid')), markdown);
771
+ export async function reviewLegacyRetryPost(ctx: Context, next: () => Promise<void>) {
772
+ const params = getEffectiveActionParams(ctx);
773
+ const { reviewId, confirmation, expectedAttempt, baseConfirmation } = params;
774
+ if (typeof reviewId !== 'string' && typeof reviewId !== 'number') ctx.throw(400, 'reviewId is required');
775
+ if (Object.prototype.hasOwnProperty.call(params, 'editedMarkdown')) {
776
+ ctx.throw(400, ctx.t('Review content cannot change while publication is unresolved', { ns: 'plugin-git-manager' }));
777
+ }
778
+ if (confirmation !== 'OUTBOUND_POST_STOPPED')
779
+ ctx.throw(400, ctx.t('Outbound post stop confirmation is required', { ns: 'plugin-git-manager' }));
780
+ if (
781
+ !Object.prototype.hasOwnProperty.call(params, 'expectedAttempt') ||
782
+ (expectedAttempt !== null && typeof expectedAttempt !== 'string')
783
+ ) {
784
+ ctx.throw(400, ctx.t('Refresh publication status before recovery', { ns: 'plugin-git-manager' }));
785
+ }
786
+ const { service, actor, roles } = legacyPostContext(ctx);
787
+ await legacyPostAction(ctx, () => service.retry(reviewId, actor, roles, expectedAttempt, baseConfirmation));
788
+ await next();
789
+ }
726
790
 
727
- const userId = (ctx as any).state?.currentUser?.id;
728
- await reviewsRepo.update({
729
- filterByTk: reviewId,
730
- values: {
731
- reviewMarkdown: markdown,
732
- postStatus: 'posted',
733
- postedNoteId: String(noteId),
734
- approvedBy: userId ? String(userId) : null,
735
- approvedAt: new Date(),
736
- error: null,
737
- },
791
+ export async function reviewLegacyReleaseHold(ctx: Context, next: () => Promise<void>) {
792
+ const params = getEffectiveActionParams(ctx);
793
+ const { reviewId, confirmation, expectedAttempt } = params;
794
+ if (typeof reviewId !== 'string' && typeof reviewId !== 'number') ctx.throw(400, 'reviewId is required');
795
+ if (confirmation !== 'OUTBOUND_POST_STOPPED')
796
+ ctx.throw(400, ctx.t('Outbound post stop confirmation is required', { ns: 'plugin-git-manager' }));
797
+ if (
798
+ !Object.prototype.hasOwnProperty.call(params, 'expectedAttempt') ||
799
+ (expectedAttempt !== null && typeof expectedAttempt !== 'string')
800
+ ) {
801
+ ctx.throw(400, ctx.t('Refresh publication status before recovery', { ns: 'plugin-git-manager' }));
802
+ }
803
+ const { service, actor, roles } = legacyPostContext(ctx);
804
+ await legacyPostAction(ctx, async () => {
805
+ await service.releaseHold(reviewId, actor, roles, expectedAttempt);
806
+ return { reviewId };
738
807
  });
739
-
740
- ctx.body = { success: true, data: { reviewId, postedNoteId: noteId } };
741
808
  await next();
742
809
  }
743
810
 
@@ -754,22 +821,65 @@ export async function reviewReject(ctx: Context, next: () => Promise<void>) {
754
821
  const reviewsRepo = ctx.db.getRepository('gitCodeReviews');
755
822
  const review = await reviewsRepo.findOne({ filterByTk: reviewId });
756
823
  if (!review) ctx.throw(404, 'Review not found');
824
+ if (
825
+ review.get('metadata')?.workflowManaged ||
826
+ (await ctx.db.getRepository('gitReviewInbox').findOne({ filter: { reviewId } }))
827
+ ) {
828
+ ctx.throw(409, ctx.t('Use the workflow approval task for this review', { ns: 'plugin-git-manager' }));
829
+ }
757
830
 
758
831
  const userId = (ctx as any).state?.currentUser?.id;
759
- await reviewsRepo.update({
760
- filterByTk: reviewId,
761
- values: {
832
+ const [changed] = await ctx.db.getCollection('gitCodeReviews').model.update(
833
+ {
762
834
  postStatus: 'rejected',
763
835
  approvedBy: userId ? String(userId) : null,
764
836
  approvedAt: new Date(),
765
837
  error: reason ? `Rejected: ${reason}` : 'Rejected',
766
838
  },
767
- });
839
+ { where: { id: reviewId, status: 'completed', targetType: 'mr', postStatus: 'pending_approval' } },
840
+ );
841
+ if (changed !== 1) ctx.throw(409, 'Review is not awaiting approval');
768
842
 
769
843
  ctx.body = { success: true, data: { reviewId } };
770
844
  await next();
771
845
  }
772
846
 
847
+ export async function reviewWorkflowRetryPost(ctx: Context, next: () => Promise<void>) {
848
+ const { reviewId, confirmation } = getEffectiveActionParams(ctx);
849
+ if (typeof reviewId !== 'string' && typeof reviewId !== 'number') ctx.throw(400, 'reviewId is required');
850
+ if (confirmation != null && confirmation !== 'OUTBOUND_POST_STOPPED')
851
+ ctx.throw(400, ctx.t('Invalid publication confirmation', { ns: 'plugin-git-manager' }));
852
+ const actor = ctx.state?.currentUser?.id;
853
+ const roles = ctx.state?.currentRoles;
854
+ if (!actor || !Array.isArray(roles) || !roles.every((role: unknown) => typeof role === 'string'))
855
+ ctx.throw(403, 'Permission denied');
856
+ const plugin = (ctx.app.pm.get('plugin-git-manager') || ctx.app.pm.get('git-manager')) as unknown as {
857
+ reviewService?: {
858
+ retryPost(id: number | string, user: number | string, roles: string[], allowResend: boolean): Promise<unknown>;
859
+ };
860
+ };
861
+ if (!plugin?.reviewService) ctx.throw(503, 'Git review workflow service is unavailable');
862
+ try {
863
+ const result = await plugin.reviewService.retryPost(
864
+ reviewId,
865
+ actor,
866
+ roles,
867
+ confirmation === 'OUTBOUND_POST_STOPPED',
868
+ );
869
+ ctx.body = { success: true, data: result };
870
+ } catch (error) {
871
+ const status =
872
+ error && typeof error === 'object' && 'status' in error && typeof error.status === 'number' ? error.status : 400;
873
+ ctx.throw(
874
+ status,
875
+ ctx.t(error instanceof Error ? error.message : 'Failed to reconcile review publication', {
876
+ ns: 'plugin-git-manager',
877
+ }),
878
+ );
879
+ }
880
+ await next();
881
+ }
882
+
773
883
  /* ───────── Helpers ───────── */
774
884
 
775
885
  interface RunReviewArgs {
@@ -1,3 +1,12 @@
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
+
1
10
  import type { Database, Model } from '@nocobase/database';
2
11
 
3
12
  function getRecordValue(record: unknown, key: string) {
@@ -31,6 +40,7 @@ export const GIT_WRITE_ACTIONS = [
31
40
  'triggerReview',
32
41
  'reviewApprovePost',
33
42
  'reviewReject',
43
+ 'reviewWorkflowRetryPost',
34
44
  'pollNow',
35
45
  'subtreeRun',
36
46
  ] as const;
@@ -1,7 +1,17 @@
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
+
1
10
  import { z } from 'zod';
2
11
  import type { Application } from '@nocobase/server';
3
12
  import * as gitlabApi from './actions/gitlab-api';
4
13
  import * as gitActions from './actions/git-actions';
14
+ import { hasRepositoryAccess } from './repository-access';
5
15
 
6
16
  /**
7
17
  * Register AI tools that allow an AI employee to inspect git repositories,
@@ -25,9 +35,9 @@ export function registerGitReviewAiTools(app: Application) {
25
35
  * and read any repository's MRs / commits / file content regardless of the
26
36
  * caller's ACL.
27
37
  */
28
- const enforceAcl = (ctx: any, resource: string, action: string, params: any) => {
38
+ const enforceAcl = async (ctx: any, resource: string, action: string, params: any) => {
29
39
  if (ctx.isBackgroundReview) {
30
- if (params.repositoryId && params.repositoryId !== ctx.reviewTargetRepositoryId) {
40
+ if (String(params.repositoryId) !== String(ctx.reviewTargetRepositoryId)) {
31
41
  const err: any = new Error('Permission denied: AI cannot access other repositories');
32
42
  err.status = 403;
33
43
  throw err;
@@ -41,14 +51,19 @@ export function registerGitReviewAiTools(app: Application) {
41
51
  throw err;
42
52
  }
43
53
  const acl = ctx.app?.acl;
44
- if (!acl?.can) return; // ACL not available — fail-open is acceptable for legacy contexts
45
- const role = ctx?.state?.currentRole || (Array.isArray(user.roles) && user.roles[0]?.name) || null;
46
- if (!role) {
54
+ const roles = Array.isArray(ctx?.state?.currentRoles)
55
+ ? ctx.state.currentRoles.filter((role: unknown): role is string => typeof role === 'string')
56
+ : typeof ctx?.state?.currentRole === 'string'
57
+ ? [ctx.state.currentRole]
58
+ : [];
59
+ if (!roles.length || !acl?.can) {
47
60
  const err: any = new Error('AI tool requires a resolvable role on the current user');
48
61
  err.status = 403;
49
62
  throw err;
50
63
  }
51
- const allowed = acl.can({ role, resource, action });
64
+ const allowed =
65
+ resource === 'gitManager' &&
66
+ (await hasRepositoryAccess({ acl, roles, repositoryId: params.repositoryId, action }));
52
67
  if (!allowed) {
53
68
  const err: any = new Error(`Permission denied: ${resource}:${action}`);
54
69
  err.status = 403;
@@ -81,13 +96,13 @@ export function registerGitReviewAiTools(app: Application) {
81
96
  params: Record<string, any>,
82
97
  gate: { resource: string; action: string },
83
98
  ) => {
84
- enforceAcl(ctx, gate.resource, gate.action, params);
99
+ await enforceAcl(ctx, gate.resource, gate.action, params);
85
100
  const synthCtx: any = {
86
101
  ...ctx,
87
102
  app: ctx.app,
88
103
  db: ctx.db,
89
104
  action: { params },
90
- request: { ...(ctx.request || {}), body: ctx.request?.body || {} },
105
+ request: { ...(ctx.request || {}), body: {} },
91
106
  throw: (status: number, message: string) => {
92
107
  const err: any = new Error(message);
93
108
  err.status = status;