run-gates.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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. expectedOutputGate(),
  227. pnpmScript('build', 'build'),
  228. pnpmScript('build:web', 'build:web'),
  229. ...hygieneLeafGates({ artifactNeeds: ['build'] }),
  230. ...docSyncLeafGates({
  231. docTypecheckNeeds: ['build'],
  232. docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  233. docTypecheckScript: 'doc-typecheck:contracts-ready',
  234. }),
  235. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  236. ]
  237. case 'hygiene':
  238. return [
  239. ...hygieneLeafGates(),
  240. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  241. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  242. pnpmScript('vendored-links', 'verify-vendored-links', { label: 'vendored links' }),
  243. ]
  244. case 'doc-sync':
  245. return docSyncLeafGates()
  246. }
  247. }
  248. function ciSharedStaticGates(): Gate[] {
  249. return [
  250. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  251. pnpmScript('application-entrypoints', 'verify-application-entrypoints', { label: 'application entrypoints' }),
  252. pnpmScript('constraints', 'constraints'),
  253. pnpmScript('dsh-package-licenses', 'verify-dsh-package-licenses', { label: 'DSH package licenses' }),
  254. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  255. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  256. pnpmScript('optional-dependency-imports', 'verify-optional-dependency-imports', {
  257. label: 'optional dependency imports',
  258. }),
  259. pnpmScript('client-packages', 'verify-client-packages', { label: 'client packages' }),
  260. pnpmScript('client-ui-i18n', 'verify-client-ui-i18n', { label: 'client UI i18n' }),
  261. pnpmScript('issue-management', 'test:issue-management', { label: 'Issue management policy' }),
  262. ]
  263. }
  264. function ciPrimaryGates(): Gate[] {
  265. return [
  266. ...ciSharedStaticGates(),
  267. typertContractsGate(),
  268. pnpmScript('typecheck', 'typecheck:contracts-ready', { needs: ['typert-contracts'] }),
  269. lintGate({ needs: ['typert-contracts'] }),
  270. pnpmScript('duplication', 'duplication'),
  271. ...coverageGates(),
  272. ...nodeCompatSmokeGates(),
  273. snapshotGate(),
  274. ...docSyncLeafGates({
  275. docTypecheckNeeds: ['typert-contracts'],
  276. docTypecheckScript: 'doc-typecheck:contracts-ready',
  277. }),
  278. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  279. pnpmScript('knip', 'knip'),
  280. // The prepared typecheck and build both drive Client tsc, while build also
  281. // repeats the Host contract pass. Wait for all three consumers so build
  282. // neither races tsbuildinfo nor replaces declarations while they are read.
  283. ciBuildGate('build', { needs: ['typecheck', 'lint', 'doc-typecheck'] }),
  284. pnpmScript('publint', 'publint', { needs: ['build'] }),
  285. pnpmScript('node-next-types', 'verify-node-next-types', {
  286. label: 'node-next types',
  287. needs: ['build'],
  288. }),
  289. builtPackageInvariantsGate(['build']),
  290. builtBinSmokeGate(),
  291. ]
  292. }
  293. function nodeCompatGates(): Gate[] {
  294. const typecheck = flagEnabled('DSH_NODE_COMPAT_SKIP_TYPECHECK')
  295. ? []
  296. : [pnpmScript('typecheck', 'typecheck')]
  297. if (runningNodeMajor() !== 22) {
  298. return [...typecheck, ...nodeCompatSmokeGates()]
  299. }
  300. return [
  301. ...typecheck,
  302. pnpmScript('build', 'build', {
  303. ...typecheck.length === 0 ? {} : { needs: ['typecheck'] },
  304. }),
  305. pnpmScript('build:web', 'build:web', {
  306. label: 'Web frontend build',
  307. needs: ['build'],
  308. }),
  309. ...nodeCompatSmokeGates({ cliSmoke: true }),
  310. ]
  311. }
  312. function nodeCompatSmokeGates(options: { cliSmoke?: boolean } = {}): Gate[] {
  313. const gates: Gate[] = [
  314. pnpmExec('source-worker-smoke', [
  315. 'vitest',
  316. 'run',
  317. 'packages/workflow/workflow-worker-thread/tests/source-worker.compat.spec.ts',
  318. ], { label: 'source worker smoke' }),
  319. pnpmExec('jsonl-zstd-smoke', [
  320. 'vitest',
  321. 'run',
  322. 'packages/session/session-persistence-jsonl/tests/zstd.compat.spec.ts',
  323. ], { label: 'JSONL Zstandard smoke' }),
  324. pnpmExec('dsh-source-launch-smoke', [
  325. 'vitest',
  326. 'run',
  327. 'apps/cli/tests/source-launch.compat.spec.ts',
  328. ], { label: 'dsh source-launch smoke' }),
  329. pnpmExec('vitest-jsdom-smoke', [
  330. 'vitest',
  331. 'run',
  332. 'scripts/vitest-environment.compat.spec.ts',
  333. ], { label: 'Vitest jsdom smoke' }),
  334. ]
  335. if (options.cliSmoke) {
  336. gates.push(
  337. pnpmExec('cli-lazy-search-startup-smoke', [
  338. 'vitest',
  339. 'run',
  340. 'apps/cli/tests/lazy-search-startup.compat.spec.ts',
  341. ], {
  342. label: 'CLI lazy-search startup smoke',
  343. env: { DSH_REQUIRE_BUILT_CLI_SMOKE: '1' },
  344. needs: ['build:web'],
  345. }),
  346. )
  347. }
  348. return gates
  349. }
  350. /** Active Node major used to select version-specific compatibility checks. */
  351. function runningNodeMajor(): number {
  352. const major = Number.parseInt(process.versions.node.split('.')[0] ?? '', 10)
  353. if (!Number.isSafeInteger(major)) {
  354. throw new Error(`run-gates: cannot parse Node version ${JSON.stringify(process.versions.node)}.`)
  355. }
  356. return major
  357. }
  358. function ciStaticGates(options: { ownsBuild: boolean }): Gate[] {
  359. return [
  360. ...ciSharedStaticGates(),
  361. ...options.ownsBuild ? [ciBuildGate()] : [],
  362. ...docSyncLeafGates({
  363. includeDocTypecheck: options.ownsBuild,
  364. ...options.ownsBuild
  365. ? {
  366. docTypecheckNeeds: ['build'],
  367. docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  368. docTypecheckScript: 'doc-typecheck:contracts-ready',
  369. }
  370. : {},
  371. docsBuildScript: 'docs:build:mpa',
  372. }),
  373. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  374. pnpmScript('knip', 'knip'),
  375. ]
  376. }
  377. function ciArtifactGates(): Gate[] {
  378. return [
  379. ciBuildGate(),
  380. pnpmScript('publint', 'publint', { needs: ['build'] }),
  381. pnpmScript('node-next-types', 'verify-node-next-types', {
  382. label: 'node-next types',
  383. needs: ['build'],
  384. }),
  385. builtPackageInvariantsGate(['build']),
  386. builtBinSmokeGate(),
  387. ]
  388. }
  389. function ciConsumerGates(): Gate[] {
  390. const builtTree = ['build']
  391. const validatedBuild = ['built-package-invariants']
  392. return [
  393. ciBuildGate(),
  394. pnpmScript('node-compat', 'check:node-compat', {
  395. label: 'Node compatibility',
  396. env: { [CLIENT_BUILD_PROFILE_SELECTOR]: 'official' },
  397. }),
  398. pnpmScript('publint', 'publint', { needs: builtTree }),
  399. builtPackageInvariantsGate(builtTree),
  400. pnpmScript('lint-and-duplication', 'check:ci:lint:contracts-ready', {
  401. label: 'lint and duplication',
  402. needs: validatedBuild,
  403. }),
  404. snapshotGate(validatedBuild),
  405. expectedOutputGate(validatedBuild),
  406. webSnapshotGate(validatedBuild),
  407. pnpmScript('doc-typecheck', 'doc-typecheck:contracts-ready', {
  408. needs: validatedBuild,
  409. env: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  410. }),
  411. pnpmScript('node-next-types', 'verify-node-next-types', {
  412. label: 'node-next types',
  413. needs: validatedBuild,
  414. }),
  415. builtBinSmokeGate(validatedBuild),
  416. ]
  417. }
  418. function webSnapshotGate(needs: string[]): Gate {
  419. const workerRaw = process.env.DSH_WEB_SNAPSHOT_WORKERS
  420. if (workerRaw !== undefined && workerRaw !== '') {
  421. const workers = Number.parseInt(workerRaw, 10)
  422. if (!Number.isSafeInteger(workers) || workers < 2 || String(workers) !== workerRaw) {
  423. throw new Error(`run-gates: DSH_WEB_SNAPSHOT_WORKERS must be an integer greater than 1, got ${JSON.stringify(workerRaw)}.`)
  424. }
  425. return pnpmScript('web-snapshot', 'test:web:ci', {
  426. label: 'web browser snapshot',
  427. displayCommand: `DSH_SNAPSHOT=replay DSH_WEB_SNAPSHOT_WORKERS=${workers} pnpm run test:web:ci`,
  428. env: { DSH_SNAPSHOT: 'replay' },
  429. needs,
  430. streamOutput: true,
  431. })
  432. }
  433. return pnpmScript('web-snapshot', 'test:web:built', {
  434. label: 'web browser snapshot',
  435. displayCommand: 'DSH_SNAPSHOT=replay pnpm run test:web:built',
  436. env: { DSH_SNAPSHOT: 'replay' },
  437. needs,
  438. })
  439. }
  440. function ciWindowsBlockingGates(): Gate[] {
  441. return [
  442. ciBuildGate('windows-build', { label: 'build' }),
  443. pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
  444. ]
  445. }
  446. function ciWindowsCompleteGates(): Gate[] {
  447. const coverage = coverageGates().map(gate => ({
  448. ...gate,
  449. needs: [...new Set(['build', ...(gate.needs ?? [])])],
  450. }))
  451. const coverageAfter = coverage.map(gate => gate.id)
  452. const observational = ciWindowsObservationalGates()
  453. // The required production site replaces the observational MPA build; both
  454. // VitePress modes write the same output directory and cannot overlap.
  455. .filter(gate => gate.id !== 'build' && gate.id !== 'docs-site-build')
  456. .map(gate => ({
  457. ...gate,
  458. allowFailure: true,
  459. after: [...new Set([...coverageAfter, ...(gate.after ?? [])])],
  460. }))
  461. return [
  462. ciBuildGate(),
  463. pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
  464. ...coverage,
  465. ...observational,
  466. ]
  467. }
  468. function ciWindowsObservationalGates(): Gate[] {
  469. return [
  470. ...ciStaticGates({ ownsBuild: true }),
  471. // Linux owns required lint and snapshots; Windows omits those duplicates.
  472. pnpmScript('duplication', 'duplication'),
  473. pnpmScript('publint', 'publint', { needs: ['build'] }),
  474. pnpmScript('node-next-types', 'verify-node-next-types', {
  475. label: 'node-next types',
  476. needs: ['build'],
  477. }),
  478. builtPackageInvariantsGate(['build']),
  479. builtBinSmokeGate(),
  480. ]
  481. }
  482. function typertContractsGate(): Gate {
  483. return pnpmScript('typert-contracts', 'build:lib:host', { label: 'Typert contracts' })
  484. }
  485. function lintGate(options: { needs?: string[] } = {}): Gate {
  486. const raw = process.env.DSH_OXLINT_THREADS
  487. const script = 'lint:contracts-ready'
  488. return pnpmScript('lint', script, {
  489. ...raw === undefined || raw === ''
  490. ? {}
  491. : { displayCommand: `DSH_OXLINT_THREADS=${raw} pnpm run ${script}` },
  492. ...options.needs === undefined ? {} : { needs: options.needs },
  493. })
  494. }
  495. // The heavy suites run uninstrumented beside the thresholded gate: their
  496. // compiler- and subprocess-bound fixtures pay a multiple of their runtime
  497. // under v8 instrumentation while contributing nothing the thresholds need
  498. // (membership rules in scripts/coverage-exempt.ts).
  499. //
  500. // DSH_COVERAGE_MAX_WORKERS is the ordinary lane's worker budget, so the two
  501. // parallel gates split it instead of each claiming it whole. When
  502. // DSH_COVERAGE_PARTITIONS is set, its single-worker processes replace the
  503. // instrumented share while this budget still sizes the exempt gate. The exempt
  504. // gate's wall clock is dominated by its longest single file, so it takes the
  505. // small share. A budget of 1 gives each gate 1 worker; lanes that need a strict
  506. // total of one (the serial reference jobs) also set DSH_GATE_CONCURRENCY=1,
  507. // which keeps the gates from overlapping at all.
  508. // DSH_COVERAGE_TEST_TIMEOUT_MS raises Vitest's per-test and expect.poll
  509. // defaults together for instrumented lanes whose scheduling overhead exceeds
  510. // those defaults. Explicit fixture timeouts remain authoritative.
  511. function coverageWorkerArgs(): { instrumented: string[]; exempt: string[] } {
  512. const [flag] = positiveIntArg('DSH_COVERAGE_MAX_WORKERS', '--maxWorkers')
  513. if (flag === undefined) return { instrumented: [], exempt: [] }
  514. const total = Number.parseInt(flag.split('=')[1] ?? '', 10)
  515. const exempt = Math.max(1, Math.floor(total / 3))
  516. const instrumented = Math.max(1, total - exempt)
  517. return {
  518. instrumented: [`--maxWorkers=${String(instrumented)}`],
  519. exempt: [`--maxWorkers=${String(exempt)}`],
  520. }
  521. }
  522. function coverageGates(): Gate[] {
  523. const workers = coverageWorkerArgs()
  524. const timeouts = coverageTestTimeoutArgs(process.env[COVERAGE_TEST_TIMEOUT_ENV])
  525. const partitions = parseCoveragePartitionCount(process.env[COVERAGE_PARTITIONS_ENV])
  526. const instrumented = partitions === undefined
  527. ? pnpmExec('coverage', [
  528. 'vitest',
  529. 'run',
  530. '--coverage',
  531. ...workers.instrumented,
  532. ...timeouts,
  533. ], {
  534. label: 'test:coverage',
  535. env: { [COVERAGE_EXEMPT_ENV]: '1' },
  536. })
  537. : pnpmScript('coverage', 'test:coverage:partitioned', {
  538. label: 'test:coverage',
  539. displayCommand: `${COVERAGE_PARTITIONS_ENV}=${partitions} pnpm run test:coverage:partitioned`,
  540. env: { [COVERAGE_EXEMPT_ENV]: '1' },
  541. streamOutput: true,
  542. })
  543. return [
  544. instrumented,
  545. pnpmExec('coverage-exempt-heavy', [
  546. 'vitest',
  547. 'run',
  548. ...coverageExemptHeavySuites.map(suite => suite.filter),
  549. ...workers.exempt,
  550. ...timeouts,
  551. ], {
  552. label: 'test:coverage-exempt-heavy',
  553. }),
  554. ]
  555. }
  556. // Recorded-session adapters boot process scenarios in `lib` mode. Callers wait
  557. // either on `build` or on a validation gate that transitively owns that build.
  558. function snapshotGate(needs: string[] = ['build']): Gate {
  559. return pnpmScript('snapshot', 'test:snapshot', {
  560. env: { DSH_EXAMPLE_MODE: 'lib' },
  561. needs,
  562. })
  563. }
  564. // Owner-local process expectations consume built package exports without entering
  565. // the recorded-session corpus or the credentialed provider lane.
  566. function expectedOutputGate(needs: string[] = ['build']): Gate {
  567. return pnpmScript('expected-output', 'test:expected', {
  568. env: { DSH_EXAMPLE_MODE: 'lib' },
  569. needs,
  570. })
  571. }
  572. function builtPackageInvariantsGate(needs?: string[]): Gate {
  573. return pnpmScript('built-package-invariants', 'verify-built-package-invariants', {
  574. label: 'built package invariants',
  575. ...needs === undefined ? {} : { needs },
  576. })
  577. }
  578. function positiveIntArg(envName: string, flag: string): string[] {
  579. const raw = process.env[envName]
  580. if (raw === undefined || raw === '') return []
  581. const parsed = Number.parseInt(raw, 10)
  582. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  583. throw new Error(`run-gates: ${envName} must be a positive integer, got ${JSON.stringify(raw)}.`)
  584. }
  585. return [`${flag}=${raw}`]
  586. }
  587. function flagEnabled(envName: string): boolean {
  588. const raw = process.env[envName]
  589. if (raw === undefined || raw === '') return false
  590. if (raw !== '1') throw new Error(`run-gates: ${envName} must be 1 when set, got ${JSON.stringify(raw)}.`)
  591. return true
  592. }
  593. function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] {
  594. const artifactOptions = options.artifactNeeds === undefined ? {} : { needs: options.artifactNeeds }
  595. return [
  596. pnpmScript('rescope-vendor', 'rescope-vendor:check', { label: 'vendor rescope' }),
  597. pnpmScript('knip', 'knip'),
  598. pnpmScript('publint', 'publint', artifactOptions),
  599. pnpmScript('constraints', 'constraints'),
  600. pnpmScript('application-entrypoints', 'verify-application-entrypoints', { label: 'application entrypoints' }),
  601. pnpmScript('dsh-package-licenses', 'verify-dsh-package-licenses', { label: 'DSH package licenses' }),
  602. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  603. builtPackageInvariantsGate(options.artifactNeeds),
  604. pnpmScript('node-next-types', 'verify-node-next-types', {
  605. label: 'node-next types',
  606. ...artifactOptions,
  607. }),
  608. pnpmScript('optional-dependency-imports', 'verify-optional-dependency-imports', {
  609. label: 'optional dependency imports',
  610. }),
  611. pnpmScript('client-packages', 'verify-client-packages', { label: 'client packages' }),
  612. pnpmScript('client-ui-i18n', 'verify-client-ui-i18n', { label: 'client UI i18n' }),
  613. ]
  614. }
  615. function docSyncLeafGates(options: {
  616. includeDocTypecheck?: boolean
  617. docTypecheckNeeds?: string[]
  618. docTypecheckEnv?: Record<string, string | undefined>
  619. docTypecheckScript?: 'doc-typecheck' | 'doc-typecheck:contracts-ready'
  620. docsBuildScript?: 'docs:build' | 'docs:build:mpa'
  621. } = {}): Gate[] {
  622. const docTypecheckOptions: Partial<Gate> = {}
  623. if (options.docTypecheckNeeds !== undefined) docTypecheckOptions.needs = options.docTypecheckNeeds
  624. if (options.docTypecheckEnv !== undefined) docTypecheckOptions.env = options.docTypecheckEnv
  625. return [
  626. // Stable FIFO starts the longest leaves first; only docs-site-build writes website/.generated.
  627. ...options.includeDocTypecheck === false
  628. ? []
  629. : [pnpmScript('doc-typecheck', options.docTypecheckScript ?? 'doc-typecheck', docTypecheckOptions)],
  630. pnpmScript('docs-site-build', options.docsBuildScript ?? 'docs:build', { label: 'documentation build' }),
  631. pnpmScript('doc-graphs', 'verify-doc-graphs', { label: 'doc graphs' }),
  632. pnpmScript('markdown-links', 'verify-md-links', { label: 'markdown links' }),
  633. pnpmScript('type-equivalence', 'verify-type-equiv', { label: 'type equivalence' }),
  634. pnpmScript('cordis-catalog', 'verify-cordis-catalog', { label: 'cordis catalog' }),
  635. pnpmScript('cordis-inspect-catalog', 'verify-cordis-inspect-catalog', { label: 'Cordis inspect catalog' }),
  636. pnpmScript('mermaid', 'verify-mermaid'),
  637. pnpmScript('scoped-events', 'verify-scoped-events', { label: 'scoped events' }),
  638. pnpmScript('translation-pairing', 'verify-translation-pairing', { label: 'translation pairing' }),
  639. pnpmScript('markdown-wrap', 'verify-md-wrap', { label: 'markdown wrap' }),
  640. pnpmScript('client-catalog', 'verify-client-catalog', { label: 'client catalog' }),
  641. pnpmScript('export-jsdoc', 'verify-export-jsdoc', { label: 'export jsdoc' }),
  642. pnpmScript('tool-catalog', 'verify-tool-catalog', { label: 'tool catalog' }),
  643. pnpmScript('config-catalog', 'verify-config-catalog', { label: 'config catalog' }),
  644. pnpmScript('persistence-catalog', 'verify-persistence-catalog', { label: 'persistence catalog' }),
  645. pnpmScript('public-repository-links', 'verify-public-repository-links', { label: 'public repository links' }),
  646. pnpmScript('doc-refs', 'verify-doc-refs', { label: 'doc refs' }),
  647. pnpmScript('subsystem-pages', 'verify-subsystem-pages', { label: 'subsystem pages' }),
  648. pnpmScript('package-paths', 'verify-package-paths', { label: 'package paths' }),
  649. pnpmScript('config-source-ownership', 'verify-config-source-ownership', { label: 'config source ownership' }),
  650. pnpmScript('package-readme-model-experience', 'verify-package-readme-model-experience', { label: 'package README model experience' }),
  651. pnpmScript('agent-note-classification', 'verify-agent-note-classification', { label: 'agent note classification' }),
  652. pnpmScript('agent-note-format', 'verify-agent-note-format', { label: 'agent note format' }),
  653. pnpmScript('archived-agent-notes', 'verify-archived-agent-notes', { label: 'archived agent notes' }),
  654. pnpmScript('skill-invocation-metadata', 'verify-skill-invocation-metadata', { label: 'skill invocation metadata' }),
  655. pnpmScript('translation-prompt', 'verify-translation-prompt', { label: 'translation prompt' }),
  656. pnpmScript('doc-budgets', 'verify-doc-budgets', { label: 'doc budgets' }),
  657. pnpmExec('docs-site-projection', ['vitest', 'run', 'scripts/project-doc-site.spec.ts', 'scripts/verify-doc-site-fragments.spec.ts'], {
  658. label: 'documentation site checks',
  659. }),
  660. pnpmScript('package-readme-limitations', 'verify-package-readme-limitations', { label: 'package README limitations' }),
  661. ]
  662. }
  663. function builtBinSmokeGate(needs: string[] = ['build']): Gate {
  664. return pnpmExec('built-bin-smoke', [
  665. 'vitest',
  666. 'run',
  667. '--config',
  668. 'vitest.e2e.config.ts',
  669. 'apps/cli/tests/profiles/headless/tests/keyless-smoke.e2e.ts',
  670. 'apps/cli/tests/built-bin.e2e.ts',
  671. 'packages/host/directory-picker-native/tests/built-worker.e2e.ts',
  672. 'packages/sdk/server/tests/built-scope-carrier.e2e.ts',
  673. 'packages/subagent/subagent-codex/tests/loader-composition.e2e.ts',
  674. 'packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts',
  675. 'packages/api/remotes/tests/built-lib.e2e.ts',
  676. // Built execution consumers: the only automated proof that package-name
  677. // imports reach their lib/ entrypoints under plain Node. The e2e lane runs
  678. // unbuilt, so these files self-skip there.
  679. 'packages/workflow/workflow-worker-thread/tests/built-worker.e2e.ts',
  680. 'packages/code-runtime/code-runtime-worker-thread/tests/built-lib.e2e.ts',
  681. 'packages/lsp/lsp-stdio/tests/built-lib.e2e.ts',
  682. ], {
  683. label: 'built-bin smoke',
  684. needs,
  685. env: { DSH_EXAMPLE_MODE: 'lib' },
  686. })
  687. }
  688. /**
  689. * Reject a gate list whose graph cannot be executed unambiguously.
  690. * @param gates - complete aggregate to validate.
  691. */
  692. function validateGateGraph(gates: readonly Gate[]): void {
  693. if (gates.length === 0) throw new Error('run-gates: gate graph has no gates.')
  694. const ids = new Set<string>()
  695. for (const gate of gates) {
  696. if (ids.has(gate.id)) throw new Error(`run-gates: duplicate gate id ${JSON.stringify(gate.id)}.`)
  697. ids.add(gate.id)
  698. }
  699. for (const gate of gates) {
  700. for (const dependency of gate.needs ?? []) {
  701. if (!ids.has(dependency)) {
  702. throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} depends on unknown gate ${JSON.stringify(dependency)}.`)
  703. }
  704. }
  705. for (const predecessor of gate.after ?? []) {
  706. if (!ids.has(predecessor)) {
  707. throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} waits for unknown gate ${JSON.stringify(predecessor)}.`)
  708. }
  709. }
  710. }
  711. const cycle = findDependencyCycle(gates)
  712. if (cycle !== undefined) throw new Error(`run-gates: dependency cycle: ${cycle.join(' -> ')}.`)
  713. }
  714. function findDependencyCycle(gates: readonly Gate[]): string[] | undefined {
  715. const byId = new Map(gates.map(gate => [gate.id, gate]))
  716. const complete = new Set<string>()
  717. const active = new Map<string, number>()
  718. const path: string[] = []
  719. const visit = (id: string): string[] | undefined => {
  720. if (complete.has(id)) return undefined
  721. const cycleStart = active.get(id)
  722. if (cycleStart !== undefined) return [...path.slice(cycleStart), id]
  723. const gate = byId.get(id)
  724. if (gate === undefined) return undefined
  725. active.set(id, path.length)
  726. path.push(id)
  727. for (const predecessor of [...(gate.needs ?? []), ...(gate.after ?? [])]) {
  728. const cycle = visit(predecessor)
  729. if (cycle !== undefined) return cycle
  730. }
  731. path.pop()
  732. active.delete(id)
  733. complete.add(id)
  734. return undefined
  735. }
  736. for (const gate of gates) {
  737. const cycle = visit(gate.id)
  738. if (cycle !== undefined) return cycle
  739. }
  740. return undefined
  741. }
  742. /**
  743. * Validate and run one aggregate before the injected executor can start a child.
  744. * @param gates - complete aggregate to execute.
  745. * @param maxActive - maximum concurrent child count.
  746. * @param execute - child-process executor.
  747. * @param observe - result observer invoked when each gate settles.
  748. * @returns results in aggregate order.
  749. */
  750. export async function runGates(
  751. gates: Gate[],
  752. maxActive: number,
  753. execute: GateExecutor,
  754. observe: ResultObserver = () => {},
  755. ): Promise<GateResult[]> {
  756. validateGateGraph(gates)
  757. if (!Number.isSafeInteger(maxActive) || maxActive < 1) {
  758. throw new Error(`run-gates: max concurrency must be a positive integer, got ${JSON.stringify(maxActive)}.`)
  759. }
  760. const states = new Map<string, GateState>(gates.map(gate => [gate.id, 'pending']))
  761. const results = new Map<string, GateResult>()
  762. const running: RunningGate[] = []
  763. for (;;) {
  764. let madeProgress = false
  765. while (running.length < maxActive) {
  766. const ready = gates.find(gate => states.get(gate.id) === 'pending' && predecessorsReady(gate, states))
  767. if (ready === undefined) break
  768. states.set(ready.id, 'running')
  769. running.push({ gate: ready, promise: execute(ready) })
  770. console.log(`run-gates: start ${ready.label}`)
  771. madeProgress = true
  772. }
  773. if (running.length === 0) {
  774. const pending = gates.filter(gate => states.get(gate.id) === 'pending')
  775. if (pending.length === 0) break
  776. const gate = pending.find(item => (item.needs ?? []).some(id => gateFailed(states.get(id))))
  777. if (gate === undefined) throw new Error('run-gates: validated graph stalled without a failed dependency.')
  778. const failedDeps = (gate.needs ?? []).filter(id => gateFailed(states.get(id)))
  779. const result: GateResult = {
  780. gate,
  781. status: 'skipped',
  782. durationMs: 0,
  783. output: [],
  784. exitCode: null,
  785. signalCode: null,
  786. error: `dependency failed or skipped: ${failedDeps.join(', ')}`,
  787. }
  788. states.set(gate.id, 'skipped')
  789. results.set(gate.id, result)
  790. observe(result)
  791. continue
  792. }
  793. if (!madeProgress) {
  794. const settled = await Promise.race(running.map(async item => ({ item, result: await item.promise })))
  795. running.splice(running.indexOf(settled.item), 1)
  796. states.set(settled.item.gate.id, settled.result.status)
  797. results.set(settled.item.gate.id, settled.result)
  798. observe(settled.result)
  799. }
  800. }
  801. return gates.map((gate) => {
  802. const result = results.get(gate.id)
  803. if (result === undefined) throw new Error(`run-gates: missing result for ${gate.id}.`)
  804. return result
  805. })
  806. }
  807. function predecessorsReady(gate: Gate, states: Map<string, GateState>): boolean {
  808. return (gate.needs ?? []).every(id => states.get(id) === 'passed')
  809. && (gate.after ?? []).every(id => gateSettled(states.get(id)))
  810. }
  811. function gateSettled(state: GateState | undefined): boolean {
  812. return state === 'passed' || state === 'failed' || state === 'skipped'
  813. }
  814. function gateFailed(state: GateState | undefined): boolean {
  815. return state === 'failed' || state === 'skipped'
  816. }
  817. /**
  818. * Execute one gate through the real shell-free child-process boundary.
  819. * @param gate - command and scheduler environment to execute.
  820. * @returns the complete process outcome.
  821. */
  822. export async function runGate(gate: Gate): Promise<GateResult> {
  823. const started = performance.now()
  824. const output: GateOutputChunk[] = []
  825. let spawnError: string | undefined
  826. const outcome = await new Promise<{
  827. exitCode: number | null
  828. signalCode: NodeJS.Signals | null
  829. }>((resolveExit) => {
  830. const child = spawn(gate.command, gate.args, {
  831. cwd: root,
  832. env: { ...process.env, ...gate.env },
  833. stdio: ['pipe', 'pipe', 'pipe'],
  834. })
  835. child.stdout.setEncoding('utf8')
  836. child.stderr.setEncoding('utf8')
  837. child.stdout.on('data', (chunk: string) => {
  838. if (gate.streamOutput === true) process.stdout.write(chunk)
  839. else output.push({ stream: 'stdout', text: chunk })
  840. })
  841. child.stderr.on('data', (chunk: string) => {
  842. if (gate.streamOutput === true) process.stderr.write(chunk)
  843. else output.push({ stream: 'stderr', text: chunk })
  844. })
  845. child.on('error', (error) => {
  846. spawnError = `failed to start command: ${error.message}`
  847. resolveExit({ exitCode: null, signalCode: null })
  848. })
  849. child.on('close', (exitCode, signalCode) => {
  850. resolveExit({ exitCode, signalCode })
  851. })
  852. child.stdin.end()
  853. })
  854. const { exitCode, signalCode } = outcome
  855. const status: GateResultStatus = exitCode === 0 && signalCode === null && spawnError === undefined ? 'passed' : 'failed'
  856. const result: GateResult = {
  857. gate,
  858. status,
  859. durationMs: performance.now() - started,
  860. output,
  861. exitCode,
  862. signalCode,
  863. }
  864. if (spawnError !== undefined) result.error = spawnError
  865. return result
  866. }
  867. /**
  868. * Format every independently observed failure fact for the aggregate summary.
  869. * @param result - unsuccessful gate result.
  870. * @returns error, exit, and signal facts without allowing one to hide another.
  871. */
  872. export function formatGateResultReason(result: GateResult): string {
  873. const facts: string[] = []
  874. if (result.error !== undefined) facts.push(result.error)
  875. if (result.exitCode !== null) facts.push(`exit ${result.exitCode}`)
  876. if (result.signalCode !== null) facts.push(`signal ${result.signalCode}`)
  877. return facts.length === 0 ? 'no exit code or signal' : facts.join(', ')
  878. }
  879. function printResult(result: GateResult): void {
  880. const verbose = process.env.DSH_GATE_VERBOSE === '1'
  881. const seconds = (result.durationMs / 1000).toFixed(2)
  882. if (result.status === 'passed' && !verbose) {
  883. console.log(`run-gates: PASS ${result.gate.label} (${seconds}s)`)
  884. return
  885. }
  886. const heading = `${result.status.toUpperCase()} ${result.gate.label} (${seconds}s)`
  887. const writeHeading = result.status === 'passed' ? console.log : console.error
  888. writeHeading(`\n== ${heading} ==`)
  889. if (result.status !== 'passed') {
  890. console.error(`command: ${result.gate.displayCommand}`)
  891. console.error(`outcome: ${formatGateResultReason(result)}`)
  892. }
  893. if (result.gate.streamOutput !== true) printOutput(result.output)
  894. }
  895. function printSummary(results: GateResult[], durationMs: number): void {
  896. const passed = results.filter(result => result.status === 'passed').length
  897. const failed = results.filter(result => result.status === 'failed').length
  898. const skipped = results.filter(result => result.status === 'skipped').length
  899. const seconds = (durationMs / 1000).toFixed(2)
  900. console.log(`\nrun-gates: ${passed} passed, ${failed} failed, ${skipped} skipped in ${seconds}s.`)
  901. const unsuccessful = results.filter(result => result.status === 'failed' || result.status === 'skipped')
  902. if (unsuccessful.length === 0) return
  903. console.error('run-gates: unsuccessful gates:')
  904. for (const result of unsuccessful) {
  905. const duration = (result.durationMs / 1000).toFixed(2)
  906. const reason = formatGateResultReason(result)
  907. const disposition = result.gate.allowFailure === true ? 'NON-BLOCKING ' : ''
  908. console.error(` - ${disposition}${result.status.toUpperCase()} ${result.gate.label} (${duration}s, ${reason})`)
  909. console.error(` ${result.gate.displayCommand}`)
  910. }
  911. }
  912. function printOutput(output: GateOutputChunk[]): void {
  913. for (const chunk of output) {
  914. if (chunk.stream === 'stdout') process.stdout.write(chunk.text)
  915. else process.stderr.write(chunk.text)
  916. }
  917. }