run-gates.ts 36 KB

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