run-gates.ts 33 KB

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