run-gates.ts 18 KB

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