run-gates.ts 36 KB

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