run-gates.ts 23 KB

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