1
0

run-gates.ts 28 KB

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