run-gates.ts 18 KB

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