plugin-git-manager 1.2.26 → 1.2.28

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 (108) hide show
  1. package/README.md +133 -108
  2. package/client-v2.d.ts +2 -2
  3. package/client-v2.js +1 -1
  4. package/client.d.ts +3 -3
  5. package/client.js +1 -1
  6. package/dist/client/{326.90c276058682b536.js → 313.d38fc1d40c4589b9.js} +1 -1
  7. package/dist/client/900.a48beac7e2ebee7d.js +10 -0
  8. package/dist/client/index.js +1 -1
  9. package/dist/client-v2/156.445366026c1cc9a8.js +10 -0
  10. package/dist/client-v2/{326.42b7b53651ffab3a.js → 313.3c867179c3a1e817.js} +1 -1
  11. package/dist/client-v2/434.19c7579c06b9077c.js +10 -0
  12. package/dist/client-v2/900.e6155002a9c97e7f.js +10 -0
  13. package/dist/client-v2/928.bba701b5a1ece58e.js +10 -0
  14. package/dist/client-v2/index.js +1 -1
  15. package/dist/externalVersion.js +9 -8
  16. package/dist/locale/en-US.json +307 -297
  17. package/dist/locale/vi-VN.json +295 -292
  18. package/dist/locale/zh-CN.json +61 -51
  19. package/dist/node_modules/simple-git/dist/cjs/index.js +25 -25
  20. package/dist/node_modules/simple-git/package.json +1 -1
  21. package/dist/node_modules/zod/index.cjs +1 -1
  22. package/dist/node_modules/zod/package.json +1 -1
  23. package/dist/server/actions/git-actions.js +90 -36
  24. package/dist/server/actions/gitlab-api.js +4 -2
  25. package/dist/server/actions/poller.js +5 -2
  26. package/dist/server/actions/review.js +20 -10
  27. package/dist/server/plugin.js +6 -4
  28. package/dist/server/poller.js +46 -45
  29. package/dist/server/request-method-policy.js +75 -0
  30. package/dist/server/services/registry-content-service.js +23 -10
  31. package/dist/server/utils/get-repo-account.js +3 -2
  32. package/dist/server/utils/url-security.js +24 -0
  33. package/package.json +61 -43
  34. package/server.d.ts +2 -2
  35. package/server.js +1 -1
  36. package/src/client/__tests__/RunReviewButton.test.tsx +73 -0
  37. package/src/client/ai-context.tsx +114 -114
  38. package/src/client/components/AIEmployeeSelect.tsx +63 -63
  39. package/src/client/components/CommitHistory.tsx +374 -374
  40. package/src/client/components/FileExplorer.tsx +386 -386
  41. package/src/client/components/GitAccounts.tsx +179 -179
  42. package/src/client/components/GitManagerSettings.tsx +160 -160
  43. package/src/client/components/GitOperations.tsx +220 -220
  44. package/src/client/components/LLMModelSelect.tsx +63 -63
  45. package/src/client/components/LLMServiceSelect.tsx +58 -58
  46. package/src/client/components/MarkdownView.tsx +80 -80
  47. package/src/client/components/MergeRequests.tsx +790 -790
  48. package/src/client/components/PollingStatus.tsx +225 -225
  49. package/src/client/components/RepositoryConfig.tsx +335 -335
  50. package/src/client/components/RepositoryPermissions.tsx +123 -123
  51. package/src/client/components/ReviewFlows.tsx +303 -303
  52. package/src/client/components/ReviewHistory.tsx +566 -566
  53. package/src/client/components/RunReviewButton.tsx +63 -55
  54. package/src/client/context/GitManagerContext.tsx +92 -92
  55. package/src/client/index.tsx +91 -82
  56. package/src/client/locale.ts +9 -9
  57. package/src/client/promptTemplates.ts +31 -31
  58. package/src/client-v2/ai-context.tsx +99 -0
  59. package/src/client-v2/components/SubtreeSplits.tsx +547 -547
  60. package/src/client-v2/index.tsx +1 -1
  61. package/src/client-v2/locale.ts +8 -8
  62. package/src/client-v2/plugin.tsx +67 -39
  63. package/src/index.ts +2 -2
  64. package/src/locale/en-US.json +307 -297
  65. package/src/locale/vi-VN.json +295 -292
  66. package/src/locale/zh-CN.json +61 -51
  67. package/src/server/__tests__/git-actions.test.ts +24 -24
  68. package/src/server/__tests__/git-security.test.ts +170 -0
  69. package/src/server/__tests__/plugin-url-security.test.ts +17 -17
  70. package/src/server/__tests__/poller-lifecycle.test.ts +71 -0
  71. package/src/server/__tests__/poller.test.ts +37 -37
  72. package/src/server/__tests__/repository-access.test.ts +752 -752
  73. package/src/server/__tests__/review.test.ts +137 -137
  74. package/src/server/__tests__/role-permissions.test.ts +147 -147
  75. package/src/server/__tests__/smoke.test.ts +139 -17
  76. package/src/server/__tests__/subtree.test.ts +85 -85
  77. package/src/server/actions/git-actions.ts +540 -480
  78. package/src/server/actions/gitlab-api.ts +422 -411
  79. package/src/server/actions/poller.ts +39 -27
  80. package/src/server/actions/review.ts +1388 -1369
  81. package/src/server/actions/role-permissions.ts +321 -321
  82. package/src/server/actions/subtree.ts +508 -508
  83. package/src/server/ai-tools.ts +319 -319
  84. package/src/server/collections/gitAccounts.ts +56 -56
  85. package/src/server/collections/gitCodeReviews.ts +199 -199
  86. package/src/server/collections/gitRepositories.ts +87 -87
  87. package/src/server/collections/gitReviewFlows.ts +108 -108
  88. package/src/server/collections/gitSubtreeConfigs.ts +38 -38
  89. package/src/server/collections/gitSubtreeRuns.ts +30 -30
  90. package/src/server/index.ts +2 -2
  91. package/src/server/migrations/20260508000000-add-auto-review-flow-id.ts +29 -29
  92. package/src/server/migrations/20260712000000-add-git-accounts.ts +198 -198
  93. package/src/server/migrations/20260730000000-migrate-legacy-repository-permissions.ts +81 -81
  94. package/src/server/plugin.ts +372 -361
  95. package/src/server/poller.ts +351 -352
  96. package/src/server/repository-access.ts +773 -773
  97. package/src/server/request-method-policy.ts +55 -0
  98. package/src/server/services/__tests__/registry-content-service.test.ts +359 -345
  99. package/src/server/services/registry-content-service.ts +33 -11
  100. package/src/server/utils/__tests__/redact.test.ts +56 -56
  101. package/src/server/utils/__tests__/url-security.test.ts +85 -85
  102. package/src/server/utils/get-repo-account.ts +51 -41
  103. package/src/server/utils/gitlab-url.ts +38 -38
  104. package/src/server/utils/redact.ts +87 -87
  105. package/src/server/utils/url-security.ts +128 -95
  106. package/dist/client/900.acf7d1fa22f95e71.js +0 -10
  107. package/dist/client-v2/434.7a27051db18526c0.js +0 -10
  108. package/dist/client-v2/900.f32b9dc85249fc0a.js +0 -10
@@ -1,361 +1,372 @@
1
- import { Plugin } from '@nocobase/server';
2
- import type { Database } from '@nocobase/database';
3
- import { resolve } from 'path';
4
- import { DataTypes } from 'sequelize';
5
- import * as gitActions from './actions/git-actions';
6
- import * as gitlabApi from './actions/gitlab-api';
7
- import * as reviewActions from './actions/review';
8
- import * as pollerActions from './actions/poller';
9
- import * as rolePermissionsActions from './actions/role-permissions';
10
- import * as subtreeActions from './actions/subtree';
11
- import { recoverStuckReviews, registerReviewQueue, unregisterReviewQueue } from './actions/review';
12
- import { registerGitReviewAiTools } from './ai-tools';
13
- import { startPoller, stopPoller } from './poller';
14
- import { RegistryGitContentService, SkillHubGitContentService } from './services/registry-content-service';
15
- import { enforceRepositoryAccess, enforceRepositoryCollectionAccess } from './repository-access';
16
- import { isGitManagerResourceResponse, redactCredentialFields } from './utils/redact';
17
- import { containsCredentialBearingUrlField, URL_USERINFO_NOT_ALLOWED } from './utils/url-security';
18
-
19
- const GIT_CONFIGURATION_URL_FIELDS = new Set(['repoUrl', 'baseUrl']);
20
-
21
- export function isGitConfigurationUrlMutation(resourceName: unknown, actionName: unknown): boolean {
22
- return (
23
- typeof actionName === 'string' &&
24
- ['create', 'update'].includes(actionName) &&
25
- isGitManagerResourceResponse(resourceName)
26
- );
27
- }
28
-
29
- export class PluginGitManagerServer extends Plugin {
30
- // @ts-ignore
31
- declare app: any;
32
- // @ts-ignore
33
- declare db: any;
34
- registryContentService!: RegistryGitContentService;
35
- skillHubContentService!: SkillHubGitContentService;
36
-
37
- async afterAdd() {
38
- this.registryContentService = new RegistryGitContentService(
39
- (this as unknown as { db: Database }).db,
40
- undefined,
41
- this.app.acl,
42
- );
43
- this.skillHubContentService = new SkillHubGitContentService(
44
- (this as unknown as { db: Database }).db,
45
- undefined,
46
- this.app.acl,
47
- );
48
- }
49
-
50
- async beforeLoad() {
51
- await (this as any).app.db.import({
52
- directory: resolve(__dirname, 'collections'),
53
- });
54
-
55
- (this as any).app.db.addMigrations({
56
- namespace: (this as any).name,
57
- directory: resolve(__dirname, 'migrations'),
58
- context: { plugin: this },
59
- });
60
- }
61
-
62
- async load() {
63
- // Ensure dayjs timezone + utc plugins are loaded globally to prevent 'm.startOf is not a function' errors
64
- const dayjsLib = require('dayjs');
65
- const utcPlugin = require('dayjs/plugin/utc');
66
- const timezonePlugin = require('dayjs/plugin/timezone');
67
- dayjsLib.extend(utcPlugin);
68
- dayjsLib.extend(timezonePlugin);
69
-
70
- (this as any).app.resourceManager.define({
71
- name: 'gitManager',
72
- actions: {
73
- clone: gitActions.clone,
74
- pull: gitActions.pull,
75
- push: gitActions.push,
76
- fetch: gitActions.fetch,
77
- diff: gitActions.diff,
78
- status: gitActions.status,
79
- log: gitActions.log,
80
- branches: gitActions.branches,
81
- checkout: gitActions.checkout,
82
- fileTree: gitActions.fileTree,
83
- fileContent: gitActions.fileContent,
84
- commitDetail: gitActions.commitDetail,
85
- mergeRequests: gitlabApi.mergeRequests,
86
- mergeRequestDetail: gitlabApi.mergeRequestDetail,
87
- mergeRequestNotes: gitlabApi.mergeRequestNotes,
88
- triggerReview: reviewActions.triggerReview,
89
- reviewApprovePost: reviewActions.reviewApprovePost,
90
- reviewReject: reviewActions.reviewReject,
91
- pollNow: pollerActions.pollNow,
92
- pollerStatus: pollerActions.pollerStatus,
93
- rolePermissions: rolePermissionsActions.rolePermissions,
94
- updateRolePermissions: rolePermissionsActions.updateRolePermissions,
95
- subtreePreview: subtreeActions.subtreePreview,
96
- subtreeOptions: subtreeActions.subtreeOptions,
97
- subtreeRun: subtreeActions.subtreeRunOnAppProcess,
98
- subtreeReplace: subtreeActions.subtreeRunOnAppProcess,
99
- },
100
- });
101
-
102
- (this as any).app.resourceManager.use(enforceRepositoryAccess);
103
- (this as any).app.resourceManager.use(enforceRepositoryCollectionAccess);
104
-
105
- // Suppress noisy workflow pre-action/post-action warnings for custom resources
106
- (this as any).app.use(async (ctx, next) => {
107
- if (ctx.logger && ctx.logger.warn) {
108
- const originalWarn = ctx.logger.warn.bind(ctx.logger);
109
- ctx.logger.warn = (message: any, ...args: any[]) => {
110
- if (
111
- typeof message === 'string' &&
112
- message.includes('[Workflow') &&
113
- message.includes('collection') &&
114
- message.includes('not found')
115
- ) {
116
- return ctx.logger;
117
- }
118
- return originalWarn(message, ...args);
119
- };
120
- }
121
- return next();
122
- });
123
-
124
- registerReviewQueue((this as any).app);
125
- registerGitReviewAiTools((this as any).app);
126
-
127
- (this as any).app.on('afterStart', async () => {
128
- await ensureAutoReviewFlowSchema((this as any).app).catch(
129
- (err) => (this as any).app.log?.error?.('plugin-git-manager: ensure schema error', err),
130
- );
131
- // Sweep any review left in `running` state from a previous process.
132
- recoverStuckReviews((this as any).app).catch(
133
- (err) => (this as any).app.log?.error?.('plugin-git-manager: recoverStuckReviews error', err),
134
- );
135
- subtreeActions
136
- .recoverStuckSubtreeRuns((this as any).app)
137
- .catch((err) => (this as any).app.log?.error?.('plugin-git-manager: recover subtree runs error', err));
138
- startPoller((this as any).app);
139
- });
140
- (this as any).app.on('beforeStop', () => {
141
- unregisterReviewQueue((this as any).app);
142
- stopPoller();
143
- });
144
- (this as any).app.on('beforeDestroy', () => {
145
- unregisterReviewQueue((this as any).app);
146
- stopPoller();
147
- });
148
-
149
- // Read-only operations available to all plugin users
150
- (this as any).app.acl.registerSnippet({
151
- name: `pm.${(this as any).name}.read`,
152
- actions: [
153
- 'gitRepositories:list',
154
- 'gitRepositories:get',
155
- 'gitAccounts:list',
156
- 'gitAccounts:get',
157
- 'gitReviewFlows:list',
158
- 'gitReviewFlows:get',
159
- 'gitCodeReviews:list',
160
- 'gitCodeReviews:get',
161
- 'gitSubtreeConfigs:list',
162
- 'gitSubtreeConfigs:get',
163
- 'gitSubtreeRuns:list',
164
- 'gitSubtreeRuns:get',
165
- 'gitManager:status',
166
- 'gitManager:log',
167
- 'gitManager:branches',
168
- 'gitManager:diff',
169
- 'gitManager:fileTree',
170
- 'gitManager:fileContent',
171
- 'gitManager:commitDetail',
172
- 'gitManager:mergeRequests',
173
- 'gitManager:mergeRequestDetail',
174
- 'gitManager:mergeRequestNotes',
175
- 'gitManager:pollerStatus',
176
- 'gitManager:subtreePreview',
177
- 'gitManager:subtreeOptions',
178
- ],
179
- });
180
-
181
- // Write operations require separate permission
182
- (this as any).app.acl.registerSnippet({
183
- name: `pm.${(this as any).name}.write`,
184
- actions: [
185
- 'gitRepositories:create',
186
- 'gitRepositories:update',
187
- 'gitRepositories:destroy',
188
- 'gitReviewFlows:create',
189
- 'gitReviewFlows:update',
190
- 'gitReviewFlows:destroy',
191
- 'gitCodeReviews:create',
192
- 'gitCodeReviews:update',
193
- 'gitCodeReviews:destroy',
194
- 'gitManager:clone',
195
- 'gitManager:pull',
196
- 'gitManager:push',
197
- 'gitManager:fetch',
198
- 'gitManager:checkout',
199
- 'gitManager:triggerReview',
200
- 'gitManager:reviewApprovePost',
201
- 'gitManager:reviewReject',
202
- 'gitManager:pollNow',
203
- 'gitSubtreeConfigs:create',
204
- 'gitSubtreeConfigs:update',
205
- 'gitSubtreeConfigs:destroy',
206
- 'gitManager:subtreeRun',
207
- ],
208
- });
209
-
210
- (this as any).app.acl.registerSnippet({
211
- name: `pm.${(this as any).name}.subtreeReplace`,
212
- actions: ['gitManager:subtreeReplace'],
213
- });
214
-
215
- // Repositories config — CRUD on gitRepositories and gitAccounts (no operations)
216
- (this as any).app.acl.registerSnippet({
217
- name: `pm.${(this as any).name}.repositories`,
218
- actions: ['gitRepositories:*', 'gitAccounts:*'],
219
- });
220
-
221
- // Full management — all git manager actions
222
- (this as any).app.acl.registerSnippet({
223
- name: `pm.${(this as any).name}.manage`,
224
- actions: [
225
- // ACL snippet actions are resource:action patterns; nested snippet names
226
- // are not expanded by the core snippet manager.
227
- 'gitRepositories:*',
228
- 'gitAccounts:*',
229
- 'gitReviewFlows:*',
230
- 'gitCodeReviews:*',
231
- 'gitSubtreeConfigs:*',
232
- 'gitSubtreeRuns:*',
233
- 'gitManager:*',
234
- ],
235
- });
236
-
237
- // Prevent overwriting PAT with obfuscated value on updates
238
- (this as any).app.resourceManager.use(async (ctx, next) => {
239
- const resource = ctx.action?.resourceName;
240
-
241
- if (
242
- resource === 'gitSubtreeConfigs' &&
243
- ['create', 'update'].includes(ctx.action?.actionName) &&
244
- ctx.action.params?.values
245
- ) {
246
- try {
247
- subtreeActions.validateSubtreeConfigInput(ctx.action.params.values);
248
- } catch (error) {
249
- const message = error instanceof Error ? error.message : String(error);
250
- ctx.throw(400, ctx.t(message, { ns: (this as any).name }));
251
- }
252
- }
253
-
254
- if (resource === 'gitAccounts' && ctx.action?.actionName === 'destroy') {
255
- const accounts = await ctx.db.getRepository('gitAccounts').find({
256
- filterByTk: ctx.action.params?.filterByTk,
257
- filter: ctx.action.params?.filter,
258
- fields: ['id'],
259
- });
260
- const accountIds: Array<number | string> = [];
261
- for (const account of accounts as Array<{ get: (attribute: string) => number | string }>) {
262
- accountIds.push(account.get('id'));
263
- }
264
- if (accountIds.length > 0) {
265
- const repositoryCount = await ctx.db.getRepository('gitRepositories').count({
266
- filter: { gitAccountId: { $in: accountIds } },
267
- });
268
- if (repositoryCount > 0) {
269
- ctx.throw(
270
- 409,
271
- ctx.t('Cannot delete this Git account because {{count}} repositories are using it', {
272
- ns: (this as any).name,
273
- count: repositoryCount,
274
- }),
275
- );
276
- }
277
- }
278
- }
279
-
280
- if (isGitConfigurationUrlMutation(resource, ctx.action?.actionName)) {
281
- const actionParams = ctx.action?.params;
282
- const requestBody = ctx.request?.body;
283
- const hasCredentialBearingUrl = [
284
- actionParams,
285
- actionParams?.values,
286
- requestBody,
287
- requestBody?.values,
288
- ctx.query,
289
- ctx.request?.query,
290
- ].some((source) => containsCredentialBearingUrlField(source, GIT_CONFIGURATION_URL_FIELDS));
291
-
292
- if (hasCredentialBearingUrl) {
293
- ctx.throw(400, ctx.t(URL_USERINFO_NOT_ALLOWED, { ns: (this as any).name }));
294
- }
295
-
296
- if (ctx.action.params?.values?.pat === '••••••••') {
297
- delete ctx.action.params.values.pat;
298
- }
299
- if (ctx.request.body?.pat === '••••••••') {
300
- delete ctx.request.body.pat;
301
- }
302
- }
303
- return next();
304
- });
305
-
306
- // Strip PAT from every Git Manager response, including nested association routes.
307
- (this as any).app.resourceManager.use(async (ctx, next) => {
308
- const resource = ctx.action?.resourceName;
309
- if (!isGitManagerResourceResponse(resource)) {
310
- return next();
311
- }
312
- await next();
313
- redactCredentialFields(ctx.body);
314
- });
315
- }
316
-
317
- async install() {
318
- await (this as any).app.db.getCollection('gitAccounts')?.sync();
319
- await (this as any).app.db.getCollection('gitRepositories')?.sync();
320
- await (this as any).app.db.getCollection('gitSubtreeConfigs')?.sync();
321
- await (this as any).app.db.getCollection('gitSubtreeRuns')?.sync();
322
- }
323
-
324
- async beforeDisable() {
325
- unregisterReviewQueue((this as any).app);
326
- stopPoller();
327
- }
328
-
329
- async beforeUnload() {
330
- unregisterReviewQueue((this as any).app);
331
- stopPoller();
332
- }
333
- }
334
-
335
- export async function ensureAutoReviewFlowSchema(app: any) {
336
- const sequelize = app.db?.sequelize;
337
- const queryInterface = sequelize?.getQueryInterface?.();
338
- if (!queryInterface) return;
339
-
340
- const tablePrefix = app.db.options?.tablePrefix || '';
341
-
342
- const repoTable = `${tablePrefix}gitRepositories`;
343
- const repoInfo = await queryInterface.describeTable(repoTable).catch(() => null);
344
- if (repoInfo && !repoInfo.autoReviewFlowId) {
345
- await queryInterface.addColumn(repoTable, 'autoReviewFlowId', {
346
- type: DataTypes.INTEGER,
347
- allowNull: true,
348
- });
349
- }
350
-
351
- const reviewTable = `${tablePrefix}gitCodeReviews`;
352
- const reviewInfo = await queryInterface.describeTable(reviewTable).catch(() => null);
353
- if (reviewInfo && !reviewInfo.folderPath) {
354
- await queryInterface.addColumn(reviewTable, 'folderPath', {
355
- type: DataTypes.STRING,
356
- allowNull: true,
357
- });
358
- }
359
- }
360
-
361
- export default PluginGitManagerServer;
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 { Plugin } from '@nocobase/server';
11
+ import type { Database } from '@nocobase/database';
12
+ import { resolve } from 'path';
13
+ import { DataTypes } from 'sequelize';
14
+ import * as gitActions from './actions/git-actions';
15
+ import * as gitlabApi from './actions/gitlab-api';
16
+ import * as reviewActions from './actions/review';
17
+ import * as pollerActions from './actions/poller';
18
+ import * as rolePermissionsActions from './actions/role-permissions';
19
+ import * as subtreeActions from './actions/subtree';
20
+ import { recoverStuckReviews, registerReviewQueue, unregisterReviewQueue } from './actions/review';
21
+ import { registerGitReviewAiTools } from './ai-tools';
22
+ import { enforceGitRequestMethod } from './request-method-policy';
23
+ import { startPoller, stopPoller } from './poller';
24
+ import { RegistryGitContentService, SkillHubGitContentService } from './services/registry-content-service';
25
+ import { enforceRepositoryAccess, enforceRepositoryCollectionAccess } from './repository-access';
26
+ import { isGitManagerResourceResponse, redactCredentialFields } from './utils/redact';
27
+ import { containsCredentialBearingUrlField, URL_USERINFO_NOT_ALLOWED } from './utils/url-security';
28
+
29
+ const GIT_CONFIGURATION_URL_FIELDS = new Set(['repoUrl', 'baseUrl']);
30
+
31
+ export function isGitConfigurationUrlMutation(resourceName: unknown, actionName: unknown): boolean {
32
+ return (
33
+ typeof actionName === 'string' &&
34
+ ['create', 'update'].includes(actionName) &&
35
+ isGitManagerResourceResponse(resourceName)
36
+ );
37
+ }
38
+
39
+ export class PluginGitManagerServer extends Plugin {
40
+ // @ts-ignore
41
+ declare app: any;
42
+ // @ts-ignore
43
+ declare db: any;
44
+ registryContentService!: RegistryGitContentService;
45
+ skillHubContentService!: SkillHubGitContentService;
46
+
47
+ async afterAdd() {
48
+ this.registryContentService = new RegistryGitContentService(
49
+ (this as unknown as { db: Database }).db,
50
+ undefined,
51
+ this.app.acl,
52
+ );
53
+ this.skillHubContentService = new SkillHubGitContentService(
54
+ (this as unknown as { db: Database }).db,
55
+ undefined,
56
+ this.app.acl,
57
+ );
58
+ }
59
+
60
+ async beforeLoad() {
61
+ await (this as any).app.db.import({
62
+ directory: resolve(__dirname, 'collections'),
63
+ });
64
+
65
+ (this as any).app.db.addMigrations({
66
+ namespace: (this as any).name,
67
+ directory: resolve(__dirname, 'migrations'),
68
+ context: { plugin: this },
69
+ });
70
+ }
71
+
72
+ async load() {
73
+ // Ensure dayjs timezone + utc plugins are loaded globally to prevent 'm.startOf is not a function' errors
74
+ const dayjsLib = require('dayjs');
75
+ const utcPlugin = require('dayjs/plugin/utc');
76
+ const timezonePlugin = require('dayjs/plugin/timezone');
77
+ dayjsLib.extend(utcPlugin);
78
+ dayjsLib.extend(timezonePlugin);
79
+
80
+ (this as any).app.resourceManager.define({
81
+ name: 'gitManager',
82
+ actions: {
83
+ clone: gitActions.clone,
84
+ pull: gitActions.pull,
85
+ push: gitActions.push,
86
+ fetch: gitActions.fetch,
87
+ diff: gitActions.diff,
88
+ status: gitActions.status,
89
+ log: gitActions.log,
90
+ branches: gitActions.branches,
91
+ checkout: gitActions.checkout,
92
+ fileTree: gitActions.fileTree,
93
+ fileContent: gitActions.fileContent,
94
+ commitDetail: gitActions.commitDetail,
95
+ mergeRequests: gitlabApi.mergeRequests,
96
+ mergeRequestDetail: gitlabApi.mergeRequestDetail,
97
+ mergeRequestNotes: gitlabApi.mergeRequestNotes,
98
+ triggerReview: reviewActions.triggerReview,
99
+ reviewApprovePost: reviewActions.reviewApprovePost,
100
+ reviewReject: reviewActions.reviewReject,
101
+ pollNow: pollerActions.pollNow,
102
+ pollerStatus: pollerActions.pollerStatus,
103
+ rolePermissions: rolePermissionsActions.rolePermissions,
104
+ updateRolePermissions: rolePermissionsActions.updateRolePermissions,
105
+ subtreePreview: subtreeActions.subtreePreview,
106
+ subtreeOptions: subtreeActions.subtreeOptions,
107
+ subtreeRun: subtreeActions.subtreeRunOnAppProcess,
108
+ subtreeReplace: subtreeActions.subtreeRunOnAppProcess,
109
+ },
110
+ });
111
+
112
+ this.app.resourceManager.use(enforceGitRequestMethod);
113
+ (this as any).app.resourceManager.use(enforceRepositoryAccess);
114
+ (this as any).app.resourceManager.use(enforceRepositoryCollectionAccess);
115
+
116
+ // Suppress noisy workflow pre-action/post-action warnings for custom resources
117
+ (this as any).app.use(async (ctx, next) => {
118
+ if (ctx.logger && ctx.logger.warn) {
119
+ const originalWarn = ctx.logger.warn.bind(ctx.logger);
120
+ ctx.logger.warn = (message: any, ...args: any[]) => {
121
+ if (
122
+ typeof message === 'string' &&
123
+ message.includes('[Workflow') &&
124
+ message.includes('collection') &&
125
+ message.includes('not found')
126
+ ) {
127
+ return ctx.logger;
128
+ }
129
+ return originalWarn(message, ...args);
130
+ };
131
+ }
132
+ return next();
133
+ });
134
+
135
+ registerReviewQueue((this as any).app);
136
+ registerGitReviewAiTools((this as any).app);
137
+
138
+ (this as any).app.on('afterStart', async () => {
139
+ await ensureAutoReviewFlowSchema((this as any).app).catch(
140
+ (err) => (this as any).app.log?.error?.('plugin-git-manager: ensure schema error', err),
141
+ );
142
+ // Sweep any review left in `running` state from a previous process.
143
+ recoverStuckReviews((this as any).app).catch(
144
+ (err) => (this as any).app.log?.error?.('plugin-git-manager: recoverStuckReviews error', err),
145
+ );
146
+ subtreeActions
147
+ .recoverStuckSubtreeRuns((this as any).app)
148
+ .catch((err) => (this as any).app.log?.error?.('plugin-git-manager: recover subtree runs error', err));
149
+ startPoller((this as any).app);
150
+ });
151
+ (this as any).app.on('beforeStop', () => {
152
+ unregisterReviewQueue((this as any).app);
153
+ stopPoller(this.app);
154
+ });
155
+ (this as any).app.on('beforeDestroy', () => {
156
+ unregisterReviewQueue((this as any).app);
157
+ stopPoller(this.app);
158
+ });
159
+
160
+ // Read-only operations available to all plugin users
161
+ (this as any).app.acl.registerSnippet({
162
+ name: `pm.${(this as any).name}.read`,
163
+ actions: [
164
+ 'gitRepositories:list',
165
+ 'gitRepositories:get',
166
+ 'gitAccounts:list',
167
+ 'gitAccounts:get',
168
+ 'gitReviewFlows:list',
169
+ 'gitReviewFlows:get',
170
+ 'gitCodeReviews:list',
171
+ 'gitCodeReviews:get',
172
+ 'gitSubtreeConfigs:list',
173
+ 'gitSubtreeConfigs:get',
174
+ 'gitSubtreeRuns:list',
175
+ 'gitSubtreeRuns:get',
176
+ 'gitManager:status',
177
+ 'gitManager:log',
178
+ 'gitManager:branches',
179
+ 'gitManager:diff',
180
+ 'gitManager:fileTree',
181
+ 'gitManager:fileContent',
182
+ 'gitManager:commitDetail',
183
+ 'gitManager:mergeRequests',
184
+ 'gitManager:mergeRequestDetail',
185
+ 'gitManager:mergeRequestNotes',
186
+ 'gitManager:pollerStatus',
187
+ 'gitManager:subtreePreview',
188
+ 'gitManager:subtreeOptions',
189
+ ],
190
+ });
191
+
192
+ // Write operations require separate permission
193
+ (this as any).app.acl.registerSnippet({
194
+ name: `pm.${(this as any).name}.write`,
195
+ actions: [
196
+ 'gitRepositories:create',
197
+ 'gitRepositories:update',
198
+ 'gitRepositories:destroy',
199
+ 'gitReviewFlows:create',
200
+ 'gitReviewFlows:update',
201
+ 'gitReviewFlows:destroy',
202
+ 'gitCodeReviews:create',
203
+ 'gitCodeReviews:update',
204
+ 'gitCodeReviews:destroy',
205
+ 'gitManager:clone',
206
+ 'gitManager:pull',
207
+ 'gitManager:push',
208
+ 'gitManager:fetch',
209
+ 'gitManager:checkout',
210
+ 'gitManager:triggerReview',
211
+ 'gitManager:reviewApprovePost',
212
+ 'gitManager:reviewReject',
213
+ 'gitManager:pollNow',
214
+ 'gitSubtreeConfigs:create',
215
+ 'gitSubtreeConfigs:update',
216
+ 'gitSubtreeConfigs:destroy',
217
+ 'gitManager:subtreeRun',
218
+ ],
219
+ });
220
+
221
+ (this as any).app.acl.registerSnippet({
222
+ name: `pm.${(this as any).name}.subtreeReplace`,
223
+ actions: ['gitManager:subtreeReplace'],
224
+ });
225
+
226
+ // Repositories config — CRUD on gitRepositories and gitAccounts (no operations)
227
+ (this as any).app.acl.registerSnippet({
228
+ name: `pm.${(this as any).name}.repositories`,
229
+ actions: ['gitRepositories:*', 'gitAccounts:*'],
230
+ });
231
+
232
+ // Full management — all git manager actions
233
+ (this as any).app.acl.registerSnippet({
234
+ name: `pm.${(this as any).name}.manage`,
235
+ actions: [
236
+ // ACL snippet actions are resource:action patterns; nested snippet names
237
+ // are not expanded by the core snippet manager.
238
+ 'gitRepositories:*',
239
+ 'gitAccounts:*',
240
+ 'gitReviewFlows:*',
241
+ 'gitCodeReviews:*',
242
+ 'gitSubtreeConfigs:*',
243
+ 'gitSubtreeRuns:*',
244
+ 'gitManager:*',
245
+ ],
246
+ });
247
+
248
+ // Prevent overwriting PAT with obfuscated value on updates
249
+ (this as any).app.resourceManager.use(async (ctx, next) => {
250
+ const resource = ctx.action?.resourceName;
251
+
252
+ if (
253
+ resource === 'gitSubtreeConfigs' &&
254
+ ['create', 'update'].includes(ctx.action?.actionName) &&
255
+ ctx.action.params?.values
256
+ ) {
257
+ try {
258
+ subtreeActions.validateSubtreeConfigInput(ctx.action.params.values);
259
+ } catch (error) {
260
+ const message = error instanceof Error ? error.message : String(error);
261
+ ctx.throw(400, ctx.t(message, { ns: (this as any).name }));
262
+ }
263
+ }
264
+
265
+ if (resource === 'gitAccounts' && ctx.action?.actionName === 'destroy') {
266
+ const accounts = await ctx.db.getRepository('gitAccounts').find({
267
+ filterByTk: ctx.action.params?.filterByTk,
268
+ filter: ctx.action.params?.filter,
269
+ fields: ['id'],
270
+ });
271
+ const accountIds: Array<number | string> = [];
272
+ for (const account of accounts as Array<{ get: (attribute: string) => number | string }>) {
273
+ accountIds.push(account.get('id'));
274
+ }
275
+ if (accountIds.length > 0) {
276
+ const repositoryCount = await ctx.db.getRepository('gitRepositories').count({
277
+ filter: { gitAccountId: { $in: accountIds } },
278
+ });
279
+ if (repositoryCount > 0) {
280
+ ctx.throw(
281
+ 409,
282
+ ctx.t('Cannot delete this Git account because {{count}} repositories are using it', {
283
+ ns: (this as any).name,
284
+ count: repositoryCount,
285
+ }),
286
+ );
287
+ }
288
+ }
289
+ }
290
+
291
+ if (isGitConfigurationUrlMutation(resource, ctx.action?.actionName)) {
292
+ const actionParams = ctx.action?.params;
293
+ const requestBody = ctx.request?.body;
294
+ const hasCredentialBearingUrl = [
295
+ actionParams,
296
+ actionParams?.values,
297
+ requestBody,
298
+ requestBody?.values,
299
+ ctx.query,
300
+ ctx.request?.query,
301
+ ].some((source) => containsCredentialBearingUrlField(source, GIT_CONFIGURATION_URL_FIELDS));
302
+
303
+ if (hasCredentialBearingUrl) {
304
+ ctx.throw(400, ctx.t(URL_USERINFO_NOT_ALLOWED, { ns: (this as any).name }));
305
+ }
306
+
307
+ if (ctx.action.params?.values?.pat === '••••••••') {
308
+ delete ctx.action.params.values.pat;
309
+ }
310
+ if (ctx.request.body?.pat === '••••••••') {
311
+ delete ctx.request.body.pat;
312
+ }
313
+ }
314
+ return next();
315
+ });
316
+
317
+ // Strip PAT from every Git Manager response, including nested association routes.
318
+ (this as any).app.resourceManager.use(async (ctx, next) => {
319
+ const resource = ctx.action?.resourceName;
320
+ if (!isGitManagerResourceResponse(resource)) {
321
+ return next();
322
+ }
323
+ await next();
324
+ redactCredentialFields(ctx.body);
325
+ });
326
+ }
327
+
328
+ async install() {
329
+ await (this as any).app.db.getCollection('gitAccounts')?.sync();
330
+ await (this as any).app.db.getCollection('gitRepositories')?.sync();
331
+ await (this as any).app.db.getCollection('gitSubtreeConfigs')?.sync();
332
+ await (this as any).app.db.getCollection('gitSubtreeRuns')?.sync();
333
+ }
334
+
335
+ async beforeDisable() {
336
+ unregisterReviewQueue((this as any).app);
337
+ stopPoller(this.app);
338
+ }
339
+
340
+ async beforeUnload() {
341
+ unregisterReviewQueue((this as any).app);
342
+ stopPoller(this.app);
343
+ }
344
+ }
345
+
346
+ export async function ensureAutoReviewFlowSchema(app: any) {
347
+ const sequelize = app.db?.sequelize;
348
+ const queryInterface = sequelize?.getQueryInterface?.();
349
+ if (!queryInterface) return;
350
+
351
+ const tablePrefix = app.db.options?.tablePrefix || '';
352
+
353
+ const repoTable = `${tablePrefix}gitRepositories`;
354
+ const repoInfo = await queryInterface.describeTable(repoTable).catch(() => null);
355
+ if (repoInfo && !repoInfo.autoReviewFlowId) {
356
+ await queryInterface.addColumn(repoTable, 'autoReviewFlowId', {
357
+ type: DataTypes.INTEGER,
358
+ allowNull: true,
359
+ });
360
+ }
361
+
362
+ const reviewTable = `${tablePrefix}gitCodeReviews`;
363
+ const reviewInfo = await queryInterface.describeTable(reviewTable).catch(() => null);
364
+ if (reviewInfo && !reviewInfo.folderPath) {
365
+ await queryInterface.addColumn(reviewTable, 'folderPath', {
366
+ type: DataTypes.STRING,
367
+ allowNull: true,
368
+ });
369
+ }
370
+ }
371
+
372
+ export default PluginGitManagerServer;