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,31 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import type { CollectionOptions } from '@nocobase/database';
11
+ import { CI_GIT_FEEDBACK_OUTBOX_COLLECTION } from '../../shared/constants';
12
+
13
+ export default {
14
+ name: CI_GIT_FEEDBACK_OUTBOX_COLLECTION,
15
+ title: 'CI Git Feedback Outbox',
16
+ indexes: [{ fields: ['status', 'nextRetryAt'] }, { fields: ['gateRunId'] }],
17
+ fields: [
18
+ { name: 'id', type: 'bigInt', autoIncrement: true, primaryKey: true },
19
+ { name: 'gateRunId', type: 'bigInt', allowNull: false },
20
+ { name: 'pipelineId', type: 'bigInt', allowNull: false },
21
+ { name: 'gitRepositoryId', type: 'bigInt' },
22
+ { name: 'kind', type: 'string', length: 32, allowNull: false },
23
+ { name: 'payload', type: 'json', allowNull: false },
24
+ { name: 'status', type: 'string', length: 32, defaultValue: 'pending' },
25
+ { name: 'attempts', type: 'integer', defaultValue: 0 },
26
+ { name: 'nextRetryAt', type: 'date' },
27
+ { name: 'lastError', type: 'text' },
28
+ { name: 'createdAt', type: 'date' },
29
+ { name: 'updatedAt', type: 'date' },
30
+ ],
31
+ } as CollectionOptions;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import type { CollectionOptions } from '@nocobase/database';
11
+ import { CI_PIPELINES_COLLECTION } from '../../shared/constants';
12
+
13
+ export default {
14
+ name: CI_PIPELINES_COLLECTION,
15
+ title: 'CI Pipelines',
16
+ indexes: [
17
+ { fields: ['key'], unique: true },
18
+ { fields: ['tenantId'] },
19
+ { fields: ['gitRepositoryId'] },
20
+ { fields: ['portainerPipelineId'] },
21
+ ],
22
+ fields: [
23
+ { name: 'id', type: 'bigInt', autoIncrement: true, primaryKey: true },
24
+ { name: 'key', type: 'string', length: 64, allowNull: false },
25
+ { name: 'name', type: 'string', length: 128, allowNull: false },
26
+ { name: 'enabled', type: 'boolean', defaultValue: true },
27
+ { name: 'tenantId', type: 'bigInt', allowNull: false },
28
+ { name: 'gitRepositoryId', type: 'bigInt' },
29
+ { name: 'branchPattern', type: 'string', length: 255, defaultValue: '*' },
30
+ { name: 'protectedBranches', type: 'json' },
31
+ { name: 'triggerOnPush', type: 'boolean', defaultValue: true },
32
+ { name: 'triggerOnMergeRequest', type: 'boolean', defaultValue: true },
33
+ { name: 'pollMergeRequests', type: 'boolean', defaultValue: false },
34
+ { name: 'webhookSecret', type: 'text' },
35
+ { name: 'runnerBackend', type: 'string', length: 32, defaultValue: 'external_ci' },
36
+ { name: 'portainerInstanceId', type: 'bigInt' },
37
+ { name: 'portainerEndpointId', type: 'bigInt' },
38
+ { name: 'runnerImage', type: 'string', length: 255 },
39
+ { name: 'runnerCommand', type: 'text' },
40
+ { name: 'runnerNetwork', type: 'string', length: 128 },
41
+ { name: 'runnerEnv', type: 'json' },
42
+ { name: 'runnerTimeoutMs', type: 'integer', defaultValue: 300000 },
43
+ { name: 'qaInstanceId', type: 'bigInt' },
44
+ { name: 'qaEndpointId', type: 'bigInt' },
45
+ { name: 'qaStackId', type: 'bigInt' },
46
+ { name: 'qaAppServices', type: 'json' },
47
+ { name: 'publishCommitStatus', type: 'boolean', defaultValue: true },
48
+ { name: 'statusContext', type: 'string', length: 128, defaultValue: 'nocobase/ci-test-manager' },
49
+ { name: 'publishPrComment', type: 'boolean', defaultValue: true },
50
+ { name: 'enrichGitReview', type: 'boolean', defaultValue: true },
51
+ { name: 'portainerPipelineId', type: 'bigInt' },
52
+ { name: 'deployStackId', type: 'bigInt' },
53
+ { name: 'deployEndpointId', type: 'bigInt' },
54
+ { name: 'deployInstanceId', type: 'bigInt' },
55
+ { name: 'deployGateMode', type: 'string', length: 32, defaultValue: 'none' },
56
+ { name: 'gateApproverIds', type: 'json' },
57
+ { name: 'dbBackwardCompatible', type: 'boolean', defaultValue: true },
58
+ { name: 'promotionHalted', type: 'boolean', defaultValue: false },
59
+ { name: 'promotionHaltReason', type: 'text' },
60
+ { name: 'lastKnownGoodSnapshot', type: 'json' },
61
+ { name: 'enableAiTriage', type: 'boolean', defaultValue: true },
62
+ { name: 'agentLoopPatternKey', type: 'string', length: 128 },
63
+ { name: 'smokeOnClusterHotReload', type: 'boolean', defaultValue: false },
64
+ { name: 'lastPolledMrHeads', type: 'json' },
65
+ { name: 'createdAt', type: 'date' },
66
+ { name: 'updatedAt', type: 'date' },
67
+ ],
68
+ } as CollectionOptions;
@@ -0,0 +1,17 @@
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
+ export { default, PluginWorkflowCiServer } from './plugin';
11
+ export * from './services/GitFeedbackService';
12
+ export * from './services/EphemeralContainerService';
13
+ export * from './services/AiTriageService';
14
+ export * from './services/CiGateWorkflowService';
15
+ export * from './instructions/CiInstructions';
16
+ export * from '../shared/constants';
17
+ export * from '../shared/types';
@@ -0,0 +1,180 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import type WorkflowPlugin from '@nocobase/plugin-workflow';
11
+ import { Instruction, JOB_STATUS, type FlowNodeModel, type JobModel, type Processor } from '@nocobase/plugin-workflow';
12
+ import type { CiGateWorkflowService } from '../services/CiGateWorkflowService';
13
+
14
+ export type CiStageRole = 'dispatch' | 'triage' | 'feedback' | 'wait_approval' | 'promote';
15
+
16
+ function resolveGateRunId(node: FlowNodeModel, processor: Processor): number | null {
17
+ const cfg = node.config && typeof node.config === 'object' ? (node.config as Record<string, unknown>) : {};
18
+ const parsed =
19
+ typeof processor.getParsedValue === 'function'
20
+ ? (processor.getParsedValue(cfg, node.id) as Record<string, unknown>)
21
+ : cfg;
22
+ if (parsed?.gateRunId !== undefined && parsed?.gateRunId !== '') {
23
+ const explicit = Number(parsed.gateRunId);
24
+ if (Number.isFinite(explicit) && explicit > 0) return explicit;
25
+ }
26
+
27
+ const ctx = processor.execution.context;
28
+ if (!ctx || typeof ctx !== 'object') return null;
29
+ const data = (ctx as { data?: unknown }).data;
30
+ if (typeof data === 'number' || typeof data === 'string') {
31
+ const n = Number(data);
32
+ return Number.isFinite(n) && n > 0 ? n : null;
33
+ }
34
+ if (data && typeof data === 'object') {
35
+ const obj = data as { gateRunId?: unknown; id?: unknown };
36
+ if (obj.gateRunId !== undefined) {
37
+ const n = Number(obj.gateRunId);
38
+ if (Number.isFinite(n) && n > 0) return n;
39
+ }
40
+ if (obj.id !== undefined) {
41
+ const n = Number(obj.id);
42
+ if (Number.isFinite(n) && n > 0) return n;
43
+ }
44
+ }
45
+ return null;
46
+ }
47
+
48
+ export class CiStageInstruction extends Instruction {
49
+ constructor(
50
+ workflow: WorkflowPlugin,
51
+ private readonly service: CiGateWorkflowService,
52
+ private readonly role: CiStageRole,
53
+ ) {
54
+ super(workflow);
55
+ }
56
+
57
+ private async executeInBackground(params: {
58
+ gateRunId: number;
59
+ workflowId: number;
60
+ executionId: number;
61
+ jobId: number;
62
+ abort: { signal: AbortSignal; dispose: () => void };
63
+ }): Promise<void> {
64
+ await new Promise<void>((resolve) => {
65
+ setImmediate(resolve);
66
+ });
67
+ const { gateRunId, workflowId, executionId, jobId, abort } = params;
68
+ try {
69
+ if (this.role === 'dispatch') {
70
+ const out = await this.service.runDispatchStage(gateRunId, {
71
+ workflowId,
72
+ executionId,
73
+ jobId,
74
+ signal: abort.signal,
75
+ });
76
+ if (!out.waitingTestRun) {
77
+ await this.service.settleJobExclusively(jobId, JOB_STATUS.RESOLVED, out.payload);
78
+ }
79
+ return;
80
+ }
81
+ if (this.role === 'triage') {
82
+ const payload = await this.service.runAiTriageStage(gateRunId);
83
+ await this.service.settleJobExclusively(jobId, JOB_STATUS.RESOLVED, payload);
84
+ return;
85
+ }
86
+ if (this.role === 'feedback') {
87
+ const payload = await this.service.runPublishGitFeedbackStage(gateRunId);
88
+ await this.service.settleJobExclusively(jobId, JOB_STATUS.RESOLVED, payload);
89
+ return;
90
+ }
91
+ if (this.role === 'wait_approval') {
92
+ const out = await this.service.runWaitApprovalStage(gateRunId, {
93
+ workflowId,
94
+ executionId,
95
+ jobId,
96
+ });
97
+ if (!out.waitingApproval) {
98
+ await this.service.settleJobExclusively(jobId, JOB_STATUS.RESOLVED, out.payload);
99
+ }
100
+ return;
101
+ }
102
+ const payload = await this.service.runPromoteDeployStage(gateRunId, abort.signal);
103
+ await this.service.settleJobExclusively(jobId, JOB_STATUS.RESOLVED, payload);
104
+ } catch (error) {
105
+ const msg = error instanceof Error ? error.message : String(error);
106
+ await this.service.markGateRunFailed(gateRunId, msg);
107
+ await this.service.settleJobExclusively(jobId, JOB_STATUS.FAILED, { gateRunId, error: msg });
108
+ } finally {
109
+ abort.dispose();
110
+ }
111
+ }
112
+
113
+ async run(node: FlowNodeModel, prevJob: JobModel | null, processor: Processor) {
114
+ const gateRunId = resolveGateRunId(node, processor);
115
+ if (!gateRunId) {
116
+ return {
117
+ status: JOB_STATUS.ERROR,
118
+ result: { error: 'Missing ciGateRuns id in workflow execution context' },
119
+ };
120
+ }
121
+
122
+ const execMeta = {
123
+ workflowId: Number(processor.execution.workflowId),
124
+ executionId: Number(processor.execution.id),
125
+ };
126
+
127
+ if (processor.isInstructionSync(node)) {
128
+ try {
129
+ if (this.role === 'dispatch') {
130
+ const out = await this.service.runDispatchStage(gateRunId, execMeta);
131
+ return { status: JOB_STATUS.RESOLVED, result: out.payload };
132
+ }
133
+ if (this.role === 'triage') {
134
+ return { status: JOB_STATUS.RESOLVED, result: await this.service.runAiTriageStage(gateRunId) };
135
+ }
136
+ if (this.role === 'feedback') {
137
+ return { status: JOB_STATUS.RESOLVED, result: await this.service.runPublishGitFeedbackStage(gateRunId) };
138
+ }
139
+ if (this.role === 'wait_approval') {
140
+ const out = await this.service.runWaitApprovalStage(gateRunId, execMeta);
141
+ return { status: JOB_STATUS.RESOLVED, result: out.payload };
142
+ }
143
+ return { status: JOB_STATUS.RESOLVED, result: await this.service.runPromoteDeployStage(gateRunId) };
144
+ } catch (error) {
145
+ const msg = error instanceof Error ? error.message : String(error);
146
+ await this.service.markGateRunFailed(gateRunId, msg);
147
+ return { status: JOB_STATUS.FAILED, result: { gateRunId, error: msg } };
148
+ }
149
+ }
150
+
151
+ const savedJob = processor.saveJob({
152
+ status: JOB_STATUS.PENDING,
153
+ nodeId: node.id,
154
+ nodeKey: node.key,
155
+ upstreamId: prevJob?.id ?? null,
156
+ result: { gateRunId, role: this.role, state: 'running' },
157
+ }) as { id: number };
158
+
159
+ const abort = processor.createBackgroundAbortHandle();
160
+ try {
161
+ await processor.exit();
162
+ } catch (error) {
163
+ abort.dispose();
164
+ throw error;
165
+ }
166
+
167
+ const backgroundPromise = this.executeInBackground({
168
+ gateRunId,
169
+ workflowId: execMeta.workflowId,
170
+ executionId: execMeta.executionId,
171
+ jobId: Number(savedJob.id),
172
+ abort,
173
+ });
174
+ this.service.trackBackgroundTask(backgroundPromise);
175
+ }
176
+
177
+ async resume(_node: FlowNodeModel, job: JobModel) {
178
+ return job;
179
+ }
180
+ }
@@ -0,0 +1,78 @@
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 { DataTypes } from '@nocobase/database';
11
+ import { Migration } from '@nocobase/server';
12
+ import { CI_GATE_RUNS_COLLECTION, CI_PIPELINES_COLLECTION } from '../../shared/constants';
13
+
14
+ export default class HardenWorkflowCiV020Migration extends Migration {
15
+ on = 'afterLoad';
16
+
17
+ private resolveTableName(collectionName: string): string | null {
18
+ const col = this.db.getCollection(collectionName);
19
+ if (!col?.model) return null;
20
+ const rawTable = col.model.getTableName();
21
+ return typeof rawTable === 'string' ? rawTable : rawTable.tableName;
22
+ }
23
+
24
+ private async ensureColumn(
25
+ tableName: string,
26
+ columnName: string,
27
+ definition: { type: unknown; allowNull?: boolean; defaultValue?: unknown },
28
+ ): Promise<void> {
29
+ const qi = this.db.sequelize.getQueryInterface();
30
+ const desc = await qi.describeTable(tableName).catch(() => null);
31
+ if (!desc || Object.prototype.hasOwnProperty.call(desc, columnName)) {
32
+ return;
33
+ }
34
+ await qi.addColumn(tableName, columnName, {
35
+ allowNull: true,
36
+ ...definition,
37
+ } as never);
38
+ }
39
+
40
+ async up() {
41
+ const pipesTable = this.resolveTableName(CI_PIPELINES_COLLECTION);
42
+ if (pipesTable) {
43
+ await this.ensureColumn(pipesTable, 'protectedBranches', { type: DataTypes.JSON });
44
+ await this.ensureColumn(pipesTable, 'qaInstanceId', { type: DataTypes.BIGINT });
45
+ await this.ensureColumn(pipesTable, 'qaEndpointId', { type: DataTypes.BIGINT });
46
+ await this.ensureColumn(pipesTable, 'qaStackId', { type: DataTypes.BIGINT });
47
+ await this.ensureColumn(pipesTable, 'qaAppServices', { type: DataTypes.JSON });
48
+ await this.ensureColumn(pipesTable, 'dbBackwardCompatible', {
49
+ type: DataTypes.BOOLEAN,
50
+ defaultValue: true,
51
+ });
52
+ await this.ensureColumn(pipesTable, 'promotionHalted', {
53
+ type: DataTypes.BOOLEAN,
54
+ defaultValue: false,
55
+ });
56
+ await this.ensureColumn(pipesTable, 'promotionHaltReason', { type: DataTypes.TEXT });
57
+ await this.ensureColumn(pipesTable, 'lastKnownGoodSnapshot', { type: DataTypes.JSON });
58
+ }
59
+
60
+ const runsTable = this.resolveTableName(CI_GATE_RUNS_COLLECTION);
61
+ if (runsTable) {
62
+ await this.ensureColumn(runsTable, 'buildRunId', { type: DataTypes.BIGINT });
63
+ await this.ensureColumn(runsTable, 'operationId', { type: DataTypes.STRING(128) });
64
+ await this.ensureColumn(runsTable, 'verdictReasonCode', { type: DataTypes.STRING(64) });
65
+ await this.ensureColumn(runsTable, 'approvalState', {
66
+ type: DataTypes.STRING(32),
67
+ defaultValue: 'not_required',
68
+ });
69
+ await this.ensureColumn(runsTable, 'approvalRecord', { type: DataTypes.JSON });
70
+ await this.ensureColumn(runsTable, 'deployOutcome', {
71
+ type: DataTypes.STRING(32),
72
+ defaultValue: 'not_applicable',
73
+ });
74
+ await this.ensureColumn(runsTable, 'rollbackRecord', { type: DataTypes.JSON });
75
+ await this.ensureColumn(runsTable, 'gitFeedbackSyncState', { type: DataTypes.STRING(32) });
76
+ }
77
+ }
78
+ }
@@ -0,0 +1,274 @@
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 { resolve } from 'node:path';
11
+ import type { Model } from '@nocobase/database';
12
+ import type WorkflowPlugin from '@nocobase/plugin-workflow';
13
+ import { Plugin } from '@nocobase/server';
14
+ import {
15
+ CI_GATE_RUNS_COLLECTION,
16
+ CI_GIT_FEEDBACK_OUTBOX_COLLECTION,
17
+ CI_INSTRUCTIONS,
18
+ CI_MANAGER_ACL_SNIPPET,
19
+ CI_MANAGER_RESOURCE,
20
+ CI_PIPELINES_COLLECTION,
21
+ PORTAINER_PIPELINE_RUNS_COLLECTION,
22
+ SECRET_MASK,
23
+ TEST_RUN_COMPLETED_EVENT,
24
+ } from '../shared/constants';
25
+ import type { CiPipelineRecord } from '../shared/types';
26
+ import { createCiManagerResourceActions } from './actions/ci-manager';
27
+ import { CiStageInstruction } from './instructions/CiInstructions';
28
+ import { AiTriageService } from './services/AiTriageService';
29
+ import { CiGateWorkflowService } from './services/CiGateWorkflowService';
30
+ import { EphemeralContainerService } from './services/EphemeralContainerService';
31
+ import { GitFeedbackService } from './services/GitFeedbackService';
32
+
33
+ export const CLUSTER_HOT_RELOAD_COMPLETED_EVENT = 'cluster-manager:hot-reload-completed';
34
+
35
+ function maskWebhookSecretInPayload(payload: unknown): unknown {
36
+ if (!payload || typeof payload !== 'object') return payload;
37
+ if (Array.isArray(payload)) return payload.map(maskWebhookSecretInPayload);
38
+ const obj = payload as Record<string, unknown>;
39
+ if (typeof obj.toJSON === 'function') {
40
+ return maskWebhookSecretInPayload((obj as { toJSON: () => unknown }).toJSON());
41
+ }
42
+ const clone: Record<string, unknown> = { ...obj };
43
+ if (typeof clone.webhookSecret === 'string' && clone.webhookSecret.length > 0) {
44
+ clone.webhookSecret = SECRET_MASK;
45
+ }
46
+ if (Array.isArray(clone.data)) {
47
+ clone.data = clone.data.map(maskWebhookSecretInPayload);
48
+ } else if (clone.data && typeof clone.data === 'object') {
49
+ clone.data = maskWebhookSecretInPayload(clone.data);
50
+ }
51
+ if (Array.isArray(clone.rows)) {
52
+ clone.rows = clone.rows.map(maskWebhookSecretInPayload);
53
+ }
54
+ return clone;
55
+ }
56
+
57
+ export class PluginWorkflowCiServer extends Plugin {
58
+ public gitFeedbackService!: GitFeedbackService;
59
+ public containerService!: EphemeralContainerService;
60
+ public aiTriageService!: AiTriageService;
61
+ public workflowService!: CiGateWorkflowService;
62
+
63
+ private handleTestRunCompleted = (testRun: Record<string, unknown>) => {
64
+ if (!this.workflowService) return;
65
+ const deferred = new Promise<void>((resolve) => {
66
+ setTimeout(resolve, 50);
67
+ })
68
+ .then(() => this.workflowService.handleTestRunCompleted(testRun))
69
+ .catch((error) => {
70
+ this.app.logger?.warn?.('[plugin-workflow-ci] Failed to handle test-manager:run-completed event', {
71
+ error: error instanceof Error ? error.message : String(error),
72
+ });
73
+ });
74
+ this.workflowService.trackBackgroundTask(deferred);
75
+ };
76
+
77
+ private handlePortainerRunSaved = (
78
+ model: Model,
79
+ options?: { transaction?: { afterCommit?: (fn: () => void) => void } },
80
+ ) => {
81
+ const dispatch = () => {
82
+ if (!this.workflowService) return;
83
+ const deferred = new Promise<void>((resolve) => {
84
+ setImmediate(resolve);
85
+ })
86
+ .then(() => this.workflowService.handlePortainerBuildRunSaved(model))
87
+ .catch((error) => {
88
+ this.app.logger?.warn?.('[plugin-workflow-ci] Failed to trigger pre-deploy CI gate from Portainer build', {
89
+ error: error instanceof Error ? error.message : String(error),
90
+ });
91
+ });
92
+ this.workflowService.trackBackgroundTask(deferred);
93
+ };
94
+ if (typeof options?.transaction?.afterCommit === 'function') {
95
+ options.transaction.afterCommit(dispatch);
96
+ return;
97
+ }
98
+ dispatch();
99
+ };
100
+
101
+ private handleClusterHotReloadCompleted = (payload: {
102
+ operationId?: string;
103
+ pluginName?: string;
104
+ commitSha?: string;
105
+ }) => {
106
+ if (!this.workflowService) return;
107
+ const deferred = new Promise<void>((resolve) => {
108
+ setImmediate(resolve);
109
+ })
110
+ .then(() => this.workflowService.triggerClusterHotReloadSmoke(payload || {}))
111
+ .catch((error) => {
112
+ this.app.logger?.warn?.('[plugin-workflow-ci] Failed to trigger cluster hot-reload smoke run', {
113
+ error: error instanceof Error ? error.message : String(error),
114
+ });
115
+ });
116
+ this.workflowService.trackBackgroundTask(deferred);
117
+ };
118
+
119
+ private handleAfterStart = async () => {
120
+ await this.workflowService?.start();
121
+ };
122
+
123
+ private handleStop = async () => {
124
+ await this.workflowService?.stop();
125
+ };
126
+
127
+ private handleDestroy = async () => {
128
+ this.app.off?.(TEST_RUN_COMPLETED_EVENT, this.handleTestRunCompleted);
129
+ this.app.off?.(CLUSTER_HOT_RELOAD_COMPLETED_EVENT, this.handleClusterHotReloadCompleted);
130
+ this.db.off(`${PORTAINER_PIPELINE_RUNS_COLLECTION}.afterSave`, this.handlePortainerRunSaved);
131
+ this.app.off?.('afterStart', this.handleAfterStart);
132
+ this.app.off?.('beforeStop', this.handleStop);
133
+ this.app.off?.('beforeDestroy', this.handleDestroy);
134
+ await this.workflowService?.stop();
135
+ };
136
+
137
+ async beforeLoad() {
138
+ this.db.addMigrations({
139
+ namespace: this.name,
140
+ directory: resolve(__dirname, 'migrations'),
141
+ context: {
142
+ plugin: this,
143
+ },
144
+ });
145
+
146
+ await this.db.import({
147
+ directory: resolve(__dirname, 'collections'),
148
+ });
149
+
150
+ this.db.on(`${CI_PIPELINES_COLLECTION}.beforeSave`, async (model: Model) => {
151
+ if (model.changed('key') && model.get('key')) {
152
+ const cleanKey = String(model.get('key'))
153
+ .trim()
154
+ .replace(/[^a-zA-Z0-9_-]+/g, '-')
155
+ .slice(0, 64);
156
+ if (!cleanKey) {
157
+ throw new Error('Valid CI pipeline key is required');
158
+ }
159
+ model.set('key', cleanKey);
160
+ }
161
+
162
+ if (this.workflowService) {
163
+ await this.workflowService.assertValidPipelineConfiguration(model.toJSON() as Partial<CiPipelineRecord>);
164
+ }
165
+
166
+ if (model.changed('webhookSecret')) {
167
+ const rawVal = model.get('webhookSecret');
168
+ if (rawVal === SECRET_MASK) {
169
+ model.set('webhookSecret', model.previous('webhookSecret'));
170
+ } else if (typeof rawVal === 'string' && rawVal.trim()) {
171
+ const encryptor = (this.app as unknown as { aesEncryptor?: { encrypt(v: string): Promise<string> | string } })
172
+ .aesEncryptor;
173
+ if (encryptor) {
174
+ model.set('webhookSecret', await encryptor.encrypt(rawVal.trim()));
175
+ }
176
+ }
177
+ }
178
+ });
179
+ }
180
+
181
+ async load() {
182
+ const workflow = (this.app.pm.get('workflow') || this.app.pm.get('@nocobase/plugin-workflow')) as
183
+ | WorkflowPlugin
184
+ | undefined;
185
+
186
+ this.gitFeedbackService = new GitFeedbackService(this.app);
187
+ this.containerService = new EphemeralContainerService(this.app);
188
+ this.aiTriageService = new AiTriageService(this.app);
189
+ this.workflowService = new CiGateWorkflowService(
190
+ this.app,
191
+ workflow,
192
+ this.gitFeedbackService,
193
+ this.containerService,
194
+ this.aiTriageService,
195
+ );
196
+
197
+ if (workflow?.registerInstruction) {
198
+ workflow.registerInstruction(
199
+ CI_INSTRUCTIONS.dispatchRun,
200
+ new CiStageInstruction(workflow, this.workflowService, 'dispatch'),
201
+ );
202
+ workflow.registerInstruction(
203
+ CI_INSTRUCTIONS.aiTriage,
204
+ new CiStageInstruction(workflow, this.workflowService, 'triage'),
205
+ );
206
+ workflow.registerInstruction(
207
+ CI_INSTRUCTIONS.publishGitFeedback,
208
+ new CiStageInstruction(workflow, this.workflowService, 'feedback'),
209
+ );
210
+ workflow.registerInstruction(
211
+ CI_INSTRUCTIONS.waitApproval,
212
+ new CiStageInstruction(workflow, this.workflowService, 'wait_approval'),
213
+ );
214
+ workflow.registerInstruction(
215
+ CI_INSTRUCTIONS.promoteDeploy,
216
+ new CiStageInstruction(workflow, this.workflowService, 'promote'),
217
+ );
218
+ }
219
+
220
+ this.app.resourceManager.define({
221
+ name: CI_MANAGER_RESOURCE,
222
+ actions: createCiManagerResourceActions(this.app, () => this.workflowService),
223
+ });
224
+
225
+ this.app.resourceManager.use(async (ctx, next) => {
226
+ await next();
227
+ if (ctx.action?.resourceName === CI_PIPELINES_COLLECTION && ctx.body) {
228
+ ctx.body = maskWebhookSecretInPayload(ctx.body);
229
+ }
230
+ });
231
+
232
+ this.app.acl.registerSnippet({
233
+ name: CI_MANAGER_ACL_SNIPPET,
234
+ actions: [
235
+ `${CI_PIPELINES_COLLECTION}:*`,
236
+ `${CI_GATE_RUNS_COLLECTION}:*`,
237
+ `${CI_GIT_FEEDBACK_OUTBOX_COLLECTION}:*`,
238
+ `${CI_MANAGER_RESOURCE}:*`,
239
+ ],
240
+ });
241
+
242
+ const teamActions = [
243
+ 'listMeta',
244
+ 'listGateRuns',
245
+ 'triggerGate',
246
+ 'approveDiffAndPromote',
247
+ 'clearPromotionHalt',
248
+ 'triggerHotReloadSmoke',
249
+ 'pollNow',
250
+ ];
251
+ for (const action of teamActions) {
252
+ this.app.acl.allow(CI_MANAGER_RESOURCE, action, 'loggedIn');
253
+ }
254
+
255
+ this.app.acl.allow(CI_MANAGER_RESOURCE, 'webhook', 'public');
256
+
257
+ this.app.on?.(TEST_RUN_COMPLETED_EVENT, this.handleTestRunCompleted);
258
+ this.app.on?.(CLUSTER_HOT_RELOAD_COMPLETED_EVENT, this.handleClusterHotReloadCompleted);
259
+ this.db.on(`${PORTAINER_PIPELINE_RUNS_COLLECTION}.afterSave`, this.handlePortainerRunSaved);
260
+ this.app.on?.('afterStart', this.handleAfterStart);
261
+ if (typeof this.app.prependListener === 'function') {
262
+ this.app.prependListener('beforeStop', this.handleStop);
263
+ } else {
264
+ this.app.on?.('beforeStop', this.handleStop);
265
+ }
266
+ this.app.on?.('beforeDestroy', this.handleDestroy);
267
+ }
268
+
269
+ async beforeDisable() {
270
+ await this.handleDestroy();
271
+ }
272
+ }
273
+
274
+ export default PluginWorkflowCiServer;