run-gates.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. /**
  2. * Run local and CI quality gates with bounded in-process scheduling.
  3. *
  4. * Package scripts own public aggregate names; this runner owns their validated
  5. * dependency graphs, scheduler environment, and process diagnostics.
  6. * @see ../.agents/notes/implemented/process/2026-07-06-parallel-pre-push-gates.md
  7. */
  8. import { spawn } from 'node:child_process'
  9. import { availableParallelism } from 'node:os'
  10. import { resolve } from 'node:path'
  11. import { performance } from 'node:perf_hooks'
  12. /** A named aggregate exposed by the gate runner. */
  13. export type Mode =
  14. | 'ci-primary'
  15. | 'ci-linux-primary'
  16. | 'ci-static'
  17. | 'ci-lint'
  18. | 'ci-coverage'
  19. | 'ci-snapshot'
  20. | 'ci-artifacts'
  21. | 'ci-consumers'
  22. | 'ci-windows-blocking'
  23. | 'ci-windows-complete'
  24. | 'ci-windows-observational'
  25. | 'node-compat'
  26. | 'check-all'
  27. | 'doc-sync'
  28. type GateResultStatus = 'passed' | 'failed' | 'skipped'
  29. type GateState = 'pending' | 'running' | GateResultStatus
  30. /** A command and its dependency metadata inside one aggregate. */
  31. export interface Gate {
  32. id: string
  33. label: string
  34. displayCommand: string
  35. command: string
  36. args: string[]
  37. needs?: string[]
  38. env?: Record<string, string | undefined>
  39. allowFailure?: boolean
  40. }
  41. /** The observed outcome of one gate process. */
  42. export interface GateResult {
  43. gate: Gate
  44. status: GateResultStatus
  45. durationMs: number
  46. output: GateOutputChunk[]
  47. exitCode: number | null
  48. signalCode: NodeJS.Signals | null
  49. error?: string
  50. }
  51. interface GateOutputChunk {
  52. stream: 'stdout' | 'stderr'
  53. text: string
  54. }
  55. interface RunningGate {
  56. gate: Gate
  57. promise: Promise<GateResult>
  58. }
  59. interface ConcurrencyDefault {
  60. workers: number
  61. source: string
  62. }
  63. type GateExecutor = (gate: Gate) => Promise<GateResult>
  64. type ResultObserver = (result: GateResult) => void
  65. const root = resolve(import.meta.dirname, '..')
  66. if (import.meta.main) {
  67. process.exitCode = await main(process.argv.slice(2))
  68. }
  69. async function main(args: string[]): Promise<number> {
  70. const mode = parseMode(args[0])
  71. const gates = gatesForMode(mode)
  72. const concurrencyDefault = defaultConcurrency(mode, gates.length)
  73. const concurrencyOverride = process.env.DSH_GATE_CONCURRENCY
  74. const maxConcurrency = concurrencyFromEnv('DSH_GATE_CONCURRENCY', concurrencyDefault.workers)
  75. const concurrencySource = concurrencyOverride === undefined || concurrencyOverride === ''
  76. ? concurrencyDefault.source
  77. : '$DSH_GATE_CONCURRENCY'
  78. const startedAt = performance.now()
  79. console.log(`run-gates: ${mode} running ${gates.length} gate(s) with ${maxConcurrency} worker(s) from ${concurrencySource}.`)
  80. const results = await runGates(gates, maxConcurrency, runGate, printResult)
  81. printSummary(results, performance.now() - startedAt)
  82. return results.some(result => result.gate.allowFailure !== true && (result.status === 'failed' || result.status === 'skipped'))
  83. ? 1
  84. : 0
  85. }
  86. function parseMode(raw: string | undefined): Mode {
  87. switch (raw) {
  88. case 'ci-primary':
  89. case 'ci-linux-primary':
  90. case 'ci-static':
  91. case 'ci-lint':
  92. case 'ci-coverage':
  93. case 'ci-snapshot':
  94. case 'ci-artifacts':
  95. case 'ci-consumers':
  96. case 'ci-windows-blocking':
  97. case 'ci-windows-complete':
  98. case 'ci-windows-observational':
  99. case 'node-compat':
  100. case 'check-all':
  101. case 'doc-sync':
  102. return raw
  103. default:
  104. throw new Error(
  105. `run-gates: expected mode ci-primary | ci-linux-primary | ci-static | ci-lint | ci-coverage | ci-snapshot | ci-artifacts | ci-consumers | ci-windows-blocking | ci-windows-complete | ci-windows-observational | node-compat | check-all | doc-sync, got ${JSON.stringify(raw)}.`,
  106. )
  107. }
  108. }
  109. /**
  110. * Resolve the default worker count for one aggregate.
  111. * @param selectedMode - aggregate whose resource posture applies.
  112. * @param total - number of gates in the aggregate.
  113. * @param available - host CPU availability for ordinary modes.
  114. * @returns the default worker count and its diagnostic source.
  115. */
  116. export function defaultConcurrency(
  117. selectedMode: Mode,
  118. total: number,
  119. available = availableParallelism(),
  120. ): ConcurrencyDefault {
  121. if (selectedMode === 'ci-consumers') return { workers: total, source: 'ci-consumers gate count' }
  122. // Local modes cap workers: several doc gates each build a full ts.Program,
  123. // so an uncapped default on a large host trades wall clock for memory blowups.
  124. const localCap = selectedMode === 'check-all' || selectedMode === 'doc-sync'
  125. const modeLimit = localCap ? Math.min(4, available) : available
  126. return {
  127. workers: Math.min(total, modeLimit),
  128. source: localCap
  129. ? `${available} available CPU(s), ${selectedMode} cap 4`
  130. : `${available} available CPU(s)`,
  131. }
  132. }
  133. function concurrencyFromEnv(name: string, fallback: number): number {
  134. const raw = process.env[name]
  135. if (raw === undefined || raw === '') return fallback
  136. const parsed = Number.parseInt(raw, 10)
  137. if (!Number.isSafeInteger(parsed) || parsed < 1) {
  138. throw new Error(`run-gates: ${name} must be a positive integer, got ${JSON.stringify(raw)}.`)
  139. }
  140. return parsed
  141. }
  142. function pnpmScript(id: string, script: string, options: Partial<Gate> = {}): Gate {
  143. return {
  144. id,
  145. label: options.label ?? script,
  146. displayCommand: `pnpm run ${script}`,
  147. ...pnpmInvocation(['run', script]),
  148. ...options,
  149. }
  150. }
  151. function pnpmExec(id: string, args: string[], options: Partial<Gate> = {}): Gate {
  152. return {
  153. id,
  154. label: options.label ?? `pnpm exec ${args.join(' ')}`,
  155. displayCommand: `pnpm exec ${args.join(' ')}`,
  156. ...pnpmInvocation(['exec', ...args]),
  157. ...options,
  158. }
  159. }
  160. function pnpmInvocation(args: string[]): Pick<Gate, 'command' | 'args'> {
  161. const entrypoint = process.env.npm_execpath
  162. if (entrypoint === undefined || entrypoint === '') {
  163. throw new Error('run-gates: npm_execpath is unavailable; invoke the runner through a pnpm package script.')
  164. }
  165. // Windows cannot spawn the pnpm.cmd shim directly; the JavaScript entrypoint keeps every host shell-free.
  166. return { command: process.execPath, args: [entrypoint, ...args] }
  167. }
  168. /**
  169. * Construct the complete gate list for a named aggregate.
  170. * @param selected - aggregate mode to construct.
  171. * @returns the aggregate's gate graph.
  172. */
  173. export function gatesForMode(selected: Mode): Gate[] {
  174. switch (selected) {
  175. case 'ci-primary':
  176. return ciPrimaryGates()
  177. case 'ci-linux-primary':
  178. return [...ciPrimaryGates(), webSnapshotGate(['built-package-invariants'])]
  179. case 'ci-static':
  180. return ciStaticGates()
  181. case 'ci-lint':
  182. return [
  183. lintGate(),
  184. pnpmScript('duplication', 'duplication'),
  185. ]
  186. case 'ci-coverage':
  187. return [coverageGate()]
  188. case 'ci-snapshot':
  189. return [pnpmScript('build', 'build'), snapshotGate()]
  190. case 'ci-artifacts':
  191. return ciArtifactGates()
  192. case 'ci-consumers':
  193. return ciConsumerGates()
  194. case 'ci-windows-blocking':
  195. return ciWindowsBlockingGates()
  196. case 'ci-windows-complete':
  197. return ciWindowsCompleteGates()
  198. case 'ci-windows-observational':
  199. return ciWindowsObservationalGates()
  200. case 'node-compat':
  201. return nodeCompatGates()
  202. case 'check-all':
  203. return [
  204. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  205. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  206. pnpmScript('client-domain-graph', 'verify-client-domain-graph', { label: 'client domain graph' }),
  207. pnpmScript('test', 'test'),
  208. pnpmScript('duplication', 'duplication'),
  209. snapshotGate(),
  210. pnpmScript('build', 'build'),
  211. pnpmScript('build:web', 'build:web'),
  212. ...hygieneLeafGates({ artifactNeeds: ['build'] }),
  213. ...docSyncLeafGates({
  214. docTypecheckNeeds: ['build'],
  215. docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  216. }),
  217. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  218. ]
  219. case 'doc-sync':
  220. return docSyncLeafGates()
  221. }
  222. }
  223. function ciPrimaryGates(): Gate[] {
  224. return [
  225. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  226. pnpmScript('constraints', 'constraints'),
  227. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  228. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  229. pnpmScript('typecheck', 'typecheck'),
  230. lintGate(),
  231. pnpmScript('duplication', 'duplication'),
  232. coverageGate(),
  233. ...nodeCompatSmokeGates(),
  234. snapshotGate(),
  235. ...docSyncLeafGates(),
  236. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  237. pnpmScript('knip', 'knip'),
  238. // typecheck and build now drive the same root solution graph; without the
  239. // dependency two concurrent `tsc -b` runs race the same tsbuildinfo files.
  240. // The tsc step is an incremental no-op after typecheck.
  241. pnpmScript('build', 'build', { needs: ['typecheck'] }),
  242. pnpmScript('publint', 'publint', { needs: ['build'] }),
  243. pnpmScript('node-next-types', 'verify-node-next-types', {
  244. label: 'node-next types',
  245. needs: ['build'],
  246. }),
  247. builtPackageInvariantsGate(['build']),
  248. builtBinSmokeGate(),
  249. ]
  250. }
  251. function nodeCompatGates(): Gate[] {
  252. return [
  253. ...flagEnabled('DSH_NODE_COMPAT_SKIP_TYPECHECK') ? [] : [pnpmScript('typecheck', 'typecheck')],
  254. ...nodeCompatSmokeGates(),
  255. ]
  256. }
  257. function nodeCompatSmokeGates(): Gate[] {
  258. return [
  259. pnpmExec('source-worker-smoke', [
  260. 'vitest',
  261. 'run',
  262. 'packages/workflow/workflow-workerthread/tests/source-worker.compat.spec.ts',
  263. ], { label: 'source worker smoke' }),
  264. pnpmExec('jsonl-zstd-smoke', [
  265. 'vitest',
  266. 'run',
  267. 'packages/session-persistence/session-persistence-jsonl/tests/zstd.compat.spec.ts',
  268. ], { label: 'JSONL Zstandard smoke' }),
  269. pnpmExec('dsh-source-launch-smoke', [
  270. 'vitest',
  271. 'run',
  272. 'apps/cli/tests/source-launch.compat.spec.ts',
  273. ], { label: 'dsh source-launch smoke' }),
  274. ]
  275. }
  276. function ciStaticGates(): Gate[] {
  277. return [
  278. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  279. pnpmScript('constraints', 'constraints'),
  280. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  281. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  282. pnpmScript('build', 'build'),
  283. ...docSyncLeafGates({
  284. docTypecheckNeeds: ['build'],
  285. docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  286. docsBuildScript: 'docs:build:mpa',
  287. }),
  288. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  289. pnpmScript('knip', 'knip'),
  290. ]
  291. }
  292. function ciArtifactGates(): Gate[] {
  293. return [
  294. pnpmScript('build', 'build'),
  295. pnpmScript('publint', 'publint', { needs: ['build'] }),
  296. pnpmScript('node-next-types', 'verify-node-next-types', {
  297. label: 'node-next types',
  298. needs: ['build'],
  299. }),
  300. builtPackageInvariantsGate(['build']),
  301. builtBinSmokeGate(),
  302. ]
  303. }
  304. function ciConsumerGates(): Gate[] {
  305. const publicArtifacts = ['publint']
  306. const restoredBuild = ['built-package-invariants']
  307. return [
  308. pnpmScript('lint-and-duplication', 'check:ci:lint', {
  309. label: 'lint and duplication',
  310. needs: restoredBuild,
  311. }),
  312. pnpmScript('node-compat', 'check:node-compat', { label: 'Node compatibility' }),
  313. snapshotGate(restoredBuild),
  314. webSnapshotGate(restoredBuild),
  315. pnpmScript('publint', 'publint'),
  316. pnpmScript('node-next-types', 'verify-node-next-types', {
  317. label: 'node-next types',
  318. needs: restoredBuild,
  319. }),
  320. builtPackageInvariantsGate(publicArtifacts),
  321. builtBinSmokeGate(restoredBuild),
  322. ]
  323. }
  324. function webSnapshotGate(needs: string[]): Gate {
  325. return pnpmScript('web-snapshot', 'test:web:built', {
  326. label: 'web browser snapshot',
  327. displayCommand: 'DSH_SNAPSHOT=replay pnpm run test:web:built',
  328. env: { DSH_SNAPSHOT: 'replay' },
  329. needs,
  330. })
  331. }
  332. function ciWindowsBlockingGates(): Gate[] {
  333. return [
  334. pnpmScript('windows-build', 'build', { label: 'build' }),
  335. pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
  336. ]
  337. }
  338. function ciWindowsCompleteGates(): Gate[] {
  339. const observational = ciWindowsObservationalGates()
  340. // The required production site replaces the observational MPA build; both
  341. // VitePress modes write the same output directory and cannot overlap.
  342. .filter(gate => gate.id !== 'build' && gate.id !== 'docs-site-build')
  343. .map(gate => ({ ...gate, allowFailure: true }))
  344. return [
  345. pnpmScript('build', 'build'),
  346. pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
  347. ...observational,
  348. ]
  349. }
  350. function ciWindowsObservationalGates(): Gate[] {
  351. return [
  352. ...ciStaticGates(),
  353. // Linux owns required lint, coverage, and snapshots; Windows omits those duplicates.
  354. pnpmScript('duplication', 'duplication'),
  355. pnpmScript('publint', 'publint', { needs: ['build'] }),
  356. pnpmScript('node-next-types', 'verify-node-next-types', {
  357. label: 'node-next types',
  358. needs: ['build'],
  359. }),
  360. builtPackageInvariantsGate(['build']),
  361. builtBinSmokeGate(),
  362. ]
  363. }
  364. function lintGate(): Gate {
  365. const raw = process.env.DSH_OXLINT_THREADS
  366. return pnpmScript('lint', 'lint', raw === undefined || raw === ''
  367. ? {}
  368. : { displayCommand: `DSH_OXLINT_THREADS=${raw} pnpm run lint` })
  369. }
  370. function coverageGate(): Gate {
  371. return pnpmExec('coverage', [
  372. 'vitest',
  373. 'run',
  374. '--coverage',
  375. ...positiveIntArg('DSH_COVERAGE_MAX_WORKERS', '--maxWorkers'),
  376. ], {
  377. label: 'test:coverage',
  378. })
  379. }
  380. // Example and package snapshots boot their bins in `lib` mode (built artifacts under plain Node,
  381. // plugins via real exports); repository-script snapshots execute their real source entry path.
  382. // Build-owning modes wait on `build`; a restored-artifact mode passes its validation dependency.
  383. function snapshotGate(needs: string[] = ['build']): Gate {
  384. return pnpmScript('snapshot', 'test:snapshot', {
  385. env: { DSH_EXAMPLE_MODE: 'lib' },
  386. needs,
  387. })
  388. }
  389. function builtPackageInvariantsGate(needs?: string[]): Gate {
  390. return pnpmScript('built-package-invariants', 'verify-built-package-invariants', {
  391. label: 'built package invariants',
  392. ...needs === undefined ? {} : { needs },
  393. })
  394. }
  395. function positiveIntArg(envName: string, flag: string): string[] {
  396. const raw = process.env[envName]
  397. if (raw === undefined || raw === '') return []
  398. const parsed = Number.parseInt(raw, 10)
  399. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  400. throw new Error(`run-gates: ${envName} must be a positive integer, got ${JSON.stringify(raw)}.`)
  401. }
  402. return [`${flag}=${raw}`]
  403. }
  404. function flagEnabled(envName: string): boolean {
  405. const raw = process.env[envName]
  406. if (raw === undefined || raw === '') return false
  407. if (raw !== '1') throw new Error(`run-gates: ${envName} must be 1 when set, got ${JSON.stringify(raw)}.`)
  408. return true
  409. }
  410. function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] {
  411. const artifactOptions = options.artifactNeeds === undefined ? {} : { needs: options.artifactNeeds }
  412. return [
  413. pnpmScript('knip', 'knip'),
  414. pnpmScript('publint', 'publint', artifactOptions),
  415. pnpmScript('constraints', 'constraints'),
  416. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  417. builtPackageInvariantsGate(options.artifactNeeds),
  418. pnpmScript('node-next-types', 'verify-node-next-types', {
  419. label: 'node-next types',
  420. ...artifactOptions,
  421. }),
  422. ]
  423. }
  424. function docSyncLeafGates(options: {
  425. docTypecheckNeeds?: string[]
  426. docTypecheckEnv?: Record<string, string | undefined>
  427. docsBuildScript?: 'docs:build' | 'docs:build:mpa'
  428. } = {}): Gate[] {
  429. const docTypecheckOptions: Partial<Gate> = {}
  430. if (options.docTypecheckNeeds !== undefined) docTypecheckOptions.needs = options.docTypecheckNeeds
  431. if (options.docTypecheckEnv !== undefined) docTypecheckOptions.env = options.docTypecheckEnv
  432. return [
  433. pnpmScript('doc-typecheck', 'doc-typecheck', docTypecheckOptions),
  434. pnpmScript('cordis-catalog', 'verify-cordis-catalog', { label: 'cordis catalog' }),
  435. pnpmScript('export-jsdoc', 'verify-export-jsdoc', { label: 'export jsdoc' }),
  436. pnpmScript('tool-catalog', 'verify-tool-catalog', { label: 'tool catalog' }),
  437. pnpmScript('config-catalog', 'verify-config-catalog', { label: 'config catalog' }),
  438. pnpmScript('persistence-catalog', 'verify-persistence-catalog', { label: 'persistence catalog' }),
  439. pnpmScript('doc-graphs', 'verify-doc-graphs', { label: 'doc graphs' }),
  440. pnpmScript('scoped-events', 'verify-scoped-events', { label: 'scoped events' }),
  441. pnpmScript('markdown-wrap', 'verify-md-wrap', { label: 'markdown wrap' }),
  442. pnpmScript('markdown-links', 'verify-md-links', { label: 'markdown links' }),
  443. pnpmScript('doc-refs', 'verify-doc-refs', { label: 'doc refs' }),
  444. pnpmScript('package-paths', 'verify-package-paths', { label: 'package paths' }),
  445. pnpmScript('package-readme-model-experience', 'verify-package-readme-model-experience', { label: 'package README model experience' }),
  446. pnpmScript('mermaid', 'verify-mermaid'),
  447. pnpmScript('agent-note-classification', 'verify-agent-note-classification', { label: 'agent note classification' }),
  448. pnpmScript('agent-note-format', 'verify-agent-note-format', { label: 'agent note format' }),
  449. pnpmScript('archived-agent-notes', 'verify-archived-agent-notes', { label: 'archived agent notes' }),
  450. pnpmScript('type-equivalence', 'verify-type-equiv', { label: 'type equivalence' }),
  451. pnpmScript('translation-prompt', 'verify-translation-prompt', { label: 'translation prompt' }),
  452. pnpmScript('translation-pairing', 'verify-translation-pairing', { label: 'translation pairing' }),
  453. pnpmScript('doc-budgets', 'verify-doc-budgets', { label: 'doc budgets' }),
  454. pnpmExec('docs-site-projection', ['vitest', 'run', 'scripts/project-doc-site.spec.ts'], {
  455. label: 'documentation projection',
  456. }),
  457. // Keep the VitePress build itself in one gate because projection rewrites website/.generated.
  458. pnpmScript('docs-site-build', options.docsBuildScript ?? 'docs:build', { label: 'documentation build' }),
  459. pnpmScript('package-readme-limitations', 'verify-package-readme-limitations', { label: 'package README limitations' }),
  460. ]
  461. }
  462. function builtBinSmokeGate(needs: string[] = ['build']): Gate {
  463. return pnpmExec('built-bin-smoke', [
  464. 'vitest',
  465. 'run',
  466. '--config',
  467. 'vitest.e2e.config.ts',
  468. 'examples/headless-agent/tests/keyless-smoke.e2e.ts',
  469. 'apps/cli/tests/tui-keyless-smoke.e2e.ts',
  470. 'packages/examples/cli-demo/tests/built-bin.e2e.ts',
  471. 'packages/examples/acp-demo/tests/built-bin.e2e.ts',
  472. 'packages/ui/jsonrpc/tests/built-scope-carrier.e2e.ts',
  473. // The worker-entry packages' built bundles: the only automated proof
  474. // that lib/index.js resolves its sibling lib/worker.cjs under plain node
  475. // (the e2e lane runs unbuilt, so these files self-skip there).
  476. 'packages/workflow/workflow-workerthread/tests/built-worker.e2e.ts',
  477. 'packages/code-runtime/code-runtime-worker/tests/built-lib.e2e.ts',
  478. ], {
  479. label: 'built-bin smoke',
  480. needs,
  481. env: { DSH_EXAMPLE_MODE: 'lib' },
  482. })
  483. }
  484. /**
  485. * Reject a gate list whose graph cannot be executed unambiguously.
  486. * @param gates - complete aggregate to validate.
  487. */
  488. function validateGateGraph(gates: readonly Gate[]): void {
  489. if (gates.length === 0) throw new Error('run-gates: gate graph has no gates.')
  490. const ids = new Set<string>()
  491. for (const gate of gates) {
  492. if (ids.has(gate.id)) throw new Error(`run-gates: duplicate gate id ${JSON.stringify(gate.id)}.`)
  493. ids.add(gate.id)
  494. }
  495. for (const gate of gates) {
  496. for (const dependency of gate.needs ?? []) {
  497. if (!ids.has(dependency)) {
  498. throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} depends on unknown gate ${JSON.stringify(dependency)}.`)
  499. }
  500. }
  501. }
  502. const cycle = findDependencyCycle(gates)
  503. if (cycle !== undefined) throw new Error(`run-gates: dependency cycle: ${cycle.join(' -> ')}.`)
  504. }
  505. function findDependencyCycle(gates: readonly Gate[]): string[] | undefined {
  506. const byId = new Map(gates.map(gate => [gate.id, gate]))
  507. const complete = new Set<string>()
  508. const active = new Map<string, number>()
  509. const path: string[] = []
  510. const visit = (id: string): string[] | undefined => {
  511. if (complete.has(id)) return undefined
  512. const cycleStart = active.get(id)
  513. if (cycleStart !== undefined) return [...path.slice(cycleStart), id]
  514. const gate = byId.get(id)
  515. if (gate === undefined) return undefined
  516. active.set(id, path.length)
  517. path.push(id)
  518. for (const dependency of gate.needs ?? []) {
  519. const cycle = visit(dependency)
  520. if (cycle !== undefined) return cycle
  521. }
  522. path.pop()
  523. active.delete(id)
  524. complete.add(id)
  525. return undefined
  526. }
  527. for (const gate of gates) {
  528. const cycle = visit(gate.id)
  529. if (cycle !== undefined) return cycle
  530. }
  531. return undefined
  532. }
  533. /**
  534. * Validate and run one aggregate before the injected executor can start a child.
  535. * @param gates - complete aggregate to execute.
  536. * @param maxActive - maximum concurrent child count.
  537. * @param execute - child-process executor.
  538. * @param observe - result observer invoked when each gate settles.
  539. * @returns results in aggregate order.
  540. */
  541. export async function runGates(
  542. gates: Gate[],
  543. maxActive: number,
  544. execute: GateExecutor,
  545. observe: ResultObserver = () => {},
  546. ): Promise<GateResult[]> {
  547. validateGateGraph(gates)
  548. if (!Number.isSafeInteger(maxActive) || maxActive < 1) {
  549. throw new Error(`run-gates: max concurrency must be a positive integer, got ${JSON.stringify(maxActive)}.`)
  550. }
  551. const states = new Map<string, GateState>(gates.map(gate => [gate.id, 'pending']))
  552. const results = new Map<string, GateResult>()
  553. const running: RunningGate[] = []
  554. for (;;) {
  555. let madeProgress = false
  556. while (running.length < maxActive) {
  557. const ready = gates.find(gate => states.get(gate.id) === 'pending' && dependenciesPassed(gate, states))
  558. if (ready === undefined) break
  559. states.set(ready.id, 'running')
  560. running.push({ gate: ready, promise: execute(ready) })
  561. console.log(`run-gates: start ${ready.label}`)
  562. madeProgress = true
  563. }
  564. if (running.length === 0) {
  565. let pending = gates.filter(gate => states.get(gate.id) === 'pending')
  566. while (pending.length > 0) {
  567. const gate = pending.find(item => (item.needs ?? []).some((id) => {
  568. const state = states.get(id)
  569. return state === 'failed' || state === 'skipped'
  570. }))
  571. if (gate === undefined) throw new Error('run-gates: validated graph stalled without a failed dependency.')
  572. const failedDeps = (gate.needs ?? []).filter((id) => {
  573. const state = states.get(id)
  574. return state === 'failed' || state === 'skipped'
  575. })
  576. const result: GateResult = {
  577. gate,
  578. status: 'skipped',
  579. durationMs: 0,
  580. output: [],
  581. exitCode: null,
  582. signalCode: null,
  583. error: `dependency failed or skipped: ${failedDeps.join(', ')}`,
  584. }
  585. states.set(gate.id, 'skipped')
  586. results.set(gate.id, result)
  587. observe(result)
  588. pending = pending.filter(item => item !== gate)
  589. }
  590. break
  591. }
  592. if (!madeProgress) {
  593. const settled = await Promise.race(running.map(async item => ({ item, result: await item.promise })))
  594. running.splice(running.indexOf(settled.item), 1)
  595. states.set(settled.item.gate.id, settled.result.status)
  596. results.set(settled.item.gate.id, settled.result)
  597. observe(settled.result)
  598. }
  599. }
  600. return gates.map((gate) => {
  601. const result = results.get(gate.id)
  602. if (result === undefined) throw new Error(`run-gates: missing result for ${gate.id}.`)
  603. return result
  604. })
  605. }
  606. function dependenciesPassed(gate: Gate, states: Map<string, GateState>): boolean {
  607. return (gate.needs ?? []).every(id => states.get(id) === 'passed')
  608. }
  609. /**
  610. * Execute one gate through the real shell-free child-process boundary.
  611. * @param gate - command and scheduler environment to execute.
  612. * @returns the complete process outcome.
  613. */
  614. export async function runGate(gate: Gate): Promise<GateResult> {
  615. const started = performance.now()
  616. const output: GateOutputChunk[] = []
  617. let spawnError: string | undefined
  618. const outcome = await new Promise<{
  619. exitCode: number | null
  620. signalCode: NodeJS.Signals | null
  621. }>((resolveExit) => {
  622. const child = spawn(gate.command, gate.args, {
  623. cwd: root,
  624. env: { ...process.env, ...gate.env },
  625. stdio: ['pipe', 'pipe', 'pipe'],
  626. })
  627. child.stdout.setEncoding('utf8')
  628. child.stderr.setEncoding('utf8')
  629. child.stdout.on('data', (chunk: string) => {
  630. output.push({ stream: 'stdout', text: chunk })
  631. })
  632. child.stderr.on('data', (chunk: string) => {
  633. output.push({ stream: 'stderr', text: chunk })
  634. })
  635. child.on('error', (error) => {
  636. spawnError = `failed to start command: ${error.message}`
  637. resolveExit({ exitCode: null, signalCode: null })
  638. })
  639. child.on('close', (exitCode, signalCode) => {
  640. resolveExit({ exitCode, signalCode })
  641. })
  642. child.stdin.end()
  643. })
  644. const { exitCode, signalCode } = outcome
  645. const status: GateResultStatus = exitCode === 0 && signalCode === null && spawnError === undefined ? 'passed' : 'failed'
  646. const result: GateResult = {
  647. gate,
  648. status,
  649. durationMs: performance.now() - started,
  650. output,
  651. exitCode,
  652. signalCode,
  653. }
  654. if (spawnError !== undefined) result.error = spawnError
  655. return result
  656. }
  657. /**
  658. * Format every independently observed failure fact for the aggregate summary.
  659. * @param result - unsuccessful gate result.
  660. * @returns error, exit, and signal facts without allowing one to hide another.
  661. */
  662. export function formatGateResultReason(result: GateResult): string {
  663. const facts: string[] = []
  664. if (result.error !== undefined) facts.push(result.error)
  665. if (result.exitCode !== null) facts.push(`exit ${result.exitCode}`)
  666. if (result.signalCode !== null) facts.push(`signal ${result.signalCode}`)
  667. return facts.length === 0 ? 'no exit code or signal' : facts.join(', ')
  668. }
  669. function printResult(result: GateResult): void {
  670. const verbose = process.env.DSH_GATE_VERBOSE === '1'
  671. const seconds = (result.durationMs / 1000).toFixed(2)
  672. if (result.status === 'passed' && !verbose) {
  673. console.log(`run-gates: PASS ${result.gate.label} (${seconds}s)`)
  674. return
  675. }
  676. const heading = `${result.status.toUpperCase()} ${result.gate.label} (${seconds}s)`
  677. const writeHeading = result.status === 'passed' ? console.log : console.error
  678. writeHeading(`\n== ${heading} ==`)
  679. if (result.status !== 'passed') {
  680. console.error(`command: ${result.gate.displayCommand}`)
  681. console.error(`outcome: ${formatGateResultReason(result)}`)
  682. }
  683. printOutput(result.output)
  684. }
  685. function printSummary(results: GateResult[], durationMs: number): void {
  686. const passed = results.filter(result => result.status === 'passed').length
  687. const failed = results.filter(result => result.status === 'failed').length
  688. const skipped = results.filter(result => result.status === 'skipped').length
  689. const seconds = (durationMs / 1000).toFixed(2)
  690. console.log(`\nrun-gates: ${passed} passed, ${failed} failed, ${skipped} skipped in ${seconds}s.`)
  691. const unsuccessful = results.filter(result => result.status === 'failed' || result.status === 'skipped')
  692. if (unsuccessful.length === 0) return
  693. console.error('run-gates: unsuccessful gates:')
  694. for (const result of unsuccessful) {
  695. const duration = (result.durationMs / 1000).toFixed(2)
  696. const reason = formatGateResultReason(result)
  697. const disposition = result.gate.allowFailure === true ? 'NON-BLOCKING ' : ''
  698. console.error(` - ${disposition}${result.status.toUpperCase()} ${result.gate.label} (${duration}s, ${reason})`)
  699. console.error(` ${result.gate.displayCommand}`)
  700. }
  701. }
  702. function printOutput(output: GateOutputChunk[]): void {
  703. for (const chunk of output) {
  704. if (chunk.stream === 'stdout') process.stdout.write(chunk.text)
  705. else process.stderr.write(chunk.text)
  706. }
  707. }