plugin-workflow-ci 0.0.0-stage → 0.2.0

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 (60) hide show
  1. package/client-v2.js +1 -0
  2. package/client.js +1 -0
  3. package/dist/client/index.js +10 -0
  4. package/dist/client-v2/index.js +10 -0
  5. package/dist/externalVersion.js +21 -0
  6. package/dist/index.js +48 -0
  7. package/dist/locale/en-US.json +105 -0
  8. package/dist/locale/vi-VN.json +105 -0
  9. package/dist/locale/zh-CN.json +105 -0
  10. package/dist/server/actions/ci-manager.js +307 -0
  11. package/dist/server/collections/ci-gate-runs.js +85 -0
  12. package/dist/server/collections/ci-git-feedback-outbox.js +51 -0
  13. package/dist/server/collections/ci-pipelines.js +88 -0
  14. package/dist/server/index.js +62 -0
  15. package/dist/server/instructions/CiInstructions.js +180 -0
  16. package/dist/server/migrations/20261206000001-harden-workflow-ci-v020.js +91 -0
  17. package/dist/server/plugin.js +255 -0
  18. package/dist/server/services/AiTriageService.js +215 -0
  19. package/dist/server/services/CiGateWorkflowService.js +1776 -0
  20. package/dist/server/services/EphemeralContainerService.js +891 -0
  21. package/dist/server/services/GitFeedbackService.js +995 -0
  22. package/dist/server/services/constants-internal.js +65 -0
  23. package/dist/shared/collection-schemas.js +125 -0
  24. package/dist/shared/constants.js +120 -0
  25. package/dist/shared/runtime-context.js +67 -0
  26. package/dist/shared/types.js +24 -0
  27. package/dist/shared/ui/CiPipelinesSettingsView.js +700 -0
  28. package/package.json +58 -4
  29. package/server.js +1 -0
  30. package/src/client/index.tsx +10 -0
  31. package/src/client/locale.ts +31 -0
  32. package/src/client/plugin.tsx +62 -0
  33. package/src/client/workflow.tsx +119 -0
  34. package/src/client-v2/index.tsx +10 -0
  35. package/src/client-v2/locale.ts +32 -0
  36. package/src/client-v2/plugin.tsx +77 -0
  37. package/src/client-v2/workflow.tsx +124 -0
  38. package/src/index.ts +11 -0
  39. package/src/locale/en-US.json +105 -0
  40. package/src/locale/vi-VN.json +105 -0
  41. package/src/locale/zh-CN.json +105 -0
  42. package/src/server/actions/ci-manager.ts +377 -0
  43. package/src/server/collections/ci-gate-runs.ts +65 -0
  44. package/src/server/collections/ci-git-feedback-outbox.ts +31 -0
  45. package/src/server/collections/ci-pipelines.ts +68 -0
  46. package/src/server/index.ts +17 -0
  47. package/src/server/instructions/CiInstructions.ts +180 -0
  48. package/src/server/migrations/20261206000001-harden-workflow-ci-v020.ts +78 -0
  49. package/src/server/plugin.ts +274 -0
  50. package/src/server/services/AiTriageService.ts +254 -0
  51. package/src/server/services/CiGateWorkflowService.ts +2310 -0
  52. package/src/server/services/EphemeralContainerService.ts +1170 -0
  53. package/src/server/services/GitFeedbackService.ts +1224 -0
  54. package/src/server/services/constants-internal.ts +27 -0
  55. package/src/shared/collection-schemas.ts +98 -0
  56. package/src/shared/constants.ts +50 -0
  57. package/src/shared/runtime-context.tsx +55 -0
  58. package/src/shared/types.ts +203 -0
  59. package/src/shared/ui/CiPipelinesSettingsView.tsx +1035 -0
  60. package/README.md +0 -3
@@ -0,0 +1,995 @@
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
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var GitFeedbackService_exports = {};
28
+ __export(GitFeedbackService_exports, {
29
+ GitFeedbackService: () => GitFeedbackService,
30
+ matchesBranchPattern: () => matchesBranchPattern,
31
+ parseGitWebhookPayload: () => parseGitWebhookPayload,
32
+ parseStickyCommentVersionMarker: () => parseStickyCommentVersionMarker,
33
+ verifyConstantTimeSecret: () => verifyConstantTimeSecret,
34
+ verifyGitHubHmacSignature: () => verifyGitHubHmacSignature
35
+ });
36
+ module.exports = __toCommonJS(GitFeedbackService_exports);
37
+ var import_node_crypto = require("node:crypto");
38
+ var import_constants = require("../../shared/constants");
39
+ const MAX_COMMENT_PAGES = 20;
40
+ const COMMENTS_PER_PAGE = 100;
41
+ const MAX_OUTBOX_ATTEMPTS = 6;
42
+ function isPlainRecord(val) {
43
+ return Boolean(val) && typeof val === "object" && !Array.isArray(val);
44
+ }
45
+ function verifyConstantTimeSecret(expected, actual) {
46
+ const cleanExpected = expected.trim();
47
+ const cleanActual = actual.trim();
48
+ if (!cleanExpected || !cleanActual) return false;
49
+ const bufA = Buffer.from(cleanExpected, "utf8");
50
+ const bufB = Buffer.from(cleanActual, "utf8");
51
+ if (bufA.length !== bufB.length) return false;
52
+ return (0, import_node_crypto.timingSafeEqual)(bufA, bufB);
53
+ }
54
+ function verifyGitHubHmacSignature(secret, rawBody, signatureHeader) {
55
+ const cleanSecret = secret.trim();
56
+ const cleanHeader = signatureHeader.trim();
57
+ if (!cleanSecret || !cleanHeader.startsWith("sha256=")) return false;
58
+ const digest = `sha256=${(0, import_node_crypto.createHmac)("sha256", cleanSecret).update(rawBody, "utf8").digest("hex")}`;
59
+ return verifyConstantTimeSecret(digest, cleanHeader);
60
+ }
61
+ function matchesBranchPattern(branch, patternRaw) {
62
+ const cleanBranch = branch.trim();
63
+ if (!cleanBranch) return false;
64
+ const raw = String(patternRaw ?? "*").trim();
65
+ if (!raw || raw === "*") return true;
66
+ const patterns = raw.split(",").map((p) => p.trim()).filter(Boolean);
67
+ if (patterns.length === 0) return true;
68
+ return patterns.some((pat) => {
69
+ if (pat === "*") return true;
70
+ const escaped = pat.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, ".*").replace(/\*/g, "[^/]*");
71
+ return new RegExp(`^${escaped}$`).test(cleanBranch);
72
+ });
73
+ }
74
+ function parseStickyCommentVersionMarker(body) {
75
+ const v2Match = /<!--\s*nocobase-ci:([^\r\n>]+?)\s*-->/.exec(body);
76
+ if (v2Match) {
77
+ const kv = {};
78
+ for (const pair of v2Match[1].split(";")) {
79
+ const eq = pair.indexOf("=");
80
+ if (eq > 0) {
81
+ kv[pair.slice(0, eq).trim()] = pair.slice(eq + 1).trim();
82
+ }
83
+ }
84
+ return {
85
+ pipelineKey: kv.pipeline,
86
+ pipelineId: kv.pipelineId ? Number(kv.pipelineId) : void 0,
87
+ mrIid: kv.mr ? Number(kv.mr) : void 0,
88
+ gateRunId: kv.gateRun ? Number(kv.gateRun) : void 0,
89
+ commitSha: kv.sha
90
+ };
91
+ }
92
+ const legacyMatch = /<!--\s*nocobase-ci-summary:pipeline-(\d+):mr-(\d+)\s*-->/.exec(body);
93
+ if (legacyMatch) {
94
+ return {
95
+ pipelineId: Number(legacyMatch[1]),
96
+ mrIid: Number(legacyMatch[2])
97
+ };
98
+ }
99
+ return null;
100
+ }
101
+ function hasNextLinkHeader(resp) {
102
+ var _a, _b, _c, _d, _e, _f;
103
+ const link = ((_b = (_a = resp.headers) == null ? void 0 : _a.get) == null ? void 0 : _b.call(_a, "link")) || ((_d = (_c = resp.headers) == null ? void 0 : _c.get) == null ? void 0 : _d.call(_c, "Link")) || "";
104
+ if (link && /rel=["']?next["']?/i.test(link)) {
105
+ return true;
106
+ }
107
+ const nextPage = ((_f = (_e = resp.headers) == null ? void 0 : _e.get) == null ? void 0 : _f.call(_e, "x-next-page")) || "";
108
+ return Boolean(nextPage && Number(nextPage) > 0);
109
+ }
110
+ function parseGitWebhookPayload(headers, body) {
111
+ const payload = isPlainRecord(body) ? body : {};
112
+ const ghEvent = (headers["x-github-event"] || "").toLowerCase();
113
+ const glEvent = (headers["x-gitlab-event"] || "").toLowerCase();
114
+ if (ghEvent) {
115
+ const repoObj = isPlainRecord(payload.repository) ? payload.repository : {};
116
+ const repoUrl2 = typeof repoObj.html_url === "string" ? repoObj.html_url : void 0;
117
+ const projectPath2 = typeof repoObj.full_name === "string" ? repoObj.full_name : void 0;
118
+ const senderObj = isPlainRecord(payload.sender) ? payload.sender : {};
119
+ const sender2 = typeof senderObj.login === "string" ? senderObj.login : null;
120
+ if (ghEvent === "push") {
121
+ const ref = String(payload.ref || "");
122
+ if (!ref.startsWith("refs/heads/") || payload.deleted === true) {
123
+ return {
124
+ provider: "github",
125
+ eventType: "ignored",
126
+ branch: "",
127
+ commitSha: "",
128
+ reason: "Not an active branch push"
129
+ };
130
+ }
131
+ const branch = ref.slice("refs/heads/".length);
132
+ const afterSha = String(payload.after || "");
133
+ const headCommit = isPlainRecord(payload.head_commit) ? payload.head_commit : {};
134
+ return {
135
+ provider: "github",
136
+ eventType: "push",
137
+ repoUrl: repoUrl2,
138
+ projectPath: projectPath2,
139
+ branch,
140
+ commitSha: afterSha,
141
+ baseSha: typeof payload.before === "string" ? payload.before : null,
142
+ commitMessage: typeof headCommit.message === "string" ? headCommit.message : null,
143
+ sender: sender2
144
+ };
145
+ }
146
+ if (ghEvent === "pull_request") {
147
+ const action = String(payload.action || "");
148
+ const pr = isPlainRecord(payload.pull_request) ? payload.pull_request : {};
149
+ if (!["opened", "synchronize", "reopened"].includes(action) || pr.state === "closed") {
150
+ return {
151
+ provider: "github",
152
+ eventType: "ignored",
153
+ branch: "",
154
+ commitSha: "",
155
+ reason: `Unsupported PR action "${action}"`
156
+ };
157
+ }
158
+ const head = isPlainRecord(pr.head) ? pr.head : {};
159
+ const base = isPlainRecord(pr.base) ? pr.base : {};
160
+ return {
161
+ provider: "github",
162
+ eventType: "merge_request",
163
+ repoUrl: repoUrl2,
164
+ projectPath: projectPath2,
165
+ branch: String(head.ref || ""),
166
+ targetBranch: typeof base.ref === "string" ? base.ref : null,
167
+ commitSha: String(head.sha || ""),
168
+ baseSha: typeof base.sha === "string" ? base.sha : null,
169
+ commitMessage: typeof pr.title === "string" ? pr.title : null,
170
+ mrIid: typeof pr.number === "number" ? pr.number : Number(payload.number || 0) || null,
171
+ sender: sender2
172
+ };
173
+ }
174
+ return {
175
+ provider: "github",
176
+ eventType: "ignored",
177
+ branch: "",
178
+ commitSha: "",
179
+ reason: `Unhandled GitHub event "${ghEvent}"`
180
+ };
181
+ }
182
+ const objectKind = String(payload.object_kind || "");
183
+ const project = isPlainRecord(payload.project) ? payload.project : {};
184
+ const repoUrl = typeof project.web_url === "string" ? project.web_url : void 0;
185
+ const projectPath = typeof project.path_with_namespace === "string" ? project.path_with_namespace : void 0;
186
+ const userObj = isPlainRecord(payload.user) ? payload.user : {};
187
+ const sender = typeof userObj.username === "string" ? userObj.username : typeof payload.user_username === "string" ? payload.user_username : null;
188
+ if (objectKind === "push" || glEvent.includes("push")) {
189
+ const ref = String(payload.ref || "");
190
+ const after = String(payload.after || "");
191
+ if (!ref.startsWith("refs/heads/") || /^0+$/.test(after)) {
192
+ return {
193
+ provider: "gitlab",
194
+ eventType: "ignored",
195
+ branch: "",
196
+ commitSha: "",
197
+ reason: "Deleted or non-branch ref"
198
+ };
199
+ }
200
+ const commits = Array.isArray(payload.commits) ? payload.commits : [];
201
+ const lastCommit = commits.length > 0 && isPlainRecord(commits[commits.length - 1]) ? commits[commits.length - 1] : {};
202
+ return {
203
+ provider: "gitlab",
204
+ eventType: "push",
205
+ repoUrl,
206
+ projectPath,
207
+ branch: ref.slice("refs/heads/".length),
208
+ commitSha: after,
209
+ baseSha: typeof payload.before === "string" ? payload.before : null,
210
+ commitMessage: typeof lastCommit.message === "string" ? lastCommit.message : null,
211
+ sender
212
+ };
213
+ }
214
+ if (objectKind === "merge_request" || glEvent.includes("merge request")) {
215
+ const attrs = isPlainRecord(payload.object_attributes) ? payload.object_attributes : {};
216
+ const action = String(attrs.action || "open");
217
+ const state = String(attrs.state || "opened");
218
+ if (state !== "opened" || !["open", "update", "reopen"].includes(action)) {
219
+ return {
220
+ provider: "gitlab",
221
+ eventType: "ignored",
222
+ branch: "",
223
+ commitSha: "",
224
+ reason: `Ignored MR action="${action}" state="${state}"`
225
+ };
226
+ }
227
+ const lastCommit = isPlainRecord(attrs.last_commit) ? attrs.last_commit : {};
228
+ return {
229
+ provider: "gitlab",
230
+ eventType: "merge_request",
231
+ repoUrl,
232
+ projectPath,
233
+ branch: String(attrs.source_branch || ""),
234
+ targetBranch: typeof attrs.target_branch === "string" ? attrs.target_branch : null,
235
+ commitSha: String(lastCommit.id || attrs.last_commit_id || ""),
236
+ commitMessage: typeof attrs.title === "string" ? attrs.title : null,
237
+ mrIid: typeof attrs.iid === "number" ? attrs.iid : Number(attrs.iid || 0) || null,
238
+ sender
239
+ };
240
+ }
241
+ return {
242
+ provider: "gitlab",
243
+ eventType: "ignored",
244
+ branch: "",
245
+ commitSha: "",
246
+ reason: "Unrecognized webhook event payload"
247
+ };
248
+ }
249
+ class GitFeedbackService {
250
+ constructor(app) {
251
+ this.app = app;
252
+ }
253
+ fetchImpl = (url, init) => fetch(url, init);
254
+ setHttpFetch(fn) {
255
+ this.fetchImpl = fn;
256
+ }
257
+ async decryptSecret(raw) {
258
+ if (typeof raw !== "string" || !raw.trim()) return "";
259
+ const encryptor = this.app.aesEncryptor;
260
+ if (!encryptor) return raw.trim();
261
+ try {
262
+ return await encryptor.decrypt(raw.trim());
263
+ } catch {
264
+ return raw.trim();
265
+ }
266
+ }
267
+ async resolveRepoAuth(gitRepositoryId) {
268
+ if (!gitRepositoryId) return null;
269
+ try {
270
+ if (!this.app.db.getCollection(import_constants.GIT_REPOSITORIES_COLLECTION)) return null;
271
+ } catch {
272
+ return null;
273
+ }
274
+ const repo = await this.app.db.getRepository(import_constants.GIT_REPOSITORIES_COLLECTION).findOne({ filterByTk: gitRepositoryId });
275
+ if (!repo) return null;
276
+ const repoUrlRaw = String(repo.get("repoUrl") || "").trim();
277
+ if (!repoUrlRaw) return null;
278
+ const parsedRepoUrl = new URL(repoUrlRaw);
279
+ if (parsedRepoUrl.protocol !== "https:" && parsedRepoUrl.protocol !== "http:") {
280
+ throw new Error(`Unsupported Git repository URL protocol: ${parsedRepoUrl.protocol}`);
281
+ }
282
+ let pat = "";
283
+ let providerHint = "";
284
+ let accountBaseUrl = "";
285
+ const gitAccountId = repo.get("gitAccountId");
286
+ if ((typeof gitAccountId === "number" || typeof gitAccountId === "string") && this.hasCollection(import_constants.GIT_ACCOUNTS_COLLECTION)) {
287
+ const account = await this.app.db.getRepository(import_constants.GIT_ACCOUNTS_COLLECTION).findOne({ filterByTk: gitAccountId });
288
+ if (account) {
289
+ pat = await this.decryptSecret(account.get("pat"));
290
+ providerHint = String(account.get("provider") || "").toLowerCase();
291
+ accountBaseUrl = String(account.get("baseUrl") || "").trim();
292
+ }
293
+ }
294
+ const cleanPath = parsedRepoUrl.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
295
+ const isGitHub = providerHint === "github" || parsedRepoUrl.hostname === "github.com";
296
+ const origin = (accountBaseUrl || `${parsedRepoUrl.protocol}//${parsedRepoUrl.host}`).replace(/\/+$/, "");
297
+ const apiBase = isGitHub ? parsedRepoUrl.hostname === "github.com" ? "https://api.github.com" : `${origin}/api/v3` : `${origin}/api/v4`;
298
+ return {
299
+ provider: isGitHub ? "github" : "gitlab",
300
+ pat,
301
+ apiBase,
302
+ projectPath: cleanPath,
303
+ encodedProject: encodeURIComponent(cleanPath),
304
+ repoWebUrl: `${parsedRepoUrl.protocol}//${parsedRepoUrl.host}/${cleanPath}`
305
+ };
306
+ }
307
+ hasCollection(name) {
308
+ try {
309
+ return Boolean(this.app.db.getCollection(name));
310
+ } catch {
311
+ return false;
312
+ }
313
+ }
314
+ async verifyBranchHeadSha(params) {
315
+ var _a, _b;
316
+ const auth = await this.resolveRepoAuth(params.gitRepositoryId);
317
+ if (!auth || !auth.pat) {
318
+ return {
319
+ verified: false,
320
+ configured: false,
321
+ detail: "Git repository PAT is not configured for remote branch HEAD verification"
322
+ };
323
+ }
324
+ const encodedBranch = encodeURIComponent(params.branch.trim());
325
+ try {
326
+ if (auth.provider === "github") {
327
+ const resp2 = await this.fetchImpl(`${auth.apiBase}/repos/${auth.projectPath}/branches/${encodedBranch}`, {
328
+ method: "GET",
329
+ headers: {
330
+ Authorization: `Bearer ${auth.pat}`,
331
+ Accept: "application/vnd.github.v3+json"
332
+ }
333
+ });
334
+ if (!resp2.ok) {
335
+ return {
336
+ verified: false,
337
+ configured: true,
338
+ detail: `GitHub branch API returned HTTP ${resp2.status} for branch "${params.branch}"`
339
+ };
340
+ }
341
+ const data2 = await resp2.json();
342
+ const headSha2 = String(((_a = data2 == null ? void 0 : data2.commit) == null ? void 0 : _a.sha) || "").trim();
343
+ return {
344
+ verified: Boolean(headSha2 && headSha2 === params.expectedSha),
345
+ configured: true,
346
+ actualHeadSha: headSha2 || null,
347
+ detail: headSha2 === params.expectedSha ? `Verified GitHub branch "${params.branch}" HEAD matches ${headSha2.slice(0, 12)}` : `Branch "${params.branch}" HEAD is ${headSha2.slice(0, 12)}, expected ${params.expectedSha.slice(
348
+ 0,
349
+ 12
350
+ )}`
351
+ };
352
+ }
353
+ const resp = await this.fetchImpl(
354
+ `${auth.apiBase}/projects/${auth.encodedProject}/repository/branches/${encodedBranch}`,
355
+ {
356
+ method: "GET",
357
+ headers: {
358
+ "PRIVATE-TOKEN": auth.pat,
359
+ Accept: "application/json"
360
+ }
361
+ }
362
+ );
363
+ if (!resp.ok) {
364
+ return {
365
+ verified: false,
366
+ configured: true,
367
+ detail: `GitLab branch API returned HTTP ${resp.status} for branch "${params.branch}"`
368
+ };
369
+ }
370
+ const data = await resp.json();
371
+ const headSha = String(((_b = data == null ? void 0 : data.commit) == null ? void 0 : _b.id) || "").trim();
372
+ return {
373
+ verified: Boolean(headSha && headSha === params.expectedSha),
374
+ configured: true,
375
+ actualHeadSha: headSha || null,
376
+ detail: headSha === params.expectedSha ? `Verified GitLab branch "${params.branch}" HEAD matches ${headSha.slice(0, 12)}` : `Branch "${params.branch}" HEAD is ${headSha.slice(0, 12)}, expected ${params.expectedSha.slice(0, 12)}`
377
+ };
378
+ } catch (error) {
379
+ return {
380
+ verified: false,
381
+ configured: true,
382
+ detail: `Failed querying branch HEAD from Git API: ${error instanceof Error ? error.message : String(error)}`
383
+ };
384
+ }
385
+ }
386
+ async enqueueOutboxItem(params) {
387
+ if (!params.gateRunId || !params.pipelineId || !this.hasCollection(import_constants.CI_GIT_FEEDBACK_OUTBOX_COLLECTION)) {
388
+ return;
389
+ }
390
+ const repo = this.app.db.getRepository(import_constants.CI_GIT_FEEDBACK_OUTBOX_COLLECTION);
391
+ const existing = await repo.findOne({
392
+ filter: {
393
+ gateRunId: params.gateRunId,
394
+ kind: params.kind,
395
+ status: "pending"
396
+ }
397
+ }).catch(() => null);
398
+ const nextRetryAt = new Date(Date.now() + 15e3).toISOString();
399
+ if (existing) {
400
+ await existing.update({
401
+ payload: params.payload,
402
+ lastError: params.lastError.slice(0, 1e3),
403
+ nextRetryAt
404
+ }).catch(() => void 0);
405
+ return;
406
+ }
407
+ await repo.create({
408
+ values: {
409
+ gateRunId: params.gateRunId,
410
+ pipelineId: params.pipelineId,
411
+ gitRepositoryId: params.gitRepositoryId ?? null,
412
+ kind: params.kind,
413
+ payload: params.payload,
414
+ status: "pending",
415
+ attempts: 1,
416
+ nextRetryAt,
417
+ lastError: params.lastError.slice(0, 1e3)
418
+ }
419
+ }).catch(() => void 0);
420
+ }
421
+ async publishCommitStatus(params) {
422
+ const auth = await this.resolveRepoAuth(params.gitRepositoryId);
423
+ if (!auth || !auth.pat || !params.commitSha) {
424
+ return { published: false, detail: "Git repository or PAT not configured; skipped commit status" };
425
+ }
426
+ const desc = params.description.slice(0, 138);
427
+ try {
428
+ if (auth.provider === "github") {
429
+ const resp2 = await this.fetchImpl(`${auth.apiBase}/repos/${auth.projectPath}/statuses/${params.commitSha}`, {
430
+ method: "POST",
431
+ headers: {
432
+ Authorization: `Bearer ${auth.pat}`,
433
+ Accept: "application/vnd.github.v3+json",
434
+ "Content-Type": "application/json"
435
+ },
436
+ body: JSON.stringify({
437
+ state: params.state,
438
+ context: params.context || "nocobase/ci-test-manager",
439
+ description: desc,
440
+ ...params.targetUrl ? { target_url: params.targetUrl } : {}
441
+ })
442
+ });
443
+ if (!resp2.ok) {
444
+ const errDetail = `GitHub status API returned HTTP ${resp2.status}`;
445
+ if (!params.skipOutboxOnError) {
446
+ await this.enqueueOutboxItem({
447
+ gateRunId: params.gateRunId,
448
+ pipelineId: params.pipelineId,
449
+ gitRepositoryId: params.gitRepositoryId,
450
+ kind: "commit_status",
451
+ payload: {
452
+ gitRepositoryId: params.gitRepositoryId ?? null,
453
+ commitSha: params.commitSha,
454
+ branch: params.branch ?? null,
455
+ state: params.state,
456
+ context: params.context,
457
+ description: desc,
458
+ targetUrl: params.targetUrl ?? null
459
+ },
460
+ lastError: errDetail
461
+ });
462
+ }
463
+ return { published: false, queuedRetry: !params.skipOutboxOnError, provider: "github", detail: errDetail };
464
+ }
465
+ return { published: true, provider: "github", detail: `Published GitHub commit status "${params.state}"` };
466
+ }
467
+ const glState = params.state === "pending" ? "running" : params.state === "success" ? "success" : "failed";
468
+ const resp = await this.fetchImpl(
469
+ `${auth.apiBase}/projects/${auth.encodedProject}/statuses/${params.commitSha}`,
470
+ {
471
+ method: "POST",
472
+ headers: {
473
+ "PRIVATE-TOKEN": auth.pat,
474
+ Accept: "application/json",
475
+ "Content-Type": "application/json"
476
+ },
477
+ body: JSON.stringify({
478
+ state: glState,
479
+ name: params.context || "nocobase/ci-test-manager",
480
+ description: desc,
481
+ ...params.branch ? { ref: params.branch } : {},
482
+ ...params.targetUrl ? { target_url: params.targetUrl } : {}
483
+ })
484
+ }
485
+ );
486
+ if (!resp.ok) {
487
+ const errDetail = `GitLab status API returned HTTP ${resp.status}`;
488
+ if (!params.skipOutboxOnError) {
489
+ await this.enqueueOutboxItem({
490
+ gateRunId: params.gateRunId,
491
+ pipelineId: params.pipelineId,
492
+ gitRepositoryId: params.gitRepositoryId,
493
+ kind: "commit_status",
494
+ payload: {
495
+ gitRepositoryId: params.gitRepositoryId ?? null,
496
+ commitSha: params.commitSha,
497
+ branch: params.branch ?? null,
498
+ state: params.state,
499
+ context: params.context,
500
+ description: desc,
501
+ targetUrl: params.targetUrl ?? null
502
+ },
503
+ lastError: errDetail
504
+ });
505
+ }
506
+ return { published: false, queuedRetry: !params.skipOutboxOnError, provider: "gitlab", detail: errDetail };
507
+ }
508
+ return { published: true, provider: "gitlab", detail: `Published GitLab commit status "${glState}"` };
509
+ } catch (error) {
510
+ const errDetail = `Commit status HTTP request failed: ${error instanceof Error ? error.message : String(error)}`;
511
+ if (!params.skipOutboxOnError) {
512
+ await this.enqueueOutboxItem({
513
+ gateRunId: params.gateRunId,
514
+ pipelineId: params.pipelineId,
515
+ gitRepositoryId: params.gitRepositoryId,
516
+ kind: "commit_status",
517
+ payload: {
518
+ gitRepositoryId: params.gitRepositoryId ?? null,
519
+ commitSha: params.commitSha,
520
+ branch: params.branch ?? null,
521
+ state: params.state,
522
+ context: params.context,
523
+ description: desc,
524
+ targetUrl: params.targetUrl ?? null
525
+ },
526
+ lastError: errDetail
527
+ });
528
+ }
529
+ return { published: false, queuedRetry: !params.skipOutboxOnError, detail: errDetail };
530
+ }
531
+ }
532
+ buildStickyCommentMarkdown(params) {
533
+ var _a, _b, _c, _d, _e;
534
+ const marker = `<!-- nocobase-ci:pipeline=${params.pipeline.key};pipelineId=${params.pipeline.id};mr=${params.gateRun.mrIid ?? 0};gateRun=${params.gateRun.id};sha=${params.gateRun.commitSha} -->`;
535
+ const verdict = String(((_a = params.testRun) == null ? void 0 : _a.verdict) || params.gateRun.testVerdict || params.gateRun.state).toUpperCase();
536
+ const approvalState = String(params.gateRun.approvalState || "not_required").toUpperCase();
537
+ const deployOutcome = String(params.gateRun.deployOutcome || "not_applicable").toUpperCase();
538
+ const reasonCode = String(((_b = params.testRun) == null ? void 0 : _b.verdictReasonCode) || params.gateRun.verdictReasonCode || "");
539
+ const badge = verdict === "PASSED" ? "\u2705 PASSED" : verdict === "DIFF_MISMATCH" && approvalState === "APPROVED" ? "\u2705 DIFF MISMATCH (QA APPROVED)" : verdict === "DIFF_MISMATCH" ? "\u26A0\uFE0F DIFF MISMATCH" : verdict === "CANCELED" ? "\u26AA CANCELED" : `\u274C ${verdict}`;
540
+ const metrics = isPlainRecord((_c = params.testRun) == null ? void 0 : _c.summaryMetrics) ? params.testRun.summaryMetrics : {};
541
+ const total = Number(metrics.total ?? 0);
542
+ const passed = Number(metrics.passed ?? 0);
543
+ const flaky = Number(metrics.flaky ?? 0);
544
+ const diffMismatch = Number(metrics.diffMismatch ?? 0);
545
+ const failed = Number(metrics.failed ?? 0);
546
+ const skipped = Number(metrics.skipped ?? 0);
547
+ const durationMs = Number(metrics.durationMs ?? ((_d = params.testRun) == null ? void 0 : _d.durationMs) ?? 0);
548
+ const schemaUsed = String(((_e = params.testRun) == null ? void 0 : _e.ephemeralSchemaName) || "tenant-default");
549
+ const lines = [
550
+ marker,
551
+ `### NocoBase CI Quality Gate \u2014 ${badge}`,
552
+ "",
553
+ `| Pipeline | Commit | Branch | Test Verdict | Approval | Deploy | Schema | Duration |`,
554
+ `| --- | --- | --- | --- | --- | --- | --- | --- |`,
555
+ `| **${params.pipeline.name}** | \`${params.gateRun.commitSha.slice(0, 8)}\` | \`${params.gateRun.branch}\` | \`${verdict}${reasonCode ? ` (${reasonCode})` : ""}\` | \`${approvalState}\` | \`${deployOutcome}\` | \`${schemaUsed}\` | ${(durationMs / 1e3).toFixed(1)}s |`,
556
+ "",
557
+ `| Total | Passed | Flaky | Diff Mismatch | Failed | Skipped |`,
558
+ `| :---: | :---: | :---: | :---: | :---: | :---: |`,
559
+ `| ${total} | ${passed} | ${flaky} | ${diffMismatch} | ${failed} | ${skipped} |`
560
+ ];
561
+ if (params.triage) {
562
+ lines.push(
563
+ "",
564
+ `#### \u{1F916} AI Failure Triage (\`${params.triage.classification}\`, confidence ${Math.round(
565
+ params.triage.confidence * 100
566
+ )}%)`,
567
+ `- **Root Cause:** ${params.triage.rootCause}`,
568
+ `- **Suggested Action:** ${params.triage.suggestedAction}`
569
+ );
570
+ if (Array.isArray(params.triage.suspectedFiles) && params.triage.suspectedFiles.length > 0) {
571
+ lines.push(`- **Suspected Files:** ${params.triage.suspectedFiles.map((f) => `\`${f}\``).join(", ")}`);
572
+ }
573
+ }
574
+ if (params.workbenchUrl) {
575
+ lines.push("", `[\u{1F50D} Inspect Multi-Layer Diff & Artifacts in NocoBase](${params.workbenchUrl})`);
576
+ }
577
+ return { marker, markdown: lines.join("\n") };
578
+ }
579
+ findMatchingCommentInPage(items, pipeline, mrIid) {
580
+ for (const item of items) {
581
+ if (!(item == null ? void 0 : item.id) || typeof item.body !== "string") continue;
582
+ const parsed = parseStickyCommentVersionMarker(item.body);
583
+ if (!parsed) continue;
584
+ const matchesPipeline = parsed.pipelineKey && parsed.pipelineKey === pipeline.key || parsed.pipelineId && parsed.pipelineId === pipeline.id;
585
+ const matchesMr = !parsed.mrIid || parsed.mrIid === mrIid;
586
+ if (matchesPipeline && matchesMr) {
587
+ return { id: String(item.id), gateRunId: parsed.gateRunId };
588
+ }
589
+ }
590
+ return null;
591
+ }
592
+ async upsertStickyPrComment(params) {
593
+ const mrIid = params.gateRun.mrIid;
594
+ if (!mrIid || mrIid <= 0) {
595
+ return { published: false, detail: "No MR/PR number associated with this CI run" };
596
+ }
597
+ const auth = await this.resolveRepoAuth(params.gateRun.gitRepositoryId ?? params.pipeline.gitRepositoryId);
598
+ if (!auth || !auth.pat) {
599
+ return { published: false, detail: "Git repository PAT unavailable; skipped PR comment" };
600
+ }
601
+ const { markdown } = this.buildStickyCommentMarkdown(params);
602
+ try {
603
+ if (auth.provider === "github") {
604
+ const headers2 = {
605
+ Authorization: `Bearer ${auth.pat}`,
606
+ Accept: "application/vnd.github.v3+json",
607
+ "Content-Type": "application/json"
608
+ };
609
+ let existingId = params.gateRun.prCommentId || "";
610
+ let existingGateRunId2;
611
+ for (let page = 1; page <= MAX_COMMENT_PAGES; page += 1) {
612
+ const listResp = await this.fetchImpl(
613
+ `${auth.apiBase}/repos/${auth.projectPath}/issues/${mrIid}/comments?per_page=${COMMENTS_PER_PAGE}&page=${page}`,
614
+ { method: "GET", headers: headers2 }
615
+ );
616
+ if (!listResp.ok) break;
617
+ const comments = await listResp.json();
618
+ if (!Array.isArray(comments) || comments.length === 0) break;
619
+ const matched = this.findMatchingCommentInPage(comments, params.pipeline, mrIid);
620
+ if (matched) {
621
+ existingId = matched.id;
622
+ existingGateRunId2 = matched.gateRunId;
623
+ break;
624
+ }
625
+ if (comments.length < COMMENTS_PER_PAGE && !hasNextLinkHeader(listResp)) {
626
+ break;
627
+ }
628
+ }
629
+ if (existingGateRunId2 && existingGateRunId2 > params.gateRun.id) {
630
+ return {
631
+ published: false,
632
+ skippedStale: true,
633
+ commentId: existingId,
634
+ detail: `Skipped overwriting sticky comment because newer gate run #${existingGateRunId2} already published`
635
+ };
636
+ }
637
+ if (existingId) {
638
+ const patchResp = await this.fetchImpl(
639
+ `${auth.apiBase}/repos/${auth.projectPath}/issues/comments/${existingId}`,
640
+ {
641
+ method: "PATCH",
642
+ headers: headers2,
643
+ body: JSON.stringify({ body: markdown })
644
+ }
645
+ );
646
+ if (patchResp.ok) {
647
+ return { published: true, commentId: existingId, detail: `Updated GitHub PR #${mrIid} comment` };
648
+ }
649
+ }
650
+ const createResp2 = await this.fetchImpl(`${auth.apiBase}/repos/${auth.projectPath}/issues/${mrIid}/comments`, {
651
+ method: "POST",
652
+ headers: headers2,
653
+ body: JSON.stringify({ body: markdown })
654
+ });
655
+ if (!createResp2.ok) {
656
+ const errDetail = `Failed to post GitHub PR comment (HTTP ${createResp2.status})`;
657
+ if (!params.skipOutboxOnError) {
658
+ await this.enqueueOutboxItem({
659
+ gateRunId: params.gateRun.id,
660
+ pipelineId: params.pipeline.id,
661
+ gitRepositoryId: params.gateRun.gitRepositoryId ?? params.pipeline.gitRepositoryId,
662
+ kind: "sticky_comment",
663
+ payload: { workbenchUrl: params.workbenchUrl ?? null },
664
+ lastError: errDetail
665
+ });
666
+ }
667
+ return { published: false, queuedRetry: !params.skipOutboxOnError, detail: errDetail };
668
+ }
669
+ const created2 = await createResp2.json();
670
+ return {
671
+ published: true,
672
+ commentId: created2.id ? String(created2.id) : void 0,
673
+ detail: `Created GitHub PR #${mrIid} sticky summary comment`
674
+ };
675
+ }
676
+ const headers = {
677
+ "PRIVATE-TOKEN": auth.pat,
678
+ Accept: "application/json",
679
+ "Content-Type": "application/json"
680
+ };
681
+ let existingNoteId = params.gateRun.prCommentId || "";
682
+ let existingGateRunId;
683
+ for (let page = 1; page <= MAX_COMMENT_PAGES; page += 1) {
684
+ const listResp = await this.fetchImpl(
685
+ `${auth.apiBase}/projects/${auth.encodedProject}/merge_requests/${mrIid}/notes?per_page=${COMMENTS_PER_PAGE}&page=${page}`,
686
+ { method: "GET", headers }
687
+ );
688
+ if (!listResp.ok) break;
689
+ const notes = await listResp.json();
690
+ if (!Array.isArray(notes) || notes.length === 0) break;
691
+ const matched = this.findMatchingCommentInPage(notes, params.pipeline, mrIid);
692
+ if (matched) {
693
+ existingNoteId = matched.id;
694
+ existingGateRunId = matched.gateRunId;
695
+ break;
696
+ }
697
+ if (notes.length < COMMENTS_PER_PAGE && !hasNextLinkHeader(listResp)) {
698
+ break;
699
+ }
700
+ }
701
+ if (existingGateRunId && existingGateRunId > params.gateRun.id) {
702
+ return {
703
+ published: false,
704
+ skippedStale: true,
705
+ commentId: existingNoteId,
706
+ detail: `Skipped overwriting GitLab MR note because newer gate run #${existingGateRunId} already published`
707
+ };
708
+ }
709
+ if (existingNoteId) {
710
+ const putResp = await this.fetchImpl(
711
+ `${auth.apiBase}/projects/${auth.encodedProject}/merge_requests/${mrIid}/notes/${existingNoteId}`,
712
+ {
713
+ method: "PUT",
714
+ headers,
715
+ body: JSON.stringify({ body: markdown })
716
+ }
717
+ );
718
+ if (putResp.ok) {
719
+ return { published: true, commentId: existingNoteId, detail: `Updated GitLab MR !${mrIid} note` };
720
+ }
721
+ }
722
+ const createResp = await this.fetchImpl(
723
+ `${auth.apiBase}/projects/${auth.encodedProject}/merge_requests/${mrIid}/notes`,
724
+ {
725
+ method: "POST",
726
+ headers,
727
+ body: JSON.stringify({ body: markdown })
728
+ }
729
+ );
730
+ if (!createResp.ok) {
731
+ const errDetail = `Failed to post GitLab MR note (HTTP ${createResp.status})`;
732
+ if (!params.skipOutboxOnError) {
733
+ await this.enqueueOutboxItem({
734
+ gateRunId: params.gateRun.id,
735
+ pipelineId: params.pipeline.id,
736
+ gitRepositoryId: params.gateRun.gitRepositoryId ?? params.pipeline.gitRepositoryId,
737
+ kind: "sticky_comment",
738
+ payload: { workbenchUrl: params.workbenchUrl ?? null },
739
+ lastError: errDetail
740
+ });
741
+ }
742
+ return { published: false, queuedRetry: !params.skipOutboxOnError, detail: errDetail };
743
+ }
744
+ const created = await createResp.json();
745
+ return {
746
+ published: true,
747
+ commentId: created.id ? String(created.id) : void 0,
748
+ detail: `Created GitLab MR !${mrIid} sticky summary note`
749
+ };
750
+ } catch (error) {
751
+ const errDetail = `Sticky comment HTTP error: ${error instanceof Error ? error.message : String(error)}`;
752
+ if (!params.skipOutboxOnError) {
753
+ await this.enqueueOutboxItem({
754
+ gateRunId: params.gateRun.id,
755
+ pipelineId: params.pipeline.id,
756
+ gitRepositoryId: params.gateRun.gitRepositoryId ?? params.pipeline.gitRepositoryId,
757
+ kind: "sticky_comment",
758
+ payload: { workbenchUrl: params.workbenchUrl ?? null },
759
+ lastError: errDetail
760
+ });
761
+ }
762
+ return { published: false, queuedRetry: !params.skipOutboxOnError, detail: errDetail };
763
+ }
764
+ }
765
+ async flushOutboxBatch(loadTestRun, limit = 15) {
766
+ if (!this.hasCollection(import_constants.CI_GIT_FEEDBACK_OUTBOX_COLLECTION)) return 0;
767
+ const repo = this.app.db.getRepository(import_constants.CI_GIT_FEEDBACK_OUTBOX_COLLECTION);
768
+ const nowIso = (/* @__PURE__ */ new Date()).toISOString();
769
+ const dueRows = await repo.find({
770
+ filter: {
771
+ status: "pending",
772
+ $or: [{ nextRetryAt: null }, { nextRetryAt: { $lte: nowIso } }]
773
+ },
774
+ sort: ["id"],
775
+ limit
776
+ }).catch(() => []);
777
+ let deliveredCount = 0;
778
+ for (const item of dueRows) {
779
+ const gateRunId = Number(item.get("gateRunId") || 0);
780
+ const pipelineId = Number(item.get("pipelineId") || 0);
781
+ const kind = String(item.get("kind") || "");
782
+ const attempts = Number(item.get("attempts") || 1);
783
+ const payload = isPlainRecord(item.get("payload")) ? item.get("payload") : {};
784
+ const gateModel = await this.app.db.getRepository(import_constants.CI_GATE_RUNS_COLLECTION).findOne({ filterByTk: gateRunId }).catch(() => null);
785
+ const pipeModel = await this.app.db.getRepository(import_constants.CI_PIPELINES_COLLECTION).findOne({ filterByTk: pipelineId }).catch(() => null);
786
+ if (!gateModel || !pipeModel) {
787
+ await item.update({ status: "exhausted", lastError: "Gate run or pipeline deleted" }).catch(() => void 0);
788
+ continue;
789
+ }
790
+ const gateRun = gateModel.toJSON();
791
+ const pipeline = pipeModel.toJSON();
792
+ let ok = false;
793
+ let errText = "";
794
+ if (kind === "commit_status") {
795
+ const res = await this.publishCommitStatus({
796
+ gitRepositoryId: Number(payload.gitRepositoryId || gateRun.gitRepositoryId || pipeline.gitRepositoryId || 0) || null,
797
+ commitSha: String(payload.commitSha || gateRun.commitSha),
798
+ branch: payload.branch ? String(payload.branch) : gateRun.branch,
799
+ state: payload.state || "error",
800
+ context: String(payload.context || pipeline.statusContext || "nocobase/ci-test-manager"),
801
+ description: String(payload.description || ""),
802
+ targetUrl: payload.targetUrl ? String(payload.targetUrl) : void 0,
803
+ skipOutboxOnError: true
804
+ });
805
+ ok = res.published;
806
+ errText = res.detail;
807
+ if (ok) {
808
+ await gateModel.update({
809
+ commitStatusState: payload.state || gateRun.commitStatusState,
810
+ gitFeedbackSyncState: "synced"
811
+ }).catch(() => void 0);
812
+ }
813
+ } else if (kind === "sticky_comment") {
814
+ const testRun = gateRun.testRunId ? await loadTestRun(gateRun.testRunId) : null;
815
+ const res = await this.upsertStickyPrComment({
816
+ pipeline,
817
+ gateRun,
818
+ testRun,
819
+ triage: gateRun.triageResult ?? null,
820
+ workbenchUrl: payload.workbenchUrl ? String(payload.workbenchUrl) : void 0,
821
+ skipOutboxOnError: true
822
+ });
823
+ ok = res.published || Boolean(res.skippedStale);
824
+ errText = res.detail;
825
+ if (ok) {
826
+ await gateModel.update({
827
+ ...res.commentId ? { prCommentId: res.commentId } : {},
828
+ gitFeedbackSyncState: "synced"
829
+ }).catch(() => void 0);
830
+ }
831
+ }
832
+ if (ok) {
833
+ deliveredCount += 1;
834
+ await item.update({ status: "delivered", lastError: null }).catch(() => void 0);
835
+ } else {
836
+ const nextAttempts = attempts + 1;
837
+ if (nextAttempts > MAX_OUTBOX_ATTEMPTS) {
838
+ await item.update({ status: "exhausted", attempts: nextAttempts, lastError: errText }).catch(() => void 0);
839
+ await gateModel.update({ gitFeedbackSyncState: "failed" }).catch(() => void 0);
840
+ } else {
841
+ const backoffMs = Math.min(3e5, 15e3 * 2 ** (nextAttempts - 1));
842
+ await item.update({
843
+ attempts: nextAttempts,
844
+ nextRetryAt: new Date(Date.now() + backoffMs).toISOString(),
845
+ lastError: errText
846
+ }).catch(() => void 0);
847
+ }
848
+ }
849
+ }
850
+ return deliveredCount;
851
+ }
852
+ hasAttr(collectionName, attrName) {
853
+ var _a, _b, _c;
854
+ try {
855
+ const col = this.app.db.getCollection(collectionName);
856
+ return Boolean(((_a = col == null ? void 0 : col.getField) == null ? void 0 : _a.call(col, attrName)) || ((_c = (_b = col == null ? void 0 : col.model) == null ? void 0 : _b.rawAttributes) == null ? void 0 : _c[attrName]));
857
+ } catch {
858
+ return false;
859
+ }
860
+ }
861
+ async enrichPendingGitReviewRequests(params) {
862
+ var _a, _b;
863
+ if (!params.gitRepositoryId) {
864
+ return 0;
865
+ }
866
+ const verdict = String(((_a = params.testRun) == null ? void 0 : _a.verdict) || "unknown");
867
+ const metrics = isPlainRecord((_b = params.testRun) == null ? void 0 : _b.summaryMetrics) ? params.testRun.summaryMetrics : {};
868
+ const ciContextLine = [
869
+ `[NocoBase CI Verdict on ${params.commitSha.slice(0, 8)}]`,
870
+ `verdict=${verdict}, passed=${Number(metrics.passed ?? 0)}, failed=${Number(
871
+ metrics.failed ?? 0
872
+ )}, diffMismatch=${Number(metrics.diffMismatch ?? 0)}, flaky=${Number(metrics.flaky ?? 0)}.`,
873
+ params.triage ? `AI Triage (${params.triage.classification}): ${params.triage.rootCause}` : ""
874
+ ].filter(Boolean).join(" ");
875
+ let enriched = 0;
876
+ if (this.hasAttr("gitCodeReviews", "repositoryId") && this.hasAttr("gitCodeReviews", "metadata")) {
877
+ const reviewFilter = {
878
+ repositoryId: params.gitRepositoryId,
879
+ ...params.mrIid && this.hasAttr("gitCodeReviews", "mrIid") ? { mrIid: params.mrIid } : {},
880
+ ...this.hasAttr("gitCodeReviews", "headSha") ? { headSha: params.commitSha } : this.hasAttr("gitCodeReviews", "commitSha") ? { commitSha: params.commitSha } : {}
881
+ };
882
+ const reviewModels = await this.app.db.getRepository("gitCodeReviews").find({
883
+ filter: reviewFilter,
884
+ limit: 10
885
+ });
886
+ for (const revModel of reviewModels) {
887
+ const status = String(revModel.get("status") || "");
888
+ if (status === "completed" || status === "approved") continue;
889
+ const meta = isPlainRecord(revModel.get("metadata")) ? { ...revModel.get("metadata") } : {};
890
+ meta.ciSummary = ciContextLine;
891
+ meta.ciVerdict = verdict;
892
+ await revModel.update({ metadata: meta });
893
+ enriched += 1;
894
+ if (this.hasAttr("gitReviewInbox", "reviewId") && this.hasAttr("gitReviewInbox", "payload")) {
895
+ const inboxRows = await this.app.db.getRepository("gitReviewInbox").find({
896
+ filter: { repositoryId: params.gitRepositoryId, reviewId: revModel.get("id"), state: "queued" },
897
+ limit: 5
898
+ });
899
+ for (const inbox of inboxRows) {
900
+ const payload = isPlainRecord(inbox.get("payload")) ? { ...inbox.get("payload") } : {};
901
+ const existingInst = typeof payload.instructions === "string" ? payload.instructions : "";
902
+ if (!existingInst.includes("[NocoBase CI Verdict on")) {
903
+ payload.instructions = existingInst ? `${existingInst}
904
+
905
+ ${ciContextLine}` : ciContextLine;
906
+ await inbox.update({ payload });
907
+ }
908
+ }
909
+ }
910
+ }
911
+ }
912
+ if (this.hasAttr(import_constants.GIT_REVIEW_REQUESTS_COLLECTION, "headSha") && this.hasAttr(import_constants.GIT_REVIEW_REQUESTS_COLLECTION, "payload")) {
913
+ const reqRepo = this.app.db.getRepository(import_constants.GIT_REVIEW_REQUESTS_COLLECTION);
914
+ const candidates = await reqRepo.find({
915
+ filter: {
916
+ repositoryId: params.gitRepositoryId,
917
+ ...params.mrIid && this.hasAttr(import_constants.GIT_REVIEW_REQUESTS_COLLECTION, "mrIid") ? { mrIid: params.mrIid } : {},
918
+ headSha: params.commitSha
919
+ },
920
+ limit: 10
921
+ });
922
+ for (const reqModel of candidates) {
923
+ if (reqModel.get("executionId")) continue;
924
+ const payload = isPlainRecord(reqModel.get("payload")) ? { ...reqModel.get("payload") } : {};
925
+ const existingInstructions = typeof payload.instructions === "string" ? payload.instructions : "";
926
+ if (existingInstructions.includes("[NocoBase CI Verdict on")) continue;
927
+ payload.instructions = existingInstructions ? `${existingInstructions}
928
+
929
+ ${ciContextLine}` : ciContextLine;
930
+ await reqModel.update({ payload });
931
+ enriched += 1;
932
+ }
933
+ }
934
+ return enriched;
935
+ }
936
+ async listOpenMergeRequests(gitRepositoryId) {
937
+ const auth = await this.resolveRepoAuth(gitRepositoryId);
938
+ if (!auth || !auth.pat) return [];
939
+ if (auth.provider === "github") {
940
+ const resp2 = await this.fetchImpl(
941
+ `${auth.apiBase}/repos/${auth.projectPath}/pulls?state=open&per_page=25&sort=updated&direction=desc`,
942
+ {
943
+ method: "GET",
944
+ headers: {
945
+ Authorization: `Bearer ${auth.pat}`,
946
+ Accept: "application/vnd.github.v3+json"
947
+ }
948
+ }
949
+ );
950
+ if (!resp2.ok) return [];
951
+ const prs = await resp2.json();
952
+ return prs.filter((pr) => {
953
+ var _a, _b;
954
+ return Boolean(pr.number && ((_a = pr.head) == null ? void 0 : _a.sha) && ((_b = pr.head) == null ? void 0 : _b.ref));
955
+ }).map((pr) => {
956
+ var _a, _b, _c;
957
+ return {
958
+ mrIid: Number(pr.number),
959
+ sourceBranch: String(((_a = pr.head) == null ? void 0 : _a.ref) || ""),
960
+ targetBranch: String(((_b = pr.base) == null ? void 0 : _b.ref) || "main"),
961
+ headSha: String(((_c = pr.head) == null ? void 0 : _c.sha) || ""),
962
+ title: String(pr.title || "")
963
+ };
964
+ });
965
+ }
966
+ const resp = await this.fetchImpl(
967
+ `${auth.apiBase}/projects/${auth.encodedProject}/merge_requests?state=opened&per_page=25&order_by=updated_at&sort=desc`,
968
+ {
969
+ method: "GET",
970
+ headers: {
971
+ "PRIVATE-TOKEN": auth.pat,
972
+ Accept: "application/json"
973
+ }
974
+ }
975
+ );
976
+ if (!resp.ok) return [];
977
+ const mrs = await resp.json();
978
+ return mrs.filter((mr) => Boolean(mr.iid && mr.sha && mr.source_branch)).map((mr) => ({
979
+ mrIid: Number(mr.iid),
980
+ sourceBranch: String(mr.source_branch || ""),
981
+ targetBranch: String(mr.target_branch || "main"),
982
+ headSha: String(mr.sha || ""),
983
+ title: String(mr.title || "")
984
+ }));
985
+ }
986
+ }
987
+ // Annotate the CommonJS export names for ESM import in node:
988
+ 0 && (module.exports = {
989
+ GitFeedbackService,
990
+ matchesBranchPattern,
991
+ parseGitWebhookPayload,
992
+ parseStickyCommentVersionMarker,
993
+ verifyConstantTimeSecret,
994
+ verifyGitHubHmacSignature
995
+ });