run-gates.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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. // Linux owns required lint, coverage, and snapshots; Windows omits those duplicates.
  295. pnpmScript('duplication', 'duplication'),
  296. pnpmScript('publint', 'publint', { needs: ['build'] }),
  297. pnpmScript('node-next-types', 'verify-node-next-types', {
  298. label: 'node-next types',
  299. needs: ['build'],
  300. }),
  301. builtPackageInvariantsGate(['build']),
  302. builtBinSmokeGate(),
  303. ]
  304. }
  305. function lintGate(eslintTargets: readonly string[] = ['.']): Gate {
  306. const concurrencyArgs = eslintConcurrencyArgs()
  307. if (process.env.DSH_ESLINT_CACHE === '1') {
  308. return pnpmExec('lint', [
  309. 'eslint',
  310. ...eslintTargets,
  311. ...concurrencyArgs,
  312. '--cache',
  313. '--cache-location',
  314. '.cache/eslint/',
  315. '--cache-strategy',
  316. 'content',
  317. ], {
  318. label: 'lint',
  319. env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') },
  320. })
  321. }
  322. if (concurrencyArgs.length > 0) {
  323. return pnpmExec('lint', ['eslint', ...eslintTargets, ...concurrencyArgs], {
  324. label: 'lint',
  325. env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') },
  326. })
  327. }
  328. return pnpmScript('lint', 'lint', {
  329. env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') },
  330. })
  331. }
  332. function eslintConcurrencyArgs(): string[] {
  333. const raw = process.env.DSH_ESLINT_CONCURRENCY
  334. if (raw === undefined || raw === '') return []
  335. if (raw === 'auto') return ['--concurrency=auto']
  336. const parsed = Number.parseInt(raw, 10)
  337. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  338. throw new Error(`run-gates: DSH_ESLINT_CONCURRENCY must be a positive integer or auto, got ${JSON.stringify(raw)}.`)
  339. }
  340. return [`--concurrency=${raw}`]
  341. }
  342. function coverageGate(): Gate {
  343. return pnpmExec('coverage', [
  344. 'vitest',
  345. 'run',
  346. '--coverage',
  347. ...positiveIntArg('DSH_COVERAGE_MAX_WORKERS', '--maxWorkers'),
  348. ], {
  349. label: 'test:coverage',
  350. })
  351. }
  352. // Example and package snapshots boot their bins in `lib` mode (built artifacts under plain Node,
  353. // plugins via real exports); repository-script snapshots execute their real source entry path.
  354. // CI and check-all already build before either class runs, so the suite waits on `build`.
  355. function snapshotGate(): Gate {
  356. return pnpmScript('snapshot', 'test:snapshot', {
  357. env: { DSH_EXAMPLE_MODE: 'lib' },
  358. needs: ['build'],
  359. })
  360. }
  361. function builtPackageInvariantsGate(needs?: string[]): Gate {
  362. return pnpmScript('built-package-invariants', 'verify-built-package-invariants', {
  363. label: 'built package invariants',
  364. ...needs === undefined ? {} : { needs },
  365. })
  366. }
  367. function positiveIntArg(envName: string, flag: string): string[] {
  368. const raw = process.env[envName]
  369. if (raw === undefined || raw === '') return []
  370. const parsed = Number.parseInt(raw, 10)
  371. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  372. throw new Error(`run-gates: ${envName} must be a positive integer, got ${JSON.stringify(raw)}.`)
  373. }
  374. return [`${flag}=${raw}`]
  375. }
  376. function flagEnabled(envName: string): boolean {
  377. const raw = process.env[envName]
  378. if (raw === undefined || raw === '') return false
  379. if (raw !== '1') throw new Error(`run-gates: ${envName} must be 1 when set, got ${JSON.stringify(raw)}.`)
  380. return true
  381. }
  382. function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] {
  383. const artifactOptions = options.artifactNeeds === undefined ? {} : { needs: options.artifactNeeds }
  384. return [
  385. pnpmScript('knip', 'knip'),
  386. pnpmScript('publint', 'publint', artifactOptions),
  387. pnpmScript('constraints', 'constraints'),
  388. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  389. builtPackageInvariantsGate(options.artifactNeeds),
  390. pnpmScript('node-next-types', 'verify-node-next-types', {
  391. label: 'node-next types',
  392. ...artifactOptions,
  393. }),
  394. ]
  395. }
  396. function docSyncLeafGates(options: {
  397. docTypecheckNeeds?: string[]
  398. docTypecheckEnv?: Record<string, string | undefined>
  399. docsBuildScript?: 'docs:build' | 'docs:build:mpa'
  400. } = {}): Gate[] {
  401. const docTypecheckOptions: Partial<Gate> = {}
  402. if (options.docTypecheckNeeds !== undefined) docTypecheckOptions.needs = options.docTypecheckNeeds
  403. if (options.docTypecheckEnv !== undefined) docTypecheckOptions.env = options.docTypecheckEnv
  404. return [
  405. pnpmScript('doc-typecheck', 'doc-typecheck', docTypecheckOptions),
  406. pnpmScript('cordis-catalog', 'verify-cordis-catalog', { label: 'cordis catalog' }),
  407. pnpmScript('cordis-api', 'verify-cordis-api', { label: 'cordis api' }),
  408. pnpmScript('export-jsdoc', 'verify-export-jsdoc', { label: 'export jsdoc' }),
  409. pnpmScript('tool-catalog', 'verify-tool-catalog', { label: 'tool catalog' }),
  410. pnpmScript('config-catalog', 'verify-config-catalog', { label: 'config catalog' }),
  411. pnpmScript('persistence-catalog', 'verify-persistence-catalog', { label: 'persistence catalog' }),
  412. pnpmScript('doc-graphs', 'verify-doc-graphs', { label: 'doc graphs' }),
  413. pnpmScript('scoped-events', 'verify-scoped-events', { label: 'scoped events' }),
  414. pnpmScript('markdown-wrap', 'verify-md-wrap', { label: 'markdown wrap' }),
  415. pnpmScript('markdown-links', 'verify-md-links', { label: 'markdown links' }),
  416. pnpmScript('doc-refs', 'verify-doc-refs', { label: 'doc refs' }),
  417. pnpmScript('package-paths', 'verify-package-paths', { label: 'package paths' }),
  418. pnpmScript('package-readme-model-experience', 'verify-package-readme-model-experience', { label: 'package README model experience' }),
  419. pnpmScript('mermaid', 'verify-mermaid'),
  420. pnpmScript('agent-note-classification', 'verify-agent-note-classification', { label: 'agent note classification' }),
  421. pnpmScript('agent-note-format', 'verify-agent-note-format', { label: 'agent note format' }),
  422. pnpmScript('archived-agent-notes', 'verify-archived-agent-notes', { label: 'archived agent notes' }),
  423. pnpmScript('type-equivalence', 'verify-type-equiv', { label: 'type equivalence' }),
  424. pnpmScript('translation-prompt', 'verify-translation-prompt', { label: 'translation prompt' }),
  425. pnpmScript('translation-pairing', 'verify-translation-pairing', { label: 'translation pairing' }),
  426. pnpmScript('doc-budgets', 'verify-doc-budgets', { label: 'doc budgets' }),
  427. pnpmExec('docs-site-projection', ['vitest', 'run', 'scripts/project-doc-site.spec.ts'], {
  428. label: 'documentation projection',
  429. }),
  430. // Keep the VitePress build itself in one gate because projection rewrites website/.generated.
  431. pnpmScript('docs-site-build', options.docsBuildScript ?? 'docs:build', { label: 'documentation build' }),
  432. pnpmScript('package-readme-limitations', 'verify-package-readme-limitations', { label: 'package README limitations' }),
  433. ]
  434. }
  435. function builtBinSmokeGate(): Gate {
  436. return pnpmExec('built-bin-smoke', [
  437. 'vitest',
  438. 'run',
  439. '--config',
  440. 'vitest.e2e.config.ts',
  441. 'examples/headless-agent/tests/keyless-smoke.e2e.ts',
  442. 'examples/tui-agent/tests/tui-keyless-smoke.e2e.ts',
  443. 'packages/examples/cli-demo/tests/built-bin.e2e.ts',
  444. 'packages/examples/acp-demo/tests/built-bin.e2e.ts',
  445. 'packages/ui/jsonrpc/tests/built-scope-carrier.e2e.ts',
  446. // The worker-entry packages' built bundles: the only automated proof
  447. // that lib/index.js resolves its sibling lib/worker.cjs under plain node
  448. // (the e2e lane runs unbuilt, so these files self-skip there).
  449. 'packages/workflow/workflow-workerthread/tests/built-worker.e2e.ts',
  450. 'packages/code-runtime/code-runtime-worker/tests/built-lib.e2e.ts',
  451. ], {
  452. label: 'built-bin smoke',
  453. needs: ['build'],
  454. env: { DSH_EXAMPLE_MODE: 'lib' },
  455. })
  456. }
  457. async function runGates(allGates: Gate[], maxActive: number): Promise<GateResult[]> {
  458. const states = new Map<string, GateStatus>(allGates.map(gate => [gate.id, 'pending']))
  459. const results = new Map<string, GateResult>()
  460. const running: RunningGate[] = []
  461. for (;;) {
  462. let madeProgress = false
  463. while (running.length < maxActive) {
  464. const ready = allGates.find(gate => states.get(gate.id) === 'pending' && dependenciesPassed(gate, states))
  465. if (ready === undefined) break
  466. states.set(ready.id, 'running')
  467. running.push({ gate: ready, promise: runGate(ready) })
  468. console.log(`run-gates: start ${ready.label}`)
  469. madeProgress = true
  470. }
  471. if (running.length === 0) {
  472. const pending = allGates.filter(gate => states.get(gate.id) === 'pending')
  473. for (const gate of pending) {
  474. const failedDeps = (gate.needs ?? []).filter(id => states.get(id) !== 'passed')
  475. const result: GateResult = {
  476. gate,
  477. status: 'skipped',
  478. durationMs: 0,
  479. stdout: '',
  480. stderr: '',
  481. output: [],
  482. exitCode: null,
  483. error: `dependency failed or skipped: ${failedDeps.join(', ')}`,
  484. }
  485. states.set(gate.id, 'skipped')
  486. results.set(gate.id, result)
  487. printResult(result)
  488. }
  489. break
  490. }
  491. if (!madeProgress) {
  492. const settled = await Promise.race(running.map(async item => ({ item, result: await item.promise })))
  493. running.splice(running.indexOf(settled.item), 1)
  494. states.set(settled.item.gate.id, settled.result.status)
  495. results.set(settled.item.gate.id, settled.result)
  496. printResult(settled.result)
  497. }
  498. }
  499. return allGates.map((gate) => {
  500. const result = results.get(gate.id)
  501. if (result === undefined) throw new Error(`run-gates: missing result for ${gate.id}.`)
  502. return result
  503. })
  504. }
  505. function dependenciesPassed(gate: Gate, states: Map<string, GateStatus>): boolean {
  506. return (gate.needs ?? []).every(id => states.get(id) === 'passed')
  507. }
  508. async function runGate(gate: Gate): Promise<GateResult> {
  509. const started = performance.now()
  510. let stdout = ''
  511. let stderr = ''
  512. const output: GateOutputChunk[] = []
  513. let spawnError: string | undefined
  514. const exitCode = await new Promise<number | null>((resolveExit) => {
  515. const child = spawn(gate.command, gate.args, {
  516. cwd: root,
  517. env: { ...process.env, ...gate.env },
  518. stdio: ['pipe', 'pipe', 'pipe'],
  519. })
  520. child.stdout.setEncoding('utf8')
  521. child.stderr.setEncoding('utf8')
  522. child.stdout.on('data', (chunk: string) => {
  523. stdout += chunk
  524. output.push({ stream: 'stdout', text: chunk })
  525. })
  526. child.stderr.on('data', (chunk: string) => {
  527. stderr += chunk
  528. output.push({ stream: 'stderr', text: chunk })
  529. })
  530. child.on('error', (error) => {
  531. spawnError = `failed to start command: ${error.message}`
  532. resolveExit(null)
  533. })
  534. child.on('close', resolveExit)
  535. if (gate.input !== undefined) child.stdin.end(gate.input)
  536. else child.stdin.end()
  537. })
  538. let status: GateStatus = exitCode === 0 && spawnError === undefined ? 'passed' : 'failed'
  539. let error = spawnError
  540. if (status === 'passed' && gate.verify !== undefined) {
  541. try {
  542. await gate.verify({ gate, status, durationMs: performance.now() - started, stdout, stderr, output, exitCode })
  543. } catch (verifyError: unknown) {
  544. status = 'failed'
  545. error = verifyError instanceof Error ? verifyError.message : String(verifyError)
  546. }
  547. }
  548. const result: GateResult = {
  549. gate,
  550. status,
  551. durationMs: performance.now() - started,
  552. stdout,
  553. stderr,
  554. output,
  555. exitCode,
  556. }
  557. if (error !== undefined) result.error = error
  558. return result
  559. }
  560. function printResult(result: GateResult): void {
  561. const seconds = (result.durationMs / 1000).toFixed(2)
  562. if (result.status === 'passed' && !verbose) {
  563. console.log(`run-gates: PASS ${result.gate.label} (${seconds}s)`)
  564. return
  565. }
  566. const heading = `${result.status.toUpperCase()} ${result.gate.label} (${seconds}s)`
  567. const writeHeading = result.status === 'passed' ? console.log : console.error
  568. writeHeading(`\n== ${heading} ==`)
  569. if (result.status !== 'passed') console.error(`command: ${result.gate.displayCommand}`)
  570. printOutput(result.output)
  571. if (result.error !== undefined) console.error(result.error)
  572. }
  573. function printSummary(results: GateResult[], durationMs: number): void {
  574. const passed = results.filter(result => result.status === 'passed').length
  575. const failed = results.filter(result => result.status === 'failed').length
  576. const skipped = results.filter(result => result.status === 'skipped').length
  577. const seconds = (durationMs / 1000).toFixed(2)
  578. console.log(`\nrun-gates: ${passed} passed, ${failed} failed, ${skipped} skipped in ${seconds}s.`)
  579. const unsuccessful = results.filter(result => result.status === 'failed' || result.status === 'skipped')
  580. if (unsuccessful.length === 0) return
  581. console.error('run-gates: unsuccessful gates:')
  582. for (const result of unsuccessful) {
  583. const duration = (result.durationMs / 1000).toFixed(2)
  584. const reason = result.error ?? (result.exitCode === null ? 'no exit code' : `exit ${result.exitCode}`)
  585. const disposition = result.gate.allowFailure === true ? 'NON-BLOCKING ' : ''
  586. console.error(` - ${disposition}${result.status.toUpperCase()} ${result.gate.label} (${duration}s, ${reason})`)
  587. console.error(` ${result.gate.displayCommand}`)
  588. }
  589. }
  590. function printOutput(output: GateOutputChunk[]): void {
  591. for (const chunk of output) {
  592. if (chunk.stream === 'stdout') process.stdout.write(chunk.text)
  593. else process.stderr.write(chunk.text)
  594. }
  595. }