run-gates.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. import { describe, expect, it, vi } from 'vitest'
  2. import {
  3. defaultConcurrency,
  4. formatGateResultReason,
  5. gatesForMode,
  6. runGate,
  7. runGates,
  8. type Gate,
  9. type GateResult,
  10. } from './run-gates.ts'
  11. function gate(id: string, options: Partial<Gate> = {}): Gate {
  12. return {
  13. id,
  14. label: id,
  15. displayCommand: `run ${id}`,
  16. command: process.execPath,
  17. args: ['-e', ''],
  18. ...options,
  19. }
  20. }
  21. function resultFor(subject: Gate, status: GateResult['status'] = 'passed'): GateResult {
  22. return {
  23. gate: subject,
  24. status,
  25. durationMs: 10,
  26. output: [],
  27. exitCode: status === 'passed' ? 0 : 1,
  28. signalCode: null,
  29. }
  30. }
  31. function withPnpmEntrypoint<T>(action: () => T, entrypoint = '/private/pnpm.cjs'): T {
  32. const previous = process.env.npm_execpath
  33. process.env.npm_execpath = entrypoint
  34. try {
  35. return action()
  36. } finally {
  37. if (previous === undefined) Reflect.deleteProperty(process.env, 'npm_execpath')
  38. else process.env.npm_execpath = previous
  39. }
  40. }
  41. function withEnv<T>(name: string, value: string | undefined, action: () => T): T {
  42. const previous = process.env[name]
  43. if (value === undefined) Reflect.deleteProperty(process.env, name)
  44. else process.env[name] = value
  45. try {
  46. return action()
  47. } finally {
  48. if (previous === undefined) Reflect.deleteProperty(process.env, name)
  49. else process.env[name] = previous
  50. }
  51. }
  52. describe('gate graph validation', () => {
  53. it.each([
  54. 'ci-primary',
  55. 'ci-linux-primary',
  56. 'ci-static',
  57. 'ci-lint-contracts-ready',
  58. 'ci-coverage',
  59. 'ci-snapshot',
  60. 'ci-artifacts',
  61. 'ci-consumers',
  62. 'ci-windows-blocking',
  63. 'ci-windows-complete',
  64. 'ci-windows-observational',
  65. 'node-compat',
  66. 'check-all',
  67. 'hygiene',
  68. 'doc-sync',
  69. ] as const)('constructs and executes preflight for a valid non-empty %s graph', async (mode) => {
  70. const subject = withPnpmEntrypoint(() => gatesForMode(mode))
  71. const execute = vi.fn(async (item: Gate) => resultFor(item))
  72. await expect(runGates(subject, subject.length, execute)).resolves.toHaveLength(subject.length)
  73. })
  74. it('keeps the public repository link policy in the documentation gate', () => {
  75. const ids = withPnpmEntrypoint(() => gatesForMode('doc-sync').map(subject => subject.id))
  76. expect(ids).toContain('public-repository-links')
  77. })
  78. it('keeps package-group subsystem ownership in the documentation gate', () => {
  79. const ids = withPnpmEntrypoint(() => gatesForMode('doc-sync').map(subject => subject.id))
  80. expect(ids).toContain('subsystem-pages')
  81. })
  82. it('keeps the hygiene aggregate aligned with the package script checks', () => {
  83. const ids = withPnpmEntrypoint(() => gatesForMode('hygiene').map(subject => subject.id))
  84. expect(ids).toEqual([
  85. 'rescope-vendor', 'knip', 'publint', 'constraints', 'application-entrypoints',
  86. 'dsh-package-licenses', 'package-invariants', 'built-package-invariants', 'node-next-types',
  87. 'optional-dependency-imports', 'client-packages', 'client-ui-i18n', 'cordis-config',
  88. 'runtime-closure', 'vendored-links',
  89. ])
  90. expect(defaultConcurrency('hygiene', ids.length, 8)).toEqual({
  91. workers: 4,
  92. source: '8 available CPU(s), hygiene cap 4',
  93. })
  94. })
  95. it('schedules the longest documentation leaves before short checks', () => {
  96. const ids = withPnpmEntrypoint(() => gatesForMode('doc-sync').map(subject => subject.id))
  97. expect(ids.slice(0, 10)).toEqual([
  98. 'doc-typecheck', 'docs-site-build', 'doc-graphs', 'markdown-links', 'type-equivalence',
  99. 'cordis-catalog', 'cordis-inspect-catalog', 'mermaid', 'scoped-events', 'translation-pairing',
  100. ])
  101. })
  102. it('launches a native pnpm entrypoint directly', () => {
  103. const entrypoint = String.raw`C:\Program Files\pnpm\pnpm.exe`
  104. const subject = withPnpmEntrypoint(() => gatesForMode('ci-windows-blocking')[0], entrypoint)
  105. expect(subject).toMatchObject({
  106. command: entrypoint,
  107. args: ['run', 'build'],
  108. })
  109. })
  110. it.each(['ci-primary', 'ci-static', 'check-all'] as const)(
  111. 'keeps the DSH package license policy in %s',
  112. (mode) => {
  113. const ids = withPnpmEntrypoint(() => gatesForMode(mode).map(subject => subject.id))
  114. expect(ids).toContain('dsh-package-licenses')
  115. },
  116. )
  117. it.each(['ci-primary', 'ci-static', 'check-all'] as const)(
  118. 'keeps the client dependency policy in %s',
  119. (mode) => {
  120. const ids = withPnpmEntrypoint(() => gatesForMode(mode).map(subject => subject.id))
  121. expect(ids).toContain('client-packages')
  122. },
  123. )
  124. it.each(['ci-primary', 'ci-static', 'check-all', 'hygiene'] as const)(
  125. 'keeps hard-coded Client UI copy enforcement in %s',
  126. (mode) => {
  127. const ids = withPnpmEntrypoint(() => gatesForMode(mode).map(subject => subject.id))
  128. expect(ids).toContain('client-ui-i18n')
  129. },
  130. )
  131. it.each(['ci-primary', 'ci-static', 'check-all', 'hygiene'] as const)(
  132. 'keeps application entrypoint enforcement in %s',
  133. (mode) => {
  134. const ids = withPnpmEntrypoint(() => gatesForMode(mode).map(subject => subject.id))
  135. expect(ids).toContain('application-entrypoints')
  136. },
  137. )
  138. it('keeps native Windows coverage blocking and behind the complete build', () => {
  139. const complete = withPnpmEntrypoint(() => gatesForMode('ci-windows-complete'))
  140. const observational = withPnpmEntrypoint(() => gatesForMode('ci-windows-observational'))
  141. .filter(gate => gate.id !== 'build' && gate.id !== 'docs-site-build')
  142. const byId = new Map(complete.map(subject => [subject.id, subject]))
  143. expect(byId.get('coverage')?.allowFailure).not.toBe(true)
  144. expect(byId.get('coverage')?.needs).toContain('build')
  145. expect(byId.get('coverage-exempt-heavy')?.allowFailure).not.toBe(true)
  146. expect(byId.get('coverage')?.needs).toContain('build')
  147. expect(byId.get('coverage-exempt-heavy')?.needs).toContain('build')
  148. expect(observational).not.toHaveLength(0)
  149. for (const gate of observational) {
  150. const completeGate = byId.get(gate.id)
  151. expect(completeGate?.allowFailure).toBe(true)
  152. expect(completeGate?.after).toEqual(expect.arrayContaining([
  153. 'coverage',
  154. 'coverage-exempt-heavy',
  155. ]))
  156. expect(completeGate?.needs).toEqual(gate.needs)
  157. }
  158. })
  159. it('applies one configured test and polling timeout to both coverage gates', () => {
  160. const gates = withEnv('DSH_COVERAGE_TEST_TIMEOUT_MS', '15000', () =>
  161. withPnpmEntrypoint(() => gatesForMode('ci-windows-complete')))
  162. for (const id of ['coverage', 'coverage-exempt-heavy']) {
  163. expect(gates.find(subject => subject.id === id)?.args).toEqual(expect.arrayContaining([
  164. '--testTimeout=15000',
  165. '--expect.poll.timeout=15000',
  166. ]))
  167. }
  168. })
  169. it('keeps Vitest timeout defaults when the coverage override is absent', () => {
  170. const gates = withEnv('DSH_COVERAGE_TEST_TIMEOUT_MS', undefined, () =>
  171. withPnpmEntrypoint(() => gatesForMode('ci-windows-complete')))
  172. for (const id of ['coverage', 'coverage-exempt-heavy']) {
  173. expect(gates.find(subject => subject.id === id)?.args).not.toEqual(expect.arrayContaining([
  174. expect.stringMatching(/^--(?:testTimeout|expect\.poll\.timeout)=/),
  175. ]))
  176. }
  177. })
  178. it('rejects an invalid coverage timeout before starting a gate', () => {
  179. expect(() => withEnv('DSH_COVERAGE_TEST_TIMEOUT_MS', '0', () =>
  180. withPnpmEntrypoint(() => gatesForMode('ci-windows-complete'))))
  181. .toThrow('DSH_COVERAGE_TEST_TIMEOUT_MS must be a positive integer')
  182. })
  183. it('selects partitioned coverage only when explicitly configured', () => {
  184. const coverage = withEnv('DSH_COVERAGE_PARTITIONS', '3', () =>
  185. withPnpmEntrypoint(() => gatesForMode('ci-windows-complete').find(subject => subject.id === 'coverage')))
  186. expect(coverage).toMatchObject({
  187. displayCommand: 'DSH_COVERAGE_PARTITIONS=3 pnpm run test:coverage:partitioned',
  188. args: ['/private/pnpm.cjs', 'run', 'test:coverage:partitioned'],
  189. streamOutput: true,
  190. })
  191. })
  192. it('rejects an invalid coverage partition count before starting a gate', () => {
  193. expect(() => withEnv('DSH_COVERAGE_PARTITIONS', '1', () =>
  194. withPnpmEntrypoint(() => gatesForMode('ci-windows-complete'))))
  195. .toThrow('DSH_COVERAGE_PARTITIONS must be an integer greater than 1')
  196. })
  197. it.each([
  198. ['empty', [], /gate graph has no gates/],
  199. ['duplicate ids', [gate('same'), gate('same')], /duplicate gate id "same"/],
  200. ['unknown dependencies', [gate('subject', { needs: ['missing'] })], /depends on unknown gate "missing"/],
  201. ['unknown ordering predecessors', [gate('subject', { after: ['missing'] })], /waits for unknown gate "missing"/],
  202. ['cycles', [gate('first', { needs: ['second'] }), gate('second', { needs: ['first'] })], /dependency cycle: first -> second -> first/],
  203. ['mixed cycles', [gate('first', { after: ['second'] }), gate('second', { needs: ['first'] })], /dependency cycle: first -> second -> first/],
  204. ] as const)('rejects %s before starting a child', async (_label, invalid, message) => {
  205. const execute = vi.fn(async (subject: Gate) => resultFor(subject))
  206. await expect(runGates([...invalid], 1, execute)).rejects.toThrow(message)
  207. expect(execute).not.toHaveBeenCalled()
  208. })
  209. it('rejects an invalid worker count before starting a child', async () => {
  210. const execute = vi.fn(async (subject: Gate) => resultFor(subject))
  211. await expect(runGates([gate('subject')], 0, execute)).rejects.toThrow('max concurrency must be a positive integer')
  212. expect(execute).not.toHaveBeenCalled()
  213. })
  214. it('skips dependents after their prerequisite fails', async () => {
  215. const dependent = gate('dependent', { needs: ['root'] })
  216. const root = gate('root')
  217. const execute = vi.fn(async (subject: Gate) => resultFor(subject, 'failed'))
  218. const results = await runGates([dependent, root], 1, execute)
  219. expect(execute).toHaveBeenCalledOnce()
  220. expect(execute).toHaveBeenCalledWith(root)
  221. expect(results[0]).toMatchObject({ gate: dependent, status: 'skipped', error: 'dependency failed or skipped: root' })
  222. })
  223. it('runs an ordered follower after its predecessor fails', async () => {
  224. const follower = gate('follower', { after: ['root'] })
  225. const root = gate('root')
  226. const execute = vi.fn(async (subject: Gate) => resultFor(subject, subject === root ? 'failed' : 'passed'))
  227. const results = await runGates([follower, root], 2, execute)
  228. expect(execute.mock.calls.map(([subject]) => subject.id)).toEqual(['root', 'follower'])
  229. expect(results.map(result => result.status)).toEqual(['passed', 'failed'])
  230. })
  231. it('runs an ordered follower after its predecessor is skipped', async () => {
  232. const follower = gate('follower', { after: ['dependent'] })
  233. const dependent = gate('dependent', { needs: ['root'] })
  234. const root = gate('root')
  235. const execute = vi.fn(async (subject: Gate) => resultFor(subject, subject === root ? 'failed' : 'passed'))
  236. const results = await runGates([follower, dependent, root], 2, execute)
  237. expect(execute.mock.calls.map(([subject]) => subject.id)).toEqual(['root', 'follower'])
  238. expect(results.map(result => result.status)).toEqual(['passed', 'skipped', 'failed'])
  239. })
  240. })
  241. describe('Oxlint gate', () => {
  242. it('uses the package script when no worker bound is configured', () => {
  243. const subject = withEnv('DSH_OXLINT_THREADS', undefined, () =>
  244. withPnpmEntrypoint(() => gatesForMode('ci-lint-contracts-ready')[0]))
  245. expect(subject).toMatchObject({
  246. id: 'lint',
  247. displayCommand: 'pnpm run lint:contracts-ready',
  248. command: process.execPath,
  249. args: ['/private/pnpm.cjs', 'run', 'lint:contracts-ready'],
  250. })
  251. })
  252. it('surfaces the configured worker bound on the shared package script', () => {
  253. const subject = withEnv('DSH_OXLINT_THREADS', '4', () =>
  254. withPnpmEntrypoint(() => gatesForMode('ci-lint-contracts-ready')[0]))
  255. expect(subject).toMatchObject({
  256. id: 'lint',
  257. displayCommand: 'DSH_OXLINT_THREADS=4 pnpm run lint:contracts-ready',
  258. command: process.execPath,
  259. args: ['/private/pnpm.cjs', 'run', 'lint:contracts-ready'],
  260. })
  261. })
  262. })
  263. describe('Typert contract preparation', () => {
  264. it('prepares primary source consumers once before they run', () => {
  265. const subject = withEnv('DSH_OXLINT_THREADS', undefined, () =>
  266. withPnpmEntrypoint(() => gatesForMode('ci-primary')))
  267. expect(subject.find(item => item.id === 'typert-contracts')).toMatchObject({
  268. displayCommand: 'pnpm run build:lib:host',
  269. args: ['/private/pnpm.cjs', 'run', 'build:lib:host'],
  270. })
  271. for (const [id, script] of [
  272. ['typecheck', 'typecheck:contracts-ready'],
  273. ['lint', 'lint:contracts-ready'],
  274. ['doc-typecheck', 'doc-typecheck:contracts-ready'],
  275. ] as const) {
  276. expect(subject.find(item => item.id === id)).toMatchObject({
  277. displayCommand: `pnpm run ${script}`,
  278. args: ['/private/pnpm.cjs', 'run', script],
  279. needs: ['typert-contracts'],
  280. })
  281. }
  282. expect(subject.find(item => item.id === 'build')?.needs).toEqual([
  283. 'typecheck',
  284. 'lint',
  285. 'doc-typecheck',
  286. ])
  287. })
  288. it('reuses contracts from the validated consumer build', () => {
  289. const subject = withPnpmEntrypoint(() => gatesForMode('ci-consumers'))
  290. expect(subject.find(item => item.id === 'lint-and-duplication')).toMatchObject({
  291. displayCommand: 'pnpm run check:ci:lint:contracts-ready',
  292. args: ['/private/pnpm.cjs', 'run', 'check:ci:lint:contracts-ready'],
  293. })
  294. expect(subject.find(item => item.id === 'doc-typecheck')).toMatchObject({
  295. displayCommand: 'pnpm run doc-typecheck:contracts-ready',
  296. args: ['/private/pnpm.cjs', 'run', 'doc-typecheck:contracts-ready'],
  297. })
  298. })
  299. it('keeps standalone doc sync responsible for preparation', () => {
  300. const docTypecheck = withPnpmEntrypoint(() =>
  301. gatesForMode('doc-sync').find(item => item.id === 'doc-typecheck'))
  302. expect(docTypecheck?.displayCommand).toBe('pnpm run doc-typecheck')
  303. })
  304. })
  305. describe('Node compatibility graph', () => {
  306. it('runs the jsdom environment smoke on every advertised Node line', () => {
  307. const subject = withPnpmEntrypoint(() => gatesForMode('node-compat'))
  308. expect(subject.find(item => item.id === 'vitest-jsdom-smoke')).toMatchObject({
  309. label: 'Vitest jsdom smoke',
  310. args: [
  311. '/private/pnpm.cjs',
  312. 'exec',
  313. 'vitest',
  314. 'run',
  315. 'scripts/vitest-environment.compat.spec.ts',
  316. ],
  317. })
  318. })
  319. })
  320. describe('Node 24 lane ownership', () => {
  321. it('keeps the static lane source-only', () => {
  322. const subject = withPnpmEntrypoint(() => gatesForMode('ci-static'))
  323. expect(subject.map(item => item.id)).not.toContain('build')
  324. expect(subject.map(item => item.id)).not.toContain('doc-typecheck')
  325. })
  326. it('owns the build and orders its artifact consumers', () => {
  327. const subject = withPnpmEntrypoint(() => gatesForMode('ci-consumers'))
  328. expect(defaultConcurrency('ci-consumers', subject.length, 4)).toEqual({
  329. workers: 11,
  330. source: 'ci-consumers gate count',
  331. })
  332. expect(subject.map(item => item.id)).toEqual([
  333. 'build',
  334. 'node-compat',
  335. 'publint',
  336. 'built-package-invariants',
  337. 'lint-and-duplication',
  338. 'snapshot',
  339. 'expected-output',
  340. 'web-snapshot',
  341. 'doc-typecheck',
  342. 'node-next-types',
  343. 'built-bin-smoke',
  344. ])
  345. expect(subject.find(item => item.id === 'publint')?.needs).toEqual(['build'])
  346. expect(subject.find(item => item.id === 'build')?.env).toEqual({
  347. DSH_BUILD_CLIENT_PROFILE: 'official',
  348. })
  349. expect(subject.find(item => item.id === 'node-compat')?.env).toEqual({
  350. DSH_BUILD_CLIENT_PROFILE: 'official',
  351. })
  352. expect(subject.find(item => item.id === 'built-package-invariants')?.needs).toEqual(['build'])
  353. expect(subject.find(item => item.id === 'lint-and-duplication')?.needs).toEqual(['built-package-invariants'])
  354. for (const id of [
  355. 'snapshot',
  356. 'expected-output',
  357. 'web-snapshot',
  358. 'doc-typecheck',
  359. 'node-next-types',
  360. 'built-bin-smoke',
  361. ]) {
  362. expect(subject.find(item => item.id === id)?.needs).toEqual(['built-package-invariants'])
  363. }
  364. expect(subject.find(item => item.id === 'snapshot')?.env).toEqual({ DSH_EXAMPLE_MODE: 'lib' })
  365. expect(subject.find(item => item.id === 'expected-output')?.env).toEqual({ DSH_EXAMPLE_MODE: 'lib' })
  366. expect(subject.find(item => item.id === 'doc-typecheck')?.env).toEqual({
  367. DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1',
  368. })
  369. expect(subject.find(item => item.id === 'built-bin-smoke')?.args).toEqual(
  370. expect.arrayContaining([
  371. 'packages/subagent/subagent-codex/tests/loader-composition.e2e.ts',
  372. 'packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts',
  373. ]),
  374. )
  375. expect(subject.find(item => item.id === 'web-snapshot')).toMatchObject({
  376. displayCommand: 'DSH_SNAPSHOT=replay pnpm run test:web:built',
  377. env: { DSH_SNAPSHOT: 'replay' },
  378. })
  379. })
  380. })
  381. describe('Linux primary graph', () => {
  382. it('adds the same compare-only web gate after built client artifacts', () => {
  383. const subject = withPnpmEntrypoint(() => gatesForMode('ci-linux-primary'))
  384. const web = subject.find(item => item.id === 'web-snapshot')
  385. expect(web).toMatchObject({
  386. displayCommand: 'DSH_SNAPSHOT=replay pnpm run test:web:built',
  387. env: { DSH_SNAPSHOT: 'replay' },
  388. needs: ['built-package-invariants'],
  389. })
  390. })
  391. })
  392. describe('gate process outcomes', () => {
  393. it('streams selected gate output without retaining it', async () => {
  394. const write = vi.spyOn(process.stdout, 'write').mockReturnValue(true)
  395. try {
  396. const result = await runGate(gate('streamed', {
  397. args: ['-e', "process.stdout.write('live output')"],
  398. streamOutput: true,
  399. }))
  400. expect(result.status).toBe('passed')
  401. expect(result.output).toEqual([])
  402. expect(write).toHaveBeenCalledWith('live output')
  403. } finally {
  404. write.mockRestore()
  405. }
  406. })
  407. it.skipIf(process.platform === 'win32')('reports signal termination independently from exit status', async () => {
  408. const result = await runGate(gate('terminated', {
  409. args: ['-e', "process.kill(process.pid, 'SIGTERM')"],
  410. }))
  411. expect(result.status).toBe('failed')
  412. expect(result.exitCode).toBeNull()
  413. expect(result.signalCode).toBe('SIGTERM')
  414. expect(formatGateResultReason(result)).toBe('signal SIGTERM')
  415. })
  416. })