run-gates.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  193. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  194. pnpmScript('typecheck', 'typecheck'),
  195. lintGate(),
  196. pnpmScript('duplication', 'duplication'),
  197. coverageGate(),
  198. snapshotGate(),
  199. ...docSyncLeafGates(),
  200. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  201. pnpmScript('knip', 'knip'),
  202. pnpmScript('build', 'build', { needs: ['typecheck'] }),
  203. pnpmScript('publint', 'publint', { needs: ['build'] }),
  204. pnpmScript('node-next-types', 'verify-node-next-types', {
  205. label: 'node-next types',
  206. needs: ['build'],
  207. }),
  208. builtPackageInvariantsGate(['build']),
  209. builtBinSmokeGate(),
  210. ]
  211. }
  212. function ciStaticGates(): Gate[] {
  213. return [
  214. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  215. pnpmScript('constraints', 'constraints'),
  216. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  217. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  218. ...docSyncLeafGates(),
  219. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  220. pnpmScript('knip', 'knip'),
  221. ]
  222. }
  223. function ciArtifactGates(): Gate[] {
  224. return [
  225. pnpmScript('build', 'build'),
  226. pnpmScript('publint', 'publint', { needs: ['build'] }),
  227. pnpmScript('node-next-types', 'verify-node-next-types', {
  228. label: 'node-next types',
  229. needs: ['build'],
  230. }),
  231. builtPackageInvariantsGate(['build']),
  232. builtBinSmokeGate(),
  233. ]
  234. }
  235. function lintGate(): Gate {
  236. if (process.env.DSH_ESLINT_CACHE === '1') {
  237. return pnpmExec('lint', [
  238. 'eslint',
  239. '.',
  240. '--cache',
  241. '--cache-location',
  242. '.cache/eslint/',
  243. '--cache-strategy',
  244. 'content',
  245. ], {
  246. label: 'lint',
  247. env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') },
  248. })
  249. }
  250. return pnpmScript('lint', 'lint', {
  251. env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') },
  252. })
  253. }
  254. function coverageGate(): Gate {
  255. return pnpmExec('coverage', [
  256. 'vitest',
  257. 'run',
  258. '--coverage',
  259. ...positiveIntArg('DSH_COVERAGE_MAX_WORKERS', '--maxWorkers'),
  260. ], {
  261. label: 'test:coverage',
  262. env: { DSH_EXAMPLE_MODE: 'lib' },
  263. needs: ['build'],
  264. })
  265. }
  266. // The snapshot suite boots the example bins in `lib` mode (built artifact under plain Node,
  267. // plugins via real exports) — CI and pre-push already build, so they exercise what ships rather
  268. // than the tsx/source path dev uses. It therefore waits on `build`.
  269. function snapshotGate(): Gate {
  270. return pnpmScript('snapshot', 'test:snapshot', {
  271. env: { DSH_EXAMPLE_MODE: 'lib' },
  272. needs: ['build'],
  273. })
  274. }
  275. function builtPackageInvariantsGate(needs?: string[]): Gate {
  276. return pnpmScript('built-package-invariants', 'verify-built-package-invariants', {
  277. label: 'built package invariants',
  278. ...needs === undefined ? {} : { needs },
  279. })
  280. }
  281. function positiveIntArg(envName: string, flag: string): string[] {
  282. const raw = process.env[envName]
  283. if (raw === undefined || raw === '') return []
  284. const parsed = Number.parseInt(raw, 10)
  285. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  286. throw new Error(`run-gates: ${envName} must be a positive integer, got ${JSON.stringify(raw)}.`)
  287. }
  288. return [`${flag}=${raw}`]
  289. }
  290. function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] {
  291. const artifactOptions = options.artifactNeeds === undefined ? {} : { needs: options.artifactNeeds }
  292. return [
  293. pnpmScript('knip', 'knip'),
  294. pnpmScript('publint', 'publint', artifactOptions),
  295. pnpmScript('constraints', 'constraints'),
  296. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  297. builtPackageInvariantsGate(options.artifactNeeds),
  298. pnpmScript('node-next-types', 'verify-node-next-types', {
  299. label: 'node-next types',
  300. ...artifactOptions,
  301. }),
  302. ]
  303. }
  304. function docSyncLeafGates(options: {
  305. docTypecheckNeeds?: string[]
  306. docTypecheckEnv?: Record<string, string | undefined>
  307. } = {}): Gate[] {
  308. const docTypecheckOptions: Partial<Gate> = {}
  309. if (options.docTypecheckNeeds !== undefined) docTypecheckOptions.needs = options.docTypecheckNeeds
  310. if (options.docTypecheckEnv !== undefined) docTypecheckOptions.env = options.docTypecheckEnv
  311. return [
  312. pnpmScript('doc-typecheck', 'doc-typecheck', docTypecheckOptions),
  313. pnpmScript('cordis-catalog', 'verify-cordis-catalog', { label: 'cordis catalog' }),
  314. pnpmScript('export-jsdoc', 'verify-export-jsdoc', { label: 'export jsdoc' }),
  315. pnpmScript('tool-catalog', 'verify-tool-catalog', { label: 'tool catalog' }),
  316. pnpmScript('config-catalog', 'verify-config-catalog', { label: 'config catalog' }),
  317. pnpmScript('persistence-catalog', 'verify-persistence-catalog', { label: 'persistence catalog' }),
  318. pnpmScript('doc-graphs', 'verify-doc-graphs', { label: 'doc graphs' }),
  319. pnpmScript('scoped-events', 'verify-scoped-events', { label: 'scoped events' }),
  320. pnpmScript('markdown-wrap', 'verify-md-wrap', { label: 'markdown wrap' }),
  321. pnpmScript('markdown-links', 'verify-md-links', { label: 'markdown links' }),
  322. pnpmScript('doc-refs', 'verify-doc-refs', { label: 'doc refs' }),
  323. pnpmScript('package-paths', 'verify-package-paths', { label: 'package paths' }),
  324. pnpmScript('package-readme-model-experience', 'verify-package-readme-model-experience', { label: 'package README model experience' }),
  325. pnpmScript('mermaid', 'verify-mermaid'),
  326. pnpmScript('agent-note-classification', 'verify-agent-note-classification', { label: 'agent note classification' }),
  327. pnpmScript('agent-note-format', 'verify-agent-note-format', { label: 'agent note format' }),
  328. pnpmScript('type-equivalence', 'verify-type-equiv', { label: 'type equivalence' }),
  329. pnpmScript('translation-prompt', 'verify-translation-prompt', { label: 'translation prompt' }),
  330. pnpmScript('translation-pairing', 'verify-translation-pairing', { label: 'translation pairing' }),
  331. pnpmScript('doc-budgets', 'verify-doc-budgets', { label: 'doc budgets' }),
  332. // Keep the VitePress build in this single gate because projection rewrites website/.generated.
  333. pnpmScript('docs-site', 'docs:check', { label: 'documentation site' }),
  334. pnpmScript('package-readme-limitations', 'verify-package-readme-limitations', { label: 'package README limitations' }),
  335. ]
  336. }
  337. function builtBinSmokeGate(): Gate {
  338. return pnpmExec('built-bin-smoke', [
  339. 'vitest',
  340. 'run',
  341. '--config',
  342. 'vitest.e2e.config.ts',
  343. 'examples/headless-agent/tests/keyless-smoke.e2e.ts',
  344. 'examples/tui-agent/tests/tui-keyless-smoke.e2e.ts',
  345. 'packages/examples/cli-demo/tests/built-bin.e2e.ts',
  346. 'packages/examples/acp-demo/tests/built-bin.e2e.ts',
  347. 'packages/ui/jsonrpc/tests/built-scope-carrier.e2e.ts',
  348. // The worker-entry packages' built bundles: the only automated proof
  349. // that lib/index.js resolves its sibling lib/worker.cjs under plain node
  350. // (the e2e lane runs unbuilt, so these files self-skip there).
  351. 'packages/workflow/workflow-workerthread/tests/built-worker.e2e.ts',
  352. 'packages/code-runtime/code-runtime-worker/tests/built-lib.e2e.ts',
  353. ], {
  354. label: 'built-bin smoke',
  355. needs: ['build'],
  356. env: { DSH_EXAMPLE_MODE: 'lib' },
  357. })
  358. }
  359. async function runGates(allGates: Gate[], maxActive: number): Promise<GateResult[]> {
  360. const states = new Map<string, GateStatus>(allGates.map(gate => [gate.id, 'pending']))
  361. const results = new Map<string, GateResult>()
  362. const running: RunningGate[] = []
  363. for (;;) {
  364. let madeProgress = false
  365. while (running.length < maxActive) {
  366. const ready = allGates.find(gate => states.get(gate.id) === 'pending' && dependenciesPassed(gate, states))
  367. if (ready === undefined) break
  368. states.set(ready.id, 'running')
  369. running.push({ gate: ready, promise: runGate(ready) })
  370. console.log(`run-gates: start ${ready.label}`)
  371. madeProgress = true
  372. }
  373. if (running.length === 0) {
  374. const pending = allGates.filter(gate => states.get(gate.id) === 'pending')
  375. for (const gate of pending) {
  376. const failedDeps = (gate.needs ?? []).filter(id => states.get(id) !== 'passed')
  377. const result: GateResult = {
  378. gate,
  379. status: 'skipped',
  380. durationMs: 0,
  381. stdout: '',
  382. stderr: '',
  383. output: [],
  384. exitCode: null,
  385. error: `dependency failed or skipped: ${failedDeps.join(', ')}`,
  386. }
  387. states.set(gate.id, 'skipped')
  388. results.set(gate.id, result)
  389. printResult(result)
  390. }
  391. break
  392. }
  393. if (!madeProgress) {
  394. const settled = await Promise.race(running.map(async item => ({ item, result: await item.promise })))
  395. running.splice(running.indexOf(settled.item), 1)
  396. states.set(settled.item.gate.id, settled.result.status)
  397. results.set(settled.item.gate.id, settled.result)
  398. printResult(settled.result)
  399. }
  400. }
  401. return allGates.map((gate) => {
  402. const result = results.get(gate.id)
  403. if (result === undefined) throw new Error(`run-gates: missing result for ${gate.id}.`)
  404. return result
  405. })
  406. }
  407. function dependenciesPassed(gate: Gate, states: Map<string, GateStatus>): boolean {
  408. return (gate.needs ?? []).every(id => states.get(id) === 'passed')
  409. }
  410. async function runGate(gate: Gate): Promise<GateResult> {
  411. const started = performance.now()
  412. let stdout = ''
  413. let stderr = ''
  414. const output: GateOutputChunk[] = []
  415. let spawnError: string | undefined
  416. const exitCode = await new Promise<number | null>((resolveExit) => {
  417. const child = spawn(gate.command, gate.args, {
  418. cwd: root,
  419. env: { ...process.env, ...gate.env },
  420. stdio: ['pipe', 'pipe', 'pipe'],
  421. })
  422. child.stdout.setEncoding('utf8')
  423. child.stderr.setEncoding('utf8')
  424. child.stdout.on('data', (chunk: string) => {
  425. stdout += chunk
  426. output.push({ stream: 'stdout', text: chunk })
  427. })
  428. child.stderr.on('data', (chunk: string) => {
  429. stderr += chunk
  430. output.push({ stream: 'stderr', text: chunk })
  431. })
  432. child.on('error', (error) => {
  433. spawnError = `failed to start command: ${error.message}`
  434. resolveExit(null)
  435. })
  436. child.on('close', resolveExit)
  437. if (gate.input !== undefined) child.stdin.end(gate.input)
  438. else child.stdin.end()
  439. })
  440. let status: GateStatus = exitCode === 0 && spawnError === undefined ? 'passed' : 'failed'
  441. let error = spawnError
  442. if (status === 'passed' && gate.verify !== undefined) {
  443. try {
  444. await gate.verify({ gate, status, durationMs: performance.now() - started, stdout, stderr, output, exitCode })
  445. } catch (verifyError: unknown) {
  446. status = 'failed'
  447. error = verifyError instanceof Error ? verifyError.message : String(verifyError)
  448. }
  449. }
  450. const result: GateResult = {
  451. gate,
  452. status,
  453. durationMs: performance.now() - started,
  454. stdout,
  455. stderr,
  456. output,
  457. exitCode,
  458. }
  459. if (error !== undefined) result.error = error
  460. return result
  461. }
  462. function printResult(result: GateResult): void {
  463. const seconds = (result.durationMs / 1000).toFixed(2)
  464. if (result.status === 'passed' && !verbose) {
  465. console.log(`run-gates: PASS ${result.gate.label} (${seconds}s)`)
  466. return
  467. }
  468. const heading = `${result.status.toUpperCase()} ${result.gate.label} (${seconds}s)`
  469. const writeHeading = result.status === 'passed' ? console.log : console.error
  470. writeHeading(`\n== ${heading} ==`)
  471. if (result.status !== 'passed') console.error(`command: ${result.gate.displayCommand}`)
  472. printOutput(result.output)
  473. if (result.error !== undefined) console.error(result.error)
  474. }
  475. function printSummary(results: GateResult[], durationMs: number): void {
  476. const passed = results.filter(result => result.status === 'passed').length
  477. const failed = results.filter(result => result.status === 'failed').length
  478. const skipped = results.filter(result => result.status === 'skipped').length
  479. const seconds = (durationMs / 1000).toFixed(2)
  480. console.log(`\nrun-gates: ${passed} passed, ${failed} failed, ${skipped} skipped in ${seconds}s.`)
  481. const unsuccessful = results.filter(result => result.status === 'failed' || result.status === 'skipped')
  482. if (unsuccessful.length === 0) return
  483. console.error('run-gates: unsuccessful gates:')
  484. for (const result of unsuccessful) {
  485. const duration = (result.durationMs / 1000).toFixed(2)
  486. const reason = result.error ?? (result.exitCode === null ? 'no exit code' : `exit ${result.exitCode}`)
  487. console.error(` - ${result.status.toUpperCase()} ${result.gate.label} (${duration}s, ${reason})`)
  488. console.error(` ${result.gate.displayCommand}`)
  489. }
  490. }
  491. function printOutput(output: GateOutputChunk[]): void {
  492. for (const chunk of output) {
  493. if (chunk.stream === 'stdout') process.stdout.write(chunk.text)
  494. else process.stderr.write(chunk.text)
  495. }
  496. }