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,1776 @@
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 CiGateWorkflowService_exports = {};
28
+ __export(CiGateWorkflowService_exports, {
29
+ CiGateWorkflowService: () => CiGateWorkflowService,
30
+ isPureBaselineDiffMismatch: () => isPureBaselineDiffMismatch
31
+ });
32
+ module.exports = __toCommonJS(CiGateWorkflowService_exports);
33
+ var import_node_crypto = require("node:crypto");
34
+ var import_plugin_workflow = require("@nocobase/plugin-workflow");
35
+ var import_constants_internal = require("./constants-internal");
36
+ var import_GitFeedbackService = require("./GitFeedbackService");
37
+ function isPlainRecord(val) {
38
+ return Boolean(val) && typeof val === "object" && !Array.isArray(val);
39
+ }
40
+ function canonicalJson(val) {
41
+ if (val === null || val === void 0) return "null";
42
+ if (typeof val !== "object") return JSON.stringify(val);
43
+ if (Array.isArray(val)) return `[${val.map(canonicalJson).join(",")}]`;
44
+ const rec = val;
45
+ const keys = Object.keys(rec).sort();
46
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(rec[k])}`).join(",")}}`;
47
+ }
48
+ function isPureBaselineDiffMismatch(testRun) {
49
+ if (!testRun) return false;
50
+ const verdict = String(testRun.verdict || "");
51
+ if (verdict !== "diff_mismatch") return false;
52
+ const reasonCode = testRun.verdictReasonCode ? String(testRun.verdictReasonCode) : "";
53
+ if (reasonCode && reasonCode !== "DIFF_MISMATCH_ONLY" && reasonCode !== "BASELINE_DIFF_MISMATCH") {
54
+ return false;
55
+ }
56
+ const metrics = isPlainRecord(testRun.summaryMetrics) ? testRun.summaryMetrics : {};
57
+ const total = Number(metrics.total ?? 0);
58
+ const executed = Number(metrics.executed ?? total - Number(metrics.skipped ?? 0));
59
+ const failed = Number(metrics.failed ?? 0);
60
+ const flaky = Number(metrics.flaky ?? 0);
61
+ const diffMismatch = Number(metrics.diffMismatch ?? 0);
62
+ return total > 0 && executed > 0 && failed === 0 && flaky === 0 && diffMismatch > 0;
63
+ }
64
+ class CiGateWorkflowService {
65
+ constructor(app, workflow, gitFeedbackService, containerService, aiTriageService) {
66
+ this.app = app;
67
+ this.workflow = workflow;
68
+ this.gitFeedbackService = gitFeedbackService;
69
+ this.containerService = containerService;
70
+ this.aiTriageService = aiTriageService;
71
+ }
72
+ reconcileTimer = null;
73
+ mrPollTimer = null;
74
+ reconciling = null;
75
+ pollingMrs = null;
76
+ stopping = false;
77
+ launchersRegistered = false;
78
+ activeTasks = /* @__PURE__ */ new Set();
79
+ localLocks = /* @__PURE__ */ new Map();
80
+ trackBackgroundTask(promise) {
81
+ const tracked = promise.catch(() => void 0).finally(() => {
82
+ this.activeTasks.delete(tracked);
83
+ });
84
+ this.activeTasks.add(tracked);
85
+ }
86
+ hasCollection(name) {
87
+ try {
88
+ return Boolean(this.app.db.getCollection(name));
89
+ } catch {
90
+ return false;
91
+ }
92
+ }
93
+ getTestManagerService() {
94
+ const tmPlugin = this.app.pm.get("plugin-test-manager") || this.app.pm.get("test-manager");
95
+ if (!(tmPlugin == null ? void 0 : tmPlugin.workflowService)) {
96
+ throw new Error("plugin-test-manager is required and must be enabled before running CI Gate workflows");
97
+ }
98
+ this.ensureLaunchersRegistered(tmPlugin.workflowService);
99
+ return tmPlugin.workflowService;
100
+ }
101
+ ensureLaunchersRegistered(tmService) {
102
+ var _a;
103
+ if (this.launchersRegistered) return;
104
+ const svc = tmService ?? ((_a = this.app.pm.get("plugin-test-manager") || this.app.pm.get("test-manager")) == null ? void 0 : _a.workflowService);
105
+ if (!svc || typeof svc.registerRunnerLauncher !== "function") return;
106
+ const createAdapter = (backend) => ({
107
+ launch: async (req) => {
108
+ var _a2, _b, _c, _d, _e;
109
+ const ctx = isPlainRecord(req.launcherContext) ? req.launcherContext : isPlainRecord((_b = (_a2 = req.run) == null ? void 0 : _a2.frozenManifest) == null ? void 0 : _b.externalLauncherContext) ? (_c = req.run.frozenManifest) == null ? void 0 : _c.externalLauncherContext : {};
110
+ const pipelineId = Number(ctx.pipelineId || 0);
111
+ const gateRunId = Number(ctx.gateRunId || 0);
112
+ const pipeModel = await this.app.db.getRepository(import_constants_internal.CI_PIPELINES_COLLECTION).findOne({ filterByTk: pipelineId });
113
+ const gateModel = await this.app.db.getRepository(import_constants_internal.CI_GATE_RUNS_COLLECTION).findOne({ filterByTk: gateRunId });
114
+ if (!pipeModel || !gateModel) {
115
+ throw new Error(`CI Pipeline #${pipelineId} or Gate Run #${gateRunId} not found for ${backend} launch`);
116
+ }
117
+ const pipeline = pipeModel.toJSON();
118
+ const gateRun = gateModel.toJSON();
119
+ const testRunId = Number(((_d = req.run) == null ? void 0 : _d.id) || ((_e = req.manifest) == null ? void 0 : _e.runId) || 0);
120
+ const launchRes = await this.containerService.launchOneShotContainer({
121
+ pipeline,
122
+ gateRun: { ...gateRun, testRunId },
123
+ testRunId,
124
+ groupId: req.groupId,
125
+ attempt: req.attempt,
126
+ tenantKey: req.manifest.tenantKey || req.tenant.key,
127
+ postgresSchema: req.manifest.postgresSchema || req.run.ephemeralSchemaName || req.tenant.postgresSchema,
128
+ targetBaseUrl: req.manifest.targetBaseUrl ?? req.tenant.targetBaseUrl ?? null,
129
+ manifestUrl: req.manifest.manifestUrl,
130
+ callbackUrl: req.manifest.callbackUrl,
131
+ callbackToken: req.scopedCallbackToken,
132
+ signal: req.signal
133
+ });
134
+ let nextLogs = gateRun.logs || "";
135
+ for (const l of launchRes.logs) {
136
+ nextLogs = this.appendGateLog(nextLogs, "CONTAINER", l);
137
+ }
138
+ await gateModel.update({
139
+ ephemeralContainerId: launchRes.containerId ?? gateRun.ephemeralContainerId ?? null,
140
+ logs: nextLogs
141
+ });
142
+ return {
143
+ launched: launchRes.launched,
144
+ resourceId: launchRes.containerId ?? null,
145
+ logs: launchRes.logs,
146
+ cleanupContext: {
147
+ pipelineId,
148
+ gateRunId
149
+ }
150
+ };
151
+ },
152
+ collectEvidence: async (params) => {
153
+ var _a2, _b, _c;
154
+ const ctx = isPlainRecord(params.cleanupContext) ? params.cleanupContext : isPlainRecord((_b = (_a2 = params.run) == null ? void 0 : _a2.frozenManifest) == null ? void 0 : _b.externalLauncherContext) ? (_c = params.run.frozenManifest) == null ? void 0 : _c.externalLauncherContext : {};
155
+ const pipelineId = Number(ctx.pipelineId || 0);
156
+ if (!pipelineId || !params.resourceId) return {};
157
+ const pipeModel = await this.app.db.getRepository(import_constants_internal.CI_PIPELINES_COLLECTION).findOne({ filterByTk: pipelineId });
158
+ if (!pipeModel) return {};
159
+ const logText = await this.containerService.readContainerLogs(
160
+ pipeModel.toJSON(),
161
+ params.resourceId,
162
+ 200
163
+ );
164
+ return logText ? { logs: logText.split("\n").filter(Boolean) } : {};
165
+ },
166
+ cleanup: async (params) => {
167
+ var _a2, _b, _c;
168
+ const ctx = isPlainRecord(params.cleanupContext) ? params.cleanupContext : isPlainRecord((_b = (_a2 = params.run) == null ? void 0 : _a2.frozenManifest) == null ? void 0 : _b.externalLauncherContext) ? (_c = params.run.frozenManifest) == null ? void 0 : _c.externalLauncherContext : {};
169
+ const pipelineId = Number(ctx.pipelineId || 0);
170
+ const gateRunId = Number(ctx.gateRunId || 0);
171
+ if (!pipelineId || !params.resourceId) return true;
172
+ const pipeModel = await this.app.db.getRepository(import_constants_internal.CI_PIPELINES_COLLECTION).findOne({ filterByTk: pipelineId });
173
+ if (!pipeModel) return false;
174
+ const removed = await this.containerService.cleanupContainer(
175
+ pipeModel.toJSON(),
176
+ params.resourceId
177
+ );
178
+ if (removed && gateRunId > 0) {
179
+ await this.app.db.getRepository(import_constants_internal.CI_GATE_RUNS_COLLECTION).update({
180
+ filter: { id: gateRunId, ephemeralContainerId: params.resourceId },
181
+ values: { ephemeralContainerId: null }
182
+ }).catch(() => void 0);
183
+ }
184
+ return removed;
185
+ }
186
+ });
187
+ svc.registerRunnerLauncher("portainer_ephemeral", createAdapter("portainer_ephemeral"));
188
+ svc.registerRunnerLauncher("cluster_ephemeral", createAdapter("cluster_ephemeral"));
189
+ this.launchersRegistered = true;
190
+ }
191
+ async runWithLock(lockKey, ttlMs, work, timeoutMs = 15e3) {
192
+ const runLocallySerialized = async () => {
193
+ const prev = this.localLocks.get(lockKey) ?? Promise.resolve();
194
+ const next = prev.catch(() => void 0).then(() => work());
195
+ const settled = next.then(
196
+ () => void 0,
197
+ () => void 0
198
+ ).finally(() => {
199
+ if (this.localLocks.get(lockKey) === settled) {
200
+ this.localLocks.delete(lockKey);
201
+ }
202
+ });
203
+ this.localLocks.set(lockKey, settled);
204
+ return next;
205
+ };
206
+ const lockManager = this.app.lockManager;
207
+ if (!(lockManager == null ? void 0 : lockManager.tryAcquire)) {
208
+ return runLocallySerialized();
209
+ }
210
+ let handle = null;
211
+ try {
212
+ handle = await lockManager.tryAcquire(lockKey, timeoutMs);
213
+ } catch {
214
+ return void 0;
215
+ }
216
+ if (!handle) return void 0;
217
+ return handle.runExclusive(runLocallySerialized, ttlMs);
218
+ }
219
+ async assertValidPipelineConfiguration(values) {
220
+ const gateMode = values.deployGateMode ?? "none";
221
+ const portainerPipelineId = values.portainerPipelineId ? Number(values.portainerPipelineId) : 0;
222
+ if (gateMode !== "none" && portainerPipelineId > 0 && this.hasCollection(import_constants_internal.PORTAINER_PIPELINES_COLLECTION)) {
223
+ const linked = await this.app.db.getRepository(import_constants_internal.PORTAINER_PIPELINES_COLLECTION).findOne({ filterByTk: portainerPipelineId });
224
+ if (linked && Boolean(linked.get("deployEnabled"))) {
225
+ const err = new Error(
226
+ `Linked Portainer Git Pipeline #${portainerPipelineId} has deployEnabled=true. Quality Gate pipelines require a build-only Portainer pipeline (deployEnabled=false) so runtime promotion cannot bypass the CI gate.`
227
+ );
228
+ err.status = 400;
229
+ throw err;
230
+ }
231
+ }
232
+ }
233
+ async provisionManagedWorkflow() {
234
+ if (!this.workflow) return null;
235
+ const provisioned = await this.runWithLock(
236
+ "workflow-ci:provision",
237
+ 6e4,
238
+ async () => {
239
+ const wfRepo = this.app.db.getRepository("workflows");
240
+ const revisions = await wfRepo.find({
241
+ filter: { key: import_constants_internal.CI_MANAGED_WORKFLOW_KEY },
242
+ sort: ["-id"]
243
+ });
244
+ const activeRev = revisions.find((r) => Boolean(r.get("enabled")));
245
+ if (activeRev) {
246
+ const opts = activeRev.get("options");
247
+ const marker = isPlainRecord(opts) ? opts[import_constants_internal.CI_WORKFLOW_TEMPLATE_MARKER] : null;
248
+ if (isPlainRecord(marker) && marker.templateVersion === import_constants_internal.CI_WORKFLOW_TEMPLATE_VERSION) {
249
+ return activeRev;
250
+ }
251
+ }
252
+ const matchingInactive = revisions.find((r) => {
253
+ const opts = r.get("options");
254
+ const marker = isPlainRecord(opts) ? opts[import_constants_internal.CI_WORKFLOW_TEMPLATE_MARKER] : null;
255
+ return isPlainRecord(marker) && marker.templateVersion === import_constants_internal.CI_WORKFLOW_TEMPLATE_VERSION;
256
+ });
257
+ if (matchingInactive) {
258
+ await this.app.db.sequelize.transaction(async (transaction) => {
259
+ await wfRepo.update({
260
+ filter: { key: import_constants_internal.CI_MANAGED_WORKFLOW_KEY },
261
+ values: { enabled: false, current: false },
262
+ transaction
263
+ });
264
+ await matchingInactive.update({ enabled: true, current: true }, { transaction });
265
+ });
266
+ return matchingInactive;
267
+ }
268
+ return this.app.db.sequelize.transaction(async (transaction) => {
269
+ if (revisions.length > 0) {
270
+ await wfRepo.update({
271
+ filter: { key: import_constants_internal.CI_MANAGED_WORKFLOW_KEY },
272
+ values: { enabled: false, current: false },
273
+ transaction
274
+ });
275
+ }
276
+ const created = await wfRepo.create({
277
+ values: {
278
+ key: import_constants_internal.CI_MANAGED_WORKFLOW_KEY,
279
+ current: true,
280
+ title: "CI Testing, Triage & Quality Gate Pipeline",
281
+ type: "collection",
282
+ sync: false,
283
+ enabled: false,
284
+ config: {
285
+ collection: import_constants_internal.CI_GATE_RUNS_COLLECTION,
286
+ mode: 1,
287
+ condition: { workflowKey: { $eq: import_constants_internal.CI_MANAGED_WORKFLOW_KEY } }
288
+ },
289
+ options: {
290
+ timeout: import_constants_internal.DEFAULT_CI_TIMEOUT_MS * 2,
291
+ [import_constants_internal.CI_WORKFLOW_TEMPLATE_MARKER]: {
292
+ managed: true,
293
+ templateVersion: import_constants_internal.CI_WORKFLOW_TEMPLATE_VERSION
294
+ }
295
+ }
296
+ },
297
+ transaction
298
+ });
299
+ const nodeDefs = [
300
+ {
301
+ key: "ci_dispatch",
302
+ type: import_constants_internal.CI_INSTRUCTIONS.dispatchRun,
303
+ title: "1. Dispatch Test Run, QA Stack Lease & Runner",
304
+ config: {}
305
+ },
306
+ {
307
+ key: "ci_triage",
308
+ type: import_constants_internal.CI_INSTRUCTIONS.aiTriage,
309
+ title: "2. AI Root-Cause Failure Triage & Agent Loop",
310
+ config: {}
311
+ },
312
+ {
313
+ key: "ci_feedback",
314
+ type: import_constants_internal.CI_INSTRUCTIONS.publishGitFeedback,
315
+ title: "3. Publish Git Commit Status, Sticky PR Comment & Review Context",
316
+ config: {}
317
+ },
318
+ {
319
+ key: "ci_wait_approval",
320
+ type: import_constants_internal.CI_INSTRUCTIONS.waitApproval,
321
+ title: "4. Await Authorized QA Baseline Approval (gateApproverIds)",
322
+ config: {}
323
+ },
324
+ {
325
+ key: "ci_promote",
326
+ type: import_constants_internal.CI_INSTRUCTIONS.promoteDeploy,
327
+ title: "5. Enforce Pre-Deploy Quality Gate, Promote & Verify Rollout",
328
+ config: {}
329
+ }
330
+ ];
331
+ let previousNode = null;
332
+ for (const def of nodeDefs) {
333
+ const node = await created.createNode(
334
+ {
335
+ ...def,
336
+ upstreamId: (previousNode == null ? void 0 : previousNode.id) ?? null
337
+ },
338
+ { transaction }
339
+ );
340
+ if (previousNode) {
341
+ await previousNode.update({ downstreamId: node.id }, { transaction });
342
+ }
343
+ previousNode = node;
344
+ }
345
+ await created.update({ enabled: true }, { transaction });
346
+ return created;
347
+ });
348
+ },
349
+ 3e4
350
+ );
351
+ if (provisioned) return provisioned;
352
+ return await this.app.db.getRepository("workflows").findOne({
353
+ filter: { key: import_constants_internal.CI_MANAGED_WORKFLOW_KEY, enabled: true }
354
+ });
355
+ }
356
+ async start() {
357
+ var _a, _b, _c, _d;
358
+ this.stopping = false;
359
+ this.ensureLaunchersRegistered();
360
+ await this.provisionManagedWorkflow();
361
+ if (!this.reconcileTimer && this.workflow) {
362
+ this.reconcileTimer = setInterval(() => {
363
+ if (!this.reconciling) {
364
+ this.reconciling = this.reconcile().catch((error) => {
365
+ var _a2, _b2;
366
+ (_b2 = (_a2 = this.app.logger) == null ? void 0 : _a2.warn) == null ? void 0 : _b2.call(_a2, "[plugin-workflow-ci] Reconcile tick error", {
367
+ error: error instanceof Error ? error.message : String(error)
368
+ });
369
+ }).finally(() => {
370
+ this.reconciling = null;
371
+ });
372
+ }
373
+ }, import_constants_internal.CI_RECONCILE_INTERVAL_MS);
374
+ (_b = (_a = this.reconcileTimer).unref) == null ? void 0 : _b.call(_a);
375
+ }
376
+ if (!this.mrPollTimer) {
377
+ this.mrPollTimer = setInterval(() => {
378
+ if (!this.pollingMrs) {
379
+ this.pollingMrs = this.pollDueMergeRequests().catch(() => void 0).finally(() => {
380
+ this.pollingMrs = null;
381
+ });
382
+ }
383
+ }, import_constants_internal.CI_MR_POLL_INTERVAL_MS);
384
+ (_d = (_c = this.mrPollTimer).unref) == null ? void 0 : _d.call(_c);
385
+ }
386
+ }
387
+ async stop() {
388
+ this.stopping = true;
389
+ if (this.reconcileTimer) {
390
+ clearInterval(this.reconcileTimer);
391
+ this.reconcileTimer = null;
392
+ }
393
+ if (this.mrPollTimer) {
394
+ clearInterval(this.mrPollTimer);
395
+ this.mrPollTimer = null;
396
+ }
397
+ if (this.reconciling) await this.reconciling.catch(() => void 0);
398
+ if (this.pollingMrs) await this.pollingMrs.catch(() => void 0);
399
+ if (this.activeTasks.size > 0) {
400
+ await Promise.allSettled([...this.activeTasks]);
401
+ }
402
+ }
403
+ async invalidateOrSupersedePriorGateRun(staleModel, supersededByCommitSha, reason) {
404
+ const stale = staleModel.toJSON();
405
+ const pendingJobId = stale.pendingJobId;
406
+ const wasWaitingApproval = stale.state === "waiting_approval" || stale.approvalState === "pending";
407
+ const prevRecord = isPlainRecord(stale.approvalRecord) ? stale.approvalRecord : {};
408
+ const nextApprovalState = wasWaitingApproval ? "invalidated" : stale.approvalState ?? "not_required";
409
+ const nextDeployOutcome = stale.eventType === "pre_deploy_gate" && stale.deployOutcome === "pending" ? "blocked" : stale.deployOutcome ?? "not_applicable";
410
+ const logs = this.appendGateLog(
411
+ stale.logs,
412
+ "SUPERSEDED",
413
+ `${reason} (newer sha=${supersededByCommitSha.slice(0, 12)})`
414
+ );
415
+ const startedMs = stale.startedAt ? new Date(stale.startedAt).getTime() : Date.now();
416
+ await staleModel.update({
417
+ state: "canceled",
418
+ approvalState: nextApprovalState,
419
+ ...wasWaitingApproval ? {
420
+ approvalRecord: {
421
+ ...prevRecord,
422
+ invalidatedAt: (/* @__PURE__ */ new Date()).toISOString(),
423
+ invalidatedReason: reason,
424
+ invalidatedByCommitSha: supersededByCommitSha
425
+ }
426
+ } : {},
427
+ deployOutcome: nextDeployOutcome,
428
+ pendingJobId: null,
429
+ errorMessage: reason,
430
+ logs,
431
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
432
+ durationMs: Math.max(0, Date.now() - startedMs)
433
+ });
434
+ if (stale.testRunId && wasWaitingApproval) {
435
+ await this.updateTestRunFields(stale.testRunId, { ciGateStatus: "gate_blocked" });
436
+ }
437
+ if (pendingJobId) {
438
+ await this.settleJobExclusively(pendingJobId, import_plugin_workflow.JOB_STATUS.RESOLVED, {
439
+ gateRunId: stale.id,
440
+ canceled: true,
441
+ invalidated: wasWaitingApproval,
442
+ reason
443
+ });
444
+ }
445
+ }
446
+ async enqueueGateRun(params) {
447
+ if (this.stopping) {
448
+ const err = new Error("CI Gate service is shutting down");
449
+ err.status = 503;
450
+ throw err;
451
+ }
452
+ const flow = await this.provisionManagedWorkflow();
453
+ if (!flow || !flow.get("enabled")) {
454
+ const err = new Error(`Managed CI workflow "${import_constants_internal.CI_MANAGED_WORKFLOW_KEY}" is unavailable`);
455
+ err.status = 503;
456
+ throw err;
457
+ }
458
+ const pipelineModel = await this.app.db.getRepository(import_constants_internal.CI_PIPELINES_COLLECTION).findOne({ filterByTk: params.pipelineId });
459
+ if (!pipelineModel) {
460
+ const err = new Error(`CI Pipeline #${params.pipelineId} not found`);
461
+ err.status = 404;
462
+ throw err;
463
+ }
464
+ const pipeline = pipelineModel.toJSON();
465
+ const cleanBranch = (params.branch || "main").trim();
466
+ const cleanSha = (params.commitSha || "HEAD").trim();
467
+ const cleanOpId = params.operationId ? String(params.operationId).trim() : null;
468
+ const lockedResult = await this.runWithLock(
469
+ `workflow-ci:enqueue:${pipeline.id}`,
470
+ 3e4,
471
+ async () => {
472
+ const gateRepo = this.app.db.getRepository(import_constants_internal.CI_GATE_RUNS_COLLECTION);
473
+ if (cleanOpId) {
474
+ const dupOp = await gateRepo.findOne({
475
+ filter: {
476
+ pipelineId: pipeline.id,
477
+ eventType: params.eventType,
478
+ operationId: cleanOpId
479
+ },
480
+ sort: ["-id"]
481
+ });
482
+ if (dupOp) {
483
+ return dupOp.toJSON();
484
+ }
485
+ } else if (params.eventType !== "manual") {
486
+ const dupSha = await gateRepo.findOne({
487
+ filter: {
488
+ pipelineId: pipeline.id,
489
+ eventType: params.eventType,
490
+ commitSha: cleanSha,
491
+ ...params.mrIid ? { mrIid: params.mrIid } : { branch: cleanBranch }
492
+ },
493
+ sort: ["-id"]
494
+ });
495
+ if (dupSha) {
496
+ return dupSha.toJSON();
497
+ }
498
+ }
499
+ if (params.eventType !== "manual" && params.eventType !== "hot_reload_smoke") {
500
+ const activeOnScope = await gateRepo.find({
501
+ filter: {
502
+ pipelineId: pipeline.id,
503
+ state: { $in: ["queued", "running_ci", "triaging", "publishing_feedback", "waiting_approval"] },
504
+ ...params.mrIid ? { mrIid: params.mrIid } : { branch: cleanBranch }
505
+ },
506
+ sort: ["-id"]
507
+ });
508
+ if (activeOnScope.length > 0) {
509
+ const newestActive = activeOnScope[0].toJSON();
510
+ if (newestActive.commitSha !== cleanSha && pipeline.gitRepositoryId && (params.eventType === "push" || params.eventType === "pre_deploy_gate")) {
511
+ const headCheck = await this.gitFeedbackService.verifyBranchHeadSha({
512
+ gitRepositoryId: pipeline.gitRepositoryId,
513
+ branch: cleanBranch,
514
+ expectedSha: cleanSha
515
+ });
516
+ if (headCheck.configured && !headCheck.verified && headCheck.actualHeadSha && headCheck.actualHeadSha === newestActive.commitSha) {
517
+ const ignoredStale = await gateRepo.create({
518
+ values: {
519
+ pipelineId: pipeline.id,
520
+ tenantId: pipeline.tenantId,
521
+ buildRunId: params.buildRunId ?? null,
522
+ gitRepositoryId: pipeline.gitRepositoryId ?? null,
523
+ eventType: params.eventType,
524
+ branch: cleanBranch,
525
+ targetBranch: params.targetBranch ?? null,
526
+ commitSha: cleanSha,
527
+ baseSha: params.baseSha ?? null,
528
+ commitMessage: params.commitMessage ?? null,
529
+ mrIid: params.mrIid ?? null,
530
+ state: "canceled",
531
+ approvalState: "not_required",
532
+ deployOutcome: "blocked",
533
+ errorMessage: `Ignored out-of-order stale commit ${cleanSha.slice(
534
+ 0,
535
+ 12
536
+ )} because branch HEAD is already ${newestActive.commitSha.slice(0, 12)}`,
537
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
538
+ durationMs: 0
539
+ }
540
+ });
541
+ return ignoredStale.toJSON();
542
+ }
543
+ }
544
+ let invalidatedAny = false;
545
+ for (const staleModel of activeOnScope) {
546
+ const staleSha = String(staleModel.get("commitSha") || "");
547
+ if (staleSha === cleanSha) continue;
548
+ const staleState = String(staleModel.get("state") || "");
549
+ if (staleState === "waiting_approval" || staleState === "queued" || staleState === "running_ci") {
550
+ await this.invalidateOrSupersedePriorGateRun(
551
+ staleModel,
552
+ cleanSha,
553
+ staleState === "waiting_approval" ? "Pending approval invalidated by newer commit on branch/PR" : "Superseded by newer commit on branch/PR"
554
+ );
555
+ invalidatedAny = true;
556
+ }
557
+ }
558
+ if (invalidatedAny) {
559
+ await new Promise((resolve) => setTimeout(resolve, 25));
560
+ }
561
+ }
562
+ }
563
+ const initialDeployOutcome = params.eventType === "pre_deploy_gate" && pipeline.deployGateMode !== "none" ? "pending" : "not_applicable";
564
+ const created = await gateRepo.create({
565
+ values: {
566
+ pipelineId: pipeline.id,
567
+ tenantId: pipeline.tenantId,
568
+ buildRunId: params.buildRunId ?? null,
569
+ operationId: cleanOpId,
570
+ gitRepositoryId: pipeline.gitRepositoryId ?? null,
571
+ eventType: params.eventType,
572
+ branch: cleanBranch,
573
+ targetBranch: params.targetBranch ?? null,
574
+ commitSha: cleanSha,
575
+ baseSha: params.baseSha ?? null,
576
+ commitMessage: params.commitMessage ?? null,
577
+ mrIid: params.mrIid ?? null,
578
+ workflowKey: String(flow.get("key")),
579
+ workflowId: Number(flow.get("id")),
580
+ state: "queued",
581
+ approvalState: "not_required",
582
+ deployOutcome: initialDeployOutcome
583
+ }
584
+ });
585
+ return created.toJSON();
586
+ },
587
+ 2e4
588
+ );
589
+ if (!lockedResult) {
590
+ throw new Error(`Timed out acquiring enqueue lock for CI Pipeline #${pipeline.id}`);
591
+ }
592
+ return lockedResult;
593
+ }
594
+ async loadGateContext(gateRunId) {
595
+ const gateModel = await this.app.db.getRepository(import_constants_internal.CI_GATE_RUNS_COLLECTION).findOne({ filterByTk: gateRunId });
596
+ if (!gateModel) {
597
+ throw new Error(`CI Gate Run #${gateRunId} not found`);
598
+ }
599
+ const gateRun = gateModel.toJSON();
600
+ const pipelineModel = await this.app.db.getRepository(import_constants_internal.CI_PIPELINES_COLLECTION).findOne({ filterByTk: gateRun.pipelineId });
601
+ if (!pipelineModel) {
602
+ throw new Error(`CI Pipeline #${gateRun.pipelineId} not found`);
603
+ }
604
+ const pipeline = pipelineModel.toJSON();
605
+ let testRun;
606
+ if (gateRun.testRunId) {
607
+ testRun = await this.fetchTestRun(gateRun.testRunId);
608
+ } else {
609
+ testRun = null;
610
+ }
611
+ return { gateModel, gateRun, pipelineModel, pipeline, testRun };
612
+ }
613
+ async resolveBuildProvenance(pipeline, gateRun) {
614
+ if (!this.hasCollection(import_constants_internal.PORTAINER_PIPELINE_RUNS_COLLECTION)) return null;
615
+ const runsRepo = this.app.db.getRepository(import_constants_internal.PORTAINER_PIPELINE_RUNS_COLLECTION);
616
+ let buildModel = null;
617
+ if (gateRun.buildRunId) {
618
+ buildModel = await runsRepo.findOne({ filterByTk: gateRun.buildRunId });
619
+ } else if (pipeline.portainerPipelineId) {
620
+ buildModel = await runsRepo.findOne({
621
+ filter: {
622
+ pipelineId: pipeline.portainerPipelineId,
623
+ commitSha: gateRun.commitSha,
624
+ state: "succeeded"
625
+ },
626
+ sort: ["-id"]
627
+ });
628
+ }
629
+ if (!buildModel) return null;
630
+ const buildRes = isPlainRecord(buildModel.get("buildResult")) ? buildModel.get("buildResult") : {};
631
+ const appliedEnv = isPlainRecord(buildModel.get("appliedEnv")) ? buildModel.get("appliedEnv") : {};
632
+ const commitSha = String(buildModel.get("commitSha") || gateRun.commitSha);
633
+ const resolvedImageTag = typeof buildRes.resolvedImageTag === "string" && buildRes.resolvedImageTag || appliedEnv.IMAGE_TAG || appliedEnv.GIT_SHORT_SHA || commitSha.slice(0, 7);
634
+ const rawArtifacts = Array.isArray(buildRes.serviceArtifacts) ? buildRes.serviceArtifacts : [];
635
+ return {
636
+ buildRunId: Number(buildModel.get("id")),
637
+ commitSha,
638
+ resolvedImageTag,
639
+ imageTagEnvName: typeof buildRes.imageTagEnvName === "string" ? buildRes.imageTagEnvName : null,
640
+ dockerDaemonId: typeof buildRes.dockerDaemonId === "string" ? buildRes.dockerDaemonId : null,
641
+ serviceArtifacts: rawArtifacts.filter(isPlainRecord).map((a) => ({
642
+ serviceName: typeof a.serviceName === "string" ? a.serviceName : void 0,
643
+ imageRef: String(a.imageRef || ""),
644
+ repository: String(a.repository || ""),
645
+ tag: String(a.tag || resolvedImageTag),
646
+ imageConfigId: typeof a.imageConfigId === "string" ? a.imageConfigId : null,
647
+ repoDigest: typeof a.repoDigest === "string" ? a.repoDigest : null,
648
+ architecture: typeof a.architecture === "string" ? a.architecture : null,
649
+ os: typeof a.os === "string" ? a.os : null
650
+ })).filter((a) => Boolean(a.imageRef))
651
+ };
652
+ }
653
+ fetchTestRun = async (testRunId) => {
654
+ try {
655
+ const tmService = this.getTestManagerService();
656
+ if (typeof tmService.getRunById === "function") {
657
+ const externalRun = await tmService.getRunById(testRunId);
658
+ if (externalRun) return externalRun;
659
+ }
660
+ } catch {
661
+ }
662
+ try {
663
+ const trModel = await this.app.db.getRepository(import_constants_internal.TEST_RUNS_COLLECTION).findOne({ filterByTk: testRunId });
664
+ return trModel ? trModel.toJSON() : null;
665
+ } catch {
666
+ return null;
667
+ }
668
+ };
669
+ async updateTestRunFields(testRunId, values) {
670
+ try {
671
+ const tmService = this.getTestManagerService();
672
+ if (typeof tmService.updateRunFields === "function") {
673
+ await tmService.updateRunFields(testRunId, values);
674
+ return;
675
+ }
676
+ } catch {
677
+ }
678
+ await this.app.db.getRepository(import_constants_internal.TEST_RUNS_COLLECTION).update({ filterByTk: testRunId, values }).catch(() => void 0);
679
+ }
680
+ appendGateLog(existing, stage, line) {
681
+ const entry = `${(/* @__PURE__ */ new Date()).toISOString()} [${stage}] ${line}`;
682
+ return existing ? `${existing}
683
+ ${entry}`.slice(-12e4) : entry;
684
+ }
685
+ async runDispatchStage(gateRunId, meta) {
686
+ const { gateModel, gateRun, pipeline } = await this.loadGateContext(gateRunId);
687
+ const tmService = this.getTestManagerService();
688
+ const basePublicUrl = (process.env.APP_PUBLIC_URL || "http://localhost:13000").replace(/\/+$/, "");
689
+ const workbenchUrl = `${basePublicUrl}/v/admin/settings/test-manager`;
690
+ let logs = this.appendGateLog(
691
+ gateRun.logs,
692
+ "DISPATCH",
693
+ `Starting CI Gate Run #${gateRun.id} for branch="${gateRun.branch}" sha="${gateRun.commitSha.slice(0, 12)}"`
694
+ );
695
+ await gateModel.update({
696
+ workflowId: meta.workflowId ?? gateRun.workflowId ?? null,
697
+ executionId: meta.executionId ?? gateRun.executionId ?? null,
698
+ pendingJobId: meta.jobId ?? null,
699
+ state: "running_ci",
700
+ startedAt: gateRun.startedAt || (/* @__PURE__ */ new Date()).toISOString(),
701
+ logs
702
+ });
703
+ if (pipeline.publishCommitStatus) {
704
+ const statusRes = await this.gitFeedbackService.publishCommitStatus({
705
+ gateRunId: gateRun.id,
706
+ pipelineId: pipeline.id,
707
+ gitRepositoryId: gateRun.gitRepositoryId ?? pipeline.gitRepositoryId,
708
+ commitSha: gateRun.commitSha,
709
+ branch: gateRun.branch,
710
+ state: "pending",
711
+ context: pipeline.statusContext || "nocobase/ci-test-manager",
712
+ description: `CI test run in progress on branch ${gateRun.branch}`,
713
+ targetUrl: workbenchUrl
714
+ });
715
+ logs = this.appendGateLog(logs, "GIT_STATUS", statusRes.detail);
716
+ await gateModel.update({
717
+ commitStatusState: statusRes.published ? "pending" : null,
718
+ gitFeedbackSyncState: statusRes.published ? "synced" : statusRes.queuedRetry ? "retrying" : "not_applicable",
719
+ logs
720
+ });
721
+ }
722
+ const buildProv = await this.resolveBuildProvenance(pipeline, gateRun);
723
+ if (buildProv && !gateRun.buildRunId) {
724
+ await gateModel.update({ buildRunId: buildProv.buildRunId });
725
+ }
726
+ const qaStackBinding = pipeline.qaStackId && pipeline.qaEndpointId ? {
727
+ instanceId: pipeline.qaInstanceId ?? pipeline.portainerInstanceId ?? null,
728
+ endpointId: Number(pipeline.qaEndpointId),
729
+ stackId: Number(pipeline.qaStackId),
730
+ appServices: Array.isArray(pipeline.qaAppServices) ? pipeline.qaAppServices : null
731
+ } : null;
732
+ const triggerSourceMap = {
733
+ push: "git_webhook",
734
+ merge_request: "git_mr",
735
+ pre_deploy_gate: "ci_gate",
736
+ hot_reload_smoke: "cluster_hot_reload",
737
+ manual: "ci_gate"
738
+ };
739
+ const usesEphemeralLauncher = pipeline.runnerBackend === "portainer_ephemeral" || pipeline.runnerBackend === "cluster_ephemeral";
740
+ const enqueuedTestRun = await tmService.enqueueRun({
741
+ tenantId: pipeline.tenantId,
742
+ pipelineId: pipeline.id,
743
+ triggerSource: triggerSourceMap[gateRun.eventType] || "ci_gate",
744
+ triggeredByUser: `ci:${pipeline.key}`,
745
+ gitRepositoryId: gateRun.gitRepositoryId ?? pipeline.gitRepositoryId ?? null,
746
+ gitBranch: gateRun.branch,
747
+ gitTargetBranch: gateRun.targetBranch ?? null,
748
+ gitBaseSha: gateRun.baseSha ?? null,
749
+ gitCommitSha: gateRun.commitSha,
750
+ gitCommitMessage: gateRun.commitMessage ?? null,
751
+ mrIid: gateRun.mrIid ?? null,
752
+ portainerPipelineId: pipeline.portainerPipelineId ?? null,
753
+ portainerPipelineRunId: (buildProv == null ? void 0 : buildProv.buildRunId) ?? gateRun.buildRunId ?? null,
754
+ buildRunId: (buildProv == null ? void 0 : buildProv.buildRunId) ?? gateRun.buildRunId ?? null,
755
+ resolvedImageTag: (buildProv == null ? void 0 : buildProv.resolvedImageTag) ?? null,
756
+ imageTagEnvName: (buildProv == null ? void 0 : buildProv.imageTagEnvName) ?? null,
757
+ expectedServiceImages: (buildProv == null ? void 0 : buildProv.serviceArtifacts) ? buildProv.serviceArtifacts.map((a) => ({
758
+ serviceName: a.serviceName,
759
+ imageRef: a.imageRef,
760
+ imageConfigId: a.imageConfigId ?? null,
761
+ repoDigest: a.repoDigest ?? null,
762
+ dockerDaemonId: buildProv.dockerDaemonId ?? null,
763
+ architecture: a.architecture ?? null,
764
+ os: a.os ?? null
765
+ })) : null,
766
+ qaStackBinding,
767
+ requireScopedToken: pipeline.deployGateMode !== "none",
768
+ externalLauncherBackend: usesEphemeralLauncher ? pipeline.runnerBackend : null,
769
+ externalLauncherContext: usesEphemeralLauncher ? {
770
+ pipelineId: pipeline.id,
771
+ gateRunId: gateRun.id
772
+ } : null,
773
+ ciGateStatus: pipeline.deployGateMode !== "none" ? "pending_gate" : "none",
774
+ cancelSuperseded: false
775
+ // CiGateWorkflowService already manages branch/PR superseding atomically
776
+ });
777
+ const testRunId = Number(enqueuedTestRun.id);
778
+ logs = this.appendGateLog(
779
+ logs,
780
+ "TEST_RUN",
781
+ `Enqueued Test Manager run #${testRunId}${qaStackBinding ? ` (QA stack lease #${qaStackBinding.stackId})` : ""}${usesEphemeralLauncher ? ` -> runner launcher "${pipeline.runnerBackend}"` : ""}`
782
+ );
783
+ await gateModel.update({ testRunId, logs });
784
+ const freshTestRun = await this.fetchTestRun(testRunId);
785
+ const freshStage = freshTestRun ? String(freshTestRun.stage || "") : "";
786
+ const freshVerdict = freshTestRun ? String(freshTestRun.verdict || "") : "";
787
+ const freshReason = (freshTestRun == null ? void 0 : freshTestRun.verdictReasonCode) ? String(freshTestRun.verdictReasonCode) : null;
788
+ const freshSnap = isPlainRecord(freshTestRun == null ? void 0 : freshTestRun.environmentSnapshot) ? freshTestRun.environmentSnapshot : null;
789
+ if (freshStage === "completed" && !(freshSnap == null ? void 0 : freshSnap.flakyRetryRunId)) {
790
+ await gateModel.update({
791
+ pendingJobId: null,
792
+ testVerdict: freshVerdict,
793
+ verdictReasonCode: freshReason
794
+ });
795
+ return {
796
+ waitingTestRun: false,
797
+ payload: {
798
+ gateRunId: gateRun.id,
799
+ testRunId,
800
+ verdict: freshVerdict,
801
+ verdictReasonCode: freshReason
802
+ }
803
+ };
804
+ }
805
+ return {
806
+ waitingTestRun: true,
807
+ payload: {
808
+ gateRunId: gateRun.id,
809
+ testRunId,
810
+ waiting: true
811
+ }
812
+ };
813
+ }
814
+ async runAiTriageStage(gateRunId) {
815
+ const { gateModel, gateRun, pipeline, testRun } = await this.loadGateContext(gateRunId);
816
+ if (!pipeline.enableAiTriage || !testRun) {
817
+ return { gateRunId, triageSkipped: true };
818
+ }
819
+ const verdict = String(testRun.verdict || gateRun.testVerdict || "");
820
+ if (verdict !== "failed" && verdict !== "diff_mismatch" && verdict !== "error") {
821
+ return { gateRunId, verdict, triageSkipped: true };
822
+ }
823
+ await gateModel.update({ state: "triaging" });
824
+ const triage = await this.aiTriageService.analyzeFailedRun({
825
+ pipeline,
826
+ gateRun,
827
+ testRun
828
+ });
829
+ if (triage) {
830
+ const dispatchNote = triage.agentDispatched ? ` [Agent Loop #${triage.agentLoopRunId}]` : triage.triageError ? ` [Agent dispatch skipped: ${triage.triageError}]` : "";
831
+ const logs = this.appendGateLog(
832
+ gateRun.logs,
833
+ "AI_TRIAGE",
834
+ `Classified as "${triage.classification}" (${Math.round(triage.confidence * 100)}%): ${triage.rootCause}${dispatchNote}`
835
+ );
836
+ await gateModel.update({ triageResult: triage, logs });
837
+ if (gateRun.testRunId) {
838
+ await this.getTestManagerService().saveAiTriageSummary(gateRun.testRunId, triage).catch(() => void 0);
839
+ }
840
+ }
841
+ return {
842
+ gateRunId,
843
+ triage: triage ?? null
844
+ };
845
+ }
846
+ async runPublishGitFeedbackStage(gateRunId) {
847
+ const { gateModel, gateRun, pipeline, testRun } = await this.loadGateContext(gateRunId);
848
+ await gateModel.update({ state: "publishing_feedback" });
849
+ const verdict = String((testRun == null ? void 0 : testRun.verdict) || gateRun.testVerdict || "error");
850
+ const reasonCode = (testRun == null ? void 0 : testRun.verdictReasonCode) ? String(testRun.verdictReasonCode) : gateRun.verdictReasonCode ?? null;
851
+ const isApprovedDiff = verdict === "diff_mismatch" && gateRun.approvalState === "approved";
852
+ const basePublicUrl = (process.env.APP_PUBLIC_URL || "http://localhost:13000").replace(/\/+$/, "");
853
+ const workbenchUrl = `${basePublicUrl}/v/admin/settings/test-manager`;
854
+ let statusState = "error";
855
+ if (verdict === "passed" || isApprovedDiff) statusState = "success";
856
+ else if (verdict === "failed" || verdict === "diff_mismatch") statusState = "failure";
857
+ let logs = gateRun.logs || "";
858
+ let prCommentId = gateRun.prCommentId ?? null;
859
+ let syncState = "not_applicable";
860
+ if (pipeline.publishCommitStatus && verdict !== "canceled") {
861
+ const metrics = isPlainRecord(testRun == null ? void 0 : testRun.summaryMetrics) ? testRun.summaryMetrics : {};
862
+ const desc = verdict === "passed" ? `Passed ${Number(metrics.passed ?? 0)}/${Number(metrics.total ?? 0)} cases` : isApprovedDiff ? `Baseline diff approved by QA (${Number(metrics.diffMismatch ?? 0)} dataset diff(s))` : `CI verdict: ${verdict}${reasonCode ? ` [${reasonCode}]` : ""} (failed=${Number(
863
+ metrics.failed ?? 0
864
+ )}, diffMismatch=${Number(metrics.diffMismatch ?? 0)})`;
865
+ const stRes = await this.gitFeedbackService.publishCommitStatus({
866
+ gateRunId: gateRun.id,
867
+ pipelineId: pipeline.id,
868
+ gitRepositoryId: gateRun.gitRepositoryId ?? pipeline.gitRepositoryId,
869
+ commitSha: gateRun.commitSha,
870
+ branch: gateRun.branch,
871
+ state: statusState,
872
+ context: pipeline.statusContext || "nocobase/ci-test-manager",
873
+ description: desc,
874
+ targetUrl: workbenchUrl
875
+ });
876
+ logs = this.appendGateLog(logs, "GIT_STATUS", stRes.detail);
877
+ syncState = stRes.published ? "synced" : stRes.queuedRetry ? "retrying" : syncState;
878
+ }
879
+ if (pipeline.publishPrComment && gateRun.mrIid) {
880
+ const commentRes = await this.gitFeedbackService.upsertStickyPrComment({
881
+ pipeline,
882
+ gateRun: { ...gateRun, testVerdict: verdict, verdictReasonCode: reasonCode },
883
+ testRun,
884
+ triage: gateRun.triageResult ?? null,
885
+ workbenchUrl
886
+ });
887
+ if (commentRes.commentId) {
888
+ prCommentId = commentRes.commentId;
889
+ }
890
+ logs = this.appendGateLog(logs, "PR_COMMENT", commentRes.detail);
891
+ if (commentRes.queuedRetry) {
892
+ syncState = "retrying";
893
+ } else if (commentRes.published && syncState !== "retrying") {
894
+ syncState = "synced";
895
+ }
896
+ }
897
+ if (pipeline.enrichGitReview) {
898
+ const enrichedCount = await this.gitFeedbackService.enrichPendingGitReviewRequests({
899
+ gitRepositoryId: gateRun.gitRepositoryId ?? pipeline.gitRepositoryId,
900
+ mrIid: gateRun.mrIid,
901
+ commitSha: gateRun.commitSha,
902
+ testRun,
903
+ triage: gateRun.triageResult ?? null
904
+ });
905
+ if (enrichedCount > 0) {
906
+ logs = this.appendGateLog(logs, "GIT_REVIEW", `Enriched ${enrichedCount} pending AI Git Review request(s)`);
907
+ }
908
+ }
909
+ await gateModel.update({
910
+ testVerdict: verdict,
911
+ verdictReasonCode: reasonCode,
912
+ commitStatusState: verdict === "canceled" ? gateRun.commitStatusState : statusState,
913
+ gitFeedbackSyncState: syncState,
914
+ prCommentId,
915
+ logs
916
+ });
917
+ return {
918
+ gateRunId,
919
+ verdict,
920
+ verdictReasonCode: reasonCode,
921
+ commitStatusState: statusState,
922
+ prCommentId
923
+ };
924
+ }
925
+ async computeDiffMismatchFingerprint(testRunId) {
926
+ const tmService = this.getTestManagerService();
927
+ const diffRows = typeof tmService.listCaseResultsForRun === "function" ? await tmService.listCaseResultsForRun(testRunId, { status: "diff_mismatch" }) : [];
928
+ const normalized = diffRows.map((r) => ({
929
+ caseCode: String(r.caseCode || ""),
930
+ datasetId: Number(r.datasetId || 0),
931
+ diffReport: r.diffReport ?? null
932
+ })).sort((a, b) => a.caseCode.localeCompare(b.caseCode));
933
+ return (0, import_node_crypto.createHash)("sha256").update(canonicalJson(normalized), "utf8").digest("hex");
934
+ }
935
+ async verifyFrozenDatasetBaselinesUnchanged(tenantId, expectedVersions) {
936
+ var _a;
937
+ if (!expectedVersions || Object.keys(expectedVersions).length === 0) {
938
+ return { ok: true };
939
+ }
940
+ const datasetIds = Object.keys(expectedVersions).map((k) => Number(k)).filter((n) => Number.isFinite(n) && n > 0);
941
+ if (datasetIds.length === 0) return { ok: true };
942
+ try {
943
+ const tenantModel = await this.app.db.getRepository("testTenants").findOne({ filterByTk: tenantId });
944
+ if (!tenantModel) return { ok: false, detail: `Tenant #${tenantId} not found` };
945
+ const tmService = this.getTestManagerService();
946
+ const dsRepo = ((_a = tmService.metadataStore) == null ? void 0 : _a.getRepo) ? await tmService.metadataStore.getRepo(tenantModel.toJSON(), "testDatasets") : this.app.db.getRepository("testDatasets");
947
+ const dsModels = await dsRepo.find({ filter: { id: { $in: datasetIds } } });
948
+ const byId = /* @__PURE__ */ new Map();
949
+ for (const m of dsModels) {
950
+ byId.set(Number(m.get("id")), Number(m.get("baselineVersion") ?? 1));
951
+ }
952
+ for (const dsId of datasetIds) {
953
+ const currentVer = byId.get(dsId);
954
+ const expectedVer = Number(expectedVersions[String(dsId)]);
955
+ if (currentVer === void 0) {
956
+ return { ok: false, detail: `Dataset #${dsId} was deleted while run was waiting approval` };
957
+ }
958
+ if (currentVer !== expectedVer) {
959
+ return {
960
+ ok: false,
961
+ detail: `Dataset #${dsId} baselineVersion changed (${expectedVer} -> ${currentVer}) while waiting approval`
962
+ };
963
+ }
964
+ }
965
+ return { ok: true };
966
+ } catch (error) {
967
+ return {
968
+ ok: false,
969
+ detail: `Failed verifying dataset baseline versions: ${error instanceof Error ? error.message : String(error)}`
970
+ };
971
+ }
972
+ }
973
+ async runWaitApprovalStage(gateRunId, meta) {
974
+ const { gateModel, gateRun, pipeline, testRun } = await this.loadGateContext(gateRunId);
975
+ const verdict = String((testRun == null ? void 0 : testRun.verdict) || gateRun.testVerdict || "error");
976
+ if (pipeline.deployGateMode !== "manual_on_diff_mismatch" || gateRun.approvalState === "approved" || !isPureBaselineDiffMismatch(testRun)) {
977
+ if (gateRun.approvalState !== "approved" && gateRun.approvalState !== "invalidated") {
978
+ await gateModel.update({ approvalState: "not_required" });
979
+ }
980
+ return {
981
+ waitingApproval: false,
982
+ payload: {
983
+ gateRunId,
984
+ verdict,
985
+ approvalState: gateRun.approvalState || "not_required"
986
+ }
987
+ };
988
+ }
989
+ const frozenManifest = isPlainRecord(testRun == null ? void 0 : testRun.frozenManifest) ? testRun == null ? void 0 : testRun.frozenManifest : {};
990
+ const frozenBaselineVersions = isPlainRecord(frozenManifest == null ? void 0 : frozenManifest.datasetBaselineVersions) ? frozenManifest.datasetBaselineVersions : {};
991
+ const originalDiffHash = gateRun.testRunId ? await this.computeDiffMismatchFingerprint(gateRun.testRunId) : null;
992
+ const approvalRecord = {
993
+ approvedBaselineVersions: frozenBaselineVersions,
994
+ originalDiffHash
995
+ };
996
+ const logs = this.appendGateLog(
997
+ gateRun.logs,
998
+ "MANUAL_GATE",
999
+ `Paused in ci_wait_approval: pure baseline diff mismatch on sha=${gateRun.commitSha.slice(
1000
+ 0,
1001
+ 12
1002
+ )} awaiting authorized QA approver`
1003
+ );
1004
+ if (gateRun.testRunId) {
1005
+ await this.updateTestRunFields(gateRun.testRunId, { ciGateStatus: "waiting_manual_approval" });
1006
+ }
1007
+ await gateModel.update({
1008
+ state: "waiting_approval",
1009
+ approvalState: "pending",
1010
+ approvalRecord,
1011
+ pendingJobId: meta.jobId ?? null,
1012
+ logs
1013
+ });
1014
+ if (meta.jobId && this.hasCollection("workflowManualTasks")) {
1015
+ await this.app.db.getRepository("workflowManualTasks").create({
1016
+ values: {
1017
+ jobId: meta.jobId,
1018
+ workflowId: meta.workflowId ?? gateRun.workflowId ?? null,
1019
+ executionId: meta.executionId ?? gateRun.executionId ?? null,
1020
+ status: 0,
1021
+ title: `Approve CI Baseline Diff \u2014 ${pipeline.name} (#${gateRun.id})`,
1022
+ assignees: Array.isArray(pipeline.gateApproverIds) ? pipeline.gateApproverIds : []
1023
+ }
1024
+ }).catch(() => void 0);
1025
+ }
1026
+ return {
1027
+ waitingApproval: true,
1028
+ payload: {
1029
+ gateRunId,
1030
+ verdict,
1031
+ approvalState: "pending"
1032
+ }
1033
+ };
1034
+ }
1035
+ isBranchAllowedForProduction(branch, pipeline) {
1036
+ if (Array.isArray(pipeline.protectedBranches) && pipeline.protectedBranches.length > 0) {
1037
+ return (0, import_GitFeedbackService.matchesBranchPattern)(branch, pipeline.protectedBranches.join(","));
1038
+ }
1039
+ return (0, import_GitFeedbackService.matchesBranchPattern)(branch, pipeline.branchPattern || "main,master,release/*");
1040
+ }
1041
+ async runPromoteDeployStage(gateRunId, signal) {
1042
+ const { gateModel, gateRun, pipelineModel, pipeline, testRun } = await this.loadGateContext(gateRunId);
1043
+ const verdict = String((testRun == null ? void 0 : testRun.verdict) || gateRun.testVerdict || "error");
1044
+ const reasonCode = (testRun == null ? void 0 : testRun.verdictReasonCode) ? String(testRun.verdictReasonCode) : gateRun.verdictReasonCode ?? null;
1045
+ const approvalState = gateRun.approvalState || "not_required";
1046
+ const isApprovedDiff = verdict === "diff_mismatch" && approvalState === "approved";
1047
+ const startedMs = gateRun.startedAt ? new Date(gateRun.startedAt).getTime() : Date.now();
1048
+ let logs = gateRun.logs || "";
1049
+ if (verdict === "canceled" || gateRun.state === "canceled") {
1050
+ await gateModel.update({
1051
+ state: "canceled",
1052
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1053
+ durationMs: Math.max(0, Date.now() - startedMs)
1054
+ });
1055
+ return { gateRunId, state: "canceled", deployOutcome: gateRun.deployOutcome || "not_applicable" };
1056
+ }
1057
+ if (pipeline.deployGateMode === "none" || gateRun.eventType !== "pre_deploy_gate") {
1058
+ const finalState = verdict === "passed" || isApprovedDiff ? "succeeded" : "failed";
1059
+ if (gateRun.testRunId && pipeline.deployGateMode !== "none") {
1060
+ await this.updateTestRunFields(gateRun.testRunId, {
1061
+ ciGateStatus: finalState === "succeeded" ? "gate_passed" : "gate_blocked"
1062
+ });
1063
+ }
1064
+ await gateModel.update({
1065
+ state: finalState,
1066
+ testVerdict: verdict,
1067
+ verdictReasonCode: reasonCode,
1068
+ deployOutcome: "not_applicable",
1069
+ ...finalState === "failed" ? { errorMessage: gateRun.errorMessage || `CI check failed with verdict="${verdict}"` } : { errorMessage: null },
1070
+ logs,
1071
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1072
+ durationMs: Math.max(0, Date.now() - startedMs)
1073
+ });
1074
+ return {
1075
+ gateRunId,
1076
+ state: finalState,
1077
+ verdict,
1078
+ approvalState,
1079
+ deployOutcome: "not_applicable"
1080
+ };
1081
+ }
1082
+ const blockPromotion = async (reason) => {
1083
+ logs = this.appendGateLog(logs, "GATE_BLOCKED", reason);
1084
+ if (gateRun.testRunId) {
1085
+ await this.updateTestRunFields(gateRun.testRunId, { ciGateStatus: "gate_blocked" });
1086
+ }
1087
+ await gateModel.update({
1088
+ state: "failed",
1089
+ testVerdict: verdict,
1090
+ verdictReasonCode: reasonCode,
1091
+ deployOutcome: "blocked",
1092
+ errorMessage: reason,
1093
+ logs,
1094
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1095
+ durationMs: Math.max(0, Date.now() - startedMs)
1096
+ });
1097
+ return {
1098
+ gateRunId,
1099
+ state: "failed",
1100
+ gateBlocked: true,
1101
+ verdict,
1102
+ deployOutcome: "blocked",
1103
+ error: reason
1104
+ };
1105
+ };
1106
+ try {
1107
+ await this.assertValidPipelineConfiguration(pipeline);
1108
+ } catch (error) {
1109
+ return blockPromotion(error instanceof Error ? error.message : String(error));
1110
+ }
1111
+ if (pipeline.gitRepositoryId && gateRun.gitRepositoryId && Number(pipeline.gitRepositoryId) !== Number(gateRun.gitRepositoryId)) {
1112
+ return blockPromotion(
1113
+ `Repository mismatch: gateRun.gitRepositoryId=${gateRun.gitRepositoryId} !== pipeline.gitRepositoryId=${pipeline.gitRepositoryId}`
1114
+ );
1115
+ }
1116
+ if (!this.isBranchAllowedForProduction(gateRun.branch, pipeline)) {
1117
+ return blockPromotion(`Branch "${gateRun.branch}" is not in pipeline protectedBranches for production promotion`);
1118
+ }
1119
+ if (pipeline.gitRepositoryId) {
1120
+ const headVerify = await this.gitFeedbackService.verifyBranchHeadSha({
1121
+ gitRepositoryId: pipeline.gitRepositoryId,
1122
+ branch: gateRun.branch,
1123
+ expectedSha: gateRun.commitSha
1124
+ });
1125
+ if (headVerify.configured && !headVerify.verified) {
1126
+ return blockPromotion(`Stale commit blocked from production promotion: ${headVerify.detail}`);
1127
+ }
1128
+ }
1129
+ if (pipeline.portainerPipelineId && this.hasCollection(import_constants_internal.PORTAINER_PIPELINES_COLLECTION)) {
1130
+ const linkedPipe = await this.app.db.getRepository(import_constants_internal.PORTAINER_PIPELINES_COLLECTION).findOne({ filterByTk: pipeline.portainerPipelineId });
1131
+ const lastKnownSha = (linkedPipe == null ? void 0 : linkedPipe.get("lastKnownSha")) ? String(linkedPipe.get("lastKnownSha")).trim() : "";
1132
+ if (lastKnownSha && lastKnownSha !== gateRun.commitSha) {
1133
+ return blockPromotion(
1134
+ `Portainer pipeline #${pipeline.portainerPipelineId} has already advanced to ${lastKnownSha.slice(
1135
+ 0,
1136
+ 12
1137
+ )}; blocking stale commit ${gateRun.commitSha.slice(0, 12)}`
1138
+ );
1139
+ }
1140
+ }
1141
+ const metrics = isPlainRecord(testRun == null ? void 0 : testRun.summaryMetrics) ? testRun.summaryMetrics : {};
1142
+ const flakyCount = Number(metrics.flaky ?? 0);
1143
+ const failedCount = Number(metrics.failed ?? 0);
1144
+ if (flakyCount > 0 || reasonCode === "AUTO_DISCOVERED_ONLY") {
1145
+ return blockPromotion(
1146
+ flakyCount > 0 ? `Quality Gate blocked promotion: run recorded ${flakyCount} flaky case(s). A clean full run (failed=0, flaky=0) on the same build artifact is required.` : "Quality Gate blocked promotion: run executed auto-discovered cases only without declared requiredCaseIds."
1147
+ );
1148
+ }
1149
+ if (!(verdict === "passed" && failedCount === 0) && !isApprovedDiff) {
1150
+ return blockPromotion(`Quality Gate blocked promotion because CI verdict is "${verdict}"`);
1151
+ }
1152
+ const buildProv = await this.resolveBuildProvenance(pipeline, gateRun);
1153
+ if (pipeline.portainerPipelineId && !buildProv) {
1154
+ return blockPromotion(`Missing verified Portainer build provenance for commit ${gateRun.commitSha.slice(0, 12)}`);
1155
+ }
1156
+ if (buildProv && buildProv.commitSha !== gateRun.commitSha) {
1157
+ return blockPromotion(
1158
+ `Build artifact SHA (${buildProv.commitSha.slice(0, 12)}) does not match gate commit (${gateRun.commitSha.slice(
1159
+ 0,
1160
+ 12
1161
+ )})`
1162
+ );
1163
+ }
1164
+ await gateModel.update({ state: "promoting_deploy", deployOutcome: "pending" });
1165
+ const targetInst = pipeline.deployInstanceId ?? pipeline.portainerInstanceId ?? 0;
1166
+ const targetEp = pipeline.deployEndpointId ?? pipeline.portainerEndpointId ?? 0;
1167
+ const targetStack = pipeline.deployStackId ?? 0;
1168
+ const prodLockKey = `workflow-ci:prod-stack:${targetInst}:${targetEp}:${targetStack}`;
1169
+ const promotion = await this.runWithLock(
1170
+ prodLockKey,
1171
+ 12e4,
1172
+ async () => {
1173
+ const freshPipeModel = await this.app.db.getRepository(import_constants_internal.CI_PIPELINES_COLLECTION).findOne({ filterByTk: pipeline.id });
1174
+ const freshPipeline = freshPipeModel ? freshPipeModel.toJSON() : pipeline;
1175
+ return this.containerService.promoteRuntimeDeployStack({
1176
+ pipeline: freshPipeline,
1177
+ gateRun,
1178
+ buildProvenance: buildProv,
1179
+ signal
1180
+ });
1181
+ },
1182
+ 3e4
1183
+ );
1184
+ if (!promotion) {
1185
+ return blockPromotion(`Timed out acquiring production stack lock (${prodLockKey})`);
1186
+ }
1187
+ logs = this.appendGateLog(logs, "PROMOTE_DEPLOY", promotion.detail);
1188
+ if (promotion.updatedGoodSnapshot) {
1189
+ await pipelineModel.update({
1190
+ lastKnownGoodSnapshot: promotion.updatedGoodSnapshot
1191
+ });
1192
+ }
1193
+ if (promotion.haltPromotion) {
1194
+ await pipelineModel.update({
1195
+ promotionHalted: true,
1196
+ promotionHaltReason: promotion.haltReason || promotion.detail
1197
+ });
1198
+ }
1199
+ const succeeded = promotion.promoted === true && promotion.deployOutcome === "deployed";
1200
+ if (gateRun.testRunId) {
1201
+ await this.updateTestRunFields(gateRun.testRunId, {
1202
+ ciGateStatus: succeeded ? "gate_passed" : "gate_blocked"
1203
+ });
1204
+ }
1205
+ await gateModel.update({
1206
+ state: succeeded ? "succeeded" : "failed",
1207
+ testVerdict: verdict,
1208
+ verdictReasonCode: reasonCode,
1209
+ deployOutcome: promotion.deployOutcome,
1210
+ deployTargetSummary: promotion,
1211
+ rollbackRecord: promotion.rollbackRecord ?? null,
1212
+ errorMessage: succeeded ? null : promotion.detail,
1213
+ logs,
1214
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1215
+ durationMs: Math.max(0, Date.now() - startedMs)
1216
+ });
1217
+ return {
1218
+ gateRunId,
1219
+ state: succeeded ? "succeeded" : "failed",
1220
+ deployOutcome: promotion.deployOutcome,
1221
+ promotion
1222
+ };
1223
+ }
1224
+ async withSqliteBusyRetry(fn, maxAttempts = 5) {
1225
+ let lastError;
1226
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
1227
+ try {
1228
+ return await fn();
1229
+ } catch (error) {
1230
+ lastError = error;
1231
+ const msg = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
1232
+ const isSqliteBusy = msg.includes("SQLITE_BUSY") || msg.includes("database is locked");
1233
+ if (!isSqliteBusy || attempt >= maxAttempts) {
1234
+ throw error;
1235
+ }
1236
+ await new Promise((resolve) => setTimeout(resolve, 50 * attempt));
1237
+ }
1238
+ }
1239
+ throw lastError;
1240
+ }
1241
+ async approveDiffAndPromote(gateRunId, actor) {
1242
+ const lockedResult = await this.runWithLock(
1243
+ `workflow-ci:approve:${gateRunId}`,
1244
+ 3e4,
1245
+ async () => {
1246
+ const { gateRun, pipeline, testRun } = await this.loadGateContext(gateRunId);
1247
+ const configuredApprovers = Array.isArray(pipeline.gateApproverIds) ? pipeline.gateApproverIds.map((id) => Number(id)).filter((n) => Number.isFinite(n) && n > 0) : [];
1248
+ if (configuredApprovers.length > 0) {
1249
+ if (!configuredApprovers.includes(Number(actor.userId))) {
1250
+ const err = new Error(
1251
+ `Forbidden: User #${actor.userId} is not listed in pipeline gateApproverIds ([${configuredApprovers.join(
1252
+ ", "
1253
+ )}])`
1254
+ );
1255
+ err.status = 403;
1256
+ throw err;
1257
+ }
1258
+ } else if (!actor.isCiAdmin) {
1259
+ const err = new Error(
1260
+ "Forbidden: CI Quality Gate admin permission is required to approve baselines"
1261
+ );
1262
+ err.status = 403;
1263
+ throw err;
1264
+ }
1265
+ if (!gateRun.testRunId) {
1266
+ const err = new Error("CI Gate Run has no linked Test Manager run");
1267
+ err.status = 400;
1268
+ throw err;
1269
+ }
1270
+ if (gateRun.state !== "waiting_approval" || gateRun.approvalState !== "pending") {
1271
+ const err = new Error(
1272
+ `Gate Run #${gateRunId} cannot be approved in state="${gateRun.state}" approvalState="${gateRun.approvalState || "not_required"}"`
1273
+ );
1274
+ err.status = 409;
1275
+ throw err;
1276
+ }
1277
+ if (!isPureBaselineDiffMismatch(testRun)) {
1278
+ const err = new Error(
1279
+ `Baseline approval is only permitted for pure baseline diff mismatches (current verdict="${String(
1280
+ testRun == null ? void 0 : testRun.verdict
1281
+ )}", reason="${String((testRun == null ? void 0 : testRun.verdictReasonCode) || "")}")`
1282
+ );
1283
+ err.status = 409;
1284
+ throw err;
1285
+ }
1286
+ const gateRepo = this.app.db.getRepository(import_constants_internal.CI_GATE_RUNS_COLLECTION);
1287
+ const newerRun = await gateRepo.findOne({
1288
+ filter: {
1289
+ pipelineId: pipeline.id,
1290
+ id: { $gt: gateRun.id },
1291
+ ...gateRun.mrIid ? { mrIid: gateRun.mrIid } : { branch: gateRun.branch },
1292
+ state: { $ne: "canceled" }
1293
+ }
1294
+ });
1295
+ if (newerRun && String(newerRun.get("commitSha")) !== gateRun.commitSha) {
1296
+ const freshModel = await gateRepo.findOne({ filterByTk: gateRunId });
1297
+ if (freshModel) {
1298
+ await this.invalidateOrSupersedePriorGateRun(
1299
+ freshModel,
1300
+ String(newerRun.get("commitSha")),
1301
+ "Approval rejected because a newer commit arrived on this branch/PR"
1302
+ );
1303
+ }
1304
+ const err = new Error(
1305
+ `Gate Run #${gateRunId} was invalidated by newer commit ${String(newerRun.get("commitSha")).slice(0, 12)}`
1306
+ );
1307
+ err.status = 409;
1308
+ throw err;
1309
+ }
1310
+ if (gateRun.eventType === "pre_deploy_gate" && pipeline.gitRepositoryId) {
1311
+ const headCheck = await this.gitFeedbackService.verifyBranchHeadSha({
1312
+ gitRepositoryId: pipeline.gitRepositoryId,
1313
+ branch: gateRun.branch,
1314
+ expectedSha: gateRun.commitSha
1315
+ });
1316
+ if (headCheck.configured && !headCheck.verified) {
1317
+ const freshModel = await gateRepo.findOne({ filterByTk: gateRunId });
1318
+ if (freshModel) {
1319
+ await this.invalidateOrSupersedePriorGateRun(
1320
+ freshModel,
1321
+ headCheck.actualHeadSha || "HEAD",
1322
+ `Approval invalidated: ${headCheck.detail}`
1323
+ );
1324
+ }
1325
+ const err = new Error(`Approval invalidated: ${headCheck.detail}`);
1326
+ err.status = 409;
1327
+ throw err;
1328
+ }
1329
+ }
1330
+ const prevApprovalRec = isPlainRecord(gateRun.approvalRecord) ? gateRun.approvalRecord : {};
1331
+ const dsVersionCheck = await this.verifyFrozenDatasetBaselinesUnchanged(
1332
+ pipeline.tenantId,
1333
+ prevApprovalRec.approvedBaselineVersions
1334
+ );
1335
+ if (!dsVersionCheck.ok) {
1336
+ const freshModel = await gateRepo.findOne({ filterByTk: gateRunId });
1337
+ if (freshModel) {
1338
+ await this.invalidateOrSupersedePriorGateRun(
1339
+ freshModel,
1340
+ gateRun.commitSha,
1341
+ dsVersionCheck.detail || "Dataset baseline version drifted"
1342
+ );
1343
+ }
1344
+ const err = new Error(`Approval invalidated: ${dsVersionCheck.detail}`);
1345
+ err.status = 409;
1346
+ throw err;
1347
+ }
1348
+ if (prevApprovalRec.originalDiffHash) {
1349
+ const currentHash = await this.computeDiffMismatchFingerprint(gateRun.testRunId);
1350
+ if (currentHash !== prevApprovalRec.originalDiffHash) {
1351
+ const err = new Error(
1352
+ "Diff mismatch fingerprint changed since gate paused; refusing stale approval"
1353
+ );
1354
+ err.status = 409;
1355
+ throw err;
1356
+ }
1357
+ }
1358
+ const approvedAt = (/* @__PURE__ */ new Date()).toISOString();
1359
+ const approvalRecord = {
1360
+ ...prevApprovalRec,
1361
+ approvedByUserId: actor.userId,
1362
+ approvedBy: actor.username,
1363
+ approvedAt,
1364
+ approvedCommitSha: gateRun.commitSha,
1365
+ approvedBuildRunId: gateRun.buildRunId ?? null
1366
+ };
1367
+ const pendingWaitJobId = gateRun.pendingJobId;
1368
+ const [claimedCount] = await gateRepo.update({
1369
+ filter: {
1370
+ id: gateRunId,
1371
+ state: "waiting_approval",
1372
+ approvalState: "pending",
1373
+ commitSha: gateRun.commitSha
1374
+ },
1375
+ values: {
1376
+ state: "promoting_deploy",
1377
+ approvalState: "approved",
1378
+ approvalRecord,
1379
+ pendingJobId: null,
1380
+ logs: this.appendGateLog(
1381
+ gateRun.logs,
1382
+ "BASELINE_APPROVED",
1383
+ `QA baseline diff approved by ${actor.username} (userId=${actor.userId}) on sha=${gateRun.commitSha.slice(
1384
+ 0,
1385
+ 12
1386
+ )}`
1387
+ )
1388
+ }
1389
+ });
1390
+ if (!claimedCount) {
1391
+ const err = new Error(`Gate Run #${gateRunId} was already approved, invalidated, or superseded`);
1392
+ err.status = 409;
1393
+ throw err;
1394
+ }
1395
+ const tmService = this.getTestManagerService();
1396
+ await tmService.approveAllRunBaselines(gateRun.testRunId, actor.username);
1397
+ if (pendingWaitJobId && this.hasCollection("workflowManualTasks")) {
1398
+ await this.app.db.getRepository("workflowManualTasks").update({
1399
+ filter: { jobId: pendingWaitJobId },
1400
+ values: { status: 1 }
1401
+ }).catch(() => void 0);
1402
+ }
1403
+ await this.runPublishGitFeedbackStage(gateRunId);
1404
+ if (pendingWaitJobId) {
1405
+ await this.settleJobExclusively(pendingWaitJobId, import_plugin_workflow.JOB_STATUS.RESOLVED, {
1406
+ gateRunId,
1407
+ approvalState: "approved",
1408
+ approvedByUserId: actor.userId,
1409
+ approvedBy: actor.username
1410
+ });
1411
+ const execRepo = this.app.db.getRepository("executions");
1412
+ const deadline = Date.now() + 15e3;
1413
+ while (Date.now() < deadline) {
1414
+ const cur = await gateRepo.findOne({ filterByTk: gateRunId });
1415
+ const st = String((cur == null ? void 0 : cur.get("state")) || "");
1416
+ const execId = Number((cur == null ? void 0 : cur.get("executionId")) || 0);
1417
+ const execModel = execId > 0 ? await execRepo.findOne({ filterByTk: execId }) : null;
1418
+ const execSettled = !execModel || Number(execModel.get("status")) !== import_plugin_workflow.EXECUTION_STATUS.STARTED;
1419
+ if ((st === "succeeded" || st === "failed" || st === "canceled") && execSettled) {
1420
+ break;
1421
+ }
1422
+ await new Promise((resolve) => setTimeout(resolve, 40));
1423
+ }
1424
+ } else {
1425
+ await this.runPromoteDeployStage(gateRunId);
1426
+ }
1427
+ const refreshed = await gateRepo.findOne({ filterByTk: gateRunId });
1428
+ return refreshed.toJSON();
1429
+ },
1430
+ 15e3
1431
+ );
1432
+ if (!lockedResult) {
1433
+ const err = new Error(`Gate Run #${gateRunId} approval is currently in progress`);
1434
+ err.status = 409;
1435
+ throw err;
1436
+ }
1437
+ return lockedResult;
1438
+ }
1439
+ async clearPromotionHalt(pipelineId, clearedBy) {
1440
+ const model = await this.app.db.getRepository(import_constants_internal.CI_PIPELINES_COLLECTION).findOne({ filterByTk: pipelineId });
1441
+ if (!model) {
1442
+ const err = new Error(`CI Pipeline #${pipelineId} not found`);
1443
+ err.status = 404;
1444
+ throw err;
1445
+ }
1446
+ await model.update({
1447
+ promotionHalted: false,
1448
+ promotionHaltReason: `Cleared by ${clearedBy} at ${(/* @__PURE__ */ new Date()).toISOString()}`
1449
+ });
1450
+ return model.toJSON();
1451
+ }
1452
+ async handleTestRunCompleted(testRun) {
1453
+ if (this.stopping) return;
1454
+ const testRunId = Number(testRun.id || 0);
1455
+ if (!testRunId) return;
1456
+ const gateModels = await this.app.db.getRepository(import_constants_internal.CI_GATE_RUNS_COLLECTION).find({
1457
+ filter: {
1458
+ testRunId,
1459
+ state: { $in: ["queued", "running_ci"] }
1460
+ },
1461
+ limit: 5
1462
+ });
1463
+ for (const gateModel of gateModels) {
1464
+ const gateRun = gateModel.toJSON();
1465
+ const pipelineModel = await this.app.db.getRepository(import_constants_internal.CI_PIPELINES_COLLECTION).findOne({ filterByTk: gateRun.pipelineId });
1466
+ const pipeline = pipelineModel ? pipelineModel.toJSON() : null;
1467
+ let containerCleared = !gateRun.ephemeralContainerId;
1468
+ if (gateRun.ephemeralContainerId && pipeline) {
1469
+ containerCleared = await this.containerService.cleanupContainer(pipeline, gateRun.ephemeralContainerId).catch(() => false);
1470
+ }
1471
+ const verdict = String(testRun.verdict || "error");
1472
+ const reasonCode = testRun.verdictReasonCode ? String(testRun.verdictReasonCode) : null;
1473
+ const pendingJobId = gateRun.pendingJobId;
1474
+ const logs = this.appendGateLog(
1475
+ gateRun.logs,
1476
+ "TEST_SETTLED",
1477
+ `Test Manager run #${testRunId} completed with verdict="${verdict}"${reasonCode ? ` [${reasonCode}]` : ""}`
1478
+ );
1479
+ await this.withSqliteBusyRetry(async () => {
1480
+ await gateModel.update({
1481
+ testVerdict: verdict,
1482
+ verdictReasonCode: reasonCode,
1483
+ pendingJobId: null,
1484
+ ...containerCleared ? { ephemeralContainerId: null } : {},
1485
+ logs
1486
+ });
1487
+ });
1488
+ if (pendingJobId) {
1489
+ await this.settleJobExclusively(pendingJobId, import_plugin_workflow.JOB_STATUS.RESOLVED, {
1490
+ gateRunId: gateRun.id,
1491
+ testRunId,
1492
+ verdict,
1493
+ verdictReasonCode: reasonCode
1494
+ });
1495
+ }
1496
+ }
1497
+ }
1498
+ async handlePortainerBuildRunSaved(model) {
1499
+ if (this.stopping) return;
1500
+ const state = String(model.get("state") || "");
1501
+ const deployEnabled = Boolean(model.get("deployEnabled"));
1502
+ if (state !== "succeeded" || deployEnabled) return;
1503
+ const buildRunId = Number(model.get("id") || 0);
1504
+ const portainerPipelineId = Number(model.get("pipelineId") || 0);
1505
+ const commitSha = String(model.get("commitSha") || "").trim();
1506
+ const branch = String(model.get("branch") || "main").trim();
1507
+ if (!portainerPipelineId || !commitSha) return;
1508
+ const ciPipelines = await this.app.db.getRepository(import_constants_internal.CI_PIPELINES_COLLECTION).find({
1509
+ filter: {
1510
+ enabled: true,
1511
+ portainerPipelineId,
1512
+ deployGateMode: { $in: ["gate_deploy", "manual_on_diff_mismatch"] }
1513
+ }
1514
+ });
1515
+ for (const pModel of ciPipelines) {
1516
+ const p = pModel.toJSON();
1517
+ if (!(0, import_GitFeedbackService.matchesBranchPattern)(branch, p.branchPattern)) continue;
1518
+ await this.enqueueGateRun({
1519
+ pipelineId: p.id,
1520
+ eventType: "pre_deploy_gate",
1521
+ branch,
1522
+ commitSha,
1523
+ buildRunId: buildRunId > 0 ? buildRunId : null,
1524
+ commitMessage: model.get("commitMessage") ? String(model.get("commitMessage")) : null
1525
+ });
1526
+ }
1527
+ }
1528
+ async triggerClusterHotReloadSmoke(params) {
1529
+ const pipelines = await this.app.db.getRepository(import_constants_internal.CI_PIPELINES_COLLECTION).find({
1530
+ filter: { enabled: true, smokeOnClusterHotReload: true }
1531
+ });
1532
+ const opId = params.operationId ? String(params.operationId).trim() : null;
1533
+ const triggered = [];
1534
+ for (const m of pipelines) {
1535
+ const p = m.toJSON();
1536
+ const run = await this.enqueueGateRun({
1537
+ pipelineId: p.id,
1538
+ eventType: "hot_reload_smoke",
1539
+ branch: "hot-reload-canary",
1540
+ commitSha: params.commitSha || (opId ? `hotreload-${opId}` : `hotreload-${Date.now()}`),
1541
+ operationId: opId,
1542
+ commitMessage: params.pluginName ? `Cluster hot-reload smoke check for ${params.pluginName}${opId ? ` (${opId})` : ""}` : `Cluster hot-reload smoke check${opId ? ` (${opId})` : ""}`
1543
+ });
1544
+ triggered.push(run);
1545
+ }
1546
+ return triggered;
1547
+ }
1548
+ async pollDueMergeRequests() {
1549
+ var _a, _b;
1550
+ if (this.stopping || !this.workflow || ((_b = (_a = this.workflow).serving) == null ? void 0 : _b.call(_a)) === false) return 0;
1551
+ let triggeredCount = 0;
1552
+ await this.runWithLock(
1553
+ "workflow-ci:mr-poll",
1554
+ 6e4,
1555
+ async () => {
1556
+ const pipeRepo = this.app.db.getRepository(import_constants_internal.CI_PIPELINES_COLLECTION);
1557
+ const pipelines = await pipeRepo.find({
1558
+ filter: { enabled: true, pollMergeRequests: true, triggerOnMergeRequest: true }
1559
+ });
1560
+ for (const pModel of pipelines) {
1561
+ if (this.stopping) return;
1562
+ const pipeline = pModel.toJSON();
1563
+ if (!pipeline.gitRepositoryId) continue;
1564
+ const openMrs = await this.gitFeedbackService.listOpenMergeRequests(pipeline.gitRepositoryId).catch(() => []);
1565
+ const knownHeads = isPlainRecord(pipeline.lastPolledMrHeads) ? { ...pipeline.lastPolledMrHeads } : {};
1566
+ let changed = false;
1567
+ for (const mr of openMrs) {
1568
+ if (!(0, import_GitFeedbackService.matchesBranchPattern)(mr.sourceBranch, pipeline.branchPattern)) continue;
1569
+ const key = String(mr.mrIid);
1570
+ if (knownHeads[key] === mr.headSha) continue;
1571
+ knownHeads[key] = mr.headSha;
1572
+ changed = true;
1573
+ await this.enqueueGateRun({
1574
+ pipelineId: pipeline.id,
1575
+ eventType: "merge_request",
1576
+ branch: mr.sourceBranch,
1577
+ targetBranch: mr.targetBranch,
1578
+ commitSha: mr.headSha,
1579
+ commitMessage: mr.title,
1580
+ mrIid: mr.mrIid
1581
+ });
1582
+ triggeredCount += 1;
1583
+ }
1584
+ if (changed) {
1585
+ await pModel.update({ lastPolledMrHeads: knownHeads });
1586
+ }
1587
+ }
1588
+ },
1589
+ 0
1590
+ );
1591
+ return triggeredCount;
1592
+ }
1593
+ async settleJobExclusively(jobId, targetStatus, resultPayload) {
1594
+ if (!this.workflow || !jobId || this.stopping) return;
1595
+ const jobRepo = this.workflow.app.db.getRepository("jobs");
1596
+ const initialJob = await jobRepo.findOne({ filterByTk: jobId });
1597
+ if (!initialJob || initialJob.status !== import_plugin_workflow.JOB_STATUS.PENDING) return;
1598
+ const execution = await initialJob.getExecution();
1599
+ if (!execution) return;
1600
+ const lockKey = (0, import_plugin_workflow.getExecutionLockKey)(execution.id);
1601
+ await this.runWithLock(
1602
+ lockKey,
1603
+ 3e4,
1604
+ async () => {
1605
+ var _a;
1606
+ const job = await jobRepo.findOne({ filterByTk: jobId });
1607
+ if (!job || job.status !== import_plugin_workflow.JOB_STATUS.PENDING) return;
1608
+ const freshExec = await job.getExecution();
1609
+ if (!freshExec) return;
1610
+ if (typeof ((_a = this.workflow) == null ? void 0 : _a.abortExecutionIfExpired) === "function") {
1611
+ if (await this.workflow.abortExecutionIfExpired(freshExec)) return;
1612
+ }
1613
+ if (freshExec.status !== import_plugin_workflow.EXECUTION_STATUS.STARTED) return;
1614
+ const [updatedCount] = await this.withSqliteBusyRetry(
1615
+ async () => jobRepo.update({
1616
+ filter: { id: jobId, status: import_plugin_workflow.JOB_STATUS.PENDING },
1617
+ values: {
1618
+ status: targetStatus,
1619
+ result: resultPayload
1620
+ }
1621
+ })
1622
+ );
1623
+ if (!updatedCount) return;
1624
+ const refreshedJob = await jobRepo.findOne({ filterByTk: jobId });
1625
+ if (refreshedJob && !this.stopping) {
1626
+ await this.withSqliteBusyRetry(async () => {
1627
+ var _a2;
1628
+ await ((_a2 = this.workflow) == null ? void 0 : _a2.resume(refreshedJob));
1629
+ });
1630
+ }
1631
+ },
1632
+ 15e3
1633
+ );
1634
+ }
1635
+ async markGateRunFailed(gateRunId, errorMessage) {
1636
+ const gateModel = await this.app.db.getRepository(import_constants_internal.CI_GATE_RUNS_COLLECTION).findOne({ filterByTk: gateRunId });
1637
+ if (!gateModel) return;
1638
+ const gateRun = gateModel.toJSON();
1639
+ let cleared = !gateRun.ephemeralContainerId;
1640
+ if (gateRun.ephemeralContainerId) {
1641
+ const pipelineModel = await this.app.db.getRepository(import_constants_internal.CI_PIPELINES_COLLECTION).findOne({ filterByTk: gateRun.pipelineId });
1642
+ if (pipelineModel) {
1643
+ cleared = await this.containerService.cleanupContainer(pipelineModel.toJSON(), gateRun.ephemeralContainerId).catch(() => false);
1644
+ }
1645
+ }
1646
+ const startedMs = gateRun.startedAt ? new Date(gateRun.startedAt).getTime() : Date.now();
1647
+ await gateModel.update({
1648
+ state: "failed",
1649
+ deployOutcome: gateRun.eventType === "pre_deploy_gate" && gateRun.deployOutcome === "pending" ? "failed" : gateRun.deployOutcome ?? "not_applicable",
1650
+ errorMessage,
1651
+ pendingJobId: null,
1652
+ ...cleared ? { ephemeralContainerId: null } : {},
1653
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1654
+ durationMs: Math.max(0, Date.now() - startedMs)
1655
+ });
1656
+ }
1657
+ async reconcile() {
1658
+ var _a, _b;
1659
+ if (this.stopping || !this.workflow || ((_b = (_a = this.workflow).serving) == null ? void 0 : _b.call(_a)) === false) return;
1660
+ await this.runWithLock(
1661
+ "workflow-ci:reconcile",
1662
+ 25e3,
1663
+ async () => {
1664
+ var _a2, _b2;
1665
+ if (typeof ((_a2 = this.workflow) == null ? void 0 : _a2.recover) === "function") {
1666
+ await this.workflow.recover();
1667
+ }
1668
+ await this.gitFeedbackService.flushOutboxBatch(this.fetchTestRun, 15).catch(() => 0);
1669
+ const flow = await this.app.db.getRepository("workflows").findOne({
1670
+ filter: { key: import_constants_internal.CI_MANAGED_WORKFLOW_KEY, enabled: true }
1671
+ });
1672
+ if (!flow) return;
1673
+ const cutoffIso = new Date(Date.now() - 45e3).toISOString();
1674
+ const unstarted = await this.app.db.getRepository(import_constants_internal.CI_GATE_RUNS_COLLECTION).find({
1675
+ filter: {
1676
+ state: "queued",
1677
+ executionId: null,
1678
+ createdAt: { $lt: cutoffIso }
1679
+ },
1680
+ limit: 20
1681
+ });
1682
+ for (const row of unstarted) {
1683
+ const id = row.get("id");
1684
+ await ((_b2 = this.workflow) == null ? void 0 : _b2.execute(
1685
+ flow,
1686
+ { data: row.toJSON() },
1687
+ { force: true, eventKey: `workflow-ci:reconcile:${String(id)}` }
1688
+ ));
1689
+ }
1690
+ const lingeringCleanups = await this.app.db.getRepository(import_constants_internal.CI_GATE_RUNS_COLLECTION).find({
1691
+ filter: {
1692
+ state: { $in: ["succeeded", "failed", "canceled", "waiting_approval"] },
1693
+ ephemeralContainerId: { $ne: null }
1694
+ },
1695
+ limit: 20
1696
+ });
1697
+ for (const row of lingeringCleanups) {
1698
+ const cid = row.get("ephemeralContainerId") ? String(row.get("ephemeralContainerId")) : "";
1699
+ if (!cid) continue;
1700
+ const pModel = await this.app.db.getRepository(import_constants_internal.CI_PIPELINES_COLLECTION).findOne({ filterByTk: row.get("pipelineId") });
1701
+ if (!pModel) continue;
1702
+ const removed = await this.containerService.cleanupContainer(pModel.toJSON(), cid).catch(() => false);
1703
+ if (removed) {
1704
+ await row.update({ ephemeralContainerId: null }).catch(() => void 0);
1705
+ }
1706
+ }
1707
+ const active = await this.app.db.getRepository(import_constants_internal.CI_GATE_RUNS_COLLECTION).find({
1708
+ filter: {
1709
+ state: { $in: ["running_ci", "triaging", "publishing_feedback", "promoting_deploy"] }
1710
+ },
1711
+ limit: 30
1712
+ });
1713
+ const nowMs = Date.now();
1714
+ for (const row of active) {
1715
+ if (this.stopping) return;
1716
+ const gateRun = row.toJSON();
1717
+ if (gateRun.state === "running_ci" && gateRun.testRunId) {
1718
+ const trJson = await this.fetchTestRun(gateRun.testRunId);
1719
+ const snap = isPlainRecord(trJson == null ? void 0 : trJson.environmentSnapshot) ? trJson == null ? void 0 : trJson.environmentSnapshot : null;
1720
+ if (trJson && trJson.stage === "completed" && !(snap == null ? void 0 : snap.flakyRetryRunId)) {
1721
+ await this.handleTestRunCompleted(trJson);
1722
+ continue;
1723
+ }
1724
+ if (gateRun.ephemeralContainerId) {
1725
+ const pModel = await this.app.db.getRepository(import_constants_internal.CI_PIPELINES_COLLECTION).findOne({ filterByTk: gateRun.pipelineId });
1726
+ const pipeline = pModel ? pModel.toJSON() : null;
1727
+ if (pipeline) {
1728
+ const cStatus = await this.containerService.inspectRunnerContainer(pipeline, gateRun.ephemeralContainerId).catch(() => ({ settled: false }));
1729
+ if (cStatus.settled && cStatus.exitCode !== 0) {
1730
+ const tail = await this.containerService.readContainerLogs(
1731
+ pipeline,
1732
+ gateRun.ephemeralContainerId,
1733
+ 120
1734
+ );
1735
+ const cleaned = await this.containerService.cleanupContainer(pipeline, gateRun.ephemeralContainerId).catch(() => false);
1736
+ if (cleaned) {
1737
+ await row.update({ ephemeralContainerId: null }).catch(() => void 0);
1738
+ }
1739
+ await this.getTestManagerService().ingestExternalResults(
1740
+ {
1741
+ runId: gateRun.testRunId,
1742
+ cases: [],
1743
+ finished: true,
1744
+ runnerError: [
1745
+ cStatus.errorMessage || `CI container exited with code ${String(cStatus.exitCode)}`,
1746
+ tail ? `Logs:
1747
+ ${tail.slice(-1500)}` : ""
1748
+ ].filter(Boolean).join("\n")
1749
+ },
1750
+ { waitDownstream: false, skipAuthCheck: true }
1751
+ ).catch(() => void 0);
1752
+ continue;
1753
+ }
1754
+ }
1755
+ }
1756
+ }
1757
+ const startedMs = gateRun.startedAt ? new Date(gateRun.startedAt).getTime() : gateRun.createdAt ? new Date(gateRun.createdAt).getTime() : nowMs;
1758
+ if (nowMs - startedMs > import_constants_internal.DEFAULT_CI_TIMEOUT_MS) {
1759
+ const staleJobId = gateRun.pendingJobId;
1760
+ await this.markGateRunFailed(gateRun.id, `CI Gate run exceeded timeout (${import_constants_internal.DEFAULT_CI_TIMEOUT_MS}ms)`);
1761
+ await this.settleJobExclusively(staleJobId, import_plugin_workflow.JOB_STATUS.FAILED, {
1762
+ gateRunId: gateRun.id,
1763
+ error: "CI Gate timed out"
1764
+ });
1765
+ }
1766
+ }
1767
+ },
1768
+ 0
1769
+ );
1770
+ }
1771
+ }
1772
+ // Annotate the CommonJS export names for ESM import in node:
1773
+ 0 && (module.exports = {
1774
+ CiGateWorkflowService,
1775
+ isPureBaselineDiffMismatch
1776
+ });