run-gates.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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. pnpmExec('dsh-source-launch-smoke', [
  269. 'vitest',
  270. 'run',
  271. 'apps/cli/tests/source-launch.compat.spec.ts',
  272. ], { label: 'dsh source-launch smoke' }),
  273. ]
  274. }
  275. function ciStaticGates(): Gate[] {
  276. return [
  277. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  278. pnpmScript('constraints', 'constraints'),
  279. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  280. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  281. pnpmScript('build', 'build'),
  282. ...docSyncLeafGates({
  283. docTypecheckNeeds: ['build'],
  284. docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  285. docsBuildScript: 'docs:build:mpa',
  286. }),
  287. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  288. pnpmScript('knip', 'knip'),
  289. ]
  290. }
  291. function ciArtifactGates(): Gate[] {
  292. return [
  293. pnpmScript('build', 'build'),
  294. pnpmScript('publint', 'publint', { needs: ['build'] }),
  295. pnpmScript('node-next-types', 'verify-node-next-types', {
  296. label: 'node-next types',
  297. needs: ['build'],
  298. }),
  299. builtPackageInvariantsGate(['build']),
  300. builtBinSmokeGate(),
  301. ]
  302. }
  303. function ciConsumerGates(): Gate[] {
  304. const publicArtifacts = ['publint']
  305. const restoredBuild = ['built-package-invariants']
  306. return [
  307. pnpmScript('lint-and-duplication', 'check:ci:lint', {
  308. label: 'lint and duplication',
  309. needs: restoredBuild,
  310. }),
  311. pnpmScript('node-compat', 'check:node-compat', { label: 'Node compatibility' }),
  312. snapshotGate(restoredBuild),
  313. pnpmScript('publint', 'publint'),
  314. pnpmScript('node-next-types', 'verify-node-next-types', {
  315. label: 'node-next types',
  316. needs: restoredBuild,
  317. }),
  318. builtPackageInvariantsGate(publicArtifacts),
  319. builtBinSmokeGate(restoredBuild),
  320. ]
  321. }
  322. function ciWindowsBlockingGates(): Gate[] {
  323. return [
  324. pnpmScript('windows-build', 'build', { label: 'build' }),
  325. pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
  326. ]
  327. }
  328. function ciWindowsCompleteGates(): Gate[] {
  329. const observational = ciWindowsObservationalGates()
  330. // The required production site replaces the observational MPA build; both
  331. // VitePress modes write the same output directory and cannot overlap.
  332. .filter(gate => gate.id !== 'build' && gate.id !== 'docs-site-build')
  333. .map(gate => ({ ...gate, allowFailure: true }))
  334. return [
  335. pnpmScript('build', 'build'),
  336. pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
  337. ...observational,
  338. ]
  339. }
  340. function ciWindowsObservationalGates(): Gate[] {
  341. return [
  342. ...ciStaticGates(),
  343. // Linux owns required lint, coverage, and snapshots; Windows omits those duplicates.
  344. pnpmScript('duplication', 'duplication'),
  345. pnpmScript('publint', 'publint', { needs: ['build'] }),
  346. pnpmScript('node-next-types', 'verify-node-next-types', {
  347. label: 'node-next types',
  348. needs: ['build'],
  349. }),
  350. builtPackageInvariantsGate(['build']),
  351. builtBinSmokeGate(),
  352. ]
  353. }
  354. function lintGate(eslintTargets: readonly string[] = ['.']): Gate {
  355. const concurrencyArgs = eslintConcurrencyArgs()
  356. if (process.env.DSH_ESLINT_CACHE === '1') {
  357. return pnpmExec('lint', [
  358. 'eslint',
  359. ...eslintTargets,
  360. ...concurrencyArgs,
  361. '--cache',
  362. '--cache-location',
  363. '.cache/eslint/',
  364. '--cache-strategy',
  365. 'content',
  366. ], {
  367. label: 'lint',
  368. env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') },
  369. })
  370. }
  371. if (concurrencyArgs.length > 0) {
  372. return pnpmExec('lint', ['eslint', ...eslintTargets, ...concurrencyArgs], {
  373. label: 'lint',
  374. env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') },
  375. })
  376. }
  377. return pnpmScript('lint', 'lint', {
  378. env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') },
  379. })
  380. }
  381. function eslintConcurrencyArgs(): string[] {
  382. const raw = process.env.DSH_ESLINT_CONCURRENCY
  383. if (raw === undefined || raw === '') return []
  384. if (raw === 'auto') return ['--concurrency=auto']
  385. const parsed = Number.parseInt(raw, 10)
  386. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  387. throw new Error(`run-gates: DSH_ESLINT_CONCURRENCY must be a positive integer or auto, got ${JSON.stringify(raw)}.`)
  388. }
  389. return [`--concurrency=${raw}`]
  390. }
  391. function coverageGate(): Gate {
  392. return pnpmExec('coverage', [
  393. 'vitest',
  394. 'run',
  395. '--coverage',
  396. ...positiveIntArg('DSH_COVERAGE_MAX_WORKERS', '--maxWorkers'),
  397. ], {
  398. label: 'test:coverage',
  399. })
  400. }
  401. // Example and package snapshots boot their bins in `lib` mode (built artifacts under plain Node,
  402. // plugins via real exports); repository-script snapshots execute their real source entry path.
  403. // Build-owning modes wait on `build`; a restored-artifact mode passes its validation dependency.
  404. function snapshotGate(needs: string[] = ['build']): Gate {
  405. return pnpmScript('snapshot', 'test:snapshot', {
  406. env: { DSH_EXAMPLE_MODE: 'lib' },
  407. needs,
  408. })
  409. }
  410. function builtPackageInvariantsGate(needs?: string[]): Gate {
  411. return pnpmScript('built-package-invariants', 'verify-built-package-invariants', {
  412. label: 'built package invariants',
  413. ...needs === undefined ? {} : { needs },
  414. })
  415. }
  416. function positiveIntArg(envName: string, flag: string): string[] {
  417. const raw = process.env[envName]
  418. if (raw === undefined || raw === '') return []
  419. const parsed = Number.parseInt(raw, 10)
  420. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  421. throw new Error(`run-gates: ${envName} must be a positive integer, got ${JSON.stringify(raw)}.`)
  422. }
  423. return [`${flag}=${raw}`]
  424. }
  425. function flagEnabled(envName: string): boolean {
  426. const raw = process.env[envName]
  427. if (raw === undefined || raw === '') return false
  428. if (raw !== '1') throw new Error(`run-gates: ${envName} must be 1 when set, got ${JSON.stringify(raw)}.`)
  429. return true
  430. }
  431. function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] {
  432. const artifactOptions = options.artifactNeeds === undefined ? {} : { needs: options.artifactNeeds }
  433. return [
  434. pnpmScript('knip', 'knip'),
  435. pnpmScript('publint', 'publint', artifactOptions),
  436. pnpmScript('constraints', 'constraints'),
  437. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  438. builtPackageInvariantsGate(options.artifactNeeds),
  439. pnpmScript('node-next-types', 'verify-node-next-types', {
  440. label: 'node-next types',
  441. ...artifactOptions,
  442. }),
  443. ]
  444. }
  445. function docSyncLeafGates(options: {
  446. docTypecheckNeeds?: string[]
  447. docTypecheckEnv?: Record<string, string | undefined>
  448. docsBuildScript?: 'docs:build' | 'docs:build:mpa'
  449. } = {}): Gate[] {
  450. const docTypecheckOptions: Partial<Gate> = {}
  451. if (options.docTypecheckNeeds !== undefined) docTypecheckOptions.needs = options.docTypecheckNeeds
  452. if (options.docTypecheckEnv !== undefined) docTypecheckOptions.env = options.docTypecheckEnv
  453. return [
  454. pnpmScript('doc-typecheck', 'doc-typecheck', docTypecheckOptions),
  455. pnpmScript('cordis-catalog', 'verify-cordis-catalog', { label: 'cordis catalog' }),
  456. pnpmScript('cordis-api', 'verify-cordis-api', { label: 'cordis api' }),
  457. pnpmScript('export-jsdoc', 'verify-export-jsdoc', { label: 'export jsdoc' }),
  458. pnpmScript('tool-catalog', 'verify-tool-catalog', { label: 'tool catalog' }),
  459. pnpmScript('config-catalog', 'verify-config-catalog', { label: 'config catalog' }),
  460. pnpmScript('persistence-catalog', 'verify-persistence-catalog', { label: 'persistence catalog' }),
  461. pnpmScript('doc-graphs', 'verify-doc-graphs', { label: 'doc graphs' }),
  462. pnpmScript('scoped-events', 'verify-scoped-events', { label: 'scoped events' }),
  463. pnpmScript('markdown-wrap', 'verify-md-wrap', { label: 'markdown wrap' }),
  464. pnpmScript('markdown-links', 'verify-md-links', { label: 'markdown links' }),
  465. pnpmScript('doc-refs', 'verify-doc-refs', { label: 'doc refs' }),
  466. pnpmScript('package-paths', 'verify-package-paths', { label: 'package paths' }),
  467. pnpmScript('package-readme-model-experience', 'verify-package-readme-model-experience', { label: 'package README model experience' }),
  468. pnpmScript('mermaid', 'verify-mermaid'),
  469. pnpmScript('agent-note-classification', 'verify-agent-note-classification', { label: 'agent note classification' }),
  470. pnpmScript('agent-note-format', 'verify-agent-note-format', { label: 'agent note format' }),
  471. pnpmScript('archived-agent-notes', 'verify-archived-agent-notes', { label: 'archived agent notes' }),
  472. pnpmScript('type-equivalence', 'verify-type-equiv', { label: 'type equivalence' }),
  473. pnpmScript('translation-prompt', 'verify-translation-prompt', { label: 'translation prompt' }),
  474. pnpmScript('translation-pairing', 'verify-translation-pairing', { label: 'translation pairing' }),
  475. pnpmScript('doc-budgets', 'verify-doc-budgets', { label: 'doc budgets' }),
  476. pnpmExec('docs-site-projection', ['vitest', 'run', 'scripts/project-doc-site.spec.ts'], {
  477. label: 'documentation projection',
  478. }),
  479. // Keep the VitePress build itself in one gate because projection rewrites website/.generated.
  480. pnpmScript('docs-site-build', options.docsBuildScript ?? 'docs:build', { label: 'documentation build' }),
  481. pnpmScript('package-readme-limitations', 'verify-package-readme-limitations', { label: 'package README limitations' }),
  482. ]
  483. }
  484. function builtBinSmokeGate(needs: string[] = ['build']): Gate {
  485. return pnpmExec('built-bin-smoke', [
  486. 'vitest',
  487. 'run',
  488. '--config',
  489. 'vitest.e2e.config.ts',
  490. 'examples/headless-agent/tests/keyless-smoke.e2e.ts',
  491. 'apps/cli/tests/tui-keyless-smoke.e2e.ts',
  492. 'packages/examples/cli-demo/tests/built-bin.e2e.ts',
  493. 'packages/examples/acp-demo/tests/built-bin.e2e.ts',
  494. 'packages/ui/jsonrpc/tests/built-scope-carrier.e2e.ts',
  495. // The worker-entry packages' built bundles: the only automated proof
  496. // that lib/index.js resolves its sibling lib/worker.cjs under plain node
  497. // (the e2e lane runs unbuilt, so these files self-skip there).
  498. 'packages/workflow/workflow-workerthread/tests/built-worker.e2e.ts',
  499. 'packages/code-runtime/code-runtime-worker/tests/built-lib.e2e.ts',
  500. ], {
  501. label: 'built-bin smoke',
  502. needs,
  503. env: { DSH_EXAMPLE_MODE: 'lib' },
  504. })
  505. }
  506. /**
  507. * Reject a gate list whose graph cannot be executed unambiguously.
  508. * @param gates - complete aggregate to validate.
  509. */
  510. function validateGateGraph(gates: readonly Gate[]): void {
  511. if (gates.length === 0) throw new Error('run-gates: gate graph has no gates.')
  512. const ids = new Set<string>()
  513. for (const gate of gates) {
  514. if (ids.has(gate.id)) throw new Error(`run-gates: duplicate gate id ${JSON.stringify(gate.id)}.`)
  515. ids.add(gate.id)
  516. }
  517. for (const gate of gates) {
  518. for (const dependency of gate.needs ?? []) {
  519. if (!ids.has(dependency)) {
  520. throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} depends on unknown gate ${JSON.stringify(dependency)}.`)
  521. }
  522. }
  523. }
  524. const cycle = findDependencyCycle(gates)
  525. if (cycle !== undefined) throw new Error(`run-gates: dependency cycle: ${cycle.join(' -> ')}.`)
  526. }
  527. function findDependencyCycle(gates: readonly Gate[]): string[] | undefined {
  528. const byId = new Map(gates.map(gate => [gate.id, gate]))
  529. const complete = new Set<string>()
  530. const active = new Map<string, number>()
  531. const path: string[] = []
  532. const visit = (id: string): string[] | undefined => {
  533. if (complete.has(id)) return undefined
  534. const cycleStart = active.get(id)
  535. if (cycleStart !== undefined) return [...path.slice(cycleStart), id]
  536. const gate = byId.get(id)
  537. if (gate === undefined) return undefined
  538. active.set(id, path.length)
  539. path.push(id)
  540. for (const dependency of gate.needs ?? []) {
  541. const cycle = visit(dependency)
  542. if (cycle !== undefined) return cycle
  543. }
  544. path.pop()
  545. active.delete(id)
  546. complete.add(id)
  547. return undefined
  548. }
  549. for (const gate of gates) {
  550. const cycle = visit(gate.id)
  551. if (cycle !== undefined) return cycle
  552. }
  553. return undefined
  554. }
  555. /**
  556. * Validate and run one aggregate before the injected executor can start a child.
  557. * @param gates - complete aggregate to execute.
  558. * @param maxActive - maximum concurrent child count.
  559. * @param execute - child-process executor.
  560. * @param observe - result observer invoked when each gate settles.
  561. * @returns results in aggregate order.
  562. */
  563. export async function runGates(
  564. gates: Gate[],
  565. maxActive: number,
  566. execute: GateExecutor,
  567. observe: ResultObserver = () => {},
  568. ): Promise<GateResult[]> {
  569. validateGateGraph(gates)
  570. if (!Number.isSafeInteger(maxActive) || maxActive < 1) {
  571. throw new Error(`run-gates: max concurrency must be a positive integer, got ${JSON.stringify(maxActive)}.`)
  572. }
  573. const states = new Map<string, GateState>(gates.map(gate => [gate.id, 'pending']))
  574. const results = new Map<string, GateResult>()
  575. const running: RunningGate[] = []
  576. for (;;) {
  577. let madeProgress = false
  578. while (running.length < maxActive) {
  579. const ready = gates.find(gate => states.get(gate.id) === 'pending' && dependenciesPassed(gate, states))
  580. if (ready === undefined) break
  581. states.set(ready.id, 'running')
  582. running.push({ gate: ready, promise: execute(ready) })
  583. console.log(`run-gates: start ${ready.label}`)
  584. madeProgress = true
  585. }
  586. if (running.length === 0) {
  587. let pending = gates.filter(gate => states.get(gate.id) === 'pending')
  588. while (pending.length > 0) {
  589. const gate = pending.find(item => (item.needs ?? []).some((id) => {
  590. const state = states.get(id)
  591. return state === 'failed' || state === 'skipped'
  592. }))
  593. if (gate === undefined) throw new Error('run-gates: validated graph stalled without a failed dependency.')
  594. const failedDeps = (gate.needs ?? []).filter((id) => {
  595. const state = states.get(id)
  596. return state === 'failed' || state === 'skipped'
  597. })
  598. const result: GateResult = {
  599. gate,
  600. status: 'skipped',
  601. durationMs: 0,
  602. output: [],
  603. exitCode: null,
  604. signalCode: null,
  605. error: `dependency failed or skipped: ${failedDeps.join(', ')}`,
  606. }
  607. states.set(gate.id, 'skipped')
  608. results.set(gate.id, result)
  609. observe(result)
  610. pending = pending.filter(item => item !== gate)
  611. }
  612. break
  613. }
  614. if (!madeProgress) {
  615. const settled = await Promise.race(running.map(async item => ({ item, result: await item.promise })))
  616. running.splice(running.indexOf(settled.item), 1)
  617. states.set(settled.item.gate.id, settled.result.status)
  618. results.set(settled.item.gate.id, settled.result)
  619. observe(settled.result)
  620. }
  621. }
  622. return gates.map((gate) => {
  623. const result = results.get(gate.id)
  624. if (result === undefined) throw new Error(`run-gates: missing result for ${gate.id}.`)
  625. return result
  626. })
  627. }
  628. function dependenciesPassed(gate: Gate, states: Map<string, GateState>): boolean {
  629. return (gate.needs ?? []).every(id => states.get(id) === 'passed')
  630. }
  631. /**
  632. * Execute one gate through the real shell-free child-process boundary.
  633. * @param gate - command and scheduler environment to execute.
  634. * @returns the complete process outcome.
  635. */
  636. export async function runGate(gate: Gate): Promise<GateResult> {
  637. const started = performance.now()
  638. const output: GateOutputChunk[] = []
  639. let spawnError: string | undefined
  640. const outcome = await new Promise<{
  641. exitCode: number | null
  642. signalCode: NodeJS.Signals | null
  643. }>((resolveExit) => {
  644. const child = spawn(gate.command, gate.args, {
  645. cwd: root,
  646. env: { ...process.env, ...gate.env },
  647. stdio: ['pipe', 'pipe', 'pipe'],
  648. })
  649. child.stdout.setEncoding('utf8')
  650. child.stderr.setEncoding('utf8')
  651. child.stdout.on('data', (chunk: string) => {
  652. output.push({ stream: 'stdout', text: chunk })
  653. })
  654. child.stderr.on('data', (chunk: string) => {
  655. output.push({ stream: 'stderr', text: chunk })
  656. })
  657. child.on('error', (error) => {
  658. spawnError = `failed to start command: ${error.message}`
  659. resolveExit({ exitCode: null, signalCode: null })
  660. })
  661. child.on('close', (exitCode, signalCode) => {
  662. resolveExit({ exitCode, signalCode })
  663. })
  664. child.stdin.end()
  665. })
  666. const { exitCode, signalCode } = outcome
  667. const status: GateResultStatus = exitCode === 0 && signalCode === null && spawnError === undefined ? 'passed' : 'failed'
  668. const result: GateResult = {
  669. gate,
  670. status,
  671. durationMs: performance.now() - started,
  672. output,
  673. exitCode,
  674. signalCode,
  675. }
  676. if (spawnError !== undefined) result.error = spawnError
  677. return result
  678. }
  679. /**
  680. * Format every independently observed failure fact for the aggregate summary.
  681. * @param result - unsuccessful gate result.
  682. * @returns error, exit, and signal facts without allowing one to hide another.
  683. */
  684. export function formatGateResultReason(result: GateResult): string {
  685. const facts: string[] = []
  686. if (result.error !== undefined) facts.push(result.error)
  687. if (result.exitCode !== null) facts.push(`exit ${result.exitCode}`)
  688. if (result.signalCode !== null) facts.push(`signal ${result.signalCode}`)
  689. return facts.length === 0 ? 'no exit code or signal' : facts.join(', ')
  690. }
  691. function printResult(result: GateResult): void {
  692. const verbose = process.env.DSH_GATE_VERBOSE === '1'
  693. const seconds = (result.durationMs / 1000).toFixed(2)
  694. if (result.status === 'passed' && !verbose) {
  695. console.log(`run-gates: PASS ${result.gate.label} (${seconds}s)`)
  696. return
  697. }
  698. const heading = `${result.status.toUpperCase()} ${result.gate.label} (${seconds}s)`
  699. const writeHeading = result.status === 'passed' ? console.log : console.error
  700. writeHeading(`\n== ${heading} ==`)
  701. if (result.status !== 'passed') {
  702. console.error(`command: ${result.gate.displayCommand}`)
  703. console.error(`outcome: ${formatGateResultReason(result)}`)
  704. }
  705. printOutput(result.output)
  706. }
  707. function printSummary(results: GateResult[], durationMs: number): void {
  708. const passed = results.filter(result => result.status === 'passed').length
  709. const failed = results.filter(result => result.status === 'failed').length
  710. const skipped = results.filter(result => result.status === 'skipped').length
  711. const seconds = (durationMs / 1000).toFixed(2)
  712. console.log(`\nrun-gates: ${passed} passed, ${failed} failed, ${skipped} skipped in ${seconds}s.`)
  713. const unsuccessful = results.filter(result => result.status === 'failed' || result.status === 'skipped')
  714. if (unsuccessful.length === 0) return
  715. console.error('run-gates: unsuccessful gates:')
  716. for (const result of unsuccessful) {
  717. const duration = (result.durationMs / 1000).toFixed(2)
  718. const reason = formatGateResultReason(result)
  719. const disposition = result.gate.allowFailure === true ? 'NON-BLOCKING ' : ''
  720. console.error(` - ${disposition}${result.status.toUpperCase()} ${result.gate.label} (${duration}s, ${reason})`)
  721. console.error(` ${result.gate.displayCommand}`)
  722. }
  723. }
  724. function printOutput(output: GateOutputChunk[]): void {
  725. for (const chunk of output) {
  726. if (chunk.stream === 'stdout') process.stdout.write(chunk.text)
  727. else process.stderr.write(chunk.text)
  728. }
  729. }