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,2310 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import { createHash } from 'node:crypto';
11
+ import type { Model } from '@nocobase/database';
12
+ import type WorkflowPlugin from '@nocobase/plugin-workflow';
13
+ import {
14
+ EXECUTION_STATUS,
15
+ getExecutionLockKey,
16
+ JOB_STATUS,
17
+ type JobModel,
18
+ type WorkflowModel,
19
+ } from '@nocobase/plugin-workflow';
20
+ import type Application from '@nocobase/server';
21
+ import {
22
+ CI_GATE_RUNS_COLLECTION,
23
+ CI_INSTRUCTIONS,
24
+ CI_MANAGED_WORKFLOW_KEY,
25
+ CI_MR_POLL_INTERVAL_MS,
26
+ CI_PIPELINES_COLLECTION,
27
+ CI_RECONCILE_INTERVAL_MS,
28
+ CI_WORKFLOW_TEMPLATE_MARKER,
29
+ CI_WORKFLOW_TEMPLATE_VERSION,
30
+ DEFAULT_CI_TIMEOUT_MS,
31
+ PORTAINER_PIPELINE_RUNS_COLLECTION,
32
+ PORTAINER_PIPELINES_COLLECTION,
33
+ TEST_RUNS_COLLECTION,
34
+ } from './constants-internal';
35
+ import type {
36
+ CiApprovalRecord,
37
+ CiApprovalState,
38
+ CiDeployOutcome,
39
+ CiEventType,
40
+ CiGateRunRecord,
41
+ CiPipelineRecord,
42
+ CiTriageSummary,
43
+ GitCommitStatusState,
44
+ ID,
45
+ } from '../../shared/types';
46
+ import { AiTriageService } from './AiTriageService';
47
+ import { type BuildProvenanceInput, EphemeralContainerService } from './EphemeralContainerService';
48
+ import { GitFeedbackService, matchesBranchPattern } from './GitFeedbackService';
49
+
50
+ interface LockHandleLike {
51
+ runExclusive<T>(fn: () => Promise<T>, ttl: number): Promise<T>;
52
+ }
53
+
54
+ interface LockManagerLike {
55
+ tryAcquire(key: string, timeout?: number): Promise<LockHandleLike | null>;
56
+ }
57
+
58
+ interface RunnerLaunchRequestLike {
59
+ run: {
60
+ id: number;
61
+ tenantId: number;
62
+ ephemeralSchemaName?: string | null;
63
+ frozenManifest?: { externalLauncherContext?: Record<string, unknown> | null } | null;
64
+ };
65
+ tenant: {
66
+ id: number;
67
+ key: string;
68
+ postgresSchema: string;
69
+ targetBaseUrl?: string | null;
70
+ };
71
+ manifest: {
72
+ runId: number;
73
+ tenantKey: string;
74
+ postgresSchema: string;
75
+ targetBaseUrl?: string | null;
76
+ manifestUrl: string;
77
+ callbackUrl: string;
78
+ };
79
+ groupId: string;
80
+ attempt: number;
81
+ scopedCallbackToken: string;
82
+ launcherContext?: Record<string, unknown> | null;
83
+ signal?: AbortSignal;
84
+ }
85
+
86
+ interface RunnerBackendLauncherLike {
87
+ launch(req: RunnerLaunchRequestLike): Promise<{
88
+ launched: boolean;
89
+ resourceId?: string | null;
90
+ logs: string[];
91
+ cleanupContext?: Record<string, unknown> | null;
92
+ }>;
93
+ collectEvidence?(params: {
94
+ run: { id: number; frozenManifest?: { externalLauncherContext?: Record<string, unknown> | null } | null };
95
+ resourceId: string;
96
+ cleanupContext?: Record<string, unknown> | null;
97
+ }): Promise<{ logs?: string[]; exitCode?: number; settled?: boolean; errorMessage?: string }>;
98
+ cleanup?(params: {
99
+ run: { id: number; frozenManifest?: { externalLauncherContext?: Record<string, unknown> | null } | null };
100
+ resourceId: string;
101
+ cleanupContext?: Record<string, unknown> | null;
102
+ }): Promise<boolean>;
103
+ }
104
+
105
+ interface TestManagerWorkflowServiceLike {
106
+ registerRunnerLauncher?(backend: string, launcher: RunnerBackendLauncherLike): void;
107
+ enqueueRun(params: Record<string, unknown>): Promise<Record<string, unknown>>;
108
+ getRunManifest(
109
+ runId: number,
110
+ callbackBaseUrl?: string,
111
+ ): Promise<{
112
+ runId: number;
113
+ tenantKey: string;
114
+ postgresSchema: string;
115
+ targetBaseUrl?: string | null;
116
+ callbackUrl: string;
117
+ manifestUrl: string;
118
+ }>;
119
+ decryptTenantCallbackToken(raw: unknown): Promise<string>;
120
+ ingestExternalResults(
121
+ payload: Record<string, unknown>,
122
+ opts?: { waitDownstream?: boolean; skipAuthCheck?: boolean },
123
+ ): Promise<Record<string, unknown>>;
124
+ saveAiTriageSummary(runId: number, summary: CiTriageSummary): Promise<Record<string, unknown>>;
125
+ approveAllRunBaselines(
126
+ runId: number,
127
+ approvedBy: string,
128
+ ): Promise<{ updatedDatasets: number; run: Record<string, unknown> }>;
129
+ getRunById?(runId: number): Promise<Record<string, unknown> | null>;
130
+ listCaseResultsForRun?(runId: number, extraFilter?: Record<string, unknown>): Promise<Array<Record<string, unknown>>>;
131
+ updateRunFields?(runId: number, values: Record<string, unknown>): Promise<Record<string, unknown> | null>;
132
+ metadataStore?: {
133
+ getRepo?: (
134
+ tenant: Record<string, unknown>,
135
+ collectionName: string,
136
+ ) => Promise<{
137
+ find: (opts?: Record<string, unknown>) => Promise<Model[]>;
138
+ }>;
139
+ };
140
+ }
141
+
142
+ export interface ApproverActor {
143
+ userId: number;
144
+ username: string;
145
+ isCiAdmin: boolean;
146
+ }
147
+
148
+ function isPlainRecord(val: unknown): val is Record<string, unknown> {
149
+ return Boolean(val) && typeof val === 'object' && !Array.isArray(val);
150
+ }
151
+
152
+ function canonicalJson(val: unknown): string {
153
+ if (val === null || val === undefined) return 'null';
154
+ if (typeof val !== 'object') return JSON.stringify(val);
155
+ if (Array.isArray(val)) return `[${val.map(canonicalJson).join(',')}]`;
156
+ const rec = val as Record<string, unknown>;
157
+ const keys = Object.keys(rec).sort();
158
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(rec[k])}`).join(',')}}`;
159
+ }
160
+
161
+ export function isPureBaselineDiffMismatch(testRun: Record<string, unknown> | null): boolean {
162
+ if (!testRun) return false;
163
+ const verdict = String(testRun.verdict || '');
164
+ if (verdict !== 'diff_mismatch') return false;
165
+ const reasonCode = testRun.verdictReasonCode ? String(testRun.verdictReasonCode) : '';
166
+ if (reasonCode && reasonCode !== 'DIFF_MISMATCH_ONLY' && reasonCode !== 'BASELINE_DIFF_MISMATCH') {
167
+ return false;
168
+ }
169
+ const metrics = isPlainRecord(testRun.summaryMetrics) ? testRun.summaryMetrics : {};
170
+ const total = Number(metrics.total ?? 0);
171
+ const executed = Number(metrics.executed ?? total - Number(metrics.skipped ?? 0));
172
+ const failed = Number(metrics.failed ?? 0);
173
+ const flaky = Number(metrics.flaky ?? 0);
174
+ const diffMismatch = Number(metrics.diffMismatch ?? 0);
175
+ return total > 0 && executed > 0 && failed === 0 && flaky === 0 && diffMismatch > 0;
176
+ }
177
+
178
+ export class CiGateWorkflowService {
179
+ private reconcileTimer: NodeJS.Timeout | null = null;
180
+ private mrPollTimer: NodeJS.Timeout | null = null;
181
+ private reconciling: Promise<void> | null = null;
182
+ private pollingMrs: Promise<void> | null = null;
183
+ private stopping = false;
184
+ private launchersRegistered = false;
185
+ private activeTasks = new Set<Promise<unknown>>();
186
+ private localLocks = new Map<string, Promise<void>>();
187
+
188
+ constructor(
189
+ private readonly app: Application,
190
+ private readonly workflow: WorkflowPlugin | undefined,
191
+ public readonly gitFeedbackService: GitFeedbackService,
192
+ public readonly containerService: EphemeralContainerService,
193
+ public readonly aiTriageService: AiTriageService,
194
+ ) {}
195
+
196
+ trackBackgroundTask(promise: Promise<unknown>): void {
197
+ const tracked = promise
198
+ .catch(() => undefined)
199
+ .finally(() => {
200
+ this.activeTasks.delete(tracked);
201
+ });
202
+ this.activeTasks.add(tracked);
203
+ }
204
+
205
+ private hasCollection(name: string): boolean {
206
+ try {
207
+ return Boolean(this.app.db.getCollection(name));
208
+ } catch {
209
+ return false;
210
+ }
211
+ }
212
+
213
+ private getTestManagerService(): TestManagerWorkflowServiceLike {
214
+ const tmPlugin = (this.app.pm.get('plugin-test-manager') || this.app.pm.get('test-manager')) as
215
+ | { workflowService?: TestManagerWorkflowServiceLike }
216
+ | undefined;
217
+ if (!tmPlugin?.workflowService) {
218
+ throw new Error('plugin-test-manager is required and must be enabled before running CI Gate workflows');
219
+ }
220
+ this.ensureLaunchersRegistered(tmPlugin.workflowService);
221
+ return tmPlugin.workflowService;
222
+ }
223
+
224
+ private ensureLaunchersRegistered(tmService?: TestManagerWorkflowServiceLike): void {
225
+ if (this.launchersRegistered) return;
226
+ const svc =
227
+ tmService ??
228
+ (
229
+ (this.app.pm.get('plugin-test-manager') || this.app.pm.get('test-manager')) as
230
+ | { workflowService?: TestManagerWorkflowServiceLike }
231
+ | undefined
232
+ )?.workflowService;
233
+ if (!svc || typeof svc.registerRunnerLauncher !== 'function') return;
234
+
235
+ const createAdapter = (backend: 'portainer_ephemeral' | 'cluster_ephemeral'): RunnerBackendLauncherLike => ({
236
+ launch: async (req) => {
237
+ const ctx = isPlainRecord(req.launcherContext)
238
+ ? req.launcherContext
239
+ : isPlainRecord(req.run?.frozenManifest?.externalLauncherContext)
240
+ ? (req.run.frozenManifest?.externalLauncherContext as Record<string, unknown>)
241
+ : {};
242
+ const pipelineId = Number(ctx.pipelineId || 0);
243
+ const gateRunId = Number(ctx.gateRunId || 0);
244
+ const pipeModel = (await this.app.db
245
+ .getRepository(CI_PIPELINES_COLLECTION)
246
+ .findOne({ filterByTk: pipelineId })) as Model | null;
247
+ const gateModel = (await this.app.db
248
+ .getRepository(CI_GATE_RUNS_COLLECTION)
249
+ .findOne({ filterByTk: gateRunId })) as Model | null;
250
+ if (!pipeModel || !gateModel) {
251
+ throw new Error(`CI Pipeline #${pipelineId} or Gate Run #${gateRunId} not found for ${backend} launch`);
252
+ }
253
+ const pipeline = pipeModel.toJSON() as CiPipelineRecord;
254
+ const gateRun = gateModel.toJSON() as CiGateRunRecord;
255
+ const testRunId = Number(req.run?.id || req.manifest?.runId || 0);
256
+
257
+ const launchRes = await this.containerService.launchOneShotContainer({
258
+ pipeline,
259
+ gateRun: { ...gateRun, testRunId },
260
+ testRunId,
261
+ groupId: req.groupId,
262
+ attempt: req.attempt,
263
+ tenantKey: req.manifest.tenantKey || req.tenant.key,
264
+ postgresSchema: req.manifest.postgresSchema || req.run.ephemeralSchemaName || req.tenant.postgresSchema,
265
+ targetBaseUrl: req.manifest.targetBaseUrl ?? req.tenant.targetBaseUrl ?? null,
266
+ manifestUrl: req.manifest.manifestUrl,
267
+ callbackUrl: req.manifest.callbackUrl,
268
+ callbackToken: req.scopedCallbackToken,
269
+ signal: req.signal,
270
+ });
271
+
272
+ let nextLogs = gateRun.logs || '';
273
+ for (const l of launchRes.logs) {
274
+ nextLogs = this.appendGateLog(nextLogs, 'CONTAINER', l);
275
+ }
276
+ await gateModel.update({
277
+ ephemeralContainerId: launchRes.containerId ?? gateRun.ephemeralContainerId ?? null,
278
+ logs: nextLogs,
279
+ });
280
+
281
+ return {
282
+ launched: launchRes.launched,
283
+ resourceId: launchRes.containerId ?? null,
284
+ logs: launchRes.logs,
285
+ cleanupContext: {
286
+ pipelineId,
287
+ gateRunId,
288
+ },
289
+ };
290
+ },
291
+ collectEvidence: async (params) => {
292
+ const ctx = isPlainRecord(params.cleanupContext)
293
+ ? params.cleanupContext
294
+ : isPlainRecord(params.run?.frozenManifest?.externalLauncherContext)
295
+ ? (params.run.frozenManifest?.externalLauncherContext as Record<string, unknown>)
296
+ : {};
297
+ const pipelineId = Number(ctx.pipelineId || 0);
298
+ if (!pipelineId || !params.resourceId) return {};
299
+ const pipeModel = (await this.app.db
300
+ .getRepository(CI_PIPELINES_COLLECTION)
301
+ .findOne({ filterByTk: pipelineId })) as Model | null;
302
+ if (!pipeModel) return {};
303
+ const logText = await this.containerService.readContainerLogs(
304
+ pipeModel.toJSON() as CiPipelineRecord,
305
+ params.resourceId,
306
+ 200,
307
+ );
308
+ return logText ? { logs: logText.split('\n').filter(Boolean) } : {};
309
+ },
310
+ cleanup: async (params) => {
311
+ const ctx = isPlainRecord(params.cleanupContext)
312
+ ? params.cleanupContext
313
+ : isPlainRecord(params.run?.frozenManifest?.externalLauncherContext)
314
+ ? (params.run.frozenManifest?.externalLauncherContext as Record<string, unknown>)
315
+ : {};
316
+ const pipelineId = Number(ctx.pipelineId || 0);
317
+ const gateRunId = Number(ctx.gateRunId || 0);
318
+ if (!pipelineId || !params.resourceId) return true;
319
+ const pipeModel = (await this.app.db
320
+ .getRepository(CI_PIPELINES_COLLECTION)
321
+ .findOne({ filterByTk: pipelineId })) as Model | null;
322
+ if (!pipeModel) return false;
323
+ const removed = await this.containerService.cleanupContainer(
324
+ pipeModel.toJSON() as CiPipelineRecord,
325
+ params.resourceId,
326
+ );
327
+ if (removed && gateRunId > 0) {
328
+ await this.app.db
329
+ .getRepository(CI_GATE_RUNS_COLLECTION)
330
+ .update({
331
+ filter: { id: gateRunId, ephemeralContainerId: params.resourceId },
332
+ values: { ephemeralContainerId: null },
333
+ })
334
+ .catch(() => undefined);
335
+ }
336
+ return removed;
337
+ },
338
+ });
339
+
340
+ svc.registerRunnerLauncher('portainer_ephemeral', createAdapter('portainer_ephemeral'));
341
+ svc.registerRunnerLauncher('cluster_ephemeral', createAdapter('cluster_ephemeral'));
342
+ this.launchersRegistered = true;
343
+ }
344
+
345
+ private async runWithLock<T>(
346
+ lockKey: string,
347
+ ttlMs: number,
348
+ work: () => Promise<T>,
349
+ timeoutMs = 15_000,
350
+ ): Promise<T | undefined> {
351
+ const runLocallySerialized = async (): Promise<T> => {
352
+ const prev = this.localLocks.get(lockKey) ?? Promise.resolve();
353
+ const next = prev.catch(() => undefined).then(() => work());
354
+ const settled = next
355
+ .then(
356
+ () => undefined,
357
+ () => undefined,
358
+ )
359
+ .finally(() => {
360
+ if (this.localLocks.get(lockKey) === settled) {
361
+ this.localLocks.delete(lockKey);
362
+ }
363
+ });
364
+ this.localLocks.set(lockKey, settled);
365
+ return next;
366
+ };
367
+
368
+ const lockManager = (this.app as unknown as { lockManager?: LockManagerLike }).lockManager;
369
+ if (!lockManager?.tryAcquire) {
370
+ return runLocallySerialized();
371
+ }
372
+ let handle: LockHandleLike | null = null;
373
+ try {
374
+ handle = await lockManager.tryAcquire(lockKey, timeoutMs);
375
+ } catch {
376
+ return undefined;
377
+ }
378
+ if (!handle) return undefined;
379
+ return handle.runExclusive(runLocallySerialized, ttlMs);
380
+ }
381
+
382
+ async assertValidPipelineConfiguration(values: Partial<CiPipelineRecord>): Promise<void> {
383
+ const gateMode = values.deployGateMode ?? 'none';
384
+ const portainerPipelineId = values.portainerPipelineId ? Number(values.portainerPipelineId) : 0;
385
+ if (gateMode !== 'none' && portainerPipelineId > 0 && this.hasCollection(PORTAINER_PIPELINES_COLLECTION)) {
386
+ const linked = (await this.app.db
387
+ .getRepository(PORTAINER_PIPELINES_COLLECTION)
388
+ .findOne({ filterByTk: portainerPipelineId })) as Model | null;
389
+ if (linked && Boolean(linked.get('deployEnabled'))) {
390
+ const err = new Error(
391
+ `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.`,
392
+ ) as Error & { status?: number };
393
+ err.status = 400;
394
+ throw err;
395
+ }
396
+ }
397
+ }
398
+
399
+ async provisionManagedWorkflow(): Promise<WorkflowModel | null> {
400
+ if (!this.workflow) return null;
401
+
402
+ const provisioned = await this.runWithLock(
403
+ 'workflow-ci:provision',
404
+ 60_000,
405
+ async () => {
406
+ const wfRepo = this.app.db.getRepository('workflows');
407
+ const revisions = (await wfRepo.find({
408
+ filter: { key: CI_MANAGED_WORKFLOW_KEY },
409
+ sort: ['-id'],
410
+ })) as WorkflowModel[];
411
+
412
+ const activeRev = revisions.find((r) => Boolean(r.get('enabled')));
413
+ if (activeRev) {
414
+ const opts = activeRev.get('options');
415
+ const marker = isPlainRecord(opts) ? opts[CI_WORKFLOW_TEMPLATE_MARKER] : null;
416
+ if (isPlainRecord(marker) && marker.templateVersion === CI_WORKFLOW_TEMPLATE_VERSION) {
417
+ return activeRev;
418
+ }
419
+ }
420
+
421
+ const matchingInactive = revisions.find((r) => {
422
+ const opts = r.get('options');
423
+ const marker = isPlainRecord(opts) ? opts[CI_WORKFLOW_TEMPLATE_MARKER] : null;
424
+ return isPlainRecord(marker) && marker.templateVersion === CI_WORKFLOW_TEMPLATE_VERSION;
425
+ });
426
+ if (matchingInactive) {
427
+ await this.app.db.sequelize.transaction(async (transaction) => {
428
+ await wfRepo.update({
429
+ filter: { key: CI_MANAGED_WORKFLOW_KEY },
430
+ values: { enabled: false, current: false },
431
+ transaction,
432
+ });
433
+ await matchingInactive.update({ enabled: true, current: true }, { transaction });
434
+ });
435
+ return matchingInactive;
436
+ }
437
+
438
+ return this.app.db.sequelize.transaction(async (transaction) => {
439
+ if (revisions.length > 0) {
440
+ await wfRepo.update({
441
+ filter: { key: CI_MANAGED_WORKFLOW_KEY },
442
+ values: { enabled: false, current: false },
443
+ transaction,
444
+ });
445
+ }
446
+
447
+ const created = (await wfRepo.create({
448
+ values: {
449
+ key: CI_MANAGED_WORKFLOW_KEY,
450
+ current: true,
451
+ title: 'CI Testing, Triage & Quality Gate Pipeline',
452
+ type: 'collection',
453
+ sync: false,
454
+ enabled: false,
455
+ config: {
456
+ collection: CI_GATE_RUNS_COLLECTION,
457
+ mode: 1,
458
+ condition: { workflowKey: { $eq: CI_MANAGED_WORKFLOW_KEY } },
459
+ },
460
+ options: {
461
+ timeout: DEFAULT_CI_TIMEOUT_MS * 2,
462
+ [CI_WORKFLOW_TEMPLATE_MARKER]: {
463
+ managed: true,
464
+ templateVersion: CI_WORKFLOW_TEMPLATE_VERSION,
465
+ },
466
+ },
467
+ },
468
+ transaction,
469
+ })) as WorkflowModel;
470
+
471
+ const nodeDefs = [
472
+ {
473
+ key: 'ci_dispatch',
474
+ type: CI_INSTRUCTIONS.dispatchRun,
475
+ title: '1. Dispatch Test Run, QA Stack Lease & Runner',
476
+ config: {},
477
+ },
478
+ {
479
+ key: 'ci_triage',
480
+ type: CI_INSTRUCTIONS.aiTriage,
481
+ title: '2. AI Root-Cause Failure Triage & Agent Loop',
482
+ config: {},
483
+ },
484
+ {
485
+ key: 'ci_feedback',
486
+ type: CI_INSTRUCTIONS.publishGitFeedback,
487
+ title: '3. Publish Git Commit Status, Sticky PR Comment & Review Context',
488
+ config: {},
489
+ },
490
+ {
491
+ key: 'ci_wait_approval',
492
+ type: CI_INSTRUCTIONS.waitApproval,
493
+ title: '4. Await Authorized QA Baseline Approval (gateApproverIds)',
494
+ config: {},
495
+ },
496
+ {
497
+ key: 'ci_promote',
498
+ type: CI_INSTRUCTIONS.promoteDeploy,
499
+ title: '5. Enforce Pre-Deploy Quality Gate, Promote & Verify Rollout',
500
+ config: {},
501
+ },
502
+ ];
503
+
504
+ let previousNode: Awaited<ReturnType<WorkflowModel['createNode']>> | null = null;
505
+ for (const def of nodeDefs) {
506
+ const node = await created.createNode(
507
+ {
508
+ ...def,
509
+ upstreamId: previousNode?.id ?? null,
510
+ },
511
+ { transaction },
512
+ );
513
+ if (previousNode) {
514
+ await previousNode.update({ downstreamId: node.id }, { transaction });
515
+ }
516
+ previousNode = node;
517
+ }
518
+
519
+ await created.update({ enabled: true }, { transaction });
520
+ return created;
521
+ });
522
+ },
523
+ 30_000,
524
+ );
525
+
526
+ if (provisioned) return provisioned;
527
+ return (await this.app.db.getRepository('workflows').findOne({
528
+ filter: { key: CI_MANAGED_WORKFLOW_KEY, enabled: true },
529
+ })) as WorkflowModel | null;
530
+ }
531
+
532
+ async start(): Promise<void> {
533
+ this.stopping = false;
534
+ this.ensureLaunchersRegistered();
535
+ await this.provisionManagedWorkflow();
536
+ if (!this.reconcileTimer && this.workflow) {
537
+ this.reconcileTimer = setInterval(() => {
538
+ if (!this.reconciling) {
539
+ this.reconciling = this.reconcile()
540
+ .catch((error) => {
541
+ this.app.logger?.warn?.('[plugin-workflow-ci] Reconcile tick error', {
542
+ error: error instanceof Error ? error.message : String(error),
543
+ });
544
+ })
545
+ .finally(() => {
546
+ this.reconciling = null;
547
+ });
548
+ }
549
+ }, CI_RECONCILE_INTERVAL_MS);
550
+ this.reconcileTimer.unref?.();
551
+ }
552
+
553
+ if (!this.mrPollTimer) {
554
+ this.mrPollTimer = setInterval(() => {
555
+ if (!this.pollingMrs) {
556
+ this.pollingMrs = this.pollDueMergeRequests()
557
+ .catch(() => undefined)
558
+ .finally(() => {
559
+ this.pollingMrs = null;
560
+ });
561
+ }
562
+ }, CI_MR_POLL_INTERVAL_MS);
563
+ this.mrPollTimer.unref?.();
564
+ }
565
+ }
566
+
567
+ async stop(): Promise<void> {
568
+ this.stopping = true;
569
+ if (this.reconcileTimer) {
570
+ clearInterval(this.reconcileTimer);
571
+ this.reconcileTimer = null;
572
+ }
573
+ if (this.mrPollTimer) {
574
+ clearInterval(this.mrPollTimer);
575
+ this.mrPollTimer = null;
576
+ }
577
+ if (this.reconciling) await this.reconciling.catch(() => undefined);
578
+ if (this.pollingMrs) await this.pollingMrs.catch(() => undefined);
579
+ if (this.activeTasks.size > 0) {
580
+ await Promise.allSettled([...this.activeTasks]);
581
+ }
582
+ }
583
+
584
+ private async invalidateOrSupersedePriorGateRun(
585
+ staleModel: Model,
586
+ supersededByCommitSha: string,
587
+ reason: string,
588
+ ): Promise<void> {
589
+ const stale = staleModel.toJSON() as CiGateRunRecord;
590
+ const pendingJobId = stale.pendingJobId;
591
+ const wasWaitingApproval = stale.state === 'waiting_approval' || stale.approvalState === 'pending';
592
+ const prevRecord = isPlainRecord(stale.approvalRecord) ? stale.approvalRecord : {};
593
+ const nextApprovalState: CiApprovalState = wasWaitingApproval
594
+ ? 'invalidated'
595
+ : stale.approvalState ?? 'not_required';
596
+ const nextDeployOutcome: CiDeployOutcome =
597
+ stale.eventType === 'pre_deploy_gate' && stale.deployOutcome === 'pending'
598
+ ? 'blocked'
599
+ : stale.deployOutcome ?? 'not_applicable';
600
+
601
+ const logs = this.appendGateLog(
602
+ stale.logs,
603
+ 'SUPERSEDED',
604
+ `${reason} (newer sha=${supersededByCommitSha.slice(0, 12)})`,
605
+ );
606
+ const startedMs = stale.startedAt ? new Date(stale.startedAt).getTime() : Date.now();
607
+
608
+ await staleModel.update({
609
+ state: 'canceled',
610
+ approvalState: nextApprovalState,
611
+ ...(wasWaitingApproval
612
+ ? {
613
+ approvalRecord: {
614
+ ...prevRecord,
615
+ invalidatedAt: new Date().toISOString(),
616
+ invalidatedReason: reason,
617
+ invalidatedByCommitSha: supersededByCommitSha,
618
+ },
619
+ }
620
+ : {}),
621
+ deployOutcome: nextDeployOutcome,
622
+ pendingJobId: null,
623
+ errorMessage: reason,
624
+ logs,
625
+ finishedAt: new Date().toISOString(),
626
+ durationMs: Math.max(0, Date.now() - startedMs),
627
+ });
628
+
629
+ if (stale.testRunId && wasWaitingApproval) {
630
+ await this.updateTestRunFields(stale.testRunId, { ciGateStatus: 'gate_blocked' });
631
+ }
632
+
633
+ if (pendingJobId) {
634
+ await this.settleJobExclusively(pendingJobId, JOB_STATUS.RESOLVED, {
635
+ gateRunId: stale.id,
636
+ canceled: true,
637
+ invalidated: wasWaitingApproval,
638
+ reason,
639
+ });
640
+ }
641
+ }
642
+
643
+ async enqueueGateRun(params: {
644
+ pipelineId: number;
645
+ eventType: CiEventType;
646
+ branch: string;
647
+ targetBranch?: string | null;
648
+ commitSha: string;
649
+ baseSha?: string | null;
650
+ commitMessage?: string | null;
651
+ mrIid?: number | null;
652
+ buildRunId?: number | null;
653
+ operationId?: string | null;
654
+ }): Promise<CiGateRunRecord> {
655
+ if (this.stopping) {
656
+ const err = new Error('CI Gate service is shutting down') as Error & { status?: number };
657
+ err.status = 503;
658
+ throw err;
659
+ }
660
+ const flow = await this.provisionManagedWorkflow();
661
+ if (!flow || !flow.get('enabled')) {
662
+ const err = new Error(`Managed CI workflow "${CI_MANAGED_WORKFLOW_KEY}" is unavailable`) as Error & {
663
+ status?: number;
664
+ };
665
+ err.status = 503;
666
+ throw err;
667
+ }
668
+
669
+ const pipelineModel = (await this.app.db
670
+ .getRepository(CI_PIPELINES_COLLECTION)
671
+ .findOne({ filterByTk: params.pipelineId })) as Model | null;
672
+ if (!pipelineModel) {
673
+ const err = new Error(`CI Pipeline #${params.pipelineId} not found`) as Error & { status?: number };
674
+ err.status = 404;
675
+ throw err;
676
+ }
677
+ const pipeline = pipelineModel.toJSON() as CiPipelineRecord;
678
+ const cleanBranch = (params.branch || 'main').trim();
679
+ const cleanSha = (params.commitSha || 'HEAD').trim();
680
+ const cleanOpId = params.operationId ? String(params.operationId).trim() : null;
681
+
682
+ const lockedResult = await this.runWithLock(
683
+ `workflow-ci:enqueue:${pipeline.id}`,
684
+ 30_000,
685
+ async () => {
686
+ const gateRepo = this.app.db.getRepository(CI_GATE_RUNS_COLLECTION);
687
+
688
+ // 1. Strict Deduplication by operationId (for cluster hot-reload smoke) or (pipelineId, eventType, commitSha)
689
+ if (cleanOpId) {
690
+ const dupOp = (await gateRepo.findOne({
691
+ filter: {
692
+ pipelineId: pipeline.id,
693
+ eventType: params.eventType,
694
+ operationId: cleanOpId,
695
+ },
696
+ sort: ['-id'],
697
+ })) as Model | null;
698
+ if (dupOp) {
699
+ return dupOp.toJSON() as CiGateRunRecord;
700
+ }
701
+ } else if (params.eventType !== 'manual') {
702
+ const dupSha = (await gateRepo.findOne({
703
+ filter: {
704
+ pipelineId: pipeline.id,
705
+ eventType: params.eventType,
706
+ commitSha: cleanSha,
707
+ ...(params.mrIid ? { mrIid: params.mrIid } : { branch: cleanBranch }),
708
+ },
709
+ sort: ['-id'],
710
+ })) as Model | null;
711
+ if (dupSha) {
712
+ return dupSha.toJSON() as CiGateRunRecord;
713
+ }
714
+ }
715
+
716
+ // 2. Check active / waiting_approval runs on the same branch or MR
717
+ if (params.eventType !== 'manual' && params.eventType !== 'hot_reload_smoke') {
718
+ const activeOnScope = (await gateRepo.find({
719
+ filter: {
720
+ pipelineId: pipeline.id,
721
+ state: { $in: ['queued', 'running_ci', 'triaging', 'publishing_feedback', 'waiting_approval'] },
722
+ ...(params.mrIid ? { mrIid: params.mrIid } : { branch: cleanBranch }),
723
+ },
724
+ sort: ['-id'],
725
+ })) as Model[];
726
+
727
+ if (activeOnScope.length > 0) {
728
+ const newestActive = activeOnScope[0].toJSON() as CiGateRunRecord;
729
+
730
+ // Guard against late/out-of-order webhook delivery for an older commit when remote HEAD is already newestActive.commitSha
731
+ if (
732
+ newestActive.commitSha !== cleanSha &&
733
+ pipeline.gitRepositoryId &&
734
+ (params.eventType === 'push' || params.eventType === 'pre_deploy_gate')
735
+ ) {
736
+ const headCheck = await this.gitFeedbackService.verifyBranchHeadSha({
737
+ gitRepositoryId: pipeline.gitRepositoryId,
738
+ branch: cleanBranch,
739
+ expectedSha: cleanSha,
740
+ });
741
+ if (
742
+ headCheck.configured &&
743
+ !headCheck.verified &&
744
+ headCheck.actualHeadSha &&
745
+ headCheck.actualHeadSha === newestActive.commitSha
746
+ ) {
747
+ const ignoredStale = (await gateRepo.create({
748
+ values: {
749
+ pipelineId: pipeline.id,
750
+ tenantId: pipeline.tenantId,
751
+ buildRunId: params.buildRunId ?? null,
752
+ gitRepositoryId: pipeline.gitRepositoryId ?? null,
753
+ eventType: params.eventType,
754
+ branch: cleanBranch,
755
+ targetBranch: params.targetBranch ?? null,
756
+ commitSha: cleanSha,
757
+ baseSha: params.baseSha ?? null,
758
+ commitMessage: params.commitMessage ?? null,
759
+ mrIid: params.mrIid ?? null,
760
+ state: 'canceled',
761
+ approvalState: 'not_required',
762
+ deployOutcome: 'blocked',
763
+ errorMessage: `Ignored out-of-order stale commit ${cleanSha.slice(
764
+ 0,
765
+ 12,
766
+ )} because branch HEAD is already ${newestActive.commitSha.slice(0, 12)}`,
767
+ finishedAt: new Date().toISOString(),
768
+ durationMs: 0,
769
+ },
770
+ })) as Model;
771
+ return ignoredStale.toJSON() as CiGateRunRecord;
772
+ }
773
+ }
774
+
775
+ // Newer commit arrived -> invalidate any prior waiting_approval run (and supersede queued/running_ci) BEFORE starting new run
776
+ let invalidatedAny = false;
777
+ for (const staleModel of activeOnScope) {
778
+ const staleSha = String(staleModel.get('commitSha') || '');
779
+ if (staleSha === cleanSha) continue;
780
+ const staleState = String(staleModel.get('state') || '');
781
+ if (staleState === 'waiting_approval' || staleState === 'queued' || staleState === 'running_ci') {
782
+ await this.invalidateOrSupersedePriorGateRun(
783
+ staleModel,
784
+ cleanSha,
785
+ staleState === 'waiting_approval'
786
+ ? 'Pending approval invalidated by newer commit on branch/PR'
787
+ : 'Superseded by newer commit on branch/PR',
788
+ );
789
+ invalidatedAny = true;
790
+ }
791
+ }
792
+ if (invalidatedAny) {
793
+ await new Promise<void>((resolve) => setTimeout(resolve, 25));
794
+ }
795
+ }
796
+ }
797
+
798
+ const initialDeployOutcome: CiDeployOutcome =
799
+ params.eventType === 'pre_deploy_gate' && pipeline.deployGateMode !== 'none' ? 'pending' : 'not_applicable';
800
+
801
+ const created = (await gateRepo.create({
802
+ values: {
803
+ pipelineId: pipeline.id,
804
+ tenantId: pipeline.tenantId,
805
+ buildRunId: params.buildRunId ?? null,
806
+ operationId: cleanOpId,
807
+ gitRepositoryId: pipeline.gitRepositoryId ?? null,
808
+ eventType: params.eventType,
809
+ branch: cleanBranch,
810
+ targetBranch: params.targetBranch ?? null,
811
+ commitSha: cleanSha,
812
+ baseSha: params.baseSha ?? null,
813
+ commitMessage: params.commitMessage ?? null,
814
+ mrIid: params.mrIid ?? null,
815
+ workflowKey: String(flow.get('key')),
816
+ workflowId: Number(flow.get('id')),
817
+ state: 'queued',
818
+ approvalState: 'not_required',
819
+ deployOutcome: initialDeployOutcome,
820
+ },
821
+ })) as Model;
822
+
823
+ return created.toJSON() as CiGateRunRecord;
824
+ },
825
+ 20_000,
826
+ );
827
+
828
+ if (!lockedResult) {
829
+ throw new Error(`Timed out acquiring enqueue lock for CI Pipeline #${pipeline.id}`);
830
+ }
831
+ return lockedResult;
832
+ }
833
+
834
+ private async loadGateContext(gateRunId: number): Promise<{
835
+ gateModel: Model;
836
+ gateRun: CiGateRunRecord;
837
+ pipelineModel: Model;
838
+ pipeline: CiPipelineRecord;
839
+ testRun: Record<string, unknown> | null;
840
+ }> {
841
+ const gateModel = (await this.app.db
842
+ .getRepository(CI_GATE_RUNS_COLLECTION)
843
+ .findOne({ filterByTk: gateRunId })) as Model | null;
844
+ if (!gateModel) {
845
+ throw new Error(`CI Gate Run #${gateRunId} not found`);
846
+ }
847
+ const gateRun = gateModel.toJSON() as CiGateRunRecord;
848
+ const pipelineModel = (await this.app.db
849
+ .getRepository(CI_PIPELINES_COLLECTION)
850
+ .findOne({ filterByTk: gateRun.pipelineId })) as Model | null;
851
+ if (!pipelineModel) {
852
+ throw new Error(`CI Pipeline #${gateRun.pipelineId} not found`);
853
+ }
854
+ const pipeline = pipelineModel.toJSON() as CiPipelineRecord;
855
+
856
+ let testRun: Record<string, unknown> | null;
857
+ if (gateRun.testRunId) {
858
+ testRun = await this.fetchTestRun(gateRun.testRunId);
859
+ } else {
860
+ testRun = null;
861
+ }
862
+
863
+ return { gateModel, gateRun, pipelineModel, pipeline, testRun };
864
+ }
865
+
866
+ private async resolveBuildProvenance(
867
+ pipeline: CiPipelineRecord,
868
+ gateRun: CiGateRunRecord,
869
+ ): Promise<BuildProvenanceInput | null> {
870
+ if (!this.hasCollection(PORTAINER_PIPELINE_RUNS_COLLECTION)) return null;
871
+ const runsRepo = this.app.db.getRepository(PORTAINER_PIPELINE_RUNS_COLLECTION);
872
+ let buildModel: Model | null = null;
873
+ if (gateRun.buildRunId) {
874
+ buildModel = (await runsRepo.findOne({ filterByTk: gateRun.buildRunId })) as Model | null;
875
+ } else if (pipeline.portainerPipelineId) {
876
+ buildModel = (await runsRepo.findOne({
877
+ filter: {
878
+ pipelineId: pipeline.portainerPipelineId,
879
+ commitSha: gateRun.commitSha,
880
+ state: 'succeeded',
881
+ },
882
+ sort: ['-id'],
883
+ })) as Model | null;
884
+ }
885
+ if (!buildModel) return null;
886
+
887
+ const buildRes = isPlainRecord(buildModel.get('buildResult'))
888
+ ? (buildModel.get('buildResult') as Record<string, unknown>)
889
+ : {};
890
+ const appliedEnv = isPlainRecord(buildModel.get('appliedEnv'))
891
+ ? (buildModel.get('appliedEnv') as Record<string, string>)
892
+ : {};
893
+ const commitSha = String(buildModel.get('commitSha') || gateRun.commitSha);
894
+ const resolvedImageTag =
895
+ (typeof buildRes.resolvedImageTag === 'string' && buildRes.resolvedImageTag) ||
896
+ appliedEnv.IMAGE_TAG ||
897
+ appliedEnv.GIT_SHORT_SHA ||
898
+ commitSha.slice(0, 7);
899
+
900
+ const rawArtifacts = Array.isArray(buildRes.serviceArtifacts) ? buildRes.serviceArtifacts : [];
901
+ return {
902
+ buildRunId: Number(buildModel.get('id')),
903
+ commitSha,
904
+ resolvedImageTag,
905
+ imageTagEnvName: typeof buildRes.imageTagEnvName === 'string' ? buildRes.imageTagEnvName : null,
906
+ dockerDaemonId: typeof buildRes.dockerDaemonId === 'string' ? buildRes.dockerDaemonId : null,
907
+ serviceArtifacts: rawArtifacts
908
+ .filter(isPlainRecord)
909
+ .map((a) => ({
910
+ serviceName: typeof a.serviceName === 'string' ? a.serviceName : undefined,
911
+ imageRef: String(a.imageRef || ''),
912
+ repository: String(a.repository || ''),
913
+ tag: String(a.tag || resolvedImageTag),
914
+ imageConfigId: typeof a.imageConfigId === 'string' ? a.imageConfigId : null,
915
+ repoDigest: typeof a.repoDigest === 'string' ? a.repoDigest : null,
916
+ architecture: typeof a.architecture === 'string' ? a.architecture : null,
917
+ os: typeof a.os === 'string' ? a.os : null,
918
+ }))
919
+ .filter((a) => Boolean(a.imageRef)),
920
+ };
921
+ }
922
+
923
+ public fetchTestRun = async (testRunId: number): Promise<Record<string, unknown> | null> => {
924
+ try {
925
+ const tmService = this.getTestManagerService();
926
+ if (typeof tmService.getRunById === 'function') {
927
+ const externalRun = await tmService.getRunById(testRunId);
928
+ if (externalRun) return externalRun;
929
+ }
930
+ } catch {
931
+ // Fall back to main DB outbox lookup
932
+ }
933
+ try {
934
+ const trModel = (await this.app.db
935
+ .getRepository(TEST_RUNS_COLLECTION)
936
+ .findOne({ filterByTk: testRunId })) as Model | null;
937
+ return trModel ? (trModel.toJSON() as Record<string, unknown>) : null;
938
+ } catch {
939
+ return null;
940
+ }
941
+ };
942
+
943
+ private async updateTestRunFields(testRunId: number, values: Record<string, unknown>): Promise<void> {
944
+ try {
945
+ const tmService = this.getTestManagerService();
946
+ if (typeof tmService.updateRunFields === 'function') {
947
+ await tmService.updateRunFields(testRunId, values);
948
+ return;
949
+ }
950
+ } catch {
951
+ // Fall back to main DB update
952
+ }
953
+ await this.app.db
954
+ .getRepository(TEST_RUNS_COLLECTION)
955
+ .update({ filterByTk: testRunId, values })
956
+ .catch(() => undefined);
957
+ }
958
+
959
+ private appendGateLog(existing: string | null | undefined, stage: string, line: string): string {
960
+ const entry = `${new Date().toISOString()} [${stage}] ${line}`;
961
+ return existing ? `${existing}\n${entry}`.slice(-120_000) : entry;
962
+ }
963
+
964
+ async runDispatchStage(
965
+ gateRunId: number,
966
+ meta: { workflowId?: number; executionId?: number; jobId?: number; signal?: AbortSignal },
967
+ ): Promise<{ waitingTestRun: boolean; payload: Record<string, unknown> }> {
968
+ const { gateModel, gateRun, pipeline } = await this.loadGateContext(gateRunId);
969
+ const tmService = this.getTestManagerService();
970
+ const basePublicUrl = (process.env.APP_PUBLIC_URL || 'http://localhost:13000').replace(/\/+$/, '');
971
+ const workbenchUrl = `${basePublicUrl}/v/admin/settings/test-manager`;
972
+
973
+ let logs = this.appendGateLog(
974
+ gateRun.logs,
975
+ 'DISPATCH',
976
+ `Starting CI Gate Run #${gateRun.id} for branch="${gateRun.branch}" sha="${gateRun.commitSha.slice(0, 12)}"`,
977
+ );
978
+
979
+ await gateModel.update({
980
+ workflowId: meta.workflowId ?? gateRun.workflowId ?? null,
981
+ executionId: meta.executionId ?? gateRun.executionId ?? null,
982
+ pendingJobId: meta.jobId ?? null,
983
+ state: 'running_ci',
984
+ startedAt: gateRun.startedAt || new Date().toISOString(),
985
+ logs,
986
+ });
987
+
988
+ if (pipeline.publishCommitStatus) {
989
+ const statusRes = await this.gitFeedbackService.publishCommitStatus({
990
+ gateRunId: gateRun.id,
991
+ pipelineId: pipeline.id,
992
+ gitRepositoryId: gateRun.gitRepositoryId ?? pipeline.gitRepositoryId,
993
+ commitSha: gateRun.commitSha,
994
+ branch: gateRun.branch,
995
+ state: 'pending',
996
+ context: pipeline.statusContext || 'nocobase/ci-test-manager',
997
+ description: `CI test run in progress on branch ${gateRun.branch}`,
998
+ targetUrl: workbenchUrl,
999
+ });
1000
+ logs = this.appendGateLog(logs, 'GIT_STATUS', statusRes.detail);
1001
+ await gateModel.update({
1002
+ commitStatusState: statusRes.published ? 'pending' : null,
1003
+ gitFeedbackSyncState: statusRes.published ? 'synced' : statusRes.queuedRetry ? 'retrying' : 'not_applicable',
1004
+ logs,
1005
+ });
1006
+ }
1007
+
1008
+ const buildProv = await this.resolveBuildProvenance(pipeline, gateRun);
1009
+ if (buildProv && !gateRun.buildRunId) {
1010
+ await gateModel.update({ buildRunId: buildProv.buildRunId });
1011
+ }
1012
+
1013
+ const qaStackBinding =
1014
+ pipeline.qaStackId && pipeline.qaEndpointId
1015
+ ? {
1016
+ instanceId: pipeline.qaInstanceId ?? pipeline.portainerInstanceId ?? null,
1017
+ endpointId: Number(pipeline.qaEndpointId),
1018
+ stackId: Number(pipeline.qaStackId),
1019
+ appServices: Array.isArray(pipeline.qaAppServices) ? pipeline.qaAppServices : null,
1020
+ }
1021
+ : null;
1022
+
1023
+ const triggerSourceMap: Record<CiEventType, string> = {
1024
+ push: 'git_webhook',
1025
+ merge_request: 'git_mr',
1026
+ pre_deploy_gate: 'ci_gate',
1027
+ hot_reload_smoke: 'cluster_hot_reload',
1028
+ manual: 'ci_gate',
1029
+ };
1030
+
1031
+ const usesEphemeralLauncher =
1032
+ pipeline.runnerBackend === 'portainer_ephemeral' || pipeline.runnerBackend === 'cluster_ephemeral';
1033
+
1034
+ const enqueuedTestRun = await tmService.enqueueRun({
1035
+ tenantId: pipeline.tenantId,
1036
+ pipelineId: pipeline.id,
1037
+ triggerSource: triggerSourceMap[gateRun.eventType] || 'ci_gate',
1038
+ triggeredByUser: `ci:${pipeline.key}`,
1039
+ gitRepositoryId: gateRun.gitRepositoryId ?? pipeline.gitRepositoryId ?? null,
1040
+ gitBranch: gateRun.branch,
1041
+ gitTargetBranch: gateRun.targetBranch ?? null,
1042
+ gitBaseSha: gateRun.baseSha ?? null,
1043
+ gitCommitSha: gateRun.commitSha,
1044
+ gitCommitMessage: gateRun.commitMessage ?? null,
1045
+ mrIid: gateRun.mrIid ?? null,
1046
+ portainerPipelineId: pipeline.portainerPipelineId ?? null,
1047
+ portainerPipelineRunId: buildProv?.buildRunId ?? gateRun.buildRunId ?? null,
1048
+ buildRunId: buildProv?.buildRunId ?? gateRun.buildRunId ?? null,
1049
+ resolvedImageTag: buildProv?.resolvedImageTag ?? null,
1050
+ imageTagEnvName: buildProv?.imageTagEnvName ?? null,
1051
+ expectedServiceImages: buildProv?.serviceArtifacts
1052
+ ? buildProv.serviceArtifacts.map((a) => ({
1053
+ serviceName: a.serviceName,
1054
+ imageRef: a.imageRef,
1055
+ imageConfigId: a.imageConfigId ?? null,
1056
+ repoDigest: a.repoDigest ?? null,
1057
+ dockerDaemonId: buildProv.dockerDaemonId ?? null,
1058
+ architecture: a.architecture ?? null,
1059
+ os: a.os ?? null,
1060
+ }))
1061
+ : null,
1062
+ qaStackBinding,
1063
+ requireScopedToken: pipeline.deployGateMode !== 'none',
1064
+ externalLauncherBackend: usesEphemeralLauncher ? pipeline.runnerBackend : null,
1065
+ externalLauncherContext: usesEphemeralLauncher
1066
+ ? {
1067
+ pipelineId: pipeline.id,
1068
+ gateRunId: gateRun.id,
1069
+ }
1070
+ : null,
1071
+ ciGateStatus: pipeline.deployGateMode !== 'none' ? 'pending_gate' : 'none',
1072
+ cancelSuperseded: false, // CiGateWorkflowService already manages branch/PR superseding atomically
1073
+ });
1074
+
1075
+ const testRunId = Number(enqueuedTestRun.id);
1076
+ logs = this.appendGateLog(
1077
+ logs,
1078
+ 'TEST_RUN',
1079
+ `Enqueued Test Manager run #${testRunId}${qaStackBinding ? ` (QA stack lease #${qaStackBinding.stackId})` : ''}${
1080
+ usesEphemeralLauncher ? ` -> runner launcher "${pipeline.runnerBackend}"` : ''
1081
+ }`,
1082
+ );
1083
+ await gateModel.update({ testRunId, logs });
1084
+
1085
+ // Check if synchronous or fast-failing test workflow already completed
1086
+ const freshTestRun = await this.fetchTestRun(testRunId);
1087
+ const freshStage = freshTestRun ? String(freshTestRun.stage || '') : '';
1088
+ const freshVerdict = freshTestRun ? String(freshTestRun.verdict || '') : '';
1089
+ const freshReason = freshTestRun?.verdictReasonCode ? String(freshTestRun.verdictReasonCode) : null;
1090
+ const freshSnap = isPlainRecord(freshTestRun?.environmentSnapshot) ? freshTestRun.environmentSnapshot : null;
1091
+
1092
+ if (freshStage === 'completed' && !freshSnap?.flakyRetryRunId) {
1093
+ await gateModel.update({
1094
+ pendingJobId: null,
1095
+ testVerdict: freshVerdict,
1096
+ verdictReasonCode: freshReason,
1097
+ });
1098
+ return {
1099
+ waitingTestRun: false,
1100
+ payload: {
1101
+ gateRunId: gateRun.id,
1102
+ testRunId,
1103
+ verdict: freshVerdict,
1104
+ verdictReasonCode: freshReason,
1105
+ },
1106
+ };
1107
+ }
1108
+
1109
+ return {
1110
+ waitingTestRun: true,
1111
+ payload: {
1112
+ gateRunId: gateRun.id,
1113
+ testRunId,
1114
+ waiting: true,
1115
+ },
1116
+ };
1117
+ }
1118
+
1119
+ async runAiTriageStage(gateRunId: number): Promise<Record<string, unknown>> {
1120
+ const { gateModel, gateRun, pipeline, testRun } = await this.loadGateContext(gateRunId);
1121
+ if (!pipeline.enableAiTriage || !testRun) {
1122
+ return { gateRunId, triageSkipped: true };
1123
+ }
1124
+
1125
+ const verdict = String(testRun.verdict || gateRun.testVerdict || '');
1126
+ if (verdict !== 'failed' && verdict !== 'diff_mismatch' && verdict !== 'error') {
1127
+ return { gateRunId, verdict, triageSkipped: true };
1128
+ }
1129
+
1130
+ await gateModel.update({ state: 'triaging' });
1131
+ const triage = await this.aiTriageService.analyzeFailedRun({
1132
+ pipeline,
1133
+ gateRun,
1134
+ testRun,
1135
+ });
1136
+
1137
+ if (triage) {
1138
+ const dispatchNote = triage.agentDispatched
1139
+ ? ` [Agent Loop #${triage.agentLoopRunId}]`
1140
+ : triage.triageError
1141
+ ? ` [Agent dispatch skipped: ${triage.triageError}]`
1142
+ : '';
1143
+ const logs = this.appendGateLog(
1144
+ gateRun.logs,
1145
+ 'AI_TRIAGE',
1146
+ `Classified as "${triage.classification}" (${Math.round(triage.confidence * 100)}%): ${
1147
+ triage.rootCause
1148
+ }${dispatchNote}`,
1149
+ );
1150
+ await gateModel.update({ triageResult: triage, logs });
1151
+ if (gateRun.testRunId) {
1152
+ await this.getTestManagerService()
1153
+ .saveAiTriageSummary(gateRun.testRunId, triage)
1154
+ .catch(() => undefined);
1155
+ }
1156
+ }
1157
+
1158
+ return {
1159
+ gateRunId,
1160
+ triage: triage ?? null,
1161
+ };
1162
+ }
1163
+
1164
+ async runPublishGitFeedbackStage(gateRunId: number): Promise<Record<string, unknown>> {
1165
+ const { gateModel, gateRun, pipeline, testRun } = await this.loadGateContext(gateRunId);
1166
+ await gateModel.update({ state: 'publishing_feedback' });
1167
+
1168
+ // Preserve immutable testVerdict; approvalState decides whether baseline mismatch was approved by QA
1169
+ const verdict = String(testRun?.verdict || gateRun.testVerdict || 'error');
1170
+ const reasonCode = testRun?.verdictReasonCode
1171
+ ? String(testRun.verdictReasonCode)
1172
+ : gateRun.verdictReasonCode ?? null;
1173
+ const isApprovedDiff = verdict === 'diff_mismatch' && gateRun.approvalState === 'approved';
1174
+
1175
+ const basePublicUrl = (process.env.APP_PUBLIC_URL || 'http://localhost:13000').replace(/\/+$/, '');
1176
+ const workbenchUrl = `${basePublicUrl}/v/admin/settings/test-manager`;
1177
+
1178
+ let statusState: GitCommitStatusState = 'error';
1179
+ if (verdict === 'passed' || isApprovedDiff) statusState = 'success';
1180
+ else if (verdict === 'failed' || verdict === 'diff_mismatch') statusState = 'failure';
1181
+
1182
+ let logs = gateRun.logs || '';
1183
+ let prCommentId = gateRun.prCommentId ?? null;
1184
+ let syncState: CiGateRunRecord['gitFeedbackSyncState'] = 'not_applicable';
1185
+
1186
+ if (pipeline.publishCommitStatus && verdict !== 'canceled') {
1187
+ const metrics = isPlainRecord(testRun?.summaryMetrics) ? testRun.summaryMetrics : {};
1188
+ const desc =
1189
+ verdict === 'passed'
1190
+ ? `Passed ${Number(metrics.passed ?? 0)}/${Number(metrics.total ?? 0)} cases`
1191
+ : isApprovedDiff
1192
+ ? `Baseline diff approved by QA (${Number(metrics.diffMismatch ?? 0)} dataset diff(s))`
1193
+ : `CI verdict: ${verdict}${reasonCode ? ` [${reasonCode}]` : ''} (failed=${Number(
1194
+ metrics.failed ?? 0,
1195
+ )}, diffMismatch=${Number(metrics.diffMismatch ?? 0)})`;
1196
+ const stRes = await this.gitFeedbackService.publishCommitStatus({
1197
+ gateRunId: gateRun.id,
1198
+ pipelineId: pipeline.id,
1199
+ gitRepositoryId: gateRun.gitRepositoryId ?? pipeline.gitRepositoryId,
1200
+ commitSha: gateRun.commitSha,
1201
+ branch: gateRun.branch,
1202
+ state: statusState,
1203
+ context: pipeline.statusContext || 'nocobase/ci-test-manager',
1204
+ description: desc,
1205
+ targetUrl: workbenchUrl,
1206
+ });
1207
+ logs = this.appendGateLog(logs, 'GIT_STATUS', stRes.detail);
1208
+ syncState = stRes.published ? 'synced' : stRes.queuedRetry ? 'retrying' : syncState;
1209
+ }
1210
+
1211
+ if (pipeline.publishPrComment && gateRun.mrIid) {
1212
+ const commentRes = await this.gitFeedbackService.upsertStickyPrComment({
1213
+ pipeline,
1214
+ gateRun: { ...gateRun, testVerdict: verdict, verdictReasonCode: reasonCode },
1215
+ testRun,
1216
+ triage: gateRun.triageResult ?? null,
1217
+ workbenchUrl,
1218
+ });
1219
+ if (commentRes.commentId) {
1220
+ prCommentId = commentRes.commentId;
1221
+ }
1222
+ logs = this.appendGateLog(logs, 'PR_COMMENT', commentRes.detail);
1223
+ if (commentRes.queuedRetry) {
1224
+ syncState = 'retrying';
1225
+ } else if (commentRes.published && syncState !== 'retrying') {
1226
+ syncState = 'synced';
1227
+ }
1228
+ }
1229
+
1230
+ if (pipeline.enrichGitReview) {
1231
+ const enrichedCount = await this.gitFeedbackService.enrichPendingGitReviewRequests({
1232
+ gitRepositoryId: gateRun.gitRepositoryId ?? pipeline.gitRepositoryId,
1233
+ mrIid: gateRun.mrIid,
1234
+ commitSha: gateRun.commitSha,
1235
+ testRun,
1236
+ triage: gateRun.triageResult ?? null,
1237
+ });
1238
+ if (enrichedCount > 0) {
1239
+ logs = this.appendGateLog(logs, 'GIT_REVIEW', `Enriched ${enrichedCount} pending AI Git Review request(s)`);
1240
+ }
1241
+ }
1242
+
1243
+ await gateModel.update({
1244
+ testVerdict: verdict,
1245
+ verdictReasonCode: reasonCode,
1246
+ commitStatusState: verdict === 'canceled' ? gateRun.commitStatusState : statusState,
1247
+ gitFeedbackSyncState: syncState,
1248
+ prCommentId,
1249
+ logs,
1250
+ });
1251
+
1252
+ return {
1253
+ gateRunId,
1254
+ verdict,
1255
+ verdictReasonCode: reasonCode,
1256
+ commitStatusState: statusState,
1257
+ prCommentId,
1258
+ };
1259
+ }
1260
+
1261
+ private async computeDiffMismatchFingerprint(testRunId: number): Promise<string> {
1262
+ const tmService = this.getTestManagerService();
1263
+ const diffRows =
1264
+ typeof tmService.listCaseResultsForRun === 'function'
1265
+ ? await tmService.listCaseResultsForRun(testRunId, { status: 'diff_mismatch' })
1266
+ : [];
1267
+ const normalized = diffRows
1268
+ .map((r) => ({
1269
+ caseCode: String(r.caseCode || ''),
1270
+ datasetId: Number(r.datasetId || 0),
1271
+ diffReport: r.diffReport ?? null,
1272
+ }))
1273
+ .sort((a, b) => a.caseCode.localeCompare(b.caseCode));
1274
+ return createHash('sha256').update(canonicalJson(normalized), 'utf8').digest('hex');
1275
+ }
1276
+
1277
+ private async verifyFrozenDatasetBaselinesUnchanged(
1278
+ tenantId: number,
1279
+ expectedVersions: Record<string, number> | null | undefined,
1280
+ ): Promise<{ ok: boolean; detail?: string }> {
1281
+ if (!expectedVersions || Object.keys(expectedVersions).length === 0) {
1282
+ return { ok: true };
1283
+ }
1284
+ const datasetIds = Object.keys(expectedVersions)
1285
+ .map((k) => Number(k))
1286
+ .filter((n) => Number.isFinite(n) && n > 0);
1287
+ if (datasetIds.length === 0) return { ok: true };
1288
+
1289
+ try {
1290
+ const tenantModel = (await this.app.db
1291
+ .getRepository('testTenants')
1292
+ .findOne({ filterByTk: tenantId })) as Model | null;
1293
+ if (!tenantModel) return { ok: false, detail: `Tenant #${tenantId} not found` };
1294
+ const tmService = this.getTestManagerService();
1295
+ const dsRepo = tmService.metadataStore?.getRepo
1296
+ ? await tmService.metadataStore.getRepo(tenantModel.toJSON() as Record<string, unknown>, 'testDatasets')
1297
+ : this.app.db.getRepository('testDatasets');
1298
+
1299
+ const dsModels = (await dsRepo.find({ filter: { id: { $in: datasetIds } } })) as Model[];
1300
+ const byId = new Map<number, number>();
1301
+ for (const m of dsModels) {
1302
+ byId.set(Number(m.get('id')), Number(m.get('baselineVersion') ?? 1));
1303
+ }
1304
+ for (const dsId of datasetIds) {
1305
+ const currentVer = byId.get(dsId);
1306
+ const expectedVer = Number(expectedVersions[String(dsId)]);
1307
+ if (currentVer === undefined) {
1308
+ return { ok: false, detail: `Dataset #${dsId} was deleted while run was waiting approval` };
1309
+ }
1310
+ if (currentVer !== expectedVer) {
1311
+ return {
1312
+ ok: false,
1313
+ detail: `Dataset #${dsId} baselineVersion changed (${expectedVer} -> ${currentVer}) while waiting approval`,
1314
+ };
1315
+ }
1316
+ }
1317
+ return { ok: true };
1318
+ } catch (error) {
1319
+ return {
1320
+ ok: false,
1321
+ detail: `Failed verifying dataset baseline versions: ${error instanceof Error ? error.message : String(error)}`,
1322
+ };
1323
+ }
1324
+ }
1325
+
1326
+ async runWaitApprovalStage(
1327
+ gateRunId: number,
1328
+ meta: { workflowId?: number; executionId?: number; jobId?: number },
1329
+ ): Promise<{ waitingApproval: boolean; payload: Record<string, unknown> }> {
1330
+ const { gateModel, gateRun, pipeline, testRun } = await this.loadGateContext(gateRunId);
1331
+ const verdict = String(testRun?.verdict || gateRun.testVerdict || 'error');
1332
+
1333
+ if (
1334
+ pipeline.deployGateMode !== 'manual_on_diff_mismatch' ||
1335
+ gateRun.approvalState === 'approved' ||
1336
+ !isPureBaselineDiffMismatch(testRun)
1337
+ ) {
1338
+ if (gateRun.approvalState !== 'approved' && gateRun.approvalState !== 'invalidated') {
1339
+ await gateModel.update({ approvalState: 'not_required' });
1340
+ }
1341
+ return {
1342
+ waitingApproval: false,
1343
+ payload: {
1344
+ gateRunId,
1345
+ verdict,
1346
+ approvalState: gateRun.approvalState || 'not_required',
1347
+ },
1348
+ };
1349
+ }
1350
+
1351
+ const frozenManifest = isPlainRecord(testRun?.frozenManifest) ? testRun?.frozenManifest : {};
1352
+ const frozenBaselineVersions = isPlainRecord(frozenManifest?.datasetBaselineVersions)
1353
+ ? (frozenManifest.datasetBaselineVersions as Record<string, number>)
1354
+ : {};
1355
+ const originalDiffHash = gateRun.testRunId ? await this.computeDiffMismatchFingerprint(gateRun.testRunId) : null;
1356
+
1357
+ const approvalRecord: CiApprovalRecord = {
1358
+ approvedBaselineVersions: frozenBaselineVersions,
1359
+ originalDiffHash,
1360
+ };
1361
+
1362
+ const logs = this.appendGateLog(
1363
+ gateRun.logs,
1364
+ 'MANUAL_GATE',
1365
+ `Paused in ci_wait_approval: pure baseline diff mismatch on sha=${gateRun.commitSha.slice(
1366
+ 0,
1367
+ 12,
1368
+ )} awaiting authorized QA approver`,
1369
+ );
1370
+
1371
+ if (gateRun.testRunId) {
1372
+ await this.updateTestRunFields(gateRun.testRunId, { ciGateStatus: 'waiting_manual_approval' });
1373
+ }
1374
+
1375
+ await gateModel.update({
1376
+ state: 'waiting_approval',
1377
+ approvalState: 'pending',
1378
+ approvalRecord,
1379
+ pendingJobId: meta.jobId ?? null,
1380
+ logs,
1381
+ });
1382
+
1383
+ // Optional sync to workflowManualTasks if @nocobase/plugin-workflow-manual is installed
1384
+ if (meta.jobId && this.hasCollection('workflowManualTasks')) {
1385
+ await this.app.db
1386
+ .getRepository('workflowManualTasks')
1387
+ .create({
1388
+ values: {
1389
+ jobId: meta.jobId,
1390
+ workflowId: meta.workflowId ?? gateRun.workflowId ?? null,
1391
+ executionId: meta.executionId ?? gateRun.executionId ?? null,
1392
+ status: 0,
1393
+ title: `Approve CI Baseline Diff — ${pipeline.name} (#${gateRun.id})`,
1394
+ assignees: Array.isArray(pipeline.gateApproverIds) ? pipeline.gateApproverIds : [],
1395
+ },
1396
+ })
1397
+ .catch(() => undefined);
1398
+ }
1399
+
1400
+ return {
1401
+ waitingApproval: true,
1402
+ payload: {
1403
+ gateRunId,
1404
+ verdict,
1405
+ approvalState: 'pending',
1406
+ },
1407
+ };
1408
+ }
1409
+
1410
+ private isBranchAllowedForProduction(branch: string, pipeline: CiPipelineRecord): boolean {
1411
+ if (Array.isArray(pipeline.protectedBranches) && pipeline.protectedBranches.length > 0) {
1412
+ return matchesBranchPattern(branch, pipeline.protectedBranches.join(','));
1413
+ }
1414
+ return matchesBranchPattern(branch, pipeline.branchPattern || 'main,master,release/*');
1415
+ }
1416
+
1417
+ async runPromoteDeployStage(gateRunId: number, signal?: AbortSignal): Promise<Record<string, unknown>> {
1418
+ const { gateModel, gateRun, pipelineModel, pipeline, testRun } = await this.loadGateContext(gateRunId);
1419
+ const verdict = String(testRun?.verdict || gateRun.testVerdict || 'error');
1420
+ const reasonCode = testRun?.verdictReasonCode
1421
+ ? String(testRun.verdictReasonCode)
1422
+ : gateRun.verdictReasonCode ?? null;
1423
+ const approvalState = gateRun.approvalState || 'not_required';
1424
+ const isApprovedDiff = verdict === 'diff_mismatch' && approvalState === 'approved';
1425
+ const startedMs = gateRun.startedAt ? new Date(gateRun.startedAt).getTime() : Date.now();
1426
+ let logs = gateRun.logs || '';
1427
+
1428
+ if (verdict === 'canceled' || gateRun.state === 'canceled') {
1429
+ await gateModel.update({
1430
+ state: 'canceled',
1431
+ finishedAt: new Date().toISOString(),
1432
+ durationMs: Math.max(0, Date.now() - startedMs),
1433
+ });
1434
+ return { gateRunId, state: 'canceled', deployOutcome: gateRun.deployOutcome || 'not_applicable' };
1435
+ }
1436
+
1437
+ // Rule 2.3: PR/MR, non-pre_deploy_gate push, manual Run CI, hot-reload canary, or deployGateMode='none' NEVER promote production!
1438
+ if (pipeline.deployGateMode === 'none' || gateRun.eventType !== 'pre_deploy_gate') {
1439
+ const finalState = verdict === 'passed' || isApprovedDiff ? 'succeeded' : 'failed';
1440
+ if (gateRun.testRunId && pipeline.deployGateMode !== 'none') {
1441
+ await this.updateTestRunFields(gateRun.testRunId, {
1442
+ ciGateStatus: finalState === 'succeeded' ? 'gate_passed' : 'gate_blocked',
1443
+ });
1444
+ }
1445
+ await gateModel.update({
1446
+ state: finalState,
1447
+ testVerdict: verdict,
1448
+ verdictReasonCode: reasonCode,
1449
+ deployOutcome: 'not_applicable',
1450
+ ...(finalState === 'failed'
1451
+ ? { errorMessage: gateRun.errorMessage || `CI check failed with verdict="${verdict}"` }
1452
+ : { errorMessage: null }),
1453
+ logs,
1454
+ finishedAt: new Date().toISOString(),
1455
+ durationMs: Math.max(0, Date.now() - startedMs),
1456
+ });
1457
+ return {
1458
+ gateRunId,
1459
+ state: finalState,
1460
+ verdict,
1461
+ approvalState,
1462
+ deployOutcome: 'not_applicable',
1463
+ };
1464
+ }
1465
+
1466
+ const blockPromotion = async (reason: string): Promise<Record<string, unknown>> => {
1467
+ logs = this.appendGateLog(logs, 'GATE_BLOCKED', reason);
1468
+ if (gateRun.testRunId) {
1469
+ await this.updateTestRunFields(gateRun.testRunId, { ciGateStatus: 'gate_blocked' });
1470
+ }
1471
+ await gateModel.update({
1472
+ state: 'failed',
1473
+ testVerdict: verdict,
1474
+ verdictReasonCode: reasonCode,
1475
+ deployOutcome: 'blocked',
1476
+ errorMessage: reason,
1477
+ logs,
1478
+ finishedAt: new Date().toISOString(),
1479
+ durationMs: Math.max(0, Date.now() - startedMs),
1480
+ });
1481
+ return {
1482
+ gateRunId,
1483
+ state: 'failed',
1484
+ gateBlocked: true,
1485
+ verdict,
1486
+ deployOutcome: 'blocked',
1487
+ error: reason,
1488
+ };
1489
+ };
1490
+
1491
+ // 1. Verify linked Portainer pipeline is build-only (deployEnabled === false)
1492
+ try {
1493
+ await this.assertValidPipelineConfiguration(pipeline);
1494
+ } catch (error) {
1495
+ return blockPromotion(error instanceof Error ? error.message : String(error));
1496
+ }
1497
+
1498
+ // 2. Verify repository & protected branch match
1499
+ if (
1500
+ pipeline.gitRepositoryId &&
1501
+ gateRun.gitRepositoryId &&
1502
+ Number(pipeline.gitRepositoryId) !== Number(gateRun.gitRepositoryId)
1503
+ ) {
1504
+ return blockPromotion(
1505
+ `Repository mismatch: gateRun.gitRepositoryId=${gateRun.gitRepositoryId} !== pipeline.gitRepositoryId=${pipeline.gitRepositoryId}`,
1506
+ );
1507
+ }
1508
+ if (!this.isBranchAllowedForProduction(gateRun.branch, pipeline)) {
1509
+ return blockPromotion(`Branch "${gateRun.branch}" is not in pipeline protectedBranches for production promotion`);
1510
+ }
1511
+
1512
+ // 3. Verify commitSha is still current HEAD of release branch via Git API (when PAT configured) & Portainer pipeline state
1513
+ if (pipeline.gitRepositoryId) {
1514
+ const headVerify = await this.gitFeedbackService.verifyBranchHeadSha({
1515
+ gitRepositoryId: pipeline.gitRepositoryId,
1516
+ branch: gateRun.branch,
1517
+ expectedSha: gateRun.commitSha,
1518
+ });
1519
+ if (headVerify.configured && !headVerify.verified) {
1520
+ return blockPromotion(`Stale commit blocked from production promotion: ${headVerify.detail}`);
1521
+ }
1522
+ }
1523
+ if (pipeline.portainerPipelineId && this.hasCollection(PORTAINER_PIPELINES_COLLECTION)) {
1524
+ const linkedPipe = (await this.app.db
1525
+ .getRepository(PORTAINER_PIPELINES_COLLECTION)
1526
+ .findOne({ filterByTk: pipeline.portainerPipelineId })) as Model | null;
1527
+ const lastKnownSha = linkedPipe?.get('lastKnownSha') ? String(linkedPipe.get('lastKnownSha')).trim() : '';
1528
+ if (lastKnownSha && lastKnownSha !== gateRun.commitSha) {
1529
+ return blockPromotion(
1530
+ `Portainer pipeline #${pipeline.portainerPipelineId} has already advanced to ${lastKnownSha.slice(
1531
+ 0,
1532
+ 12,
1533
+ )}; blocking stale commit ${gateRun.commitSha.slice(0, 12)}`,
1534
+ );
1535
+ }
1536
+ }
1537
+
1538
+ // 4. Verify strict verdict & flaky / auto-discovered-only guards
1539
+ const metrics = isPlainRecord(testRun?.summaryMetrics) ? testRun.summaryMetrics : {};
1540
+ const flakyCount = Number(metrics.flaky ?? 0);
1541
+ const failedCount = Number(metrics.failed ?? 0);
1542
+
1543
+ if (flakyCount > 0 || reasonCode === 'AUTO_DISCOVERED_ONLY') {
1544
+ return blockPromotion(
1545
+ flakyCount > 0
1546
+ ? `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.`
1547
+ : 'Quality Gate blocked promotion: run executed auto-discovered cases only without declared requiredCaseIds.',
1548
+ );
1549
+ }
1550
+
1551
+ if (!(verdict === 'passed' && failedCount === 0) && !isApprovedDiff) {
1552
+ return blockPromotion(`Quality Gate blocked promotion because CI verdict is "${verdict}"`);
1553
+ }
1554
+
1555
+ const buildProv = await this.resolveBuildProvenance(pipeline, gateRun);
1556
+ if (pipeline.portainerPipelineId && !buildProv) {
1557
+ return blockPromotion(`Missing verified Portainer build provenance for commit ${gateRun.commitSha.slice(0, 12)}`);
1558
+ }
1559
+ if (buildProv && buildProv.commitSha !== gateRun.commitSha) {
1560
+ return blockPromotion(
1561
+ `Build artifact SHA (${buildProv.commitSha.slice(0, 12)}) does not match gate commit (${gateRun.commitSha.slice(
1562
+ 0,
1563
+ 12,
1564
+ )})`,
1565
+ );
1566
+ }
1567
+
1568
+ await gateModel.update({ state: 'promoting_deploy', deployOutcome: 'pending' });
1569
+
1570
+ const targetInst = pipeline.deployInstanceId ?? pipeline.portainerInstanceId ?? 0;
1571
+ const targetEp = pipeline.deployEndpointId ?? pipeline.portainerEndpointId ?? 0;
1572
+ const targetStack = pipeline.deployStackId ?? 0;
1573
+ const prodLockKey = `workflow-ci:prod-stack:${targetInst}:${targetEp}:${targetStack}`;
1574
+
1575
+ const promotion = await this.runWithLock(
1576
+ prodLockKey,
1577
+ 120_000,
1578
+ async () => {
1579
+ const freshPipeModel = (await this.app.db
1580
+ .getRepository(CI_PIPELINES_COLLECTION)
1581
+ .findOne({ filterByTk: pipeline.id })) as Model | null;
1582
+ const freshPipeline = freshPipeModel ? (freshPipeModel.toJSON() as CiPipelineRecord) : pipeline;
1583
+ return this.containerService.promoteRuntimeDeployStack({
1584
+ pipeline: freshPipeline,
1585
+ gateRun,
1586
+ buildProvenance: buildProv,
1587
+ signal,
1588
+ });
1589
+ },
1590
+ 30_000,
1591
+ );
1592
+
1593
+ if (!promotion) {
1594
+ return blockPromotion(`Timed out acquiring production stack lock (${prodLockKey})`);
1595
+ }
1596
+
1597
+ logs = this.appendGateLog(logs, 'PROMOTE_DEPLOY', promotion.detail);
1598
+
1599
+ if (promotion.updatedGoodSnapshot) {
1600
+ await pipelineModel.update({
1601
+ lastKnownGoodSnapshot: promotion.updatedGoodSnapshot,
1602
+ });
1603
+ }
1604
+ if (promotion.haltPromotion) {
1605
+ await pipelineModel.update({
1606
+ promotionHalted: true,
1607
+ promotionHaltReason: promotion.haltReason || promotion.detail,
1608
+ });
1609
+ }
1610
+
1611
+ const succeeded = promotion.promoted === true && promotion.deployOutcome === 'deployed';
1612
+ if (gateRun.testRunId) {
1613
+ await this.updateTestRunFields(gateRun.testRunId, {
1614
+ ciGateStatus: succeeded ? 'gate_passed' : 'gate_blocked',
1615
+ });
1616
+ }
1617
+
1618
+ await gateModel.update({
1619
+ state: succeeded ? 'succeeded' : 'failed',
1620
+ testVerdict: verdict,
1621
+ verdictReasonCode: reasonCode,
1622
+ deployOutcome: promotion.deployOutcome,
1623
+ deployTargetSummary: promotion as unknown as Record<string, unknown>,
1624
+ rollbackRecord: promotion.rollbackRecord ?? null,
1625
+ errorMessage: succeeded ? null : promotion.detail,
1626
+ logs,
1627
+ finishedAt: new Date().toISOString(),
1628
+ durationMs: Math.max(0, Date.now() - startedMs),
1629
+ });
1630
+
1631
+ return {
1632
+ gateRunId,
1633
+ state: succeeded ? 'succeeded' : 'failed',
1634
+ deployOutcome: promotion.deployOutcome,
1635
+ promotion,
1636
+ };
1637
+ }
1638
+
1639
+ private async withSqliteBusyRetry<T>(fn: () => Promise<T>, maxAttempts = 5): Promise<T> {
1640
+ let lastError: unknown;
1641
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
1642
+ try {
1643
+ return await fn();
1644
+ } catch (error) {
1645
+ lastError = error;
1646
+ const msg = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
1647
+ const isSqliteBusy = msg.includes('SQLITE_BUSY') || msg.includes('database is locked');
1648
+ if (!isSqliteBusy || attempt >= maxAttempts) {
1649
+ throw error;
1650
+ }
1651
+ await new Promise<void>((resolve) => setTimeout(resolve, 50 * attempt));
1652
+ }
1653
+ }
1654
+ throw lastError;
1655
+ }
1656
+
1657
+ async approveDiffAndPromote(gateRunId: number, actor: ApproverActor): Promise<CiGateRunRecord> {
1658
+ const lockedResult = await this.runWithLock(
1659
+ `workflow-ci:approve:${gateRunId}`,
1660
+ 30_000,
1661
+ async () => {
1662
+ const { gateRun, pipeline, testRun } = await this.loadGateContext(gateRunId);
1663
+
1664
+ // 1. Strict gateApproverIds check (no admin bypass when gateApproverIds is configured!)
1665
+ const configuredApprovers = Array.isArray(pipeline.gateApproverIds)
1666
+ ? pipeline.gateApproverIds.map((id) => Number(id)).filter((n) => Number.isFinite(n) && n > 0)
1667
+ : [];
1668
+ if (configuredApprovers.length > 0) {
1669
+ if (!configuredApprovers.includes(Number(actor.userId))) {
1670
+ const err = new Error(
1671
+ `Forbidden: User #${actor.userId} is not listed in pipeline gateApproverIds ([${configuredApprovers.join(
1672
+ ', ',
1673
+ )}])`,
1674
+ ) as Error & { status?: number };
1675
+ err.status = 403;
1676
+ throw err;
1677
+ }
1678
+ } else if (!actor.isCiAdmin) {
1679
+ const err = new Error(
1680
+ 'Forbidden: CI Quality Gate admin permission is required to approve baselines',
1681
+ ) as Error & {
1682
+ status?: number;
1683
+ };
1684
+ err.status = 403;
1685
+ throw err;
1686
+ }
1687
+
1688
+ if (!gateRun.testRunId) {
1689
+ const err = new Error('CI Gate Run has no linked Test Manager run') as Error & { status?: number };
1690
+ err.status = 400;
1691
+ throw err;
1692
+ }
1693
+
1694
+ if (gateRun.state !== 'waiting_approval' || gateRun.approvalState !== 'pending') {
1695
+ const err = new Error(
1696
+ `Gate Run #${gateRunId} cannot be approved in state="${gateRun.state}" approvalState="${
1697
+ gateRun.approvalState || 'not_required'
1698
+ }"`,
1699
+ ) as Error & { status?: number };
1700
+ err.status = 409;
1701
+ throw err;
1702
+ }
1703
+
1704
+ if (!isPureBaselineDiffMismatch(testRun)) {
1705
+ const err = new Error(
1706
+ `Baseline approval is only permitted for pure baseline diff mismatches (current verdict="${String(
1707
+ testRun?.verdict,
1708
+ )}", reason="${String(testRun?.verdictReasonCode || '')}")`,
1709
+ ) as Error & { status?: number };
1710
+ err.status = 409;
1711
+ throw err;
1712
+ }
1713
+
1714
+ // 2. Check superseding runs & branch HEAD & dataset baseline version / diff hash consistency BEFORE CAS
1715
+ const gateRepo = this.app.db.getRepository(CI_GATE_RUNS_COLLECTION);
1716
+ const newerRun = (await gateRepo.findOne({
1717
+ filter: {
1718
+ pipelineId: pipeline.id,
1719
+ id: { $gt: gateRun.id },
1720
+ ...(gateRun.mrIid ? { mrIid: gateRun.mrIid } : { branch: gateRun.branch }),
1721
+ state: { $ne: 'canceled' },
1722
+ },
1723
+ })) as Model | null;
1724
+ if (newerRun && String(newerRun.get('commitSha')) !== gateRun.commitSha) {
1725
+ const freshModel = (await gateRepo.findOne({ filterByTk: gateRunId })) as Model | null;
1726
+ if (freshModel) {
1727
+ await this.invalidateOrSupersedePriorGateRun(
1728
+ freshModel,
1729
+ String(newerRun.get('commitSha')),
1730
+ 'Approval rejected because a newer commit arrived on this branch/PR',
1731
+ );
1732
+ }
1733
+ const err = new Error(
1734
+ `Gate Run #${gateRunId} was invalidated by newer commit ${String(newerRun.get('commitSha')).slice(0, 12)}`,
1735
+ ) as Error & { status?: number };
1736
+ err.status = 409;
1737
+ throw err;
1738
+ }
1739
+
1740
+ if (gateRun.eventType === 'pre_deploy_gate' && pipeline.gitRepositoryId) {
1741
+ const headCheck = await this.gitFeedbackService.verifyBranchHeadSha({
1742
+ gitRepositoryId: pipeline.gitRepositoryId,
1743
+ branch: gateRun.branch,
1744
+ expectedSha: gateRun.commitSha,
1745
+ });
1746
+ if (headCheck.configured && !headCheck.verified) {
1747
+ const freshModel = (await gateRepo.findOne({ filterByTk: gateRunId })) as Model | null;
1748
+ if (freshModel) {
1749
+ await this.invalidateOrSupersedePriorGateRun(
1750
+ freshModel,
1751
+ headCheck.actualHeadSha || 'HEAD',
1752
+ `Approval invalidated: ${headCheck.detail}`,
1753
+ );
1754
+ }
1755
+ const err = new Error(`Approval invalidated: ${headCheck.detail}`) as Error & { status?: number };
1756
+ err.status = 409;
1757
+ throw err;
1758
+ }
1759
+ }
1760
+
1761
+ const prevApprovalRec = isPlainRecord(gateRun.approvalRecord)
1762
+ ? (gateRun.approvalRecord as CiApprovalRecord)
1763
+ : {};
1764
+ const dsVersionCheck = await this.verifyFrozenDatasetBaselinesUnchanged(
1765
+ pipeline.tenantId,
1766
+ prevApprovalRec.approvedBaselineVersions,
1767
+ );
1768
+ if (!dsVersionCheck.ok) {
1769
+ const freshModel = (await gateRepo.findOne({ filterByTk: gateRunId })) as Model | null;
1770
+ if (freshModel) {
1771
+ await this.invalidateOrSupersedePriorGateRun(
1772
+ freshModel,
1773
+ gateRun.commitSha,
1774
+ dsVersionCheck.detail || 'Dataset baseline version drifted',
1775
+ );
1776
+ }
1777
+ const err = new Error(`Approval invalidated: ${dsVersionCheck.detail}`) as Error & { status?: number };
1778
+ err.status = 409;
1779
+ throw err;
1780
+ }
1781
+
1782
+ if (prevApprovalRec.originalDiffHash) {
1783
+ const currentHash = await this.computeDiffMismatchFingerprint(gateRun.testRunId);
1784
+ if (currentHash !== prevApprovalRec.originalDiffHash) {
1785
+ const err = new Error(
1786
+ 'Diff mismatch fingerprint changed since gate paused; refusing stale approval',
1787
+ ) as Error & {
1788
+ status?: number;
1789
+ };
1790
+ err.status = 409;
1791
+ throw err;
1792
+ }
1793
+ }
1794
+
1795
+ // 3. Atomic CAS claim on ciGateRuns so double-click / concurrent requests approve & promote AT MOST ONCE!
1796
+ const approvedAt = new Date().toISOString();
1797
+ const approvalRecord: CiApprovalRecord = {
1798
+ ...prevApprovalRec,
1799
+ approvedByUserId: actor.userId,
1800
+ approvedBy: actor.username,
1801
+ approvedAt,
1802
+ approvedCommitSha: gateRun.commitSha,
1803
+ approvedBuildRunId: gateRun.buildRunId ?? null,
1804
+ };
1805
+ const pendingWaitJobId = gateRun.pendingJobId;
1806
+
1807
+ const [claimedCount] = await gateRepo.update({
1808
+ filter: {
1809
+ id: gateRunId,
1810
+ state: 'waiting_approval',
1811
+ approvalState: 'pending',
1812
+ commitSha: gateRun.commitSha,
1813
+ },
1814
+ values: {
1815
+ state: 'promoting_deploy',
1816
+ approvalState: 'approved',
1817
+ approvalRecord,
1818
+ pendingJobId: null,
1819
+ logs: this.appendGateLog(
1820
+ gateRun.logs,
1821
+ 'BASELINE_APPROVED',
1822
+ `QA baseline diff approved by ${actor.username} (userId=${actor.userId}) on sha=${gateRun.commitSha.slice(
1823
+ 0,
1824
+ 12,
1825
+ )}`,
1826
+ ),
1827
+ },
1828
+ });
1829
+
1830
+ if (!claimedCount) {
1831
+ const err = new Error(`Gate Run #${gateRunId} was already approved, invalidated, or superseded`) as Error & {
1832
+ status?: number;
1833
+ };
1834
+ err.status = 409;
1835
+ throw err;
1836
+ }
1837
+
1838
+ const tmService = this.getTestManagerService();
1839
+ await tmService.approveAllRunBaselines(gateRun.testRunId, actor.username);
1840
+
1841
+ if (pendingWaitJobId && this.hasCollection('workflowManualTasks')) {
1842
+ await this.app.db
1843
+ .getRepository('workflowManualTasks')
1844
+ .update({
1845
+ filter: { jobId: pendingWaitJobId },
1846
+ values: { status: 1 },
1847
+ })
1848
+ .catch(() => undefined);
1849
+ }
1850
+
1851
+ // Refresh Git commit status & sticky comment to reflect QA approval (while keeping testVerdict='diff_mismatch' immutable!)
1852
+ await this.runPublishGitFeedbackStage(gateRunId);
1853
+
1854
+ if (pendingWaitJobId) {
1855
+ await this.settleJobExclusively(pendingWaitJobId, JOB_STATUS.RESOLVED, {
1856
+ gateRunId,
1857
+ approvalState: 'approved',
1858
+ approvedByUserId: actor.userId,
1859
+ approvedBy: actor.username,
1860
+ });
1861
+ // Wait briefly for downstream ci_promote node and workflow execution to settle so caller receives final state
1862
+ const execRepo = this.app.db.getRepository('executions');
1863
+ const deadline = Date.now() + 15_000;
1864
+ while (Date.now() < deadline) {
1865
+ const cur = (await gateRepo.findOne({ filterByTk: gateRunId })) as Model | null;
1866
+ const st = String(cur?.get('state') || '');
1867
+ const execId = Number(cur?.get('executionId') || 0);
1868
+ const execModel = execId > 0 ? ((await execRepo.findOne({ filterByTk: execId })) as Model | null) : null;
1869
+ const execSettled = !execModel || Number(execModel.get('status')) !== EXECUTION_STATUS.STARTED;
1870
+ if ((st === 'succeeded' || st === 'failed' || st === 'canceled') && execSettled) {
1871
+ break;
1872
+ }
1873
+ await new Promise<void>((resolve) => setTimeout(resolve, 40));
1874
+ }
1875
+ } else {
1876
+ await this.runPromoteDeployStage(gateRunId);
1877
+ }
1878
+
1879
+ const refreshed = (await gateRepo.findOne({ filterByTk: gateRunId })) as Model;
1880
+ return refreshed.toJSON() as CiGateRunRecord;
1881
+ },
1882
+ 15_000,
1883
+ );
1884
+
1885
+ if (!lockedResult) {
1886
+ const err = new Error(`Gate Run #${gateRunId} approval is currently in progress`) as Error & { status?: number };
1887
+ err.status = 409;
1888
+ throw err;
1889
+ }
1890
+ return lockedResult;
1891
+ }
1892
+
1893
+ async clearPromotionHalt(pipelineId: number, clearedBy: string): Promise<CiPipelineRecord> {
1894
+ const model = (await this.app.db
1895
+ .getRepository(CI_PIPELINES_COLLECTION)
1896
+ .findOne({ filterByTk: pipelineId })) as Model | null;
1897
+ if (!model) {
1898
+ const err = new Error(`CI Pipeline #${pipelineId} not found`) as Error & { status?: number };
1899
+ err.status = 404;
1900
+ throw err;
1901
+ }
1902
+ await model.update({
1903
+ promotionHalted: false,
1904
+ promotionHaltReason: `Cleared by ${clearedBy} at ${new Date().toISOString()}`,
1905
+ });
1906
+ return model.toJSON() as CiPipelineRecord;
1907
+ }
1908
+
1909
+ async handleTestRunCompleted(testRun: Record<string, unknown>): Promise<void> {
1910
+ if (this.stopping) return;
1911
+ const testRunId = Number(testRun.id || 0);
1912
+ if (!testRunId) return;
1913
+
1914
+ const gateModels = (await this.app.db.getRepository(CI_GATE_RUNS_COLLECTION).find({
1915
+ filter: {
1916
+ testRunId,
1917
+ state: { $in: ['queued', 'running_ci'] },
1918
+ },
1919
+ limit: 5,
1920
+ })) as Model[];
1921
+
1922
+ for (const gateModel of gateModels) {
1923
+ const gateRun = gateModel.toJSON() as CiGateRunRecord;
1924
+ const pipelineModel = (await this.app.db
1925
+ .getRepository(CI_PIPELINES_COLLECTION)
1926
+ .findOne({ filterByTk: gateRun.pipelineId })) as Model | null;
1927
+ const pipeline = pipelineModel ? (pipelineModel.toJSON() as CiPipelineRecord) : null;
1928
+
1929
+ let containerCleared = !gateRun.ephemeralContainerId;
1930
+ if (gateRun.ephemeralContainerId && pipeline) {
1931
+ containerCleared = await this.containerService
1932
+ .cleanupContainer(pipeline, gateRun.ephemeralContainerId)
1933
+ .catch(() => false);
1934
+ }
1935
+
1936
+ const verdict = String(testRun.verdict || 'error');
1937
+ const reasonCode = testRun.verdictReasonCode ? String(testRun.verdictReasonCode) : null;
1938
+ const pendingJobId = gateRun.pendingJobId;
1939
+ const logs = this.appendGateLog(
1940
+ gateRun.logs,
1941
+ 'TEST_SETTLED',
1942
+ `Test Manager run #${testRunId} completed with verdict="${verdict}"${reasonCode ? ` [${reasonCode}]` : ''}`,
1943
+ );
1944
+
1945
+ await this.withSqliteBusyRetry(async () => {
1946
+ await gateModel.update({
1947
+ testVerdict: verdict,
1948
+ verdictReasonCode: reasonCode,
1949
+ pendingJobId: null,
1950
+ ...(containerCleared ? { ephemeralContainerId: null } : {}),
1951
+ logs,
1952
+ });
1953
+ });
1954
+
1955
+ if (pendingJobId) {
1956
+ await this.settleJobExclusively(pendingJobId, JOB_STATUS.RESOLVED, {
1957
+ gateRunId: gateRun.id,
1958
+ testRunId,
1959
+ verdict,
1960
+ verdictReasonCode: reasonCode,
1961
+ });
1962
+ }
1963
+ }
1964
+ }
1965
+
1966
+ async handlePortainerBuildRunSaved(model: Model): Promise<void> {
1967
+ if (this.stopping) return;
1968
+ const state = String(model.get('state') || '');
1969
+ const deployEnabled = Boolean(model.get('deployEnabled'));
1970
+ // Pre-deploy gate triggers ONLY when a build-only Portainer Git pipeline succeeds (deployEnabled=false)
1971
+ if (state !== 'succeeded' || deployEnabled) return;
1972
+
1973
+ const buildRunId = Number(model.get('id') || 0);
1974
+ const portainerPipelineId = Number(model.get('pipelineId') || 0);
1975
+ const commitSha = String(model.get('commitSha') || '').trim();
1976
+ const branch = String(model.get('branch') || 'main').trim();
1977
+ if (!portainerPipelineId || !commitSha) return;
1978
+
1979
+ const ciPipelines = (await this.app.db.getRepository(CI_PIPELINES_COLLECTION).find({
1980
+ filter: {
1981
+ enabled: true,
1982
+ portainerPipelineId,
1983
+ deployGateMode: { $in: ['gate_deploy', 'manual_on_diff_mismatch'] },
1984
+ },
1985
+ })) as Model[];
1986
+
1987
+ for (const pModel of ciPipelines) {
1988
+ const p = pModel.toJSON() as CiPipelineRecord;
1989
+ if (!matchesBranchPattern(branch, p.branchPattern)) continue;
1990
+
1991
+ await this.enqueueGateRun({
1992
+ pipelineId: p.id,
1993
+ eventType: 'pre_deploy_gate',
1994
+ branch,
1995
+ commitSha,
1996
+ buildRunId: buildRunId > 0 ? buildRunId : null,
1997
+ commitMessage: model.get('commitMessage') ? String(model.get('commitMessage')) : null,
1998
+ });
1999
+ }
2000
+ }
2001
+
2002
+ async triggerClusterHotReloadSmoke(params: {
2003
+ pluginName?: string;
2004
+ commitSha?: string;
2005
+ operationId?: string;
2006
+ }): Promise<CiGateRunRecord[]> {
2007
+ const pipelines = (await this.app.db.getRepository(CI_PIPELINES_COLLECTION).find({
2008
+ filter: { enabled: true, smokeOnClusterHotReload: true },
2009
+ })) as Model[];
2010
+
2011
+ const opId = params.operationId ? String(params.operationId).trim() : null;
2012
+ const triggered: CiGateRunRecord[] = [];
2013
+ for (const m of pipelines) {
2014
+ const p = m.toJSON() as CiPipelineRecord;
2015
+ const run = await this.enqueueGateRun({
2016
+ pipelineId: p.id,
2017
+ eventType: 'hot_reload_smoke',
2018
+ branch: 'hot-reload-canary',
2019
+ commitSha: params.commitSha || (opId ? `hotreload-${opId}` : `hotreload-${Date.now()}`),
2020
+ operationId: opId,
2021
+ commitMessage: params.pluginName
2022
+ ? `Cluster hot-reload smoke check for ${params.pluginName}${opId ? ` (${opId})` : ''}`
2023
+ : `Cluster hot-reload smoke check${opId ? ` (${opId})` : ''}`,
2024
+ });
2025
+ triggered.push(run);
2026
+ }
2027
+ return triggered;
2028
+ }
2029
+
2030
+ async pollDueMergeRequests(): Promise<number> {
2031
+ if (this.stopping || !this.workflow || this.workflow.serving?.() === false) return 0;
2032
+ let triggeredCount = 0;
2033
+
2034
+ await this.runWithLock(
2035
+ 'workflow-ci:mr-poll',
2036
+ 60_000,
2037
+ async () => {
2038
+ const pipeRepo = this.app.db.getRepository(CI_PIPELINES_COLLECTION);
2039
+ const pipelines = (await pipeRepo.find({
2040
+ filter: { enabled: true, pollMergeRequests: true, triggerOnMergeRequest: true },
2041
+ })) as Model[];
2042
+
2043
+ for (const pModel of pipelines) {
2044
+ if (this.stopping) return;
2045
+ const pipeline = pModel.toJSON() as CiPipelineRecord;
2046
+ if (!pipeline.gitRepositoryId) continue;
2047
+
2048
+ const openMrs = await this.gitFeedbackService.listOpenMergeRequests(pipeline.gitRepositoryId).catch(() => []);
2049
+ const knownHeads: Record<string, string> = isPlainRecord(pipeline.lastPolledMrHeads)
2050
+ ? { ...(pipeline.lastPolledMrHeads as Record<string, string>) }
2051
+ : {};
2052
+ let changed = false;
2053
+
2054
+ for (const mr of openMrs) {
2055
+ if (!matchesBranchPattern(mr.sourceBranch, pipeline.branchPattern)) continue;
2056
+ const key = String(mr.mrIid);
2057
+ if (knownHeads[key] === mr.headSha) continue;
2058
+
2059
+ knownHeads[key] = mr.headSha;
2060
+ changed = true;
2061
+ await this.enqueueGateRun({
2062
+ pipelineId: pipeline.id,
2063
+ eventType: 'merge_request',
2064
+ branch: mr.sourceBranch,
2065
+ targetBranch: mr.targetBranch,
2066
+ commitSha: mr.headSha,
2067
+ commitMessage: mr.title,
2068
+ mrIid: mr.mrIid,
2069
+ });
2070
+ triggeredCount += 1;
2071
+ }
2072
+
2073
+ if (changed) {
2074
+ await pModel.update({ lastPolledMrHeads: knownHeads });
2075
+ }
2076
+ }
2077
+ },
2078
+ 0,
2079
+ );
2080
+
2081
+ return triggeredCount;
2082
+ }
2083
+
2084
+ async settleJobExclusively(
2085
+ jobId: number | null | undefined,
2086
+ targetStatus: number,
2087
+ resultPayload: Record<string, unknown>,
2088
+ ): Promise<void> {
2089
+ if (!this.workflow || !jobId || this.stopping) return;
2090
+ const jobRepo = this.workflow.app.db.getRepository('jobs');
2091
+ const initialJob = (await jobRepo.findOne({ filterByTk: jobId })) as JobModel | null;
2092
+ if (!initialJob || initialJob.status !== JOB_STATUS.PENDING) return;
2093
+
2094
+ const execution = await initialJob.getExecution();
2095
+ if (!execution) return;
2096
+
2097
+ const lockKey = getExecutionLockKey(execution.id);
2098
+ await this.runWithLock(
2099
+ lockKey,
2100
+ 30_000,
2101
+ async () => {
2102
+ const job = (await jobRepo.findOne({ filterByTk: jobId })) as JobModel | null;
2103
+ if (!job || job.status !== JOB_STATUS.PENDING) return;
2104
+
2105
+ const freshExec = await job.getExecution();
2106
+ if (!freshExec) return;
2107
+ if (typeof this.workflow?.abortExecutionIfExpired === 'function') {
2108
+ if (await this.workflow.abortExecutionIfExpired(freshExec)) return;
2109
+ }
2110
+ if (freshExec.status !== EXECUTION_STATUS.STARTED) return;
2111
+
2112
+ const [updatedCount] = await this.withSqliteBusyRetry(async () =>
2113
+ jobRepo.update({
2114
+ filter: { id: jobId, status: JOB_STATUS.PENDING },
2115
+ values: {
2116
+ status: targetStatus,
2117
+ result: resultPayload,
2118
+ },
2119
+ }),
2120
+ );
2121
+ if (!updatedCount) return;
2122
+
2123
+ const refreshedJob = (await jobRepo.findOne({ filterByTk: jobId })) as JobModel | null;
2124
+ if (refreshedJob && !this.stopping) {
2125
+ await this.withSqliteBusyRetry(async () => {
2126
+ await this.workflow?.resume(refreshedJob);
2127
+ });
2128
+ }
2129
+ },
2130
+ 15_000,
2131
+ );
2132
+ }
2133
+
2134
+ async markGateRunFailed(gateRunId: number, errorMessage: string): Promise<void> {
2135
+ const gateModel = (await this.app.db
2136
+ .getRepository(CI_GATE_RUNS_COLLECTION)
2137
+ .findOne({ filterByTk: gateRunId })) as Model | null;
2138
+ if (!gateModel) return;
2139
+ const gateRun = gateModel.toJSON() as CiGateRunRecord;
2140
+
2141
+ let cleared = !gateRun.ephemeralContainerId;
2142
+ if (gateRun.ephemeralContainerId) {
2143
+ const pipelineModel = (await this.app.db
2144
+ .getRepository(CI_PIPELINES_COLLECTION)
2145
+ .findOne({ filterByTk: gateRun.pipelineId })) as Model | null;
2146
+ if (pipelineModel) {
2147
+ cleared = await this.containerService
2148
+ .cleanupContainer(pipelineModel.toJSON() as CiPipelineRecord, gateRun.ephemeralContainerId)
2149
+ .catch(() => false);
2150
+ }
2151
+ }
2152
+
2153
+ const startedMs = gateRun.startedAt ? new Date(gateRun.startedAt).getTime() : Date.now();
2154
+ await gateModel.update({
2155
+ state: 'failed',
2156
+ deployOutcome:
2157
+ gateRun.eventType === 'pre_deploy_gate' && gateRun.deployOutcome === 'pending'
2158
+ ? 'failed'
2159
+ : gateRun.deployOutcome ?? 'not_applicable',
2160
+ errorMessage,
2161
+ pendingJobId: null,
2162
+ ...(cleared ? { ephemeralContainerId: null } : {}),
2163
+ finishedAt: new Date().toISOString(),
2164
+ durationMs: Math.max(0, Date.now() - startedMs),
2165
+ });
2166
+ }
2167
+
2168
+ async reconcile(): Promise<void> {
2169
+ if (this.stopping || !this.workflow || this.workflow.serving?.() === false) return;
2170
+
2171
+ await this.runWithLock(
2172
+ 'workflow-ci:reconcile',
2173
+ 25_000,
2174
+ async () => {
2175
+ if (typeof this.workflow?.recover === 'function') {
2176
+ await this.workflow.recover();
2177
+ }
2178
+
2179
+ await this.gitFeedbackService.flushOutboxBatch(this.fetchTestRun, 15).catch(() => 0);
2180
+
2181
+ const flow = (await this.app.db.getRepository('workflows').findOne({
2182
+ filter: { key: CI_MANAGED_WORKFLOW_KEY, enabled: true },
2183
+ })) as WorkflowModel | null;
2184
+ if (!flow) return;
2185
+
2186
+ const cutoffIso = new Date(Date.now() - 45_000).toISOString();
2187
+ const unstarted = (await this.app.db.getRepository(CI_GATE_RUNS_COLLECTION).find({
2188
+ filter: {
2189
+ state: 'queued',
2190
+ executionId: null,
2191
+ createdAt: { $lt: cutoffIso },
2192
+ },
2193
+ limit: 20,
2194
+ })) as Model[];
2195
+
2196
+ for (const row of unstarted) {
2197
+ const id = row.get('id') as ID;
2198
+ await this.workflow?.execute(
2199
+ flow,
2200
+ { data: row.toJSON() },
2201
+ { force: true, eventKey: `workflow-ci:reconcile:${String(id)}` },
2202
+ );
2203
+ }
2204
+
2205
+ // Retry lingering ephemeral container cleanups on completed/failed/canceled runs
2206
+ const lingeringCleanups = (await this.app.db.getRepository(CI_GATE_RUNS_COLLECTION).find({
2207
+ filter: {
2208
+ state: { $in: ['succeeded', 'failed', 'canceled', 'waiting_approval'] },
2209
+ ephemeralContainerId: { $ne: null },
2210
+ },
2211
+ limit: 20,
2212
+ })) as Model[];
2213
+ for (const row of lingeringCleanups) {
2214
+ const cid = row.get('ephemeralContainerId') ? String(row.get('ephemeralContainerId')) : '';
2215
+ if (!cid) continue;
2216
+ const pModel = (await this.app.db
2217
+ .getRepository(CI_PIPELINES_COLLECTION)
2218
+ .findOne({ filterByTk: row.get('pipelineId') })) as Model | null;
2219
+ if (!pModel) continue;
2220
+ const removed = await this.containerService
2221
+ .cleanupContainer(pModel.toJSON() as CiPipelineRecord, cid)
2222
+ .catch(() => false);
2223
+ if (removed) {
2224
+ await row.update({ ephemeralContainerId: null }).catch(() => undefined);
2225
+ }
2226
+ }
2227
+
2228
+ const active = (await this.app.db.getRepository(CI_GATE_RUNS_COLLECTION).find({
2229
+ filter: {
2230
+ state: { $in: ['running_ci', 'triaging', 'publishing_feedback', 'promoting_deploy'] },
2231
+ },
2232
+ limit: 30,
2233
+ })) as Model[];
2234
+
2235
+ const nowMs = Date.now();
2236
+ for (const row of active) {
2237
+ if (this.stopping) return;
2238
+ const gateRun = row.toJSON() as CiGateRunRecord;
2239
+
2240
+ if (gateRun.state === 'running_ci' && gateRun.testRunId) {
2241
+ const trJson = await this.fetchTestRun(gateRun.testRunId);
2242
+ const snap = isPlainRecord(trJson?.environmentSnapshot) ? trJson?.environmentSnapshot : null;
2243
+
2244
+ if (trJson && trJson.stage === 'completed' && !snap?.flakyRetryRunId) {
2245
+ await this.handleTestRunCompleted(trJson);
2246
+ continue;
2247
+ }
2248
+
2249
+ if (gateRun.ephemeralContainerId) {
2250
+ const pModel = (await this.app.db
2251
+ .getRepository(CI_PIPELINES_COLLECTION)
2252
+ .findOne({ filterByTk: gateRun.pipelineId })) as Model | null;
2253
+ const pipeline = pModel ? (pModel.toJSON() as CiPipelineRecord) : null;
2254
+ if (pipeline) {
2255
+ const cStatus = await this.containerService
2256
+ .inspectRunnerContainer(pipeline, gateRun.ephemeralContainerId)
2257
+ .catch(() => ({ settled: false as const }));
2258
+ if (cStatus.settled && cStatus.exitCode !== 0) {
2259
+ const tail = await this.containerService.readContainerLogs(
2260
+ pipeline,
2261
+ gateRun.ephemeralContainerId,
2262
+ 120,
2263
+ );
2264
+ const cleaned = await this.containerService
2265
+ .cleanupContainer(pipeline, gateRun.ephemeralContainerId)
2266
+ .catch(() => false);
2267
+ if (cleaned) {
2268
+ await row.update({ ephemeralContainerId: null }).catch(() => undefined);
2269
+ }
2270
+ await this.getTestManagerService()
2271
+ .ingestExternalResults(
2272
+ {
2273
+ runId: gateRun.testRunId,
2274
+ cases: [],
2275
+ finished: true,
2276
+ runnerError: [
2277
+ cStatus.errorMessage || `CI container exited with code ${String(cStatus.exitCode)}`,
2278
+ tail ? `Logs:\n${tail.slice(-1500)}` : '',
2279
+ ]
2280
+ .filter(Boolean)
2281
+ .join('\n'),
2282
+ },
2283
+ { waitDownstream: false, skipAuthCheck: true },
2284
+ )
2285
+ .catch(() => undefined);
2286
+ continue;
2287
+ }
2288
+ }
2289
+ }
2290
+ }
2291
+
2292
+ const startedMs = gateRun.startedAt
2293
+ ? new Date(gateRun.startedAt).getTime()
2294
+ : gateRun.createdAt
2295
+ ? new Date(gateRun.createdAt).getTime()
2296
+ : nowMs;
2297
+ if (nowMs - startedMs > DEFAULT_CI_TIMEOUT_MS) {
2298
+ const staleJobId = gateRun.pendingJobId;
2299
+ await this.markGateRunFailed(gateRun.id, `CI Gate run exceeded timeout (${DEFAULT_CI_TIMEOUT_MS}ms)`);
2300
+ await this.settleJobExclusively(staleJobId, JOB_STATUS.FAILED, {
2301
+ gateRunId: gateRun.id,
2302
+ error: 'CI Gate timed out',
2303
+ });
2304
+ }
2305
+ }
2306
+ },
2307
+ 0,
2308
+ );
2309
+ }
2310
+ }