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,352 +1,351 @@
1
- import type { Application } from '@nocobase/server';
2
- import { triggerReviewInternal, branchMatches } from './actions/review';
3
- import { parseGitLabProject } from './utils/gitlab-url';
4
- import { getRepoAccount } from './utils/get-repo-account';
5
-
6
- const POLL_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
7
- const MR_PAGE_SIZE = 50;
8
- /**
9
- * Maximum duration a single poll cycle is allowed to hold the lock.
10
- * If a cycle exceeds this, the stale lock is forcibly released so future
11
- * ticks are not permanently blocked.
12
- */
13
- const STALE_POLL_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes
14
-
15
- let timer: NodeJS.Timeout | null = null;
16
- let isPolling = false;
17
- let pollStartedAt: number | null = null;
18
- let lastTickAt: Date | null = null;
19
- let lastError: string | null = null;
20
-
21
- /**
22
- * Start the background poller. Idempotent — calling twice is a no-op.
23
- * The poller scans repos with autoReview=true, lists their open MRs from GitLab,
24
- * and triggers a review if no record exists for the MR's current head SHA.
25
- */
26
- export function startPoller(app: Application) {
27
- if (timer) return;
28
- app.log?.info?.('plugin-git-manager: starting MR poller (interval 5min)');
29
- // First tick after a short delay so app is fully ready
30
- timer = setInterval(() => tick(app).catch((e) => app.log?.error?.('poller tick error', e)), POLL_INTERVAL_MS);
31
- }
32
-
33
- export function stopPoller() {
34
- if (timer) {
35
- clearInterval(timer);
36
- timer = null;
37
- }
38
- }
39
-
40
- export function getPollerStatus() {
41
- return {
42
- running: !!timer,
43
- polling: isPolling,
44
- lastTickAt: lastTickAt?.toISOString() ?? null,
45
- lastError,
46
- intervalSec: POLL_INTERVAL_MS / 1000,
47
- };
48
- }
49
-
50
- /**
51
- * Handle returned by `tryAcquirePollerLock`. Caller must invoke `release()`
52
- * exactly once when done. Returning a handle (rather than a boolean) lets us
53
- * pin a Sequelize transaction to a single connection so that
54
- * `pg_advisory_unlock` / `RELEASE_LOCK` run on the same connection that
55
- * acquired the lock — pool-based queries previously could release on the
56
- * wrong connection, leaving the lock held until that connection recycled.
57
- */
58
- interface PollerLockHandle {
59
- release: () => Promise<void>;
60
- }
61
-
62
- const ADVISORY_LOCK_KEY = 777_042;
63
-
64
- /**
65
- * Attempt to acquire a DB-level advisory lock so that only one node in an
66
- * HA cluster runs the poller at any given time.
67
- *
68
- * Returns a handle when acquired, `null` when another node holds the lock.
69
- * Falls back to a no-op handle when the DB doesn't support advisory locks
70
- * (SQLite, unknown dialects) or when an unexpected error occurs.
71
- */
72
- async function tryAcquirePollerLock(app: Application): Promise<PollerLockHandle | null> {
73
- const noop: PollerLockHandle = { release: async () => undefined };
74
- const sequelize = (app.db as any).sequelize;
75
- if (!sequelize) return noop;
76
- const dialect = sequelize.getDialect?.();
77
-
78
- if (dialect !== 'postgres' && dialect !== 'mysql' && dialect !== 'mariadb') {
79
- return noop; // SQLite / unknown — no distributed locking, allow
80
- }
81
-
82
- // A transaction pins all queries (and the lock) to a single connection.
83
- let transaction: any;
84
- try {
85
- transaction = await sequelize.transaction();
86
- } catch {
87
- return noop; // can't open txn — fall back to allowing
88
- }
89
-
90
- try {
91
- let acquired = false;
92
- if (dialect === 'postgres') {
93
- const [results] = await sequelize.query(`SELECT pg_try_advisory_lock(${ADVISORY_LOCK_KEY}) AS locked`, {
94
- transaction,
95
- });
96
- acquired = (results as any)?.[0]?.locked === true;
97
- } else {
98
- const [results] = await sequelize.query(`SELECT GET_LOCK('git_poller', 0) AS locked`, { transaction });
99
- const v = (results as any)?.[0]?.locked;
100
- acquired = v === 1 || v === '1' || v === true;
101
- }
102
-
103
- if (!acquired) {
104
- try {
105
- await transaction.rollback();
106
- } catch {
107
- /* ignore */
108
- }
109
- return null;
110
- }
111
-
112
- return {
113
- release: async () => {
114
- try {
115
- if (dialect === 'postgres') {
116
- await sequelize.query(`SELECT pg_advisory_unlock(${ADVISORY_LOCK_KEY})`, { transaction });
117
- } else {
118
- await sequelize.query(`SELECT RELEASE_LOCK('git_poller')`, { transaction });
119
- }
120
- } catch {
121
- // best-effort release — txn close still recycles the connection
122
- } finally {
123
- try {
124
- await transaction.commit();
125
- } catch {
126
- try {
127
- await transaction.rollback();
128
- } catch {
129
- /* ignore */
130
- }
131
- }
132
- }
133
- },
134
- };
135
- } catch {
136
- try {
137
- await transaction.rollback();
138
- } catch {
139
- /* ignore */
140
- }
141
- return noop; // on error, fall back to allowing
142
- }
143
- }
144
-
145
- /**
146
- * Run one poll cycle for all auto-enabled repos. Public so that the
147
- * gitManager:pollNow action can force a tick on demand.
148
- */
149
- export async function pollAllRepos(app: Application): Promise<{ scanned: number; triggered: number }> {
150
- // M-4 fix: recover from stale isPolling flag
151
- if (isPolling) {
152
- if (pollStartedAt && Date.now() - pollStartedAt > STALE_POLL_TIMEOUT_MS) {
153
- app.log?.warn?.('poller: stale isPolling flag detected — forcibly resetting');
154
- isPolling = false;
155
- pollStartedAt = null;
156
- } else {
157
- return { scanned: 0, triggered: 0 };
158
- }
159
- }
160
-
161
- // C-1 fix: acquire distributed lock for HA — handle pins the connection
162
- // so unlock runs on the same connection that acquired the lock.
163
- const lock = await tryAcquirePollerLock(app);
164
- if (!lock) {
165
- app.log?.debug?.('poller: another node holds the advisory lock — skipping');
166
- return { scanned: 0, triggered: 0 };
167
- }
168
-
169
- isPolling = true;
170
- pollStartedAt = Date.now();
171
- lastTickAt = new Date();
172
- lastError = null;
173
-
174
- let scanned = 0;
175
- let triggered = 0;
176
-
177
- try {
178
- const reposRepo = app.db.getRepository('gitRepositories');
179
- const repos = await reposRepo.find({ filter: { autoReview: true } });
180
- for (const repo of repos) {
181
- try {
182
- const result = await pollOneRepo(app, repo);
183
- scanned += result.scanned;
184
- triggered += result.triggered;
185
- } catch (err: any) {
186
- app.log?.error?.(`poller: repo ${repo.get('id')} failed: ${err?.message}`);
187
- }
188
- }
189
- } catch (err: any) {
190
- lastError = err?.message || String(err);
191
- app.log?.error?.('poller: cycle failed', err);
192
- } finally {
193
- isPolling = false;
194
- pollStartedAt = null;
195
- await lock.release();
196
- }
197
- return { scanned, triggered };
198
- }
199
-
200
- async function tick(app: Application) {
201
- await pollAllRepos(app);
202
- }
203
-
204
- /**
205
- * Poll a single repo for MR changes. Returns counts.
206
- */
207
- export async function pollOneRepo(app: Application, repo: any): Promise<{ scanned: number; triggered: number }> {
208
- const flowsRepo = app.db.getRepository('gitReviewFlows');
209
- const reviewsRepo = app.db.getRepository('gitCodeReviews');
210
- const reposRepo = app.db.getRepository('gitRepositories');
211
-
212
- // Find auto-trigger flows scoped to this repo or global
213
- const flows = await flowsRepo.find({
214
- filter: {
215
- enabled: true,
216
- triggerMode: { $in: ['onMergeRequestCreated', 'both'] },
217
- $or: [{ repositoryId: repo.get('id') }, { repositoryId: null }],
218
- },
219
- sort: ['-repositoryId'],
220
- });
221
- if (!flows?.length) return { scanned: 0, triggered: 0 };
222
-
223
- const primaryFlowId = repo.get('autoReviewFlowId') as number | null;
224
- const primaryFlow = primaryFlowId
225
- ? flows.find((flow: any) => Number(flow.get('id')) === Number(primaryFlowId))
226
- : null;
227
-
228
- // Need PAT to query GitLab
229
- const account = await getRepoAccount(app.db, repo);
230
- const pat = account?.pat || '';
231
- if (!pat) return { scanned: 0, triggered: 0 };
232
-
233
- const lastPolledAt = repo.get('lastPolledAt') as Date | null;
234
- const mrs = await listMergeRequests(repo, pat, lastPolledAt);
235
-
236
- let triggered = 0;
237
- for (const mr of mrs) {
238
- // Prefer the repository's configured primary auto-review flow, then fall
239
- // back to the first matching auto-trigger flow.
240
- const flow =
241
- primaryFlow && branchMatches(primaryFlow, mr.source_branch)
242
- ? primaryFlow
243
- : flows.find((f: any) => branchMatches(f, mr.source_branch));
244
- if (!flow) continue;
245
-
246
- // Auto-poll only triggers for MRs that have NEVER been reviewed.
247
- // For existing reviews we just refresh latestSha so the UI can flag
248
- // "new commits available" — re-review must be done manually by the user.
249
- const existing = await reviewsRepo.findOne({
250
- filter: {
251
- repositoryId: repo.get('id'),
252
- targetType: 'mr',
253
- mrIid: mr.iid,
254
- },
255
- });
256
- if (existing) {
257
- if (existing.get('latestSha') !== mr.sha) {
258
- await reviewsRepo.update({
259
- filterByTk: existing.get('id'),
260
- values: { latestSha: mr.sha },
261
- });
262
- }
263
- continue;
264
- }
265
-
266
- try {
267
- await triggerReviewInternal(app, {
268
- flowId: flow.get('id'),
269
- repositoryId: repo.get('id'),
270
- targetType: 'mr',
271
- mrIid: mr.iid,
272
- branch: mr.source_branch,
273
- headSha: mr.sha,
274
- triggeredBy: 'poll',
275
- });
276
- triggered++;
277
- } catch (err: any) {
278
- app.log?.error?.(`poller: triggerReviewInternal failed for MR !${mr.iid}: ${err?.message}`);
279
- }
280
- }
281
-
282
- await reposRepo.update({
283
- filterByTk: repo.get('id'),
284
- values: { lastPolledAt: new Date() },
285
- });
286
-
287
- return { scanned: mrs.length, triggered };
288
- }
289
-
290
- async function listMergeRequests(repo: any, pat: string, updatedAfter: Date | null): Promise<any[]> {
291
- const repoUrl = repo.get('repoUrl') as string;
292
- const isGitHub = typeof repoUrl === 'string' && repoUrl.includes('github.com');
293
-
294
- if (isGitHub) {
295
- // GitHub PRs: list endpoint sorts by updated; GitHub has no `updated_after`,
296
- // so we filter client-side after fetching the most recently updated page.
297
- const { projectPath } = parseGitLabProject(repoUrl);
298
- const params = new URLSearchParams({
299
- state: 'open',
300
- per_page: String(MR_PAGE_SIZE),
301
- sort: 'updated',
302
- direction: 'desc',
303
- });
304
- const headers: Record<string, string> = { Accept: 'application/vnd.github.v3+json' };
305
- if (pat) headers['Authorization'] = `Bearer ${pat}`;
306
-
307
- const response = await fetch(`https://api.github.com/repos/${projectPath}/pulls?${params.toString()}`, { headers });
308
- if (!response.ok) {
309
- const body = await response.text().catch(() => '');
310
- throw new Error(`GitHub API error ${response.status}: ${body}`);
311
- }
312
- let prs = (await response.json()) as any[];
313
- if (Array.isArray(prs) && updatedAfter) {
314
- const cutoff = updatedAfter.getTime() - 1000;
315
- prs = prs.filter((pr: any) => {
316
- const t = pr?.updated_at ? new Date(pr.updated_at).getTime() : 0;
317
- return t >= cutoff;
318
- });
319
- }
320
- // Normalise to the GitLab MR shape that pollOneRepo consumes.
321
- return (prs || []).map((pr: any) => ({
322
- iid: pr.number,
323
- sha: pr.head?.sha,
324
- source_branch: pr.head?.ref,
325
- target_branch: pr.base?.ref,
326
- }));
327
- }
328
-
329
- // GitLab
330
- const { apiBase, encodedProject } = parseGitLabProject(repoUrl);
331
- const params = new URLSearchParams({
332
- state: 'opened',
333
- per_page: String(MR_PAGE_SIZE),
334
- order_by: 'updated_at',
335
- sort: 'desc',
336
- });
337
- if (updatedAfter) {
338
- // GitLab `updated_after` is exclusive; subtract 1s so MRs updated within
339
- // the same second as the last poll aren't dropped.
340
- const safeBound = new Date(updatedAfter.getTime() - 1000);
341
- params.set('updated_after', safeBound.toISOString());
342
- }
343
-
344
- const response = await fetch(`${apiBase}/projects/${encodedProject}/merge_requests?${params.toString()}`, {
345
- headers: { 'PRIVATE-TOKEN': pat, Accept: 'application/json' },
346
- });
347
- if (!response.ok) {
348
- const body = await response.text().catch(() => '');
349
- throw new Error(`GitLab API error ${response.status}: ${body}`);
350
- }
351
- return response.json();
352
- }
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 { Application } from '@nocobase/server';
11
+ import { triggerReviewInternal, branchMatches } from './actions/review';
12
+ import { parseGitLabProject } from './utils/gitlab-url';
13
+ import { getRepoAccount } from './utils/get-repo-account';
14
+
15
+ const POLL_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
16
+ const MR_PAGE_SIZE = 50;
17
+ interface PollerState {
18
+ timer: NodeJS.Timeout | null;
19
+ polling: boolean;
20
+ lastTickAt: Date | null;
21
+ lastError: string | null;
22
+ }
23
+
24
+ const pollers = new WeakMap<Application, PollerState>();
25
+
26
+ function stateFor(app: Application): PollerState {
27
+ let state = pollers.get(app);
28
+ if (!state) {
29
+ state = { timer: null, polling: false, lastTickAt: null, lastError: null };
30
+ pollers.set(app, state);
31
+ }
32
+ return state;
33
+ }
34
+
35
+ export function startPoller(app: Application) {
36
+ const state = stateFor(app);
37
+ if (state.timer) return;
38
+ app.log?.info?.('plugin-git-manager: starting MR poller (interval 5min)');
39
+ state.timer = setInterval(() => tick(app).catch((e) => app.log?.error?.('poller tick error', e)), POLL_INTERVAL_MS);
40
+ }
41
+
42
+ export function stopPoller(app: Application) {
43
+ const state = stateFor(app);
44
+ if (state.timer) clearInterval(state.timer);
45
+ state.timer = null;
46
+ }
47
+
48
+ export function getPollerStatus(app: Application) {
49
+ const state = stateFor(app);
50
+ return {
51
+ running: !!state.timer,
52
+ polling: state.polling,
53
+ lastTickAt: state.lastTickAt?.toISOString() ?? null,
54
+ lastError: state.lastError,
55
+ intervalSec: POLL_INTERVAL_MS / 1000,
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Handle returned by `tryAcquirePollerLock`. Caller must invoke `release()`
61
+ * exactly once when done. Returning a handle (rather than a boolean) lets us
62
+ * pin a Sequelize transaction to a single connection so that
63
+ * `pg_advisory_unlock` / `RELEASE_LOCK` run on the same connection that
64
+ * acquired the lock — pool-based queries previously could release on the
65
+ * wrong connection, leaving the lock held until that connection recycled.
66
+ */
67
+ interface PollerLockHandle {
68
+ release: () => Promise<void>;
69
+ }
70
+
71
+ const ADVISORY_LOCK_KEY = 777_042;
72
+
73
+ /**
74
+ * Attempt to acquire a DB-level advisory lock so that only one node in an
75
+ * HA cluster runs the poller at any given time.
76
+ *
77
+ * Returns a handle when acquired, `null` when another node holds the lock.
78
+ * Falls back to a no-op handle when the DB doesn't support advisory locks
79
+ * (SQLite, unknown dialects) or when an unexpected error occurs.
80
+ */
81
+ async function tryAcquirePollerLock(app: Application): Promise<PollerLockHandle | null> {
82
+ const noop: PollerLockHandle = { release: async () => undefined };
83
+ const sequelize = (app.db as any).sequelize;
84
+ if (!sequelize) return noop;
85
+ const dialect = sequelize.getDialect?.();
86
+
87
+ if (dialect !== 'postgres' && dialect !== 'mysql' && dialect !== 'mariadb') {
88
+ return noop; // SQLite / unknown — no distributed locking, allow
89
+ }
90
+
91
+ // A transaction pins all queries (and the lock) to a single connection.
92
+ let transaction: any;
93
+ try {
94
+ transaction = await sequelize.transaction();
95
+ } catch {
96
+ return noop; // can't open txn — fall back to allowing
97
+ }
98
+
99
+ try {
100
+ let acquired = false;
101
+ if (dialect === 'postgres') {
102
+ const [results] = await sequelize.query(`SELECT pg_try_advisory_lock(${ADVISORY_LOCK_KEY}) AS locked`, {
103
+ transaction,
104
+ });
105
+ acquired = (results as any)?.[0]?.locked === true;
106
+ } else {
107
+ const [results] = await sequelize.query(`SELECT GET_LOCK('git_poller', 0) AS locked`, { transaction });
108
+ const v = (results as any)?.[0]?.locked;
109
+ acquired = v === 1 || v === '1' || v === true;
110
+ }
111
+
112
+ if (!acquired) {
113
+ try {
114
+ await transaction.rollback();
115
+ } catch {
116
+ /* ignore */
117
+ }
118
+ return null;
119
+ }
120
+
121
+ return {
122
+ release: async () => {
123
+ try {
124
+ if (dialect === 'postgres') {
125
+ await sequelize.query(`SELECT pg_advisory_unlock(${ADVISORY_LOCK_KEY})`, { transaction });
126
+ } else {
127
+ await sequelize.query(`SELECT RELEASE_LOCK('git_poller')`, { transaction });
128
+ }
129
+ } catch {
130
+ // best-effort release — txn close still recycles the connection
131
+ } finally {
132
+ try {
133
+ await transaction.commit();
134
+ } catch {
135
+ try {
136
+ await transaction.rollback();
137
+ } catch {
138
+ /* ignore */
139
+ }
140
+ }
141
+ }
142
+ },
143
+ };
144
+ } catch {
145
+ try {
146
+ await transaction.rollback();
147
+ } catch {
148
+ /* ignore */
149
+ }
150
+ return noop; // on error, fall back to allowing
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Run one poll cycle for all auto-enabled repos. Public so that the
156
+ * gitManager:pollNow action can force a tick on demand.
157
+ */
158
+ export async function pollAllRepos(app: Application): Promise<{ scanned: number; triggered: number }> {
159
+ const state = stateFor(app);
160
+ if (state.polling) return { scanned: 0, triggered: 0 };
161
+ // Claim the local guard before awaiting the distributed lock.
162
+ state.polling = true;
163
+ let lock: PollerLockHandle | null = null;
164
+ let scanned = 0;
165
+ let triggered = 0;
166
+ try {
167
+ lock = await tryAcquirePollerLock(app);
168
+ if (!lock) return { scanned: 0, triggered: 0 };
169
+ state.lastTickAt = new Date();
170
+ state.lastError = null;
171
+ const reposRepo = app.db.getRepository('gitRepositories');
172
+ const repos = await reposRepo.find({ filter: { autoReview: true } });
173
+ for (const repo of repos) {
174
+ try {
175
+ const result = await pollOneRepo(app, repo);
176
+ scanned += result.scanned;
177
+ triggered += result.triggered;
178
+ } catch (err: any) {
179
+ app.log?.error?.(`poller: repo ${repo.get('id')} failed: ${err?.message}`);
180
+ }
181
+ }
182
+ } catch (err: any) {
183
+ state.lastError = err?.message || String(err);
184
+ app.log?.error?.('poller: cycle failed', err);
185
+ } finally {
186
+ try {
187
+ await lock?.release();
188
+ } finally {
189
+ state.polling = false;
190
+ }
191
+ }
192
+ return { scanned, triggered };
193
+ }
194
+
195
+ async function tick(app: Application) {
196
+ await pollAllRepos(app);
197
+ }
198
+
199
+ /**
200
+ * Poll a single repo for MR changes. Returns counts.
201
+ */
202
+ export async function pollOneRepo(app: Application, repo: any): Promise<{ scanned: number; triggered: number }> {
203
+ const flowsRepo = app.db.getRepository('gitReviewFlows');
204
+ const reviewsRepo = app.db.getRepository('gitCodeReviews');
205
+ const reposRepo = app.db.getRepository('gitRepositories');
206
+
207
+ // Find auto-trigger flows scoped to this repo or global
208
+ const flows = await flowsRepo.find({
209
+ filter: {
210
+ enabled: true,
211
+ triggerMode: { $in: ['onMergeRequestCreated', 'both'] },
212
+ $or: [{ repositoryId: repo.get('id') }, { repositoryId: null }],
213
+ },
214
+ sort: ['-repositoryId'],
215
+ });
216
+ if (!flows?.length) return { scanned: 0, triggered: 0 };
217
+
218
+ const primaryFlowId = repo.get('autoReviewFlowId') as number | null;
219
+ const primaryFlow = primaryFlowId
220
+ ? flows.find((flow: any) => Number(flow.get('id')) === Number(primaryFlowId))
221
+ : null;
222
+
223
+ // Need PAT to query GitLab
224
+ const account = await getRepoAccount(app.db, repo);
225
+ const pat = account?.pat || '';
226
+ if (!pat) return { scanned: 0, triggered: 0 };
227
+
228
+ const lastPolledAt = repo.get('lastPolledAt') as Date | null;
229
+ const mrs = await listMergeRequests(repo, pat, lastPolledAt);
230
+
231
+ let triggered = 0;
232
+ for (const mr of mrs) {
233
+ // Prefer the repository's configured primary auto-review flow, then fall
234
+ // back to the first matching auto-trigger flow.
235
+ const flow =
236
+ primaryFlow && branchMatches(primaryFlow, mr.source_branch)
237
+ ? primaryFlow
238
+ : flows.find((f: any) => branchMatches(f, mr.source_branch));
239
+ if (!flow) continue;
240
+
241
+ // Auto-poll only triggers for MRs that have NEVER been reviewed.
242
+ // For existing reviews we just refresh latestSha so the UI can flag
243
+ // "new commits available" — re-review must be done manually by the user.
244
+ const existing = await reviewsRepo.findOne({
245
+ filter: {
246
+ repositoryId: repo.get('id'),
247
+ targetType: 'mr',
248
+ mrIid: mr.iid,
249
+ },
250
+ });
251
+ if (existing) {
252
+ if (existing.get('latestSha') !== mr.sha) {
253
+ await reviewsRepo.update({
254
+ filterByTk: existing.get('id'),
255
+ values: { latestSha: mr.sha },
256
+ });
257
+ }
258
+ continue;
259
+ }
260
+
261
+ try {
262
+ await triggerReviewInternal(app, {
263
+ flowId: flow.get('id'),
264
+ repositoryId: repo.get('id'),
265
+ targetType: 'mr',
266
+ mrIid: mr.iid,
267
+ branch: mr.source_branch,
268
+ headSha: mr.sha,
269
+ triggeredBy: 'poll',
270
+ });
271
+ triggered++;
272
+ } catch (err: any) {
273
+ app.log?.error?.(`poller: triggerReviewInternal failed for MR !${mr.iid}: ${err?.message}`);
274
+ }
275
+ }
276
+
277
+ await reposRepo.update({
278
+ filterByTk: repo.get('id'),
279
+ values: { lastPolledAt: new Date() },
280
+ });
281
+
282
+ return { scanned: mrs.length, triggered };
283
+ }
284
+
285
+ async function listMergeRequests(repo: any, pat: string, updatedAfter: Date | null): Promise<any[]> {
286
+ const repoUrl = repo.get('repoUrl') as string;
287
+ const isGitHub = typeof repoUrl === 'string' && new URL(repoUrl).hostname === 'github.com';
288
+
289
+ if (isGitHub) {
290
+ // GitHub PRs: list endpoint sorts by updated; GitHub has no `updated_after`,
291
+ // so we filter client-side after fetching the most recently updated page.
292
+ const { projectPath } = parseGitLabProject(repoUrl);
293
+ const params = new URLSearchParams({
294
+ state: 'open',
295
+ per_page: String(MR_PAGE_SIZE),
296
+ sort: 'updated',
297
+ direction: 'desc',
298
+ });
299
+ const headers: Record<string, string> = { Accept: 'application/vnd.github.v3+json' };
300
+ if (pat) headers['Authorization'] = `Bearer ${pat}`;
301
+
302
+ const response = await fetch(`https://api.github.com/repos/${projectPath}/pulls?${params.toString()}`, {
303
+ headers,
304
+ redirect: 'error',
305
+ });
306
+ if (!response.ok) {
307
+ const body = await response.text().catch(() => '');
308
+ throw new Error(`GitHub API error ${response.status}: ${body}`);
309
+ }
310
+ let prs = (await response.json()) as any[];
311
+ if (Array.isArray(prs) && updatedAfter) {
312
+ const cutoff = updatedAfter.getTime() - 1000;
313
+ prs = prs.filter((pr: any) => {
314
+ const t = pr?.updated_at ? new Date(pr.updated_at).getTime() : 0;
315
+ return t >= cutoff;
316
+ });
317
+ }
318
+ // Normalise to the GitLab MR shape that pollOneRepo consumes.
319
+ return (prs || []).map((pr: any) => ({
320
+ iid: pr.number,
321
+ sha: pr.head?.sha,
322
+ source_branch: pr.head?.ref,
323
+ target_branch: pr.base?.ref,
324
+ }));
325
+ }
326
+
327
+ // GitLab
328
+ const { apiBase, encodedProject } = parseGitLabProject(repoUrl);
329
+ const params = new URLSearchParams({
330
+ state: 'opened',
331
+ per_page: String(MR_PAGE_SIZE),
332
+ order_by: 'updated_at',
333
+ sort: 'desc',
334
+ });
335
+ if (updatedAfter) {
336
+ // GitLab `updated_after` is exclusive; subtract 1s so MRs updated within
337
+ // the same second as the last poll aren't dropped.
338
+ const safeBound = new Date(updatedAfter.getTime() - 1000);
339
+ params.set('updated_after', safeBound.toISOString());
340
+ }
341
+
342
+ const response = await fetch(`${apiBase}/projects/${encodedProject}/merge_requests?${params.toString()}`, {
343
+ redirect: 'error',
344
+ headers: { 'PRIVATE-TOKEN': pat, Accept: 'application/json' },
345
+ });
346
+ if (!response.ok) {
347
+ const body = await response.text().catch(() => '');
348
+ throw new Error(`GitLab API error ${response.status}: ${body}`);
349
+ }
350
+ return response.json();
351
+ }