run-gates.ts 37 KB

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