run-gates.ts 19 KB

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