run-gates.ts 20 KB

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