run-gates.ts 29 KB

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