run-gates.ts 32 KB

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