run-gates.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. /**
  2. * Run local and CI quality gates with bounded in-process scheduling.
  3. *
  4. * Package scripts own public aggregate names; this runner owns their validated
  5. * dependency graphs, scheduler environment, and process diagnostics.
  6. * @see ../.agents/notes/implemented/process/2026-07-06-parallel-pre-push-gates.md
  7. */
  8. import { spawn } from 'node:child_process'
  9. import { availableParallelism } from 'node:os'
  10. import { resolve } from 'node:path'
  11. import { performance } from 'node:perf_hooks'
  12. /** A named aggregate exposed by the gate runner. */
  13. export type Mode =
  14. | 'ci-primary'
  15. | 'ci-static'
  16. | 'ci-lint'
  17. | 'ci-coverage'
  18. | 'ci-snapshot'
  19. | 'ci-artifacts'
  20. | 'ci-consumers'
  21. | 'ci-windows-blocking'
  22. | 'ci-windows-complete'
  23. | 'ci-windows-observational'
  24. | 'node-compat'
  25. | 'check-all'
  26. | 'doc-sync'
  27. type GateResultStatus = 'passed' | 'failed' | 'skipped'
  28. type GateState = 'pending' | 'running' | GateResultStatus
  29. /** A command and its dependency metadata inside one aggregate. */
  30. export interface Gate {
  31. id: string
  32. label: string
  33. displayCommand: string
  34. command: string
  35. args: string[]
  36. needs?: string[]
  37. env?: Record<string, string | undefined>
  38. allowFailure?: boolean
  39. }
  40. /** The observed outcome of one gate process. */
  41. export interface GateResult {
  42. gate: Gate
  43. status: GateResultStatus
  44. durationMs: number
  45. output: GateOutputChunk[]
  46. exitCode: number | null
  47. signalCode: NodeJS.Signals | null
  48. error?: string
  49. }
  50. interface GateOutputChunk {
  51. stream: 'stdout' | 'stderr'
  52. text: string
  53. }
  54. interface RunningGate {
  55. gate: Gate
  56. promise: Promise<GateResult>
  57. }
  58. interface ConcurrencyDefault {
  59. workers: number
  60. source: string
  61. }
  62. type GateExecutor = (gate: Gate) => Promise<GateResult>
  63. type ResultObserver = (result: GateResult) => void
  64. const root = resolve(import.meta.dirname, '..')
  65. if (import.meta.main) {
  66. process.exitCode = await main(process.argv.slice(2))
  67. }
  68. async function main(args: string[]): Promise<number> {
  69. const mode = parseMode(args[0])
  70. const gates = gatesForMode(mode)
  71. const concurrencyDefault = defaultConcurrency(mode, gates.length)
  72. const concurrencyOverride = process.env.DSH_GATE_CONCURRENCY
  73. const maxConcurrency = concurrencyFromEnv('DSH_GATE_CONCURRENCY', concurrencyDefault.workers)
  74. const concurrencySource = concurrencyOverride === undefined || concurrencyOverride === ''
  75. ? concurrencyDefault.source
  76. : '$DSH_GATE_CONCURRENCY'
  77. const startedAt = performance.now()
  78. console.log(`run-gates: ${mode} running ${gates.length} gate(s) with ${maxConcurrency} worker(s) from ${concurrencySource}.`)
  79. const results = await runGates(gates, maxConcurrency, runGate, printResult)
  80. printSummary(results, performance.now() - startedAt)
  81. return results.some(result => result.gate.allowFailure !== true && (result.status === 'failed' || result.status === 'skipped'))
  82. ? 1
  83. : 0
  84. }
  85. function parseMode(raw: string | undefined): Mode {
  86. switch (raw) {
  87. case 'ci-primary':
  88. case 'ci-static':
  89. case 'ci-lint':
  90. case 'ci-coverage':
  91. case 'ci-snapshot':
  92. case 'ci-artifacts':
  93. case 'ci-consumers':
  94. case 'ci-windows-blocking':
  95. case 'ci-windows-complete':
  96. case 'ci-windows-observational':
  97. case 'node-compat':
  98. case 'check-all':
  99. case 'doc-sync':
  100. return raw
  101. default:
  102. throw new Error(
  103. `run-gates: expected mode ci-primary | ci-static | ci-lint | ci-coverage | ci-snapshot | ci-artifacts | ci-consumers | ci-windows-blocking | ci-windows-complete | ci-windows-observational | node-compat | check-all | doc-sync, got ${JSON.stringify(raw)}.`,
  104. )
  105. }
  106. }
  107. /**
  108. * Resolve the default worker count for one aggregate.
  109. * @param selectedMode - aggregate whose resource posture applies.
  110. * @param total - number of gates in the aggregate.
  111. * @param available - host CPU availability for ordinary modes.
  112. * @returns the default worker count and its diagnostic source.
  113. */
  114. export function defaultConcurrency(
  115. selectedMode: Mode,
  116. total: number,
  117. available = availableParallelism(),
  118. ): ConcurrencyDefault {
  119. if (selectedMode === 'ci-consumers') return { workers: total, source: 'ci-consumers gate count' }
  120. // Local modes cap workers: several doc gates each build a full ts.Program,
  121. // so an uncapped default on a large host trades wall clock for memory blowups.
  122. const localCap = selectedMode === 'check-all' || selectedMode === 'doc-sync'
  123. const modeLimit = localCap ? Math.min(4, available) : available
  124. return {
  125. workers: Math.min(total, modeLimit),
  126. source: localCap
  127. ? `${available} available CPU(s), ${selectedMode} cap 4`
  128. : `${available} available CPU(s)`,
  129. }
  130. }
  131. function concurrencyFromEnv(name: string, fallback: number): number {
  132. const raw = process.env[name]
  133. if (raw === undefined || raw === '') return fallback
  134. const parsed = Number.parseInt(raw, 10)
  135. if (!Number.isSafeInteger(parsed) || parsed < 1) {
  136. throw new Error(`run-gates: ${name} must be a positive integer, got ${JSON.stringify(raw)}.`)
  137. }
  138. return parsed
  139. }
  140. function pnpmScript(id: string, script: string, options: Partial<Gate> = {}): Gate {
  141. return {
  142. id,
  143. label: options.label ?? script,
  144. displayCommand: `pnpm run ${script}`,
  145. ...pnpmInvocation(['run', script]),
  146. ...options,
  147. }
  148. }
  149. function pnpmExec(id: string, args: string[], options: Partial<Gate> = {}): Gate {
  150. return {
  151. id,
  152. label: options.label ?? `pnpm exec ${args.join(' ')}`,
  153. displayCommand: `pnpm exec ${args.join(' ')}`,
  154. ...pnpmInvocation(['exec', ...args]),
  155. ...options,
  156. }
  157. }
  158. function pnpmInvocation(args: string[]): Pick<Gate, 'command' | 'args'> {
  159. const entrypoint = process.env.npm_execpath
  160. if (entrypoint === undefined || entrypoint === '') {
  161. throw new Error('run-gates: npm_execpath is unavailable; invoke the runner through a pnpm package script.')
  162. }
  163. // Windows cannot spawn the pnpm.cmd shim directly; the JavaScript entrypoint keeps every host shell-free.
  164. return { command: process.execPath, args: [entrypoint, ...args] }
  165. }
  166. function nodeOptions(...options: string[]): string {
  167. return [process.env.NODE_OPTIONS, ...options].filter(option => option !== undefined && option !== '').join(' ')
  168. }
  169. /**
  170. * Construct the complete gate list for a named aggregate.
  171. * @param selected - aggregate mode to construct.
  172. * @returns the aggregate's gate graph.
  173. */
  174. export function gatesForMode(selected: Mode): Gate[] {
  175. switch (selected) {
  176. case 'ci-primary':
  177. return ciPrimaryGates()
  178. case 'ci-static':
  179. return ciStaticGates()
  180. case 'ci-lint':
  181. return [
  182. lintGate(),
  183. pnpmScript('duplication', 'duplication'),
  184. ]
  185. case 'ci-coverage':
  186. return [coverageGate()]
  187. case 'ci-snapshot':
  188. return [pnpmScript('build', 'build'), snapshotGate()]
  189. case 'ci-artifacts':
  190. return ciArtifactGates()
  191. case 'ci-consumers':
  192. return ciConsumerGates()
  193. case 'ci-windows-blocking':
  194. return ciWindowsBlockingGates()
  195. case 'ci-windows-complete':
  196. return ciWindowsCompleteGates()
  197. case 'ci-windows-observational':
  198. return ciWindowsObservationalGates()
  199. case 'node-compat':
  200. return nodeCompatGates()
  201. case 'check-all':
  202. return [
  203. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  204. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  205. pnpmScript('client-domain-graph', 'verify-client-domain-graph', { label: 'client domain graph' }),
  206. pnpmScript('test', 'test'),
  207. pnpmScript('duplication', 'duplication'),
  208. snapshotGate(),
  209. pnpmScript('build', 'build'),
  210. pnpmScript('build:web', 'build:web'),
  211. ...hygieneLeafGates({ artifactNeeds: ['build'] }),
  212. ...docSyncLeafGates({
  213. docTypecheckNeeds: ['build'],
  214. docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  215. }),
  216. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  217. ]
  218. case 'doc-sync':
  219. return docSyncLeafGates()
  220. }
  221. }
  222. function ciPrimaryGates(): Gate[] {
  223. return [
  224. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  225. pnpmScript('constraints', 'constraints'),
  226. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  227. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  228. pnpmScript('typecheck', 'typecheck'),
  229. lintGate(),
  230. pnpmScript('duplication', 'duplication'),
  231. coverageGate(),
  232. ...nodeCompatSmokeGates(),
  233. snapshotGate(),
  234. ...docSyncLeafGates(),
  235. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  236. pnpmScript('knip', 'knip'),
  237. // typecheck and build now drive the same root solution graph; without the
  238. // dependency two concurrent `tsc -b` runs race the same tsbuildinfo files.
  239. // The tsc step is an incremental no-op after typecheck.
  240. pnpmScript('build', 'build', { needs: ['typecheck'] }),
  241. pnpmScript('publint', 'publint', { needs: ['build'] }),
  242. pnpmScript('node-next-types', 'verify-node-next-types', {
  243. label: 'node-next types',
  244. needs: ['build'],
  245. }),
  246. builtPackageInvariantsGate(['build']),
  247. builtBinSmokeGate(),
  248. ]
  249. }
  250. function nodeCompatGates(): Gate[] {
  251. return [
  252. ...flagEnabled('DSH_NODE_COMPAT_SKIP_TYPECHECK') ? [] : [pnpmScript('typecheck', 'typecheck')],
  253. ...nodeCompatSmokeGates(),
  254. ]
  255. }
  256. function nodeCompatSmokeGates(): Gate[] {
  257. return [
  258. pnpmExec('source-worker-smoke', [
  259. 'vitest',
  260. 'run',
  261. 'packages/workflow/workflow-workerthread/tests/source-worker.compat.spec.ts',
  262. ], { label: 'source worker smoke' }),
  263. pnpmExec('jsonl-zstd-smoke', [
  264. 'vitest',
  265. 'run',
  266. 'packages/session-persistence/session-persistence-jsonl/tests/zstd.compat.spec.ts',
  267. ], { label: 'JSONL Zstandard smoke' }),
  268. ]
  269. }
  270. function ciStaticGates(): Gate[] {
  271. return [
  272. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  273. pnpmScript('constraints', 'constraints'),
  274. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  275. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  276. pnpmScript('build', 'build'),
  277. ...docSyncLeafGates({
  278. docTypecheckNeeds: ['build'],
  279. docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  280. docsBuildScript: 'docs:build:mpa',
  281. }),
  282. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  283. pnpmScript('knip', 'knip'),
  284. ]
  285. }
  286. function ciArtifactGates(): Gate[] {
  287. return [
  288. pnpmScript('build', 'build'),
  289. pnpmScript('publint', 'publint', { needs: ['build'] }),
  290. pnpmScript('node-next-types', 'verify-node-next-types', {
  291. label: 'node-next types',
  292. needs: ['build'],
  293. }),
  294. builtPackageInvariantsGate(['build']),
  295. builtBinSmokeGate(),
  296. ]
  297. }
  298. function ciConsumerGates(): Gate[] {
  299. const publicArtifacts = ['publint']
  300. const restoredBuild = ['built-package-invariants']
  301. return [
  302. pnpmScript('lint-and-duplication', 'check:ci:lint', {
  303. label: 'lint and duplication',
  304. needs: restoredBuild,
  305. }),
  306. pnpmScript('node-compat', 'check:node-compat', { label: 'Node compatibility' }),
  307. snapshotGate(restoredBuild),
  308. pnpmScript('publint', 'publint'),
  309. pnpmScript('node-next-types', 'verify-node-next-types', {
  310. label: 'node-next types',
  311. needs: restoredBuild,
  312. }),
  313. builtPackageInvariantsGate(publicArtifacts),
  314. builtBinSmokeGate(restoredBuild),
  315. ]
  316. }
  317. function ciWindowsBlockingGates(): Gate[] {
  318. return [
  319. pnpmScript('windows-build', 'build', { label: 'build' }),
  320. pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
  321. ]
  322. }
  323. function ciWindowsCompleteGates(): Gate[] {
  324. const observational = ciWindowsObservationalGates()
  325. // The required production site replaces the observational MPA build; both
  326. // VitePress modes write the same output directory and cannot overlap.
  327. .filter(gate => gate.id !== 'build' && gate.id !== 'docs-site-build')
  328. .map(gate => ({ ...gate, allowFailure: true }))
  329. return [
  330. pnpmScript('build', 'build'),
  331. pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
  332. ...observational,
  333. ]
  334. }
  335. function ciWindowsObservationalGates(): Gate[] {
  336. return [
  337. ...ciStaticGates(),
  338. // Linux owns required lint, coverage, and snapshots; Windows omits those duplicates.
  339. pnpmScript('duplication', 'duplication'),
  340. pnpmScript('publint', 'publint', { needs: ['build'] }),
  341. pnpmScript('node-next-types', 'verify-node-next-types', {
  342. label: 'node-next types',
  343. needs: ['build'],
  344. }),
  345. builtPackageInvariantsGate(['build']),
  346. builtBinSmokeGate(),
  347. ]
  348. }
  349. function lintGate(eslintTargets: readonly string[] = ['.']): Gate {
  350. const concurrencyArgs = eslintConcurrencyArgs()
  351. if (process.env.DSH_ESLINT_CACHE === '1') {
  352. return pnpmExec('lint', [
  353. 'eslint',
  354. ...eslintTargets,
  355. ...concurrencyArgs,
  356. '--cache',
  357. '--cache-location',
  358. '.cache/eslint/',
  359. '--cache-strategy',
  360. 'content',
  361. ], {
  362. label: 'lint',
  363. env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') },
  364. })
  365. }
  366. if (concurrencyArgs.length > 0) {
  367. return pnpmExec('lint', ['eslint', ...eslintTargets, ...concurrencyArgs], {
  368. label: 'lint',
  369. env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') },
  370. })
  371. }
  372. return pnpmScript('lint', 'lint', {
  373. env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') },
  374. })
  375. }
  376. function eslintConcurrencyArgs(): string[] {
  377. const raw = process.env.DSH_ESLINT_CONCURRENCY
  378. if (raw === undefined || raw === '') return []
  379. if (raw === 'auto') return ['--concurrency=auto']
  380. const parsed = Number.parseInt(raw, 10)
  381. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  382. throw new Error(`run-gates: DSH_ESLINT_CONCURRENCY must be a positive integer or auto, got ${JSON.stringify(raw)}.`)
  383. }
  384. return [`--concurrency=${raw}`]
  385. }
  386. function coverageGate(): Gate {
  387. return pnpmExec('coverage', [
  388. 'vitest',
  389. 'run',
  390. '--coverage',
  391. ...positiveIntArg('DSH_COVERAGE_MAX_WORKERS', '--maxWorkers'),
  392. ], {
  393. label: 'test:coverage',
  394. })
  395. }
  396. // Example and package snapshots boot their bins in `lib` mode (built artifacts under plain Node,
  397. // plugins via real exports); repository-script snapshots execute their real source entry path.
  398. // Build-owning modes wait on `build`; a restored-artifact mode passes its validation dependency.
  399. function snapshotGate(needs: string[] = ['build']): Gate {
  400. return pnpmScript('snapshot', 'test:snapshot', {
  401. env: { DSH_EXAMPLE_MODE: 'lib' },
  402. needs,
  403. })
  404. }
  405. function builtPackageInvariantsGate(needs?: string[]): Gate {
  406. return pnpmScript('built-package-invariants', 'verify-built-package-invariants', {
  407. label: 'built package invariants',
  408. ...needs === undefined ? {} : { needs },
  409. })
  410. }
  411. function positiveIntArg(envName: string, flag: string): string[] {
  412. const raw = process.env[envName]
  413. if (raw === undefined || raw === '') return []
  414. const parsed = Number.parseInt(raw, 10)
  415. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  416. throw new Error(`run-gates: ${envName} must be a positive integer, got ${JSON.stringify(raw)}.`)
  417. }
  418. return [`${flag}=${raw}`]
  419. }
  420. function flagEnabled(envName: string): boolean {
  421. const raw = process.env[envName]
  422. if (raw === undefined || raw === '') return false
  423. if (raw !== '1') throw new Error(`run-gates: ${envName} must be 1 when set, got ${JSON.stringify(raw)}.`)
  424. return true
  425. }
  426. function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] {
  427. const artifactOptions = options.artifactNeeds === undefined ? {} : { needs: options.artifactNeeds }
  428. return [
  429. pnpmScript('knip', 'knip'),
  430. pnpmScript('publint', 'publint', artifactOptions),
  431. pnpmScript('constraints', 'constraints'),
  432. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  433. builtPackageInvariantsGate(options.artifactNeeds),
  434. pnpmScript('node-next-types', 'verify-node-next-types', {
  435. label: 'node-next types',
  436. ...artifactOptions,
  437. }),
  438. ]
  439. }
  440. function docSyncLeafGates(options: {
  441. docTypecheckNeeds?: string[]
  442. docTypecheckEnv?: Record<string, string | undefined>
  443. docsBuildScript?: 'docs:build' | 'docs:build:mpa'
  444. } = {}): Gate[] {
  445. const docTypecheckOptions: Partial<Gate> = {}
  446. if (options.docTypecheckNeeds !== undefined) docTypecheckOptions.needs = options.docTypecheckNeeds
  447. if (options.docTypecheckEnv !== undefined) docTypecheckOptions.env = options.docTypecheckEnv
  448. return [
  449. pnpmScript('doc-typecheck', 'doc-typecheck', docTypecheckOptions),
  450. pnpmScript('cordis-catalog', 'verify-cordis-catalog', { label: 'cordis catalog' }),
  451. pnpmScript('cordis-api', 'verify-cordis-api', { label: 'cordis api' }),
  452. pnpmScript('export-jsdoc', 'verify-export-jsdoc', { label: 'export jsdoc' }),
  453. pnpmScript('tool-catalog', 'verify-tool-catalog', { label: 'tool catalog' }),
  454. pnpmScript('config-catalog', 'verify-config-catalog', { label: 'config catalog' }),
  455. pnpmScript('persistence-catalog', 'verify-persistence-catalog', { label: 'persistence catalog' }),
  456. pnpmScript('doc-graphs', 'verify-doc-graphs', { label: 'doc graphs' }),
  457. pnpmScript('scoped-events', 'verify-scoped-events', { label: 'scoped events' }),
  458. pnpmScript('markdown-wrap', 'verify-md-wrap', { label: 'markdown wrap' }),
  459. pnpmScript('markdown-links', 'verify-md-links', { label: 'markdown links' }),
  460. pnpmScript('doc-refs', 'verify-doc-refs', { label: 'doc refs' }),
  461. pnpmScript('package-paths', 'verify-package-paths', { label: 'package paths' }),
  462. pnpmScript('package-readme-model-experience', 'verify-package-readme-model-experience', { label: 'package README model experience' }),
  463. pnpmScript('mermaid', 'verify-mermaid'),
  464. pnpmScript('agent-note-classification', 'verify-agent-note-classification', { label: 'agent note classification' }),
  465. pnpmScript('agent-note-format', 'verify-agent-note-format', { label: 'agent note format' }),
  466. pnpmScript('archived-agent-notes', 'verify-archived-agent-notes', { label: 'archived agent notes' }),
  467. pnpmScript('type-equivalence', 'verify-type-equiv', { label: 'type equivalence' }),
  468. pnpmScript('translation-prompt', 'verify-translation-prompt', { label: 'translation prompt' }),
  469. pnpmScript('translation-pairing', 'verify-translation-pairing', { label: 'translation pairing' }),
  470. pnpmScript('doc-budgets', 'verify-doc-budgets', { label: 'doc budgets' }),
  471. pnpmExec('docs-site-projection', ['vitest', 'run', 'scripts/project-doc-site.spec.ts'], {
  472. label: 'documentation projection',
  473. }),
  474. // Keep the VitePress build itself in one gate because projection rewrites website/.generated.
  475. pnpmScript('docs-site-build', options.docsBuildScript ?? 'docs:build', { label: 'documentation build' }),
  476. pnpmScript('package-readme-limitations', 'verify-package-readme-limitations', { label: 'package README limitations' }),
  477. ]
  478. }
  479. function builtBinSmokeGate(needs: string[] = ['build']): Gate {
  480. return pnpmExec('built-bin-smoke', [
  481. 'vitest',
  482. 'run',
  483. '--config',
  484. 'vitest.e2e.config.ts',
  485. 'examples/headless-agent/tests/keyless-smoke.e2e.ts',
  486. 'examples/tui-agent/tests/tui-keyless-smoke.e2e.ts',
  487. 'packages/examples/cli-demo/tests/built-bin.e2e.ts',
  488. 'packages/examples/acp-demo/tests/built-bin.e2e.ts',
  489. 'packages/ui/jsonrpc/tests/built-scope-carrier.e2e.ts',
  490. // The worker-entry packages' built bundles: the only automated proof
  491. // that lib/index.js resolves its sibling lib/worker.cjs under plain node
  492. // (the e2e lane runs unbuilt, so these files self-skip there).
  493. 'packages/workflow/workflow-workerthread/tests/built-worker.e2e.ts',
  494. 'packages/code-runtime/code-runtime-worker/tests/built-lib.e2e.ts',
  495. ], {
  496. label: 'built-bin smoke',
  497. needs,
  498. env: { DSH_EXAMPLE_MODE: 'lib' },
  499. })
  500. }
  501. /**
  502. * Reject a gate list whose graph cannot be executed unambiguously.
  503. * @param gates - complete aggregate to validate.
  504. */
  505. function validateGateGraph(gates: readonly Gate[]): void {
  506. if (gates.length === 0) throw new Error('run-gates: gate graph has no gates.')
  507. const ids = new Set<string>()
  508. for (const gate of gates) {
  509. if (ids.has(gate.id)) throw new Error(`run-gates: duplicate gate id ${JSON.stringify(gate.id)}.`)
  510. ids.add(gate.id)
  511. }
  512. for (const gate of gates) {
  513. for (const dependency of gate.needs ?? []) {
  514. if (!ids.has(dependency)) {
  515. throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} depends on unknown gate ${JSON.stringify(dependency)}.`)
  516. }
  517. }
  518. }
  519. const cycle = findDependencyCycle(gates)
  520. if (cycle !== undefined) throw new Error(`run-gates: dependency cycle: ${cycle.join(' -> ')}.`)
  521. }
  522. function findDependencyCycle(gates: readonly Gate[]): string[] | undefined {
  523. const byId = new Map(gates.map(gate => [gate.id, gate]))
  524. const complete = new Set<string>()
  525. const active = new Map<string, number>()
  526. const path: string[] = []
  527. const visit = (id: string): string[] | undefined => {
  528. if (complete.has(id)) return undefined
  529. const cycleStart = active.get(id)
  530. if (cycleStart !== undefined) return [...path.slice(cycleStart), id]
  531. const gate = byId.get(id)
  532. if (gate === undefined) return undefined
  533. active.set(id, path.length)
  534. path.push(id)
  535. for (const dependency of gate.needs ?? []) {
  536. const cycle = visit(dependency)
  537. if (cycle !== undefined) return cycle
  538. }
  539. path.pop()
  540. active.delete(id)
  541. complete.add(id)
  542. return undefined
  543. }
  544. for (const gate of gates) {
  545. const cycle = visit(gate.id)
  546. if (cycle !== undefined) return cycle
  547. }
  548. return undefined
  549. }
  550. /**
  551. * Validate and run one aggregate before the injected executor can start a child.
  552. * @param gates - complete aggregate to execute.
  553. * @param maxActive - maximum concurrent child count.
  554. * @param execute - child-process executor.
  555. * @param observe - result observer invoked when each gate settles.
  556. * @returns results in aggregate order.
  557. */
  558. export async function runGates(
  559. gates: Gate[],
  560. maxActive: number,
  561. execute: GateExecutor,
  562. observe: ResultObserver = () => {},
  563. ): Promise<GateResult[]> {
  564. validateGateGraph(gates)
  565. if (!Number.isSafeInteger(maxActive) || maxActive < 1) {
  566. throw new Error(`run-gates: max concurrency must be a positive integer, got ${JSON.stringify(maxActive)}.`)
  567. }
  568. const states = new Map<string, GateState>(gates.map(gate => [gate.id, 'pending']))
  569. const results = new Map<string, GateResult>()
  570. const running: RunningGate[] = []
  571. for (;;) {
  572. let madeProgress = false
  573. while (running.length < maxActive) {
  574. const ready = gates.find(gate => states.get(gate.id) === 'pending' && dependenciesPassed(gate, states))
  575. if (ready === undefined) break
  576. states.set(ready.id, 'running')
  577. running.push({ gate: ready, promise: execute(ready) })
  578. console.log(`run-gates: start ${ready.label}`)
  579. madeProgress = true
  580. }
  581. if (running.length === 0) {
  582. let pending = gates.filter(gate => states.get(gate.id) === 'pending')
  583. while (pending.length > 0) {
  584. const gate = pending.find(item => (item.needs ?? []).some((id) => {
  585. const state = states.get(id)
  586. return state === 'failed' || state === 'skipped'
  587. }))
  588. if (gate === undefined) throw new Error('run-gates: validated graph stalled without a failed dependency.')
  589. const failedDeps = (gate.needs ?? []).filter((id) => {
  590. const state = states.get(id)
  591. return state === 'failed' || state === 'skipped'
  592. })
  593. const result: GateResult = {
  594. gate,
  595. status: 'skipped',
  596. durationMs: 0,
  597. output: [],
  598. exitCode: null,
  599. signalCode: null,
  600. error: `dependency failed or skipped: ${failedDeps.join(', ')}`,
  601. }
  602. states.set(gate.id, 'skipped')
  603. results.set(gate.id, result)
  604. observe(result)
  605. pending = pending.filter(item => item !== gate)
  606. }
  607. break
  608. }
  609. if (!madeProgress) {
  610. const settled = await Promise.race(running.map(async item => ({ item, result: await item.promise })))
  611. running.splice(running.indexOf(settled.item), 1)
  612. states.set(settled.item.gate.id, settled.result.status)
  613. results.set(settled.item.gate.id, settled.result)
  614. observe(settled.result)
  615. }
  616. }
  617. return gates.map((gate) => {
  618. const result = results.get(gate.id)
  619. if (result === undefined) throw new Error(`run-gates: missing result for ${gate.id}.`)
  620. return result
  621. })
  622. }
  623. function dependenciesPassed(gate: Gate, states: Map<string, GateState>): boolean {
  624. return (gate.needs ?? []).every(id => states.get(id) === 'passed')
  625. }
  626. /**
  627. * Execute one gate through the real shell-free child-process boundary.
  628. * @param gate - command and scheduler environment to execute.
  629. * @returns the complete process outcome.
  630. */
  631. export async function runGate(gate: Gate): Promise<GateResult> {
  632. const started = performance.now()
  633. const output: GateOutputChunk[] = []
  634. let spawnError: string | undefined
  635. const outcome = await new Promise<{
  636. exitCode: number | null
  637. signalCode: NodeJS.Signals | null
  638. }>((resolveExit) => {
  639. const child = spawn(gate.command, gate.args, {
  640. cwd: root,
  641. env: { ...process.env, ...gate.env },
  642. stdio: ['pipe', 'pipe', 'pipe'],
  643. })
  644. child.stdout.setEncoding('utf8')
  645. child.stderr.setEncoding('utf8')
  646. child.stdout.on('data', (chunk: string) => {
  647. output.push({ stream: 'stdout', text: chunk })
  648. })
  649. child.stderr.on('data', (chunk: string) => {
  650. output.push({ stream: 'stderr', text: chunk })
  651. })
  652. child.on('error', (error) => {
  653. spawnError = `failed to start command: ${error.message}`
  654. resolveExit({ exitCode: null, signalCode: null })
  655. })
  656. child.on('close', (exitCode, signalCode) => {
  657. resolveExit({ exitCode, signalCode })
  658. })
  659. child.stdin.end()
  660. })
  661. const { exitCode, signalCode } = outcome
  662. const status: GateResultStatus = exitCode === 0 && signalCode === null && spawnError === undefined ? 'passed' : 'failed'
  663. const result: GateResult = {
  664. gate,
  665. status,
  666. durationMs: performance.now() - started,
  667. output,
  668. exitCode,
  669. signalCode,
  670. }
  671. if (spawnError !== undefined) result.error = spawnError
  672. return result
  673. }
  674. /**
  675. * Format every independently observed failure fact for the aggregate summary.
  676. * @param result - unsuccessful gate result.
  677. * @returns error, exit, and signal facts without allowing one to hide another.
  678. */
  679. export function formatGateResultReason(result: GateResult): string {
  680. const facts: string[] = []
  681. if (result.error !== undefined) facts.push(result.error)
  682. if (result.exitCode !== null) facts.push(`exit ${result.exitCode}`)
  683. if (result.signalCode !== null) facts.push(`signal ${result.signalCode}`)
  684. return facts.length === 0 ? 'no exit code or signal' : facts.join(', ')
  685. }
  686. function printResult(result: GateResult): void {
  687. const verbose = process.env.DSH_GATE_VERBOSE === '1'
  688. const seconds = (result.durationMs / 1000).toFixed(2)
  689. if (result.status === 'passed' && !verbose) {
  690. console.log(`run-gates: PASS ${result.gate.label} (${seconds}s)`)
  691. return
  692. }
  693. const heading = `${result.status.toUpperCase()} ${result.gate.label} (${seconds}s)`
  694. const writeHeading = result.status === 'passed' ? console.log : console.error
  695. writeHeading(`\n== ${heading} ==`)
  696. if (result.status !== 'passed') {
  697. console.error(`command: ${result.gate.displayCommand}`)
  698. console.error(`outcome: ${formatGateResultReason(result)}`)
  699. }
  700. printOutput(result.output)
  701. }
  702. function printSummary(results: GateResult[], durationMs: number): void {
  703. const passed = results.filter(result => result.status === 'passed').length
  704. const failed = results.filter(result => result.status === 'failed').length
  705. const skipped = results.filter(result => result.status === 'skipped').length
  706. const seconds = (durationMs / 1000).toFixed(2)
  707. console.log(`\nrun-gates: ${passed} passed, ${failed} failed, ${skipped} skipped in ${seconds}s.`)
  708. const unsuccessful = results.filter(result => result.status === 'failed' || result.status === 'skipped')
  709. if (unsuccessful.length === 0) return
  710. console.error('run-gates: unsuccessful gates:')
  711. for (const result of unsuccessful) {
  712. const duration = (result.durationMs / 1000).toFixed(2)
  713. const reason = formatGateResultReason(result)
  714. const disposition = result.gate.allowFailure === true ? 'NON-BLOCKING ' : ''
  715. console.error(` - ${disposition}${result.status.toUpperCase()} ${result.gate.label} (${duration}s, ${reason})`)
  716. console.error(` ${result.gate.displayCommand}`)
  717. }
  718. }
  719. function printOutput(output: GateOutputChunk[]): void {
  720. for (const chunk of output) {
  721. if (chunk.stream === 'stdout') process.stdout.write(chunk.text)
  722. else process.stderr.write(chunk.text)
  723. }
  724. }