run-gates.ts 25 KB

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