run-gates.ts 36 KB

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