run-gates.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. /**
  2. * Run local and CI quality gates with bounded in-process scheduling.
  3. *
  4. * The gate vocabulary stays in package.json; this runner only decides which
  5. * independent commands can overlap and which commands wait for built artifacts.
  6. */
  7. import { spawn } from 'node:child_process'
  8. import { availableParallelism } from 'node:os'
  9. import { resolve } from 'node:path'
  10. import { performance } from 'node:perf_hooks'
  11. import { coverageArgs } from './coverage-shards.ts'
  12. import { selectLintShard } from './lint-shards.ts'
  13. import { selectSnapshotLane } from './snapshot-shards.ts'
  14. import { selectStaticGates } from './static-shards.ts'
  15. type Mode =
  16. | 'ci-primary'
  17. | 'ci-static'
  18. | 'ci-lint'
  19. | 'ci-coverage'
  20. | 'ci-snapshot'
  21. | 'ci-artifacts'
  22. | 'node-compat'
  23. | 'pre-push'
  24. | 'doc-sync'
  25. type GateStatus = 'pending' | 'running' | 'passed' | 'failed' | 'skipped'
  26. interface Gate {
  27. id: string
  28. label: string
  29. displayCommand: string
  30. command: string
  31. args: string[]
  32. needs?: string[]
  33. env?: Record<string, string | undefined>
  34. input?: string
  35. verify?: (result: GateResult) => Promise<void>
  36. }
  37. interface GateResult {
  38. gate: Gate
  39. status: GateStatus
  40. durationMs: number
  41. stdout: string
  42. stderr: string
  43. output: GateOutputChunk[]
  44. exitCode: number | null
  45. error?: string
  46. }
  47. interface GateOutputChunk {
  48. stream: 'stdout' | 'stderr'
  49. text: string
  50. }
  51. interface RunningGate {
  52. gate: Gate
  53. promise: Promise<GateResult>
  54. }
  55. interface ConcurrencyDefault {
  56. workers: number
  57. source: string
  58. }
  59. const root = resolve(import.meta.dirname, '..')
  60. const mode = parseMode(process.argv[2])
  61. const gates = gatesForMode(mode)
  62. const concurrencyDefault = defaultConcurrency(mode, gates.length)
  63. const concurrencyOverride = process.env.DSH_GATE_CONCURRENCY
  64. const maxConcurrency = concurrencyFromEnv('DSH_GATE_CONCURRENCY', concurrencyDefault.workers)
  65. const verbose = process.env.DSH_GATE_VERBOSE === '1'
  66. const startedAt = performance.now()
  67. const concurrencySource = concurrencyOverride === undefined || concurrencyOverride === ''
  68. ? concurrencyDefault.source
  69. : '$DSH_GATE_CONCURRENCY'
  70. console.log(`run-gates: ${mode} running ${gates.length} gate(s) with ${maxConcurrency} worker(s) from ${concurrencySource}.`)
  71. const results = await runGates(gates, maxConcurrency)
  72. printSummary(results, performance.now() - startedAt)
  73. if (results.some(result => result.status === 'failed' || result.status === 'skipped')) process.exit(1)
  74. function parseMode(raw: string | undefined): Mode {
  75. switch (raw) {
  76. case 'ci-primary':
  77. case 'ci-static':
  78. case 'ci-lint':
  79. case 'ci-coverage':
  80. case 'ci-snapshot':
  81. case 'ci-artifacts':
  82. case 'node-compat':
  83. case 'pre-push':
  84. case 'doc-sync':
  85. return raw
  86. default:
  87. throw new Error(
  88. `run-gates: expected mode ci-primary | ci-static | ci-lint | ci-coverage | ci-snapshot | ci-artifacts | node-compat | pre-push | doc-sync, got ${JSON.stringify(raw)}.`,
  89. )
  90. }
  91. }
  92. function defaultConcurrency(selectedMode: Mode, total: number): ConcurrencyDefault {
  93. const available = availableParallelism()
  94. // Local modes cap workers: several doc gates each build a full ts.Program,
  95. // so an uncapped default on a large host trades wall clock for memory blowups.
  96. const localCap = selectedMode === 'pre-push' || selectedMode === 'doc-sync'
  97. const modeLimit = localCap ? Math.min(4, available) : available
  98. return {
  99. workers: Math.min(total, modeLimit),
  100. source: localCap
  101. ? `${available} available CPU(s), ${selectedMode} cap 4`
  102. : `${available} available CPU(s)`,
  103. }
  104. }
  105. function concurrencyFromEnv(name: string, fallback: number): number {
  106. const raw = process.env[name]
  107. if (raw === undefined || raw === '') return fallback
  108. const parsed = Number.parseInt(raw, 10)
  109. if (!Number.isSafeInteger(parsed) || parsed < 1) {
  110. throw new Error(`run-gates: ${name} must be a positive integer, got ${JSON.stringify(raw)}.`)
  111. }
  112. return parsed
  113. }
  114. function pnpmScript(id: string, script: string, options: Partial<Gate> = {}): Gate {
  115. return {
  116. id,
  117. label: options.label ?? script,
  118. displayCommand: `pnpm run ${script}`,
  119. ...pnpmInvocation(['run', script]),
  120. ...options,
  121. }
  122. }
  123. function pnpmExec(id: string, args: string[], options: Partial<Gate> = {}): Gate {
  124. return {
  125. id,
  126. label: options.label ?? `pnpm exec ${args.join(' ')}`,
  127. displayCommand: `pnpm exec ${args.join(' ')}`,
  128. ...pnpmInvocation(['exec', ...args]),
  129. ...options,
  130. }
  131. }
  132. function pnpmInvocation(args: string[]): Pick<Gate, 'command' | 'args'> {
  133. const entrypoint = process.env.npm_execpath
  134. if (entrypoint === undefined || entrypoint === '') {
  135. throw new Error('run-gates: npm_execpath is unavailable; invoke the runner through a pnpm package script.')
  136. }
  137. // Windows cannot spawn the pnpm.cmd shim directly; the JavaScript entrypoint keeps every host shell-free.
  138. return { command: process.execPath, args: [entrypoint, ...args] }
  139. }
  140. function nodeOptions(...options: string[]): string {
  141. return [process.env.NODE_OPTIONS, ...options].filter(option => option !== undefined && option !== '').join(' ')
  142. }
  143. function gatesForMode(selected: Mode): Gate[] {
  144. switch (selected) {
  145. case 'ci-primary':
  146. return ciPrimaryGates()
  147. case 'ci-static':
  148. return ciStaticGates()
  149. case 'ci-lint': {
  150. const selection = selectLintShard(process.env.DSH_LINT_SHARD)
  151. return [
  152. lintGate(selection.eslintTargets),
  153. ...selection.includeDuplication ? [pnpmScript('duplication', 'duplication')] : [],
  154. ]
  155. }
  156. case 'ci-coverage':
  157. return [coverageGate()]
  158. case 'ci-snapshot':
  159. return flagEnabled('DSH_SNAPSHOT_PREBUILT')
  160. ? [snapshotGate([])]
  161. : [pnpmScript('build', 'build'), snapshotGate()]
  162. case 'ci-artifacts':
  163. return ciArtifactGates()
  164. case 'node-compat':
  165. return [
  166. ...flagEnabled('DSH_NODE_COMPAT_SKIP_TYPECHECK') ? [] : [pnpmScript('typecheck', 'typecheck')],
  167. pnpmExec('source-worker-smoke', [
  168. 'vitest',
  169. 'run',
  170. 'packages/workflow/workflow-workerthread/tests/source-worker.compat.spec.ts',
  171. ], { label: 'source worker smoke' }),
  172. pnpmExec('jsonl-zstd-smoke', [
  173. 'vitest',
  174. 'run',
  175. 'packages/session-persistence/session-persistence-jsonl/tests/zstd.compat.spec.ts',
  176. ], { label: 'JSONL Zstandard smoke' }),
  177. ]
  178. case 'pre-push':
  179. return [
  180. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  181. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  182. pnpmScript('test', 'test'),
  183. pnpmScript('duplication', 'duplication'),
  184. snapshotGate(),
  185. pnpmScript('build', 'build'),
  186. ...hygieneLeafGates({ artifactNeeds: ['build'] }),
  187. ...docSyncLeafGates({
  188. docTypecheckNeeds: ['build'],
  189. docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  190. }),
  191. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  192. ]
  193. case 'doc-sync':
  194. return docSyncLeafGates()
  195. }
  196. }
  197. function ciPrimaryGates(): Gate[] {
  198. return [
  199. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  200. pnpmScript('constraints', 'constraints'),
  201. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  202. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  203. pnpmScript('typecheck', 'typecheck'),
  204. lintGate(),
  205. pnpmScript('duplication', 'duplication'),
  206. coverageGate(),
  207. snapshotGate(),
  208. ...docSyncLeafGates(),
  209. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  210. pnpmScript('knip', 'knip'),
  211. pnpmScript('build', 'build', { needs: ['typecheck'] }),
  212. pnpmScript('publint', 'publint', { needs: ['build'] }),
  213. pnpmScript('node-next-types', 'verify-node-next-types', {
  214. label: 'node-next types',
  215. needs: ['build'],
  216. }),
  217. builtPackageInvariantsGate(['build']),
  218. builtBinSmokeGate(),
  219. ]
  220. }
  221. function ciStaticGates(): Gate[] {
  222. const gates = [
  223. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  224. pnpmScript('constraints', 'constraints'),
  225. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  226. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  227. pnpmScript('build', 'build'),
  228. ...docSyncLeafGates({
  229. docTypecheckNeeds: ['build'],
  230. docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  231. docsBuildScript: 'docs:build:mpa',
  232. }),
  233. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  234. pnpmScript('knip', 'knip'),
  235. ]
  236. return selectStaticGates(gates, process.env.DSH_STATIC_SHARD)
  237. }
  238. function ciArtifactGates(): Gate[] {
  239. const shard = process.env.DSH_ARTIFACT_SHARD
  240. const metadataGates = [
  241. pnpmScript('build', 'build'),
  242. pnpmScript('publint', 'publint', { needs: ['build'] }),
  243. pnpmScript('node-next-types', 'verify-node-next-types', {
  244. label: 'node-next types',
  245. needs: ['build'],
  246. }),
  247. builtPackageInvariantsGate(['build']),
  248. ]
  249. if (shard === 'metadata') return metadataGates
  250. if (shard === 'smoke') return [pnpmScript('build', 'build'), builtBinSmokeGate()]
  251. if (shard !== undefined && shard !== '') {
  252. throw new Error(`run-gates: unknown DSH_ARTIFACT_SHARD ${JSON.stringify(shard)}.`)
  253. }
  254. return [...metadataGates, builtBinSmokeGate()]
  255. }
  256. function lintGate(eslintTargets: readonly string[] = ['.']): Gate {
  257. if (process.env.DSH_ESLINT_CACHE === '1') {
  258. return pnpmExec('lint', [
  259. 'eslint',
  260. ...eslintTargets,
  261. '--cache',
  262. '--cache-location',
  263. '.cache/eslint/',
  264. '--cache-strategy',
  265. 'content',
  266. ], {
  267. label: 'lint',
  268. env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') },
  269. })
  270. }
  271. return pnpmScript('lint', 'lint', {
  272. env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') },
  273. })
  274. }
  275. function coverageGate(): Gate {
  276. const shard = process.env.DSH_COVERAGE_SHARD
  277. return pnpmExec('coverage', [
  278. 'vitest',
  279. 'run',
  280. '--coverage',
  281. ...(shard === undefined || shard === '' ? [] : coverageArgs(shard)),
  282. ...positiveIntArg('DSH_COVERAGE_MAX_WORKERS', '--maxWorkers'),
  283. ], {
  284. label: 'test:coverage',
  285. })
  286. }
  287. // The snapshot suite boots the example bins in `lib` mode (built artifact under plain Node,
  288. // plugins via real exports) — CI and pre-push already build, so they exercise what ships rather
  289. // than the tsx/source path dev uses. It therefore waits on `build`.
  290. function snapshotGate(needs: string[] = ['build']): Gate {
  291. const lane = selectSnapshotLane(process.env.DSH_SNAPSHOT_LANE)
  292. return pnpmExec('snapshot', [
  293. 'vitest',
  294. 'run',
  295. '--config',
  296. 'vitest.snapshot.config.ts',
  297. ...lane.files,
  298. ], {
  299. label: 'test:snapshot',
  300. env: {
  301. DSH_EXAMPLE_MODE: 'lib',
  302. ...lane.scenarioShard === undefined ? {} : { DSH_SNAPSHOT_SCENARIO_SHARD: lane.scenarioShard },
  303. },
  304. ...needs.length === 0 ? {} : { needs },
  305. })
  306. }
  307. function builtPackageInvariantsGate(needs?: string[]): Gate {
  308. return pnpmScript('built-package-invariants', 'verify-built-package-invariants', {
  309. label: 'built package invariants',
  310. ...needs === undefined ? {} : { needs },
  311. })
  312. }
  313. function positiveIntArg(envName: string, flag: string): string[] {
  314. const raw = process.env[envName]
  315. if (raw === undefined || raw === '') return []
  316. const parsed = Number.parseInt(raw, 10)
  317. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  318. throw new Error(`run-gates: ${envName} must be a positive integer, got ${JSON.stringify(raw)}.`)
  319. }
  320. return [`${flag}=${raw}`]
  321. }
  322. function flagEnabled(envName: string): boolean {
  323. const raw = process.env[envName]
  324. if (raw === undefined || raw === '') return false
  325. if (raw !== '1') throw new Error(`run-gates: ${envName} must be 1 when set, got ${JSON.stringify(raw)}.`)
  326. return true
  327. }
  328. function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] {
  329. const artifactOptions = options.artifactNeeds === undefined ? {} : { needs: options.artifactNeeds }
  330. return [
  331. pnpmScript('knip', 'knip'),
  332. pnpmScript('publint', 'publint', artifactOptions),
  333. pnpmScript('constraints', 'constraints'),
  334. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  335. builtPackageInvariantsGate(options.artifactNeeds),
  336. pnpmScript('node-next-types', 'verify-node-next-types', {
  337. label: 'node-next types',
  338. ...artifactOptions,
  339. }),
  340. ]
  341. }
  342. function docSyncLeafGates(options: {
  343. docTypecheckNeeds?: string[]
  344. docTypecheckEnv?: Record<string, string | undefined>
  345. docsBuildScript?: 'docs:build' | 'docs:build:mpa'
  346. } = {}): Gate[] {
  347. const docTypecheckOptions: Partial<Gate> = {}
  348. if (options.docTypecheckNeeds !== undefined) docTypecheckOptions.needs = options.docTypecheckNeeds
  349. if (options.docTypecheckEnv !== undefined) docTypecheckOptions.env = options.docTypecheckEnv
  350. return [
  351. pnpmScript('doc-typecheck', 'doc-typecheck', docTypecheckOptions),
  352. pnpmScript('cordis-catalog', 'verify-cordis-catalog', { label: 'cordis catalog' }),
  353. pnpmScript('cordis-api', 'verify-cordis-api', { label: 'cordis api' }),
  354. pnpmScript('export-jsdoc', 'verify-export-jsdoc', { label: 'export jsdoc' }),
  355. pnpmScript('tool-catalog', 'verify-tool-catalog', { label: 'tool catalog' }),
  356. pnpmScript('config-catalog', 'verify-config-catalog', { label: 'config catalog' }),
  357. pnpmScript('persistence-catalog', 'verify-persistence-catalog', { label: 'persistence catalog' }),
  358. pnpmScript('doc-graphs', 'verify-doc-graphs', { label: 'doc graphs' }),
  359. pnpmScript('scoped-events', 'verify-scoped-events', { label: 'scoped events' }),
  360. pnpmScript('markdown-wrap', 'verify-md-wrap', { label: 'markdown wrap' }),
  361. pnpmScript('markdown-links', 'verify-md-links', { label: 'markdown links' }),
  362. pnpmScript('doc-refs', 'verify-doc-refs', { label: 'doc refs' }),
  363. pnpmScript('package-paths', 'verify-package-paths', { label: 'package paths' }),
  364. pnpmScript('package-readme-model-experience', 'verify-package-readme-model-experience', { label: 'package README model experience' }),
  365. pnpmScript('mermaid', 'verify-mermaid'),
  366. pnpmScript('agent-note-classification', 'verify-agent-note-classification', { label: 'agent note classification' }),
  367. pnpmScript('agent-note-format', 'verify-agent-note-format', { label: 'agent note format' }),
  368. pnpmScript('type-equivalence', 'verify-type-equiv', { label: 'type equivalence' }),
  369. pnpmScript('translation-prompt', 'verify-translation-prompt', { label: 'translation prompt' }),
  370. pnpmScript('translation-pairing', 'verify-translation-pairing', { label: 'translation pairing' }),
  371. pnpmScript('doc-budgets', 'verify-doc-budgets', { label: 'doc budgets' }),
  372. pnpmExec('docs-site-projection', ['vitest', 'run', 'scripts/project-doc-site.spec.ts'], {
  373. label: 'documentation projection',
  374. }),
  375. // Keep the VitePress build itself in one gate because projection rewrites website/.generated.
  376. pnpmScript('docs-site-build', options.docsBuildScript ?? 'docs:build', { label: 'documentation build' }),
  377. pnpmScript('package-readme-limitations', 'verify-package-readme-limitations', { label: 'package README limitations' }),
  378. ]
  379. }
  380. function builtBinSmokeGate(shard?: string): Gate {
  381. return pnpmExec('built-bin-smoke', [
  382. 'vitest',
  383. 'run',
  384. '--config',
  385. 'vitest.e2e.config.ts',
  386. 'examples/headless-agent/tests/keyless-smoke.e2e.ts',
  387. 'examples/tui-agent/tests/tui-keyless-smoke.e2e.ts',
  388. 'packages/examples/cli-demo/tests/built-bin.e2e.ts',
  389. 'packages/examples/acp-demo/tests/built-bin.e2e.ts',
  390. 'packages/ui/jsonrpc/tests/built-scope-carrier.e2e.ts',
  391. // The worker-entry packages' built bundles: the only automated proof
  392. // that lib/index.js resolves its sibling lib/worker.cjs under plain node
  393. // (the e2e lane runs unbuilt, so these files self-skip there).
  394. 'packages/workflow/workflow-workerthread/tests/built-worker.e2e.ts',
  395. 'packages/code-runtime/code-runtime-worker/tests/built-lib.e2e.ts',
  396. ...(shard === undefined ? [] : [`--shard=${shard}`]),
  397. ], {
  398. label: 'built-bin smoke',
  399. needs: ['build'],
  400. env: { DSH_EXAMPLE_MODE: 'lib' },
  401. })
  402. }
  403. async function runGates(allGates: Gate[], maxActive: number): Promise<GateResult[]> {
  404. const states = new Map<string, GateStatus>(allGates.map(gate => [gate.id, 'pending']))
  405. const results = new Map<string, GateResult>()
  406. const running: RunningGate[] = []
  407. for (;;) {
  408. let madeProgress = false
  409. while (running.length < maxActive) {
  410. const ready = allGates.find(gate => states.get(gate.id) === 'pending' && dependenciesPassed(gate, states))
  411. if (ready === undefined) break
  412. states.set(ready.id, 'running')
  413. running.push({ gate: ready, promise: runGate(ready) })
  414. console.log(`run-gates: start ${ready.label}`)
  415. madeProgress = true
  416. }
  417. if (running.length === 0) {
  418. const pending = allGates.filter(gate => states.get(gate.id) === 'pending')
  419. for (const gate of pending) {
  420. const failedDeps = (gate.needs ?? []).filter(id => states.get(id) !== 'passed')
  421. const result: GateResult = {
  422. gate,
  423. status: 'skipped',
  424. durationMs: 0,
  425. stdout: '',
  426. stderr: '',
  427. output: [],
  428. exitCode: null,
  429. error: `dependency failed or skipped: ${failedDeps.join(', ')}`,
  430. }
  431. states.set(gate.id, 'skipped')
  432. results.set(gate.id, result)
  433. printResult(result)
  434. }
  435. break
  436. }
  437. if (!madeProgress) {
  438. const settled = await Promise.race(running.map(async item => ({ item, result: await item.promise })))
  439. running.splice(running.indexOf(settled.item), 1)
  440. states.set(settled.item.gate.id, settled.result.status)
  441. results.set(settled.item.gate.id, settled.result)
  442. printResult(settled.result)
  443. }
  444. }
  445. return allGates.map((gate) => {
  446. const result = results.get(gate.id)
  447. if (result === undefined) throw new Error(`run-gates: missing result for ${gate.id}.`)
  448. return result
  449. })
  450. }
  451. function dependenciesPassed(gate: Gate, states: Map<string, GateStatus>): boolean {
  452. return (gate.needs ?? []).every(id => states.get(id) === 'passed')
  453. }
  454. async function runGate(gate: Gate): Promise<GateResult> {
  455. const started = performance.now()
  456. let stdout = ''
  457. let stderr = ''
  458. const output: GateOutputChunk[] = []
  459. let spawnError: string | undefined
  460. const exitCode = await new Promise<number | null>((resolveExit) => {
  461. const child = spawn(gate.command, gate.args, {
  462. cwd: root,
  463. env: { ...process.env, ...gate.env },
  464. stdio: ['pipe', 'pipe', 'pipe'],
  465. })
  466. child.stdout.setEncoding('utf8')
  467. child.stderr.setEncoding('utf8')
  468. child.stdout.on('data', (chunk: string) => {
  469. stdout += chunk
  470. output.push({ stream: 'stdout', text: chunk })
  471. })
  472. child.stderr.on('data', (chunk: string) => {
  473. stderr += chunk
  474. output.push({ stream: 'stderr', text: chunk })
  475. })
  476. child.on('error', (error) => {
  477. spawnError = `failed to start command: ${error.message}`
  478. resolveExit(null)
  479. })
  480. child.on('close', resolveExit)
  481. if (gate.input !== undefined) child.stdin.end(gate.input)
  482. else child.stdin.end()
  483. })
  484. let status: GateStatus = exitCode === 0 && spawnError === undefined ? 'passed' : 'failed'
  485. let error = spawnError
  486. if (status === 'passed' && gate.verify !== undefined) {
  487. try {
  488. await gate.verify({ gate, status, durationMs: performance.now() - started, stdout, stderr, output, exitCode })
  489. } catch (verifyError: unknown) {
  490. status = 'failed'
  491. error = verifyError instanceof Error ? verifyError.message : String(verifyError)
  492. }
  493. }
  494. const result: GateResult = {
  495. gate,
  496. status,
  497. durationMs: performance.now() - started,
  498. stdout,
  499. stderr,
  500. output,
  501. exitCode,
  502. }
  503. if (error !== undefined) result.error = error
  504. return result
  505. }
  506. function printResult(result: GateResult): void {
  507. const seconds = (result.durationMs / 1000).toFixed(2)
  508. if (result.status === 'passed' && !verbose) {
  509. console.log(`run-gates: PASS ${result.gate.label} (${seconds}s)`)
  510. return
  511. }
  512. const heading = `${result.status.toUpperCase()} ${result.gate.label} (${seconds}s)`
  513. const writeHeading = result.status === 'passed' ? console.log : console.error
  514. writeHeading(`\n== ${heading} ==`)
  515. if (result.status !== 'passed') console.error(`command: ${result.gate.displayCommand}`)
  516. printOutput(result.output)
  517. if (result.error !== undefined) console.error(result.error)
  518. }
  519. function printSummary(results: GateResult[], durationMs: number): void {
  520. const passed = results.filter(result => result.status === 'passed').length
  521. const failed = results.filter(result => result.status === 'failed').length
  522. const skipped = results.filter(result => result.status === 'skipped').length
  523. const seconds = (durationMs / 1000).toFixed(2)
  524. console.log(`\nrun-gates: ${passed} passed, ${failed} failed, ${skipped} skipped in ${seconds}s.`)
  525. const unsuccessful = results.filter(result => result.status === 'failed' || result.status === 'skipped')
  526. if (unsuccessful.length === 0) return
  527. console.error('run-gates: unsuccessful gates:')
  528. for (const result of unsuccessful) {
  529. const duration = (result.durationMs / 1000).toFixed(2)
  530. const reason = result.error ?? (result.exitCode === null ? 'no exit code' : `exit ${result.exitCode}`)
  531. console.error(` - ${result.status.toUpperCase()} ${result.gate.label} (${duration}s, ${reason})`)
  532. console.error(` ${result.gate.displayCommand}`)
  533. }
  534. }
  535. function printOutput(output: GateOutputChunk[]): void {
  536. for (const chunk of output) {
  537. if (chunk.stream === 'stdout') process.stdout.write(chunk.text)
  538. else process.stderr.write(chunk.text)
  539. }
  540. }