run-gates.ts 15 KB

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