run-gates.ts 16 KB

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