-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsophia.Jenkinsfile
More file actions
484 lines (449 loc) · 20 KB
/
sophia.Jenkinsfile
File metadata and controls
484 lines (449 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// SHIM: Copy of sophia/Jenkinsfile (inside git submodule).
// Jenkins cannot read Jenkinsfiles from submodules — GitHub API returns
// gitlink objects, and lightweight checkout doesn't init submodules.
// When updating sophia/Jenkinsfile, copy changes here too.
// TODO: Eliminate this shim by publishing sophia to a registry (see
// genesis/plans/2026-03-11-pnpm-workspace-normalization-design.md)
/**
* Sophia Pipeline (elohim-sophia)
*
* Builds and publishes the Sophia rendering library (React/TypeScript monorepo).
* Triggered by orchestrator when sophia/ files change.
*
* What this pipeline builds:
* - Sophia monorepo packages (lint, typecheck, test, build)
* - sophia-element UMD bundle for downstream consumption
*
* Environment Architecture:
* - main -> sophia SonarQube project (blocking gate)
* - staging* -> sophia-staging SonarQube project
* - dev/* -> sophia-alpha SonarQube project
*
* Trigger behavior:
* - Only runs when triggered by orchestrator or manual
* - Shows NOT_BUILT when triggered directly by webhook
*
* Artifact dependency:
* - Downstream: elohim-app consumes sophia-element UMD bundle + CSS
*
* @see orchestrator/Jenkinsfile for central trigger logic
*/
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
def shouldRunStep(String stepName) {
def steps = (params.STEPS ?: 'all').split(',').collect { it.trim() }
return steps.contains('all') || steps.contains(stepName)
}
/**
* Determine SonarQube project config based on branch.
* Returns: [projectKey: String, shouldEnforce: Boolean, env: String]
*/
@NonCPS
def getSonarProjectConfig() {
def targetBranch = env.CHANGE_TARGET ?: env.BRANCH_NAME
if (targetBranch == 'main') {
return [projectKey: 'sophia', shouldEnforce: true, env: 'prod']
} else if (targetBranch == 'staging' || targetBranch ==~ /staging-.+/) {
return [projectKey: 'sophia-staging', shouldEnforce: false, env: 'staging']
} else {
return [projectKey: 'sophia-alpha', shouldEnforce: false, env: 'alpha']
}
}
pipeline {
agent {
kubernetes {
cloud 'kubernetes'
yaml '''
apiVersion: v1
kind: Pod
spec:
serviceAccount: ee-jenkins
nodeSelector:
node-type: performance
tolerations:
- key: "workload-type"
operator: "Equal"
value: "build"
effect: "NoSchedule"
containers:
- name: node
image: node:20
command: [cat]
tty: true
resources:
requests:
memory: "8Gi"
cpu: "2"
ephemeral-storage: "3Gi"
limits:
memory: "16Gi"
cpu: "4"
ephemeral-storage: "6Gi"
- name: builder
image: harbor.ethosengine.com/ethosengine/ci-builder:latest
command: [cat]
tty: true
'''
}
}
environment {
NPM_TOKEN = credentials('ee-nexus-npm-token')
}
parameters {
booleanParam(
name: 'FORCE_BUILD',
defaultValue: false,
description: 'Force full rebuild even without code changes'
)
string(name: 'STEPS', defaultValue: 'all', description: 'Comma-separated build steps to run. "all" runs everything.')
}
options {
timeout(time: 45, unit: 'MINUTES')
disableConcurrentBuilds(abortPrevious: true)
buildDiscarder(logRotator(numToKeepStr: '50'))
overrideIndexTriggers(false) // Only orchestrator or manual triggers - no webhook/branch indexing
}
// No triggers - orchestrator handles all webhook events
stages {
stage('Check Trigger') {
steps {
script {
def validTrigger = currentBuild.getBuildCauses().any { cause ->
cause._class.contains('UserIdCause') ||
cause._class.contains('UpstreamCause')
}
if (!validTrigger) {
echo "Pipeline skipped - use orchestrator"
currentBuild.result = 'NOT_BUILT'
currentBuild.displayName = "#${env.BUILD_NUMBER} SKIPPED"
env.PIPELINE_SKIPPED = 'true'
} else {
echo "Valid trigger: ${currentBuild.getBuildCauses()*.shortDescription.join(', ')}"
}
}
}
}
stage('Checkout') {
when { expression { env.PIPELINE_SKIPPED != 'true' } }
steps {
container('node') {
checkout scm
sh 'git config --global --add safe.directory "$PWD"'
sh 'git submodule update --init --recursive sophia'
// Remove parent workspace config so pnpm treats sophia as standalone.
// Must happen after checkout, before any pnpm command.
sh '''
rm -f pnpm-workspace.yaml package.json
# Keep only registry config from parent .npmrc, drop workspace-specific settings
grep -E '^(registry=|//)' .npmrc > /tmp/registry-npmrc || true
rm -f .npmrc
if [ -s /tmp/registry-npmrc ]; then cp /tmp/registry-npmrc .npmrc; fi
'''
echo "Building Sophia for branch: ${env.BRANCH_NAME}"
}
}
}
stage('Install') {
when { expression { env.PIPELINE_SKIPPED != 'true' } }
steps {
container('node') {
dir('sophia') {
sh '''#!/bin/bash
set -euo pipefail
# Install pnpm globally
corepack enable
corepack prepare pnpm@latest --activate
pnpm install --frozen-lockfile
'''
}
}
}
}
stage('Lint') {
when { expression { env.PIPELINE_SKIPPED != 'true' } }
steps {
container('node') {
dir('sophia') {
sh '''#!/bin/bash
set -euo pipefail
pnpm lint
'''
}
}
}
}
stage('Type Check') {
when { expression { env.PIPELINE_SKIPPED != 'true' } }
steps {
container('node') {
dir('sophia') {
sh '''#!/bin/bash
set -euo pipefail
pnpm typecheck
'''
}
}
}
}
stage('Unit Tests') {
when { expression { env.PIPELINE_SKIPPED != 'true' } }
steps {
container('node') {
dir('sophia') {
sh '''#!/bin/bash
set -euo pipefail
# Coverage instrumentation 2-3x memory; run tests without it
export NODE_OPTIONS="--max-old-space-size=4096"
pnpm exec jest --ci --maxWorkers=2 --forceExit
'''
}
}
}
}
stage('Build') {
when { expression { env.PIPELINE_SKIPPED != 'true' } }
steps {
container('node') {
dir('sophia') {
sh '''#!/bin/bash
set -euo pipefail
pnpm build
pnpm build:types
'''
}
}
}
}
stage('Build UMD') {
when { allOf {
expression { env.PIPELINE_SKIPPED != 'true' }
expression { shouldRunStep('build-sophia-umd') }
}}
steps {
container('node') {
dir('sophia') {
sh '''#!/bin/bash
set -euo pipefail
pnpm --filter @ethosengine/sophia-element build:umd
# Verify UMD bundle was produced
UMD_PATH="packages/sophia-element/dist/sophia-element.umd.js"
if [ ! -f "$UMD_PATH" ]; then
echo "ERROR: UMD bundle not found at $UMD_PATH"
exit 1
fi
UMD_SIZE=$(stat -c%s "$UMD_PATH" 2>/dev/null || stat -f%z "$UMD_PATH")
echo "UMD bundle: $UMD_PATH ($UMD_SIZE bytes)"
'''
}
}
}
}
stage('SonarQube Analysis') {
when {
allOf {
expression { env.PIPELINE_SKIPPED != 'true' }
anyOf {
branch 'main'
branch 'staging'
branch 'dev'
expression { env.BRANCH_NAME ==~ /staging-.+/ }
expression { env.BRANCH_NAME ==~ /feat-.+/ }
expression { env.BRANCH_NAME ==~ /claude\/.+/ }
changeRequest target: 'main'
changeRequest target: 'staging'
changeRequest target: 'dev'
}
}
}
steps {
container('builder') {
dir('sophia') {
script {
def sonarConfig = getSonarProjectConfig()
echo "SonarQube Analysis: project=${sonarConfig.projectKey}, env=${sonarConfig.env}, enforce=${sonarConfig.shouldEnforce}"
withSonarQubeEnv('ee-sonarqube') {
sh """
sonar-scanner \
-Dsonar.projectKey=${sonarConfig.projectKey} \
-Dsonar.sources=packages \
-Dsonar.tests=packages \
-Dsonar.test.inclusions=**/*.test.ts,**/*.test.tsx \
-Dsonar.javascript.lcov.reportPaths=coverage/lcov.info \
-Dsonar.coverage.exclusions=**/*.test.ts,**/*.test.tsx,**/*.stories.tsx,**/dist/**,**/__docs__/**,**/node_modules/** \
-Dsonar.qualitygate.wait=false
"""
}
echo "Waiting for SonarQube quality gate..."
try {
timeout(time: 10, unit: 'MINUTES') {
def qg = waitForQualityGate abortPipeline: false
if (qg.status != 'OK') {
if (sonarConfig.shouldEnforce) {
// Production: Block on quality gate failure
error "SonarQube Quality Gate FAILED: ${qg.status}\nReview issues at: ${env.SONAR_HOST_URL}/dashboard?id=${sonarConfig.projectKey}"
} else {
// Alpha/Staging: Log warning but don't block
echo "SonarQube Quality Gate status: ${qg.status}"
echo "Review issues at: ${env.SONAR_HOST_URL}/dashboard?id=${sonarConfig.projectKey}"
currentBuild.result = 'UNSTABLE'
}
} else {
echo "SonarQube quality gate passed (${sonarConfig.env})"
}
}
} catch (Exception e) {
echo "SonarQube quality gate check failed: ${e.message}"
echo "This may be due to webhook configuration issues."
echo "Review results at: ${env.SONAR_HOST_URL}/dashboard?id=${sonarConfig.projectKey}"
if (sonarConfig.shouldEnforce) {
currentBuild.result = 'UNSTABLE'
echo "Marking build UNSTABLE - production quality gate could not be verified"
} else {
echo "Continuing pipeline..."
}
}
}
}
}
}
}
stage('Publish to npm') {
when {
allOf {
expression { env.PIPELINE_SKIPPED != 'true' }
anyOf {
branch 'main'
branch 'staging'
}
}
}
steps {
container('node') {
dir('sophia') {
script {
withCredentials([string(credentialsId: 'npm-publish-token', variable: 'NPM_TOKEN')]) {
sh '''#!/bin/bash
set -euo pipefail
echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc
pnpm --filter @ethosengine/sophia-element publish --no-git-checks
'''
}
echo "Published @ethosengine/sophia-element to npm registry"
}
}
}
}
}
stage('Publish to Nexus') {
when { expression { env.PIPELINE_SKIPPED != 'true' } }
steps {
container('node') {
dir('sophia') {
script {
withCredentials([string(credentialsId: 'ee-nexus-npm-token', variable: 'NEXUS_TOKEN')]) {
sh '''#!/bin/bash
set -euo pipefail
PKG_VERSION=$(node -p "require('./packages/sophia-element/package.json').version")
echo "Checking if @ethosengine/sophia-element@${PKG_VERSION} exists on Nexus..."
if npm view "@ethosengine/sophia-element@${PKG_VERSION}" --registry=https://nexus.ethosengine.com/repository/npm/ version 2>/dev/null; then
echo "ℹ️ @ethosengine/sophia-element@${PKG_VERSION} already published to Nexus, skipping"
else
echo "Publishing @ethosengine/sophia-element@${PKG_VERSION} to Nexus..."
echo "//nexus.ethosengine.com/repository/npm-hosted/:_authToken=${NEXUS_TOKEN}" > ~/.npmrc
pnpm --filter @ethosengine/sophia-element publish --no-git-checks --registry=https://nexus.ethosengine.com/repository/npm-hosted/
echo "✅ Published @ethosengine/sophia-element@${PKG_VERSION} to Nexus"
fi
'''
}
}
}
}
}
}
stage('Archive Artifacts') {
when { expression { env.PIPELINE_SKIPPED != 'true' } }
steps {
container('node') {
dir('sophia') {
script {
// Stash UMD bundle + CSS for downstream pipelines (e.g. elohim-app)
stash(
name: 'sophia-umd',
includes: 'packages/sophia-element/dist/**'
)
archiveArtifacts(
artifacts: 'packages/sophia-element/dist/sophia-element.umd.js,packages/sophia-element/dist/**/*.css',
allowEmptyArchive: false
)
echo "Archived sophia-element UMD bundle and CSS for downstream consumption"
}
}
}
}
}
stage('Publish GitHub Release') {
// TODO: Re-enable when GitHub release publishing is needed.
// Currently disabled — sophia UMD is consumed via file copy, not GitHub Releases.
when { expression { false } }
steps {
container('node') {
dir('sophia') {
script {
def version = sh(
script: "node -p \"require('./packages/sophia-element/package.json').version\"",
returnStdout: true
).trim()
def tag = "sophia-v${version}"
def umd = 'packages/sophia-element/dist/sophia-element.umd.js'
def umdMap = 'packages/sophia-element/dist/sophia-element.umd.js.map'
def styles = 'packages/sophia/dist/index.css'
withCredentials([string(credentialsId: 'github-token', variable: 'GH_TOKEN')]) {
// Check if release exists; create or update
def exists = sh(
script: "gh release view ${tag} --repo ethosengine/elohim 2>/dev/null && echo yes || echo no",
returnStdout: true
).trim().endsWith('yes')
if (exists) {
echo "Updating existing release ${tag}..."
sh "gh release upload ${tag} ${umd} ${umdMap} '${styles}#sophia-styles.css' --repo ethosengine/elohim --clobber"
} else {
echo "Creating release ${tag}..."
sh """gh release create ${tag} \
${umd} ${umdMap} '${styles}#sophia-styles.css' \
--repo ethosengine/elohim \
--title 'Sophia Element ${version}' \
--notes 'sophia-element UMD bundle + styles for elohim-app consumption.'"""
}
}
echo "Published sophia-element ${version} as GitHub Release: ${tag}"
}
}
}
}
}
}
post {
always {
script {
if (env.PIPELINE_SKIPPED != 'true') {
def sonarConfig = getSonarProjectConfig()
currentBuild.description = [
"branch:${env.BRANCH_NAME}",
"sonar:${sonarConfig.projectKey}"
].join(' | ')
}
}
}
success {
echo "Sophia pipeline completed successfully"
}
failure {
echo "Sophia pipeline failed"
echo "Check the logs above for details. Common issues:"
echo " - pnpm install failures: Check lockfile consistency"
echo " - Lint/typecheck errors: Fix source code issues"
echo " - UMD build missing: Ensure sophia-element build:umd script is defined"
}
}
}