run-gates.ts 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589
  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, spawnSync } from 'node:child_process'
  9. import { readdirSync, readFileSync } from 'node:fs'
  10. import { availableParallelism } from 'node:os'
  11. import { resolve } from 'node:path'
  12. import { performance } from 'node:perf_hooks'
  13. import { CLIENT_BUILD_PROFILE_SELECTOR } from './client-build-environment.ts'
  14. import { COVERAGE_EXEMPT_ENV, coverageExemptHeavySuites } from './coverage-exempt.ts'
  15. import {
  16. COVERAGE_PARTITIONS_ENV,
  17. COVERAGE_TEST_TIMEOUT_ENV,
  18. coverageTestTimeoutArgs,
  19. parseCoveragePartitionCount,
  20. } from './coverage-partitions.ts'
  21. import { pnpmInvocation } from './pnpm-invocation.ts'
  22. /** A named aggregate exposed by the gate runner. */
  23. export type Mode =
  24. | 'ci-primary'
  25. | 'ci-linux-primary'
  26. | 'ci-static'
  27. | 'ci-lint-contracts-ready'
  28. | 'ci-coverage'
  29. | 'ci-bench'
  30. | 'ci-snapshot'
  31. | 'ci-artifacts'
  32. | 'ci-consumers'
  33. | 'ci-windows-blocking'
  34. | 'ci-windows-complete'
  35. | 'ci-windows-observational'
  36. | 'node-compat'
  37. | 'check-all'
  38. | 'hygiene'
  39. | 'doc-sync'
  40. | 'doc-quick'
  41. type GateResultStatus = 'passed' | 'failed' | 'skipped'
  42. type GateState = 'pending' | 'running' | GateResultStatus
  43. /** A command and its dependency metadata inside one aggregate. */
  44. export interface Gate {
  45. id: string
  46. label: string
  47. displayCommand: string
  48. command: string
  49. args: string[]
  50. needs?: string[]
  51. /** Gate ids that must settle, regardless of outcome, before this gate starts. */
  52. after?: string[]
  53. env?: Record<string, string | undefined>
  54. /** Include this leaf in the build-free documentation aggregate. */
  55. quick?: boolean
  56. /** Keep a failure visible without failing the aggregate. */
  57. allowFailure?: boolean
  58. /** Write child output as it arrives instead of buffering it until completion. */
  59. streamOutput?: boolean
  60. }
  61. /** The observed outcome of one gate process. */
  62. export interface GateResult {
  63. gate: Gate
  64. status: GateResultStatus
  65. durationMs: number
  66. output: GateOutputChunk[]
  67. exitCode: number | null
  68. signalCode: NodeJS.Signals | null
  69. error?: string
  70. /** True when the shared abort signal terminated this gate before its outcome
  71. * was observed; such a result must not be reported as passed, even if the
  72. * child trapped the signal and exited zero. */
  73. aborted?: boolean
  74. }
  75. interface GateOutputChunk {
  76. stream: 'stdout' | 'stderr'
  77. text: string
  78. }
  79. interface RunningGate {
  80. gate: Gate
  81. promise: Promise<GateResult>
  82. }
  83. interface ConcurrencyDefault {
  84. workers: number
  85. source: string
  86. }
  87. type GateExecutor = (gate: Gate, signal?: AbortSignal) => Promise<GateResult>
  88. type ResultObserver = (result: GateResult) => void
  89. const root = resolve(import.meta.dirname, '..')
  90. if (import.meta.main) {
  91. process.exitCode = await main(process.argv.slice(2))
  92. }
  93. async function main(args: string[]): Promise<number> {
  94. const mode = parseMode(args[0])
  95. const gates = gatesForMode(mode)
  96. const concurrencyDefault = defaultConcurrency(mode, gates.length)
  97. const concurrencyOverride = process.env.DSH_GATE_CONCURRENCY
  98. const maxConcurrency = concurrencyFromEnv('DSH_GATE_CONCURRENCY', concurrencyDefault.workers)
  99. const concurrencySource = concurrencyOverride === undefined || concurrencyOverride === ''
  100. ? concurrencyDefault.source
  101. : '$DSH_GATE_CONCURRENCY'
  102. const failFast = flagEnabled('DSH_GATE_FAIL_FAST')
  103. const startedAt = performance.now()
  104. console.log(`run-gates: ${mode} running ${gates.length} gate(s) with ${maxConcurrency} worker(s) from ${concurrencySource}${failFast ? ', fail-fast after first blocking failure' : ''}.`)
  105. const results = await runGates(gates, maxConcurrency, runGate, printResult, cliGateOptions(failFast))
  106. printSummary(results, performance.now() - startedAt)
  107. return results.some(result => result.gate.allowFailure !== true && (result.status === 'failed' || result.status === 'skipped'))
  108. ? 1
  109. : 0
  110. }
  111. /**
  112. * The options the CLI entrypoint hands to the scheduler. Host signal
  113. * forwarding always follows fail-fast: children are detached only then, so
  114. * without it the forwarding would have no tree to drain.
  115. * @param failFast - whether `DSH_GATE_FAIL_FAST` is enabled.
  116. * @returns the scheduler options for the entrypoint.
  117. */
  118. export function cliGateOptions(failFast: boolean): RunGatesOptions {
  119. return { failFast, forwardProcessSignals: failFast }
  120. }
  121. function parseMode(raw: string | undefined): Mode {
  122. switch (raw) {
  123. case 'ci-primary':
  124. case 'ci-linux-primary':
  125. case 'ci-static':
  126. case 'ci-lint-contracts-ready':
  127. case 'ci-coverage':
  128. case 'ci-bench':
  129. case 'ci-snapshot':
  130. case 'ci-artifacts':
  131. case 'ci-consumers':
  132. case 'ci-windows-blocking':
  133. case 'ci-windows-complete':
  134. case 'ci-windows-observational':
  135. case 'node-compat':
  136. case 'check-all':
  137. case 'hygiene':
  138. case 'doc-sync':
  139. case 'doc-quick':
  140. return raw
  141. default:
  142. throw new Error(
  143. `run-gates: expected mode ci-primary | ci-linux-primary | ci-static | ci-lint-contracts-ready | ci-coverage | ci-bench | ci-snapshot | ci-artifacts | ci-consumers | ci-windows-blocking | ci-windows-complete | ci-windows-observational | node-compat | check-all | hygiene | doc-sync | doc-quick, got ${JSON.stringify(raw)}.`,
  144. )
  145. }
  146. }
  147. /**
  148. * Resolve the default worker count for one aggregate.
  149. * @param selectedMode - aggregate whose resource posture applies.
  150. * @param total - number of gates in the aggregate.
  151. * @param available - host CPU availability for ordinary modes.
  152. * @returns the default worker count and its diagnostic source.
  153. */
  154. export function defaultConcurrency(
  155. selectedMode: Mode,
  156. total: number,
  157. available = availableParallelism(),
  158. ): ConcurrencyDefault {
  159. if (selectedMode === 'ci-consumers') return { workers: total, source: 'ci-consumers gate count' }
  160. // Local modes cap workers: several doc gates each build a full ts.Program,
  161. // so an uncapped default on a large host trades wall clock for memory blowups.
  162. const localCap = selectedMode === 'check-all'
  163. || selectedMode === 'hygiene'
  164. || selectedMode === 'doc-sync'
  165. || selectedMode === 'doc-quick'
  166. const modeLimit = localCap ? Math.min(4, available) : available
  167. return {
  168. workers: Math.min(total, modeLimit),
  169. source: localCap
  170. ? `${available} available CPU(s), ${selectedMode} cap 4`
  171. : `${available} available CPU(s)`,
  172. }
  173. }
  174. function concurrencyFromEnv(name: string, fallback: number): number {
  175. const raw = process.env[name]
  176. if (raw === undefined || raw === '') return fallback
  177. const parsed = Number.parseInt(raw, 10)
  178. if (!Number.isSafeInteger(parsed) || parsed < 1) {
  179. throw new Error(`run-gates: ${name} must be a positive integer, got ${JSON.stringify(raw)}.`)
  180. }
  181. return parsed
  182. }
  183. function pnpmScript(id: string, script: string, options: Partial<Gate> = {}): Gate {
  184. return {
  185. id,
  186. label: options.label ?? script,
  187. displayCommand: `pnpm run ${script}`,
  188. ...pnpmInvocation(['run', script]),
  189. ...options,
  190. }
  191. }
  192. /** Build official client artifacts inside a CI aggregate without changing sibling gate environments. */
  193. function ciBuildGate(id = 'build', options: Partial<Gate> = {}): Gate {
  194. return pnpmScript(id, 'build', {
  195. ...options,
  196. env: { ...options.env, [CLIENT_BUILD_PROFILE_SELECTOR]: 'official' },
  197. })
  198. }
  199. function pnpmExec(id: string, args: string[], options: Partial<Gate> = {}): Gate {
  200. return {
  201. id,
  202. label: options.label ?? `pnpm exec ${args.join(' ')}`,
  203. displayCommand: `pnpm exec ${args.join(' ')}`,
  204. ...pnpmInvocation(['exec', ...args]),
  205. ...options,
  206. }
  207. }
  208. /**
  209. * Construct the complete gate list for a named aggregate.
  210. * @param selected - aggregate mode to construct.
  211. * @returns the aggregate's gate graph.
  212. */
  213. export function gatesForMode(selected: Mode): Gate[] {
  214. switch (selected) {
  215. case 'ci-primary':
  216. return ciPrimaryGates()
  217. case 'ci-linux-primary':
  218. return [...ciPrimaryGates(), webSnapshotGate(['built-package-invariants'])]
  219. case 'ci-static':
  220. return ciStaticGates({ ownsBuild: false })
  221. case 'ci-lint-contracts-ready':
  222. return [
  223. lintGate(),
  224. pnpmScript('duplication', 'duplication'),
  225. ]
  226. case 'ci-coverage':
  227. return coverageGates()
  228. case 'ci-bench':
  229. return [pnpmScript('bench', 'test:bench', { label: 'performance benchmarks' })]
  230. case 'ci-snapshot':
  231. return [ciBuildGate(), snapshotGate()]
  232. case 'ci-artifacts':
  233. return ciArtifactGates()
  234. case 'ci-consumers':
  235. return ciConsumerGates()
  236. case 'ci-windows-blocking':
  237. return ciWindowsBlockingGates()
  238. case 'ci-windows-complete':
  239. return ciWindowsCompleteGates()
  240. case 'ci-windows-observational':
  241. return ciWindowsObservationalGates()
  242. case 'node-compat':
  243. return nodeCompatGates()
  244. case 'check-all':
  245. return [
  246. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  247. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  248. pnpmScript('client-domain-graph', 'verify-client-domain-graph', { label: 'client domain graph' }),
  249. pnpmScript('test', 'test'),
  250. pnpmScript('approval-policy', 'test:approval-policy', { label: 'Weighted approval policy' }),
  251. pnpmScript('issue-management', 'test:issue-management', { label: 'Issue management policy' }),
  252. pnpmScript('duplication', 'duplication'),
  253. snapshotGate(),
  254. expectedOutputGate(),
  255. pnpmScript('build', 'build'),
  256. pnpmScript('build:web', 'build:web'),
  257. ...hygieneLeafGates({ artifactNeeds: ['build'] }),
  258. ...docSyncLeafGates({
  259. docTypecheckNeeds: ['build'],
  260. docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  261. docTypecheckScript: 'doc-typecheck:contracts-ready',
  262. }),
  263. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  264. ]
  265. case 'hygiene':
  266. return [
  267. ...hygieneLeafGates(),
  268. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  269. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  270. ]
  271. case 'doc-sync':
  272. return docSyncLeafGates()
  273. case 'doc-quick':
  274. return docQuickLeafGates()
  275. }
  276. }
  277. function ciSharedStaticGates(): Gate[] {
  278. return [
  279. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  280. pnpmScript('application-entrypoints', 'verify-application-entrypoints', { label: 'application entrypoints' }),
  281. pnpmScript('constraints', 'constraints'),
  282. pnpmScript('package-dependencies', 'verify-package-dependencies', { label: 'package dependencies' }),
  283. pnpmScript('dsh-package-licenses', 'verify-dsh-package-licenses', { label: 'DSH package licenses' }),
  284. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  285. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  286. pnpmScript('optional-dependency-imports', 'verify-optional-dependency-imports', {
  287. label: 'optional dependency imports',
  288. }),
  289. pnpmScript('client-packages', 'verify-client-packages', { label: 'client packages' }),
  290. pnpmScript('client-ui-i18n', 'verify-client-ui-i18n', { label: 'client UI i18n' }),
  291. pnpmScript('no-bare-dispatcher', 'verify-no-bare-dispatcher', { label: 'proxy-aware dispatchers' }),
  292. pnpmScript('approval-policy', 'test:approval-policy', { label: 'Weighted approval policy' }),
  293. pnpmScript('issue-management', 'test:issue-management', { label: 'Issue management policy' }),
  294. ]
  295. }
  296. function ciPrimaryGates(): Gate[] {
  297. return [
  298. ...ciSharedStaticGates(),
  299. typertContractsGate(),
  300. pnpmScript('typecheck', 'typecheck:contracts-ready', { needs: ['typert-contracts'] }),
  301. lintGate({ needs: ['typert-contracts'] }),
  302. pnpmScript('duplication', 'duplication'),
  303. ...coverageGates(),
  304. ...nodeCompatSmokeGates(),
  305. snapshotGate(),
  306. ...docSyncLeafGates({
  307. docTypecheckNeeds: ['typert-contracts'],
  308. docTypecheckScript: 'doc-typecheck:contracts-ready',
  309. }),
  310. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  311. // The prepared typecheck and build both drive Client tsc, while build also
  312. // repeats the Host contract pass. Wait for all three consumers so build
  313. // neither races tsbuildinfo nor replaces declarations while they are read.
  314. ciBuildGate('build', { needs: ['typecheck', 'lint', 'doc-typecheck'] }),
  315. pnpmScript('publint', 'publint', { needs: ['build'] }),
  316. pnpmScript('node-next-types', 'verify-node-next-types', {
  317. label: 'node-next types',
  318. needs: ['build'],
  319. }),
  320. builtPackageInvariantsGate(['build']),
  321. builtBinSmokeGate(),
  322. ]
  323. }
  324. function nodeCompatGates(): Gate[] {
  325. const typecheck = flagEnabled('DSH_NODE_COMPAT_SKIP_TYPECHECK')
  326. ? []
  327. : [pnpmScript('typecheck', 'typecheck')]
  328. if (runningNodeMajor() !== 22) {
  329. return [...typecheck, ...nodeCompatSmokeGates()]
  330. }
  331. return [
  332. ...typecheck,
  333. pnpmScript('build', 'build', {
  334. ...typecheck.length === 0 ? {} : { needs: ['typecheck'] },
  335. }),
  336. pnpmScript('build:web', 'build:web', {
  337. label: 'Web frontend build',
  338. needs: ['build'],
  339. }),
  340. ...nodeCompatSmokeGates({ cliSmoke: true }),
  341. ]
  342. }
  343. function nodeCompatSmokeGates(options: { cliSmoke?: boolean } = {}): Gate[] {
  344. const gates: Gate[] = [
  345. pnpmExec('source-worker-smoke', [
  346. 'vitest',
  347. 'run',
  348. 'packages/workflow/workflow-worker-thread/tests/source-worker.compat.spec.ts',
  349. ], { label: 'source worker smoke' }),
  350. pnpmExec('jsonl-zstd-smoke', [
  351. 'vitest',
  352. 'run',
  353. 'packages/session/session-persistence-jsonl/tests/zstd.compat.spec.ts',
  354. ], { label: 'JSONL Zstandard smoke' }),
  355. pnpmExec('dsh-source-launch-smoke', [
  356. 'vitest',
  357. 'run',
  358. 'apps/cli/tests/source-launch.compat.spec.ts',
  359. ], { label: 'dsh source-launch smoke' }),
  360. pnpmExec('vitest-jsdom-smoke', [
  361. 'vitest',
  362. 'run',
  363. 'scripts/vitest-environment.compat.spec.ts',
  364. ], { label: 'Vitest jsdom smoke' }),
  365. ]
  366. if (options.cliSmoke) {
  367. gates.push(
  368. pnpmExec('cli-lazy-search-startup-smoke', [
  369. 'vitest',
  370. 'run',
  371. 'apps/cli/tests/lazy-search-startup.compat.spec.ts',
  372. ], {
  373. label: 'CLI lazy-search startup smoke',
  374. env: { DSH_REQUIRE_BUILT_CLI_SMOKE: '1' },
  375. needs: ['build:web'],
  376. }),
  377. )
  378. }
  379. return gates
  380. }
  381. /** Active Node major used to select version-specific compatibility checks. */
  382. function runningNodeMajor(): number {
  383. const major = Number.parseInt(process.versions.node.split('.')[0] ?? '', 10)
  384. if (!Number.isSafeInteger(major)) {
  385. throw new Error(`run-gates: cannot parse Node version ${JSON.stringify(process.versions.node)}.`)
  386. }
  387. return major
  388. }
  389. function ciStaticGates(options: { ownsBuild: boolean }): Gate[] {
  390. return [
  391. ...ciSharedStaticGates(),
  392. ...options.ownsBuild ? [ciBuildGate()] : [],
  393. ...docSyncLeafGates({
  394. includeDocTypecheck: options.ownsBuild,
  395. ...options.ownsBuild
  396. ? {
  397. docTypecheckNeeds: ['build'],
  398. docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  399. docTypecheckScript: 'doc-typecheck:contracts-ready',
  400. }
  401. : {},
  402. docsBuildScript: 'docs:build:mpa',
  403. }),
  404. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  405. ]
  406. }
  407. function ciArtifactGates(): Gate[] {
  408. return [
  409. ciBuildGate(),
  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 ciConsumerGates(): Gate[] {
  420. const builtTree = ['build']
  421. const validatedBuild = ['built-package-invariants']
  422. // The HMR web test starts `dev:web`, which rewrites the shared `lib/` and
  423. // `apps/web/dist/` trees. Let every build-artifact reader settle before that
  424. // writer starts; `after` preserves the web diagnostic even if a reader fails.
  425. const buildArtifactReaders = [
  426. 'publint',
  427. 'lint-and-duplication',
  428. 'snapshot',
  429. 'expected-output',
  430. 'doc-typecheck',
  431. 'node-next-types',
  432. 'built-bin-smoke',
  433. ]
  434. return [
  435. ciBuildGate(),
  436. pnpmScript('node-compat', 'check:node-compat', {
  437. label: 'Node compatibility',
  438. env: { [CLIENT_BUILD_PROFILE_SELECTOR]: 'official' },
  439. }),
  440. pnpmScript('publint', 'publint', { needs: builtTree }),
  441. builtPackageInvariantsGate(builtTree),
  442. pnpmScript('lint-and-duplication', 'check:ci:lint:contracts-ready', {
  443. label: 'lint and duplication',
  444. needs: validatedBuild,
  445. }),
  446. snapshotGate(validatedBuild),
  447. expectedOutputGate(validatedBuild),
  448. webSnapshotGate(validatedBuild, buildArtifactReaders),
  449. pnpmScript('doc-typecheck', 'doc-typecheck:contracts-ready', {
  450. needs: validatedBuild,
  451. env: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  452. }),
  453. pnpmScript('node-next-types', 'verify-node-next-types', {
  454. label: 'node-next types',
  455. needs: validatedBuild,
  456. }),
  457. builtBinSmokeGate(validatedBuild),
  458. ]
  459. }
  460. function webSnapshotGate(needs: string[], after?: string[]): Gate {
  461. const order = after === undefined ? { needs } : { needs, after }
  462. const workerRaw = process.env.DSH_WEB_SNAPSHOT_WORKERS
  463. if (workerRaw !== undefined && workerRaw !== '') {
  464. const workers = Number.parseInt(workerRaw, 10)
  465. if (!Number.isSafeInteger(workers) || workers < 2 || String(workers) !== workerRaw) {
  466. throw new Error(`run-gates: DSH_WEB_SNAPSHOT_WORKERS must be an integer greater than 1, got ${JSON.stringify(workerRaw)}.`)
  467. }
  468. return pnpmScript('web-snapshot', 'test:web:ci', {
  469. label: 'web browser snapshot',
  470. displayCommand: `DSH_SNAPSHOT=replay DSH_WEB_SNAPSHOT_WORKERS=${workers} pnpm run test:web:ci`,
  471. env: { DSH_SNAPSHOT: 'replay' },
  472. ...order,
  473. streamOutput: true,
  474. })
  475. }
  476. return pnpmScript('web-snapshot', 'test:web:built', {
  477. label: 'web browser snapshot',
  478. displayCommand: 'DSH_SNAPSHOT=replay pnpm run test:web:built',
  479. env: { DSH_SNAPSHOT: 'replay' },
  480. ...order,
  481. })
  482. }
  483. function ciWindowsBlockingGates(): Gate[] {
  484. return [
  485. ciBuildGate('windows-build', { label: 'build' }),
  486. pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
  487. ]
  488. }
  489. function ciWindowsCompleteGates(): Gate[] {
  490. const coverage = coverageGates().map(gate => ({
  491. ...gate,
  492. needs: [...new Set(['build', ...(gate.needs ?? [])])],
  493. }))
  494. const coverageAfter = coverage.map(gate => gate.id)
  495. const observational = ciWindowsObservationalGates()
  496. // The required production site replaces the observational MPA build; both
  497. // VitePress modes write the same output directory and cannot overlap.
  498. .filter(gate => gate.id !== 'build' && gate.id !== 'docs-site-build')
  499. .map(gate => ({
  500. ...gate,
  501. allowFailure: true,
  502. after: [...new Set([
  503. ...coverageAfter,
  504. ...(gate.after ?? []).map(id => id === 'docs-site-build' ? 'windows-site' : id),
  505. ])],
  506. }))
  507. return [
  508. ciBuildGate(),
  509. pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
  510. ...coverage,
  511. ...observational,
  512. ]
  513. }
  514. function ciWindowsObservationalGates(): Gate[] {
  515. const predecessors = [
  516. ...ciStaticGates({ ownsBuild: true }),
  517. // Linux owns required lint and snapshots; Windows omits those duplicates.
  518. pnpmScript('duplication', 'duplication'),
  519. pnpmScript('publint', 'publint', { needs: ['build'] }),
  520. pnpmScript('node-next-types', 'verify-node-next-types', {
  521. label: 'node-next types',
  522. needs: ['build'],
  523. }),
  524. builtPackageInvariantsGate(['build']),
  525. ]
  526. return [
  527. ...predecessors,
  528. {
  529. ...builtBinSmokeGate(),
  530. // This smoke starts real application children with bounded startup
  531. // deadlines. Let other Windows processes settle before measuring startup.
  532. after: predecessors.map(gate => gate.id),
  533. },
  534. ]
  535. }
  536. function typertContractsGate(): Gate {
  537. return pnpmScript('typert-contracts', 'build:lib:host', { label: 'Typert contracts' })
  538. }
  539. function lintGate(options: { needs?: string[] } = {}): Gate {
  540. const raw = process.env.DSH_OXLINT_THREADS
  541. const script = 'lint:contracts-ready'
  542. return pnpmScript('lint', script, {
  543. ...raw === undefined || raw === ''
  544. ? {}
  545. : { displayCommand: `DSH_OXLINT_THREADS=${raw} pnpm run ${script}` },
  546. ...options.needs === undefined ? {} : { needs: options.needs },
  547. })
  548. }
  549. // The heavy suites run uninstrumented beside the thresholded gate: their
  550. // compiler- and subprocess-bound fixtures pay a multiple of their runtime
  551. // under v8 instrumentation while contributing nothing the thresholds need
  552. // (membership rules in scripts/coverage-exempt.ts).
  553. //
  554. // DSH_COVERAGE_MAX_WORKERS is the ordinary lane's worker budget, so the two
  555. // parallel gates split it instead of each claiming it whole. When
  556. // DSH_COVERAGE_PARTITIONS is set, its single-worker processes replace the
  557. // instrumented share while this budget still sizes the exempt gate. The exempt
  558. // gate's wall clock is dominated by its longest single file, so it takes the
  559. // small share. A budget of 1 gives each gate 1 worker; lanes that need a strict
  560. // total of one (the serial reference jobs) also set DSH_GATE_CONCURRENCY=1,
  561. // which keeps the gates from overlapping at all.
  562. // DSH_COVERAGE_TEST_TIMEOUT_MS raises Vitest's per-test, expect.poll, and hook
  563. // defaults together for instrumented lanes whose scheduling overhead exceeds
  564. // those defaults. Explicit fixture timeouts remain authoritative.
  565. function coverageWorkerArgs(): { instrumented: string[]; exempt: string[] } {
  566. const [flag] = positiveIntArg('DSH_COVERAGE_MAX_WORKERS', '--maxWorkers')
  567. if (flag === undefined) return { instrumented: [], exempt: [] }
  568. const total = Number.parseInt(flag.split('=')[1] ?? '', 10)
  569. const exempt = Math.max(1, Math.floor(total / 3))
  570. const instrumented = Math.max(1, total - exempt)
  571. return {
  572. instrumented: [`--maxWorkers=${String(instrumented)}`],
  573. exempt: [`--maxWorkers=${String(exempt)}`],
  574. }
  575. }
  576. function coverageGates(): Gate[] {
  577. const workers = coverageWorkerArgs()
  578. const timeouts = coverageTestTimeoutArgs(process.env[COVERAGE_TEST_TIMEOUT_ENV])
  579. const partitions = parseCoveragePartitionCount(process.env[COVERAGE_PARTITIONS_ENV])
  580. const instrumented = partitions === undefined
  581. ? pnpmExec('coverage', [
  582. 'vitest',
  583. 'run',
  584. '--coverage',
  585. ...workers.instrumented,
  586. ...timeouts,
  587. ], {
  588. label: 'test:coverage',
  589. env: { [COVERAGE_EXEMPT_ENV]: '1' },
  590. })
  591. : pnpmScript('coverage', 'test:coverage:partitioned', {
  592. label: 'test:coverage',
  593. displayCommand: `${COVERAGE_PARTITIONS_ENV}=${partitions} pnpm run test:coverage:partitioned`,
  594. env: { [COVERAGE_EXEMPT_ENV]: '1' },
  595. streamOutput: true,
  596. })
  597. return [
  598. pnpmScript('native-system', 'build:native-system'),
  599. { ...instrumented, needs: ['native-system'] },
  600. pnpmExec('coverage-exempt-heavy', [
  601. 'vitest',
  602. 'run',
  603. ...coverageExemptHeavySuites.map(suite => suite.filter),
  604. ...workers.exempt,
  605. ...timeouts,
  606. ], {
  607. label: 'test:coverage-exempt-heavy',
  608. needs: ['native-system'],
  609. }),
  610. ]
  611. }
  612. // Recorded-session adapters boot process scenarios in `lib` mode. Callers wait
  613. // either on `build` or on a validation gate that transitively owns that build.
  614. function snapshotGate(needs: string[] = ['build']): Gate {
  615. return pnpmScript('snapshot', 'test:snapshot', {
  616. env: { DSH_EXAMPLE_MODE: 'lib' },
  617. needs,
  618. })
  619. }
  620. // Owner-local process expectations consume built package exports without entering
  621. // the recorded-session corpus or the credentialed provider lane.
  622. function expectedOutputGate(needs: string[] = ['build']): Gate {
  623. return pnpmScript('expected-output', 'test:expected', {
  624. env: { DSH_EXAMPLE_MODE: 'lib' },
  625. needs,
  626. })
  627. }
  628. function builtPackageInvariantsGate(needs?: string[]): Gate {
  629. return pnpmScript('built-package-invariants', 'verify-built-package-invariants', {
  630. label: 'built package invariants',
  631. ...needs === undefined ? {} : { needs },
  632. })
  633. }
  634. function positiveIntArg(envName: string, flag: string): string[] {
  635. const raw = process.env[envName]
  636. if (raw === undefined || raw === '') return []
  637. const parsed = Number.parseInt(raw, 10)
  638. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  639. throw new Error(`run-gates: ${envName} must be a positive integer, got ${JSON.stringify(raw)}.`)
  640. }
  641. return [`${flag}=${raw}`]
  642. }
  643. function flagEnabled(envName: string): boolean {
  644. const raw = process.env[envName]
  645. if (raw === undefined || raw === '') return false
  646. if (raw !== '1') throw new Error(`run-gates: ${envName} must be 1 when set, got ${JSON.stringify(raw)}.`)
  647. return true
  648. }
  649. function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] {
  650. const artifactOptions = options.artifactNeeds === undefined ? {} : { needs: options.artifactNeeds }
  651. return [
  652. pnpmScript('rescope-vendor', 'rescope-vendor:check', { label: 'vendor rescope' }),
  653. pnpmScript('publint', 'publint', artifactOptions),
  654. pnpmScript('constraints', 'constraints'),
  655. pnpmScript('package-dependencies', 'verify-package-dependencies', { label: 'package dependencies' }),
  656. pnpmScript('application-entrypoints', 'verify-application-entrypoints', { label: 'application entrypoints' }),
  657. pnpmScript('dsh-package-licenses', 'verify-dsh-package-licenses', { label: 'DSH package licenses' }),
  658. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  659. builtPackageInvariantsGate(options.artifactNeeds),
  660. pnpmScript('node-next-types', 'verify-node-next-types', {
  661. label: 'node-next types',
  662. ...artifactOptions,
  663. }),
  664. pnpmScript('optional-dependency-imports', 'verify-optional-dependency-imports', {
  665. label: 'optional dependency imports',
  666. }),
  667. pnpmScript('client-packages', 'verify-client-packages', { label: 'client packages' }),
  668. pnpmScript('client-ui-i18n', 'verify-client-ui-i18n', { label: 'client UI i18n' }),
  669. pnpmScript('no-bare-dispatcher', 'verify-no-bare-dispatcher', { label: 'proxy-aware dispatchers' }),
  670. ]
  671. }
  672. function docSyncLeafGates(options: {
  673. includeDocTypecheck?: boolean
  674. docTypecheckNeeds?: string[]
  675. docTypecheckEnv?: Record<string, string | undefined>
  676. docTypecheckScript?: 'doc-typecheck' | 'doc-typecheck:contracts-ready'
  677. docsBuildScript?: 'docs:build' | 'docs:build:mpa'
  678. } = {}): Gate[] {
  679. const docTypecheckOptions: Partial<Gate> = {}
  680. if (options.docTypecheckNeeds !== undefined) docTypecheckOptions.needs = options.docTypecheckNeeds
  681. if (options.docTypecheckEnv !== undefined) docTypecheckOptions.env = options.docTypecheckEnv
  682. return [
  683. // Stable FIFO starts the longest leaves first; only docs-site-build writes website/.generated.
  684. ...options.includeDocTypecheck === false
  685. ? []
  686. : [pnpmScript('doc-typecheck', options.docTypecheckScript ?? 'doc-typecheck', docTypecheckOptions)],
  687. pnpmScript('docs-site-build', options.docsBuildScript ?? 'docs:build', { label: 'documentation build' }),
  688. pnpmScript('doc-graphs', 'verify-doc-graphs', { label: 'doc graphs' }),
  689. pnpmScript('markdown-links', 'verify-md-links', { label: 'markdown links', quick: true }),
  690. pnpmScript('type-equivalence', 'verify-type-equiv', { label: 'type equivalence', quick: true }),
  691. pnpmScript('cordis-catalog', 'verify-cordis-catalog', { label: 'cordis catalog' }),
  692. pnpmScript('cordis-inspect-catalog', 'verify-cordis-inspect-catalog', { label: 'Cordis inspect catalog' }),
  693. pnpmScript('mermaid', 'verify-mermaid'),
  694. pnpmScript('scoped-events', 'verify-scoped-events', { label: 'scoped events' }),
  695. pnpmScript('translation-pairing', 'verify-translation-pairing', { label: 'translation pairing', quick: true }),
  696. pnpmScript('markdown-wrap', 'verify-md-wrap', { label: 'markdown wrap', quick: true }),
  697. pnpmScript('client-catalog', 'verify-client-catalog', { label: 'client catalog' }),
  698. pnpmScript('export-jsdoc', 'verify-export-jsdoc', { label: 'export jsdoc' }),
  699. pnpmScript('tool-catalog', 'verify-tool-catalog', { label: 'tool catalog' }),
  700. pnpmScript('config-catalog', 'verify-config-catalog', { label: 'config catalog' }),
  701. pnpmScript('persistence-catalog', 'verify-persistence-catalog', { label: 'persistence catalog' }),
  702. pnpmScript('session-format-catalog', 'verify-session-format-catalog', { label: 'Session format catalog' }),
  703. pnpmScript('public-repository-links', 'verify-public-repository-links', { label: 'public repository links', quick: true }),
  704. pnpmScript('doc-refs', 'verify-doc-refs', { label: 'doc refs', quick: true }),
  705. pnpmScript('subsystem-pages', 'verify-subsystem-pages', { label: 'subsystem pages' }),
  706. pnpmScript('package-paths', 'verify-package-paths', { label: 'package paths' }),
  707. pnpmScript('tsconfig-paths', 'verify-tsconfig-paths', { label: 'tsconfig paths' }),
  708. pnpmScript('config-source-ownership', 'verify-config-source-ownership', { label: 'config source ownership' }),
  709. pnpmScript('package-readme-summaries', 'verify-package-readme-summaries', { label: 'package README Summaries', quick: true }),
  710. pnpmScript('package-readme-model-experience', 'verify-package-readme-model-experience', { label: 'package README model experience', quick: true }),
  711. pnpmScript('agent-note-classification', 'verify-agent-note-classification', { label: 'agent note classification', quick: true }),
  712. pnpmScript('agent-note-format', 'verify-agent-note-format', { label: 'agent note format', quick: true }),
  713. pnpmScript('archived-agent-notes', 'verify-archived-agent-notes', { label: 'archived agent notes', quick: true }),
  714. pnpmScript('skill-invocation-metadata', 'verify-skill-invocation-metadata', { label: 'skill invocation metadata', quick: true }),
  715. pnpmScript('translation-prompt', 'verify-translation-prompt', { label: 'translation prompt', quick: true }),
  716. pnpmScript('doc-budgets', 'verify-doc-budgets', { label: 'doc budgets', quick: true }),
  717. pnpmExec('doc-standard-tests', ['vitest', 'run', 'scripts/doc-standard.spec.ts'], {
  718. label: 'documentation standard tests',
  719. quick: true,
  720. }),
  721. pnpmExec('docs-site-projection', ['vitest', 'run', 'scripts/project-doc-site.spec.ts', 'scripts/verify-doc-site-fragments.spec.ts'], {
  722. label: 'documentation site checks',
  723. }),
  724. pnpmScript('package-readme-limitations', 'verify-package-readme-limitations', { label: 'package README limitations', quick: true }),
  725. ]
  726. }
  727. /**
  728. * The quick comprehensive documentation-standard aggregate for `test:docs`.
  729. * It covers the prose, pairing, README, budget, and Agent Note gates
  730. * without builds, generator regeneration, or the VitePress site build.
  731. */
  732. function docQuickLeafGates(): Gate[] {
  733. return docSyncLeafGates({ includeDocTypecheck: false }).filter(gate => gate.quick === true)
  734. }
  735. function builtBinSmokeGate(needs: string[] = ['build']): Gate {
  736. return pnpmExec('built-bin-smoke', [
  737. 'vitest',
  738. 'run',
  739. '--config',
  740. 'vitest.e2e.config.ts',
  741. 'apps/cli/tests/profiles/headless/tests/keyless-smoke.e2e.ts',
  742. 'apps/cli/tests/built-bin.e2e.ts',
  743. 'packages/host/directory-picker-native/tests/built-worker.e2e.ts',
  744. 'packages/sdk/server/tests/built-scope-carrier.e2e.ts',
  745. 'packages/fs/tool-present/tests/built-errors.e2e.ts',
  746. 'packages/subprocess/subprocess-local/tests/spawn-runner-built.e2e.ts',
  747. 'packages/subagent/subagent-codex/tests/loader-composition.e2e.ts',
  748. 'packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts',
  749. 'packages/api/remotes/tests/built-lib.e2e.ts',
  750. 'packages/experimental/agent-team/tests/built-lib.e2e.ts',
  751. // Built execution consumers: the only automated proof that package-name
  752. // imports reach their lib/ entrypoints under plain Node. The e2e lane runs
  753. // unbuilt, so these files self-skip there.
  754. 'packages/workflow/workflow-worker-thread/tests/built-worker.e2e.ts',
  755. 'packages/code-runtime/code-runtime-worker-thread/tests/built-lib.e2e.ts',
  756. 'packages/session/session-persistence-jsonl/tests/built-migration-worker.e2e.ts',
  757. 'packages/lsp/lsp-stdio/tests/built-lib.e2e.ts',
  758. ], {
  759. label: 'built-bin smoke',
  760. needs,
  761. env: { DSH_EXAMPLE_MODE: 'lib' },
  762. })
  763. }
  764. /**
  765. * Reject a gate list whose graph cannot be executed unambiguously.
  766. * @param gates - complete aggregate to validate.
  767. */
  768. function validateGateGraph(gates: readonly Gate[]): void {
  769. if (gates.length === 0) throw new Error('run-gates: gate graph has no gates.')
  770. const ids = new Set<string>()
  771. for (const gate of gates) {
  772. if (ids.has(gate.id)) throw new Error(`run-gates: duplicate gate id ${JSON.stringify(gate.id)}.`)
  773. ids.add(gate.id)
  774. }
  775. for (const gate of gates) {
  776. for (const dependency of gate.needs ?? []) {
  777. if (!ids.has(dependency)) {
  778. throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} depends on unknown gate ${JSON.stringify(dependency)}.`)
  779. }
  780. }
  781. for (const predecessor of gate.after ?? []) {
  782. if (!ids.has(predecessor)) {
  783. throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} waits for unknown gate ${JSON.stringify(predecessor)}.`)
  784. }
  785. }
  786. }
  787. const cycle = findDependencyCycle(gates)
  788. if (cycle !== undefined) throw new Error(`run-gates: dependency cycle: ${cycle.join(' -> ')}.`)
  789. }
  790. function findDependencyCycle(gates: readonly Gate[]): string[] | undefined {
  791. const byId = new Map(gates.map(gate => [gate.id, gate]))
  792. const complete = new Set<string>()
  793. const active = new Map<string, number>()
  794. const path: string[] = []
  795. const visit = (id: string): string[] | undefined => {
  796. if (complete.has(id)) return undefined
  797. const cycleStart = active.get(id)
  798. if (cycleStart !== undefined) return [...path.slice(cycleStart), id]
  799. const gate = byId.get(id)
  800. if (gate === undefined) return undefined
  801. active.set(id, path.length)
  802. path.push(id)
  803. for (const predecessor of [...(gate.needs ?? []), ...(gate.after ?? [])]) {
  804. const cycle = visit(predecessor)
  805. if (cycle !== undefined) return cycle
  806. }
  807. path.pop()
  808. active.delete(id)
  809. complete.add(id)
  810. return undefined
  811. }
  812. for (const gate of gates) {
  813. const cycle = visit(gate.id)
  814. if (cycle !== undefined) return cycle
  815. }
  816. return undefined
  817. }
  818. /**
  819. * Scheduling options for one aggregate.
  820. */
  821. export interface RunGatesOptions {
  822. /** Stop the aggregate at the first blocking gate failure. */
  823. failFast?: boolean
  824. /** Forward host SIGINT/SIGTERM to the abort path so detached gate trees are
  825. * terminated when the run itself is interrupted or the runner cancels it.
  826. * Tree termination additionally requires failFast, because only then is the
  827. * abort signal passed to the executor and children detached. */
  828. forwardProcessSignals?: boolean
  829. }
  830. /**
  831. * Validate and run one aggregate before the injected executor can start a child.
  832. * @param gates - complete aggregate to execute.
  833. * @param maxActive - maximum concurrent child count.
  834. * @param execute - child-process executor; receives the abort signal only when
  835. * fail-fast is enabled, so ordinary runs keep their children in the host
  836. * process group.
  837. * @param observe - result observer invoked when each gate settles.
  838. * @param options - scheduling options; fail-fast aborts the aggregate at the
  839. * first blocking gate failure by killing running children and skipping every
  840. * not-yet-run gate.
  841. * @returns results in aggregate order.
  842. */
  843. export async function runGates(
  844. gates: Gate[],
  845. maxActive: number,
  846. execute: GateExecutor,
  847. observe: ResultObserver = () => {},
  848. options: RunGatesOptions = {},
  849. ): Promise<GateResult[]> {
  850. validateGateGraph(gates)
  851. if (!Number.isSafeInteger(maxActive) || maxActive < 1) {
  852. throw new Error(`run-gates: max concurrency must be a positive integer, got ${JSON.stringify(maxActive)}.`)
  853. }
  854. if (options.forwardProcessSignals === true && options.failFast !== true) {
  855. throw new Error('run-gates: forwardProcessSignals requires failFast, otherwise no child is detached or killed.')
  856. }
  857. const states = new Map<string, GateState>(gates.map(gate => [gate.id, 'pending']))
  858. const results = new Map<string, GateResult>()
  859. const running: RunningGate[] = []
  860. const abort = new AbortController()
  861. let abortCause: string | undefined
  862. // Host interruption (terminal Ctrl+C, runner cancellation) drains through
  863. // the same abort path as a gate failure, so detached trees are killed and
  864. // never orphaned. Handlers are removed before returning.
  865. const hostSignals = options.forwardProcessSignals === true ? ['SIGINT', 'SIGTERM'] as const : []
  866. const hostHandlers = hostSignals.map((name) => {
  867. const handler = () => {
  868. abortCause = abortCause ?? 'host interruption'
  869. abort.abort()
  870. }
  871. process.on(name, handler)
  872. return { name, handler }
  873. })
  874. const failFastSignal = options.failFast === true ? abort.signal : undefined
  875. try {
  876. for (;;) {
  877. let madeProgress = false
  878. if (abortCause === undefined) {
  879. while (running.length < maxActive) {
  880. const ready = gates.find(gate => states.get(gate.id) === 'pending' && predecessorsReady(gate, states))
  881. if (ready === undefined) break
  882. states.set(ready.id, 'running')
  883. running.push({ gate: ready, promise: execute(ready, failFastSignal) })
  884. console.log(`run-gates: start ${ready.label}`)
  885. madeProgress = true
  886. }
  887. }
  888. if (running.length === 0) {
  889. if (abortCause !== undefined) {
  890. for (const gate of gates) {
  891. if (states.get(gate.id) !== 'pending') continue
  892. const skipped = skippedByFailFast(gate, abortCause)
  893. states.set(gate.id, 'skipped')
  894. results.set(gate.id, skipped)
  895. observe(skipped)
  896. }
  897. break
  898. }
  899. const pending = gates.filter(gate => states.get(gate.id) === 'pending')
  900. if (pending.length === 0) break
  901. const gate = pending.find(item => (item.needs ?? []).some(id => gateFailed(states.get(id))))
  902. if (gate === undefined) throw new Error('run-gates: validated graph stalled without a failed dependency.')
  903. const failedDeps = (gate.needs ?? []).filter(id => gateFailed(states.get(id)))
  904. const result: GateResult = {
  905. gate,
  906. status: 'skipped',
  907. durationMs: 0,
  908. output: [],
  909. exitCode: null,
  910. signalCode: null,
  911. error: `dependency failed or skipped: ${failedDeps.join(', ')}`,
  912. }
  913. states.set(gate.id, 'skipped')
  914. results.set(gate.id, result)
  915. observe(result)
  916. continue
  917. }
  918. if (!madeProgress) {
  919. const settled = await Promise.race(running.map(async item => ({ item, result: await item.promise })))
  920. running.splice(running.indexOf(settled.item), 1)
  921. const observed = abortCause === undefined || settled.result.aborted !== true
  922. ? settled.result
  923. : skippedByFailFast(settled.item.gate, abortCause)
  924. states.set(settled.item.gate.id, observed.status)
  925. results.set(settled.item.gate.id, observed)
  926. observe(observed)
  927. if (abortCause === undefined && options.failFast === true
  928. && observed.status === 'failed' && settled.item.gate.allowFailure !== true) {
  929. abortCause = `${observed.gate.label} failed`
  930. abort.abort()
  931. console.error(`run-gates: fail-fast aborting: ${abortCause}.`)
  932. for (const gate of gates) {
  933. if (states.get(gate.id) !== 'pending') continue
  934. const skipped = skippedByFailFast(gate, abortCause)
  935. states.set(gate.id, 'skipped')
  936. results.set(gate.id, skipped)
  937. observe(skipped)
  938. }
  939. }
  940. }
  941. }
  942. } finally {
  943. for (const { name, handler } of hostHandlers) process.removeListener(name, handler)
  944. }
  945. return gates.map((gate) => {
  946. const result = results.get(gate.id)
  947. if (result === undefined) throw new Error(`run-gates: missing result for ${gate.id}.`)
  948. return result
  949. })
  950. }
  951. /**
  952. * The result of a gate that produced no evidence because fail-fast aborted.
  953. * A gate whose process settled before the abort took effect keeps its real
  954. * result instead: it did produce evidence, and the summary must say so. Any
  955. * result settling after the abort — including a genuine independent failure
  956. * in the race window, and a child that trapped the signal and exited zero —
  957. * is recorded skipped with its partial output discarded, because on Windows a
  958. * killed process is indistinguishable from a failed one by exit code alone.
  959. * @param gate - the gate that produced no evidence.
  960. * @param cause - the full clause naming what aborted the aggregate, e.g.
  961. * `typecheck failed` or `host interruption`.
  962. * @returns the skipped record with the fail-fast error.
  963. */
  964. function skippedByFailFast(gate: Gate, cause: string): GateResult {
  965. return {
  966. gate,
  967. status: 'skipped',
  968. durationMs: 0,
  969. output: [],
  970. exitCode: null,
  971. signalCode: null,
  972. error: `aborted by fail-fast: ${cause}`,
  973. }
  974. }
  975. function predecessorsReady(gate: Gate, states: Map<string, GateState>): boolean {
  976. return (gate.needs ?? []).every(id => states.get(id) === 'passed')
  977. && (gate.after ?? []).every(id => gateSettled(states.get(id)))
  978. }
  979. function gateSettled(state: GateState | undefined): boolean {
  980. return state === 'passed' || state === 'failed' || state === 'skipped'
  981. }
  982. function gateFailed(state: GateState | undefined): boolean {
  983. return state === 'failed' || state === 'skipped'
  984. }
  985. /**
  986. * Execute one gate through the real shell-free child-process boundary.
  987. * @param gate - command and scheduler environment to execute.
  988. * @param signal - abort signal that terminates the whole gate process tree when
  989. * the aggregate fails fast; an already-aborted signal terminates it
  990. * immediately. A provided signal spawns the child detached so POSIX can signal
  991. * its process group and Windows can reach its tree through taskkill.
  992. * @returns the complete process outcome.
  993. */
  994. export async function runGate(gate: Gate, signal?: AbortSignal): Promise<GateResult> {
  995. const started = performance.now()
  996. const output: GateOutputChunk[] = []
  997. let spawnError: string | undefined
  998. let aborted = false
  999. const outcome = await new Promise<{
  1000. exitCode: number | null
  1001. signalCode: NodeJS.Signals | null
  1002. }>((resolveExit) => {
  1003. const child = spawn(gate.command, gate.args, {
  1004. cwd: root,
  1005. env: { ...process.env, ...gate.env },
  1006. stdio: ['pipe', 'pipe', 'pipe'],
  1007. detached: signal !== undefined && process.platform !== 'win32',
  1008. })
  1009. child.stdout.setEncoding('utf8')
  1010. child.stderr.setEncoding('utf8')
  1011. child.stdout.on('data', (chunk: string) => {
  1012. if (gate.streamOutput === true) process.stdout.write(chunk)
  1013. else output.push({ stream: 'stdout', text: chunk })
  1014. })
  1015. child.stderr.on('data', (chunk: string) => {
  1016. if (gate.streamOutput === true) process.stderr.write(chunk)
  1017. else output.push({ stream: 'stderr', text: chunk })
  1018. })
  1019. // Deliver one signal to the entire gate tree: the negative pid targets the
  1020. // POSIX process group the detached child leads; Windows has no groups, so
  1021. // taskkill walks the tree rooted at the child and force-terminates (a
  1022. // taskkill without `/F` does not terminate console processes, which is
  1023. // what gate commands are). Outcomes are deliberately unchecked because
  1024. // delivery races tree exit, and a missing taskkill binary is as tolerable
  1025. // as ESRCH. Mirrors the subprocess package's teardown contract
  1026. // (packages/subprocess/subprocess-local/src/spawn.ts).
  1027. const treeKill = (signalToSend: 'SIGTERM' | 'SIGKILL') => {
  1028. const pid = child.pid
  1029. if (pid === undefined) return
  1030. if (process.platform === 'win32') {
  1031. for (const args of taskkillArgs(pid, descendants)) {
  1032. spawnSync('taskkill', args, { stdio: 'ignore' })
  1033. }
  1034. return
  1035. }
  1036. try {
  1037. process.kill(-pid, signalToSend)
  1038. } catch {
  1039. // The group is gone; the direct child may still be alive alone.
  1040. child.kill(signalToSend)
  1041. }
  1042. // The captured list stays valid after the group kill reparents the
  1043. // detached descendants of a nested run-gates (the `check:node-compat`
  1044. // and `check:ci:lint:contracts-ready` gates in ci-consumers): pids do
  1045. // not change on reparenting, so the escalation reaches leaves that
  1046. // ignored SIGTERM without re-enumerating.
  1047. for (const descendantPid of descendants) {
  1048. try {
  1049. process.kill(descendantPid, signalToSend)
  1050. } catch {
  1051. // The descendant exited between the enumeration and the signal.
  1052. }
  1053. }
  1054. }
  1055. let escalation: ReturnType<typeof setTimeout> | undefined
  1056. let terminatedAt = 0
  1057. // Captured once at terminate and re-signalled on escalation: the group
  1058. // kill reaps the direct child, after which its detached descendants are
  1059. // reparented and unreachable by parent id, so the escalation cannot
  1060. // re-enumerate them.
  1061. let descendants: number[] = []
  1062. let pipeDrain: ReturnType<typeof setTimeout> | undefined
  1063. const terminate = () => {
  1064. aborted = true
  1065. const pid = child.pid
  1066. // Merge while the child is still alive: re-enumerating alone would drop
  1067. // a descendant that an exited intermediate reparented out of the parent
  1068. // chain, and replacing the list entirely would lose the sampler's
  1069. // last-known entries when the child already exited. Union preserves both.
  1070. // The sampler runs on every platform (including Windows, where an
  1071. // exited intermediate's table record vanishes and a fresh enumeration
  1072. // cannot cross the gap), so the cache is the source of truth once the
  1073. // child is gone.
  1074. if (pid !== undefined && child.exitCode === null && child.signalCode === null) {
  1075. descendants = [...new Set([...descendants, ...descendantPids(pid)])]
  1076. }
  1077. treeKill('SIGTERM')
  1078. if (escalation === undefined) {
  1079. terminatedAt = Date.now()
  1080. // Force-kill at the deadline regardless of the direct child's exit
  1081. // state: when the wrapper dies but a grandchild ignores SIGTERM and
  1082. // still holds the stdio pipes, `close` has not fired and the tree must
  1083. // still be killed. treeKill swallows an already-absent group.
  1084. escalation = setTimeout(() => { treeKill('SIGKILL') }, 5000)
  1085. }
  1086. if (pipeDrain === undefined) {
  1087. // `close` can stay pending past the direct child's exit when a
  1088. // descendant holds the stdio write ends (escaped process group, or
  1089. // uninterruptible I/O that keeps the SIGKILL pending). Bound the wait
  1090. // past the 5-second SIGKILL grace and force the streams closed so
  1091. // fail-fast settles instead of hanging to the job timeout. Only the
  1092. // abort path arms it: on an ordinary run a gate that outlives its
  1093. // descendants must keep waiting rather than report passed over a live
  1094. // leak. Armed in terminate (not only at `exit`) so the window where
  1095. // the child already exited before the abort is covered too.
  1096. pipeDrain = setTimeout(() => {
  1097. child.stdout.destroy()
  1098. child.stderr.destroy()
  1099. child.stdin.destroy()
  1100. }, 10000)
  1101. }
  1102. }
  1103. if (signal !== undefined) {
  1104. if (signal.aborted) terminate()
  1105. else signal.addEventListener('abort', terminate, { once: true })
  1106. }
  1107. // Refresh the descendant cache while the child runs, so an abort that
  1108. // arrives after the child already exited can still reach a detached
  1109. // descendant the child left behind: once the child is gone, its
  1110. // descendants are reparented (POSIX) or their intermediate's table record
  1111. // is gone (Windows), so a fresh enumeration cannot cross the gap. The
  1112. // cache is primed at spawn and refreshed every 5 seconds, so a descendant
  1113. // is captured once it appears in any enumeration whose parent chain is
  1114. // still fully present in the table; the residual window is a descendant
  1115. // that never appears in such a snapshot — created after one enumeration
  1116. // and orphaned before the next. Enumeration is asynchronous (a slow
  1117. // WMI/CIM call is bounded by its own 10-second timeout), so a gate's
  1118. // output draining and exit handling are never blocked while the sampler
  1119. // reads the process table. Fail-fast runs only; ordinary runs never
  1120. // abort.
  1121. let descendantSampler: ReturnType<typeof setInterval> | undefined
  1122. if (signal !== undefined) {
  1123. let enumerationInFlight: { cancel: () => void } | undefined
  1124. const refreshDescendants = () => {
  1125. const pid = child.pid
  1126. if (pid === undefined || child.exitCode !== null || child.signalCode !== null) return
  1127. if (enumerationInFlight !== undefined) return
  1128. const handle = descendantPidsAsync(pid, process.platform)
  1129. enumerationInFlight = handle
  1130. void handle.promise.then((fresh) => {
  1131. if (enumerationInFlight === handle) enumerationInFlight = undefined
  1132. // Merge regardless of the child's exit state: the enumeration
  1133. // started while the child was alive, so its snapshot is the last
  1134. // reliable view of the tree. The child may exit (its intermediate
  1135. // gone, its table record vanished) before the promise settles while
  1136. // a grandchild still holds the stdio write ends and keeps `close`
  1137. // pending — exactly when terminate needs this list.
  1138. // Merge instead of replacing, like terminate: an intermediate that
  1139. // exited since the last tick reparented its detached descendants
  1140. // out of the parent chain, so a fresh enumeration alone would drop
  1141. // them. Filter the cache to the still-executing so a long gate
  1142. // does not accumulate stale pids; while sampler ticks still run the
  1143. // live filter also keeps the escalation from signalling a reused
  1144. // pid, but once ticks stop (child exited) the cache can go stale,
  1145. // and a pid reused after that is the accepted sampling window.
  1146. descendants = [...new Set([...descendants.filter(processAlive), ...fresh])]
  1147. })
  1148. }
  1149. const cancelInFlightEnumeration = () => {
  1150. if (enumerationInFlight !== undefined) enumerationInFlight.cancel()
  1151. enumerationInFlight = undefined
  1152. }
  1153. refreshDescendants()
  1154. descendantSampler = setInterval(refreshDescendants, 5000)
  1155. // A gate that settles while an enumeration is still running must not
  1156. // leave the PowerShell subprocess holding stdio handles until its own
  1157. // timeout: stop it as soon as the child's outcome is known.
  1158. child.once('close', cancelInFlightEnumeration)
  1159. child.once('error', cancelInFlightEnumeration)
  1160. }
  1161. child.on('error', (error) => {
  1162. if (escalation !== undefined) clearTimeout(escalation)
  1163. if (pipeDrain !== undefined) clearTimeout(pipeDrain)
  1164. if (descendantSampler !== undefined) clearInterval(descendantSampler)
  1165. if (signal !== undefined) signal.removeEventListener('abort', terminate)
  1166. spawnError = `failed to start command: ${error.message}`
  1167. resolveExit({ exitCode: null, signalCode: null })
  1168. })
  1169. child.on('close', (exitCode, signalCode) => {
  1170. if (pipeDrain !== undefined) clearTimeout(pipeDrain)
  1171. if (descendantSampler !== undefined) clearInterval(descendantSampler)
  1172. if (signal !== undefined) signal.removeEventListener('abort', terminate)
  1173. if (escalation !== undefined && process.platform !== 'win32') {
  1174. // `close` only means the direct child's stdio closed; a grandchild
  1175. // that ignored SIGTERM and redirected its stdio can outlive it. Do
  1176. // not settle until the process group and the captured descendants are
  1177. // confirmed gone — the deadline SIGKILL covers members still alive at
  1178. // the grace end — so runGate returns only once the tree is quiescent.
  1179. const confirmGroupGone = () => {
  1180. if (!groupAlive(child.pid) && descendants.every(descendantPid => !processAlive(descendantPid))) {
  1181. clearTimeout(escalation)
  1182. resolveExit({ exitCode, signalCode })
  1183. return
  1184. }
  1185. if (Date.now() - terminatedAt < 8000) {
  1186. setTimeout(confirmGroupGone, 50)
  1187. return
  1188. }
  1189. // The grace ended with members still alive (e.g. uninterruptible
  1190. // I/O that even SIGKILL cannot cut). Fail loud instead of reporting
  1191. // a quiescent tree: the gate is recorded failed either way.
  1192. console.error(`run-gates: gate tree not quiescent after 8s (${gate.label}).`)
  1193. clearTimeout(escalation)
  1194. resolveExit({ exitCode, signalCode })
  1195. }
  1196. confirmGroupGone()
  1197. return
  1198. }
  1199. if (escalation !== undefined) clearTimeout(escalation)
  1200. resolveExit({ exitCode, signalCode })
  1201. })
  1202. child.stdin.end()
  1203. })
  1204. const { exitCode, signalCode } = outcome
  1205. const status: GateResultStatus = exitCode === 0 && signalCode === null && spawnError === undefined ? 'passed' : 'failed'
  1206. const result: GateResult = {
  1207. gate,
  1208. status,
  1209. durationMs: performance.now() - started,
  1210. output,
  1211. exitCode,
  1212. signalCode,
  1213. }
  1214. result.aborted = aborted
  1215. if (spawnError !== undefined) result.error = spawnError
  1216. return result
  1217. }
  1218. /**
  1219. * Parse the state, parent, and process-group fields from a `/proc/<pid>/stat`
  1220. * line. The comm field may contain spaces and parentheses, so the state starts
  1221. * after the last closing parenthesis.
  1222. * @param stat - one `/proc/<pid>/stat` line.
  1223. * @returns state, parent pid, and process-group pid; undefined when truncated.
  1224. */
  1225. function procStatFields(stat: string): { state: string; ppid: number; pgrp: number } | undefined {
  1226. const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ')
  1227. const state = fields[0]
  1228. const ppid = fields[1]
  1229. const pgrp = fields[2]
  1230. if (state === undefined || ppid === undefined || pgrp === undefined) return undefined
  1231. return { state, ppid: Number(ppid), pgrp: Number(pgrp) }
  1232. }
  1233. /**
  1234. * Whether one process is still executing. Zombies (state `Z`) do not count:
  1235. * they are dead records awaiting reaping, and kill(pid, 0) would report them
  1236. * as alive. Linux reads /proc/<pid>/stat to distinguish; other platforms fall
  1237. * back to the signal probe.
  1238. * @param pid - the process to probe.
  1239. */
  1240. function processAlive(pid: number): boolean {
  1241. if (process.platform === 'linux') {
  1242. try {
  1243. const parsed = procStatFields(readFileSync(`/proc/${pid}/stat`, 'utf8'))
  1244. return parsed !== undefined && parsed.state !== 'Z'
  1245. } catch {
  1246. return false
  1247. }
  1248. }
  1249. try {
  1250. process.kill(pid, 0)
  1251. return true
  1252. } catch {
  1253. return false
  1254. }
  1255. }
  1256. /**
  1257. * Whether any member of the child's POSIX process group is still executing.
  1258. * Zombie entries (state `Z`) do not count: they are dead records awaiting
  1259. * reaping, and the kill(-pid, 0) group probe would report them as alive.
  1260. * Linux enumerates /proc to distinguish after a fast-path group probe; other
  1261. * POSIX platforms fall back to the probe alone.
  1262. * @param pid - the group leader's pid; undefined or non-positive means the
  1263. * spawn failed and nothing is alive.
  1264. */
  1265. function groupAlive(pid: number | undefined): boolean {
  1266. if (pid === undefined || pid <= 0) return false
  1267. if (process.platform === 'linux') {
  1268. try {
  1269. process.kill(-pid, 0)
  1270. } catch {
  1271. // ESRCH: the group has no entries at all.
  1272. return false
  1273. }
  1274. try {
  1275. for (const entry of readdirSync('/proc')) {
  1276. if (!/^\d+$/.test(entry)) continue
  1277. try {
  1278. const parsed = procStatFields(readFileSync(`/proc/${entry}/stat`, 'utf8'))
  1279. if (parsed !== undefined && parsed.pgrp === pid && parsed.state !== 'Z') return true
  1280. } catch {
  1281. // The process exited mid-scan; it is not a live member.
  1282. }
  1283. }
  1284. return false
  1285. } catch {
  1286. return false
  1287. }
  1288. }
  1289. try {
  1290. process.kill(-pid, 0)
  1291. return true
  1292. } catch {
  1293. return false
  1294. }
  1295. }
  1296. /**
  1297. * The pids of every transitive descendant of `root`, read from the live
  1298. * process table. Linux walks /proc/<pid>/stat parent fields; other platforms
  1299. * parse `ps` (POSIX) or the CIM process table (Windows) output. This is one
  1300. * snapshot, not the full tree-ownership mechanism: terminate and the sampler
  1301. * rely on the 5-second cache to cross an intermediate that exited between
  1302. * ticks (reparented on POSIX, table record gone on Windows), so a single
  1303. * enumeration reaches only the descendants whose parent chain is still fully
  1304. * present in the table.
  1305. * @param root - the pid whose descendants are wanted.
  1306. * @returns descendant pids in breadth-first order; empty on enumeration failure.
  1307. */
  1308. function descendantPids(root: number): number[] {
  1309. if (root <= 0) return []
  1310. if (process.platform === 'linux') {
  1311. const rows: Array<[number, number]> = []
  1312. try {
  1313. for (const entry of readdirSync('/proc')) {
  1314. if (!/^\d+$/.test(entry)) continue
  1315. try {
  1316. const parsed = procStatFields(readFileSync(`/proc/${entry}/stat`, 'utf8'))
  1317. if (parsed !== undefined) rows.push([Number(entry), parsed.ppid])
  1318. } catch {
  1319. // The process exited mid-scan; skip it.
  1320. }
  1321. }
  1322. } catch {
  1323. return []
  1324. }
  1325. return collectDescendants(root, rows)
  1326. }
  1327. let ps: { error?: Error; stdout: string }
  1328. if (process.platform === 'win32') {
  1329. // taskkill /T covers the tree only while the root is alive; once the
  1330. // direct child exits (a descendant still holding the stdio write ends
  1331. // keeps `close` pending), abort must reach the survivors from a fresh
  1332. // enumeration. Windows keeps the exited parent's pid in its descendants'
  1333. // parent column, so this walk still finds the whole tree. A hung
  1334. // PowerShell (WMI/CIM service trouble) must not stall the abort path
  1335. // indefinitely, so the enumeration is bounded.
  1336. ps = spawnSync('powershell', processTableArgs('win32'), { encoding: 'utf8', timeout: 10000 })
  1337. } else {
  1338. ps = spawnSync('ps', processTableArgs('posix'), { encoding: 'utf8' })
  1339. }
  1340. if (ps.error !== undefined) return []
  1341. return collectDescendants(root, parsePidPpidLines(ps.stdout))
  1342. }
  1343. /**
  1344. * The process-table enumeration command for one platform. Windows queries the
  1345. * CIM provider through PowerShell (each line `pid ppid`); other platforms use
  1346. * `ps -axo pid=,ppid=`.
  1347. * @param platform - the target platform.
  1348. * @returns the command arguments to enumerate every live process's pid/ppid.
  1349. */
  1350. function processTableArgs(platform: 'win32' | 'posix'): string[] {
  1351. if (platform === 'win32') {
  1352. return ['-NoProfile', '-NonInteractive', '-Command', 'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId)" }']
  1353. }
  1354. return ['-axo', 'pid=,ppid=']
  1355. }
  1356. /**
  1357. * Asynchronous descendant enumeration, so a slow WMI/CIM call (bounded by a
  1358. * 10-second timeout) cannot block the event loop: the sampler runs it while
  1359. * the gate's output streams and exit handling must keep flowing. Returns the
  1360. * same descendant list as {@link descendantPids}; used by the fail-fast
  1361. * sampler only, never on the abort path (which needs the synchronous walk to
  1362. * capture the tree before any member exits).
  1363. * @param root - the pid whose descendants are wanted.
  1364. * @param platform - the platform whose table the enumeration reads.
  1365. * @returns a promise of descendant pids in breadth-first order; empty on
  1366. * enumeration failure.
  1367. */
  1368. function descendantPidsAsync(root: number, platform: NodeJS.Platform): { promise: Promise<number[]>; cancel: () => void } {
  1369. if (root <= 0 || platform === 'linux') {
  1370. // The /proc walk is synchronous inside the async wrapper so the sampler
  1371. // keeps the same contract on every platform; /proc reads are fast and
  1372. // need no subprocess, and a completed enumeration needs no cancellation.
  1373. return { promise: Promise.resolve(descendantPids(root)), cancel: () => {} }
  1374. }
  1375. const [command, args] = platform === 'win32'
  1376. ? ['powershell', processTableArgs('win32')]
  1377. : ['ps', processTableArgs('posix')]
  1378. const child = spawn(command, args, {
  1379. stdio: ['ignore', 'pipe', 'ignore'],
  1380. timeout: platform === 'win32' ? 10000 : undefined,
  1381. })
  1382. child.stdout.setEncoding('utf8')
  1383. let stdout = ''
  1384. let settled = false
  1385. let settle!: (value: number[]) => void
  1386. const promise = new Promise<number[]>((resolve) => { settle = resolve })
  1387. const finish = (value: number[]) => {
  1388. if (settled) return
  1389. settled = true
  1390. // The enumeration completed (or was cancelled): stop the subprocess so
  1391. // the gate does not wait on its stdio handles.
  1392. child.kill('SIGTERM')
  1393. settle(value)
  1394. }
  1395. child.stdout.on('data', (chunk: string) => { stdout += chunk })
  1396. child.on('error', () => { finish([]) })
  1397. child.on('close', () => { finish(collectDescendants(root, parsePidPpidLines(stdout))) })
  1398. return {
  1399. promise,
  1400. cancel: () => { finish([]) },
  1401. }
  1402. }
  1403. /** Parse `pid ppid` rows from a process-table dump. Both the POSIX `ps -axo
  1404. * pid=,ppid=` output and the Windows PowerShell `Get-CimInstance Win32_Process`
  1405. * projection emit one `pid ppid` pair per line.
  1406. * @param output - the raw dump text.
  1407. * @returns the parsed pid/ppid rows in line order; blank and malformed lines
  1408. * are dropped.
  1409. */
  1410. export function parsePidPpidLines(output: string): Array<[number, number]> {
  1411. const rows: Array<[number, number]> = []
  1412. for (const line of output.split('\n')) {
  1413. const match = line.trim().match(/^(\d+)\s+(\d+)$/)
  1414. if (match !== null) rows.push([Number(match[1]), Number(match[2])])
  1415. }
  1416. return rows
  1417. }
  1418. /**
  1419. * The taskkill invocations that terminate one Windows gate tree. The direct
  1420. * child leads, because a live `taskkill /T` walks its whole subtree in one
  1421. * call; each captured descendant follows individually, because when the root
  1422. * already exited (a descendant holding the stdio write ends keeps `close`
  1423. * pending) `taskkill /T` rooted at the dead pid finds nothing — Windows never
  1424. * reparents, so the ppid chain captured at terminate still reaches the whole
  1425. * tree, and `/T` lets a surviving intermediate carry its own subtree. A pid
  1426. * that exited between capture and termination is as tolerable as ESRCH on
  1427. * POSIX: taskkill reports a nonzero status that is deliberately unchecked.
  1428. * @param rootPid - the direct child's pid.
  1429. * @param descendants - the captured descendant pids.
  1430. * @returns one `taskkill` argument list per pid, in termination order.
  1431. */
  1432. export function taskkillArgs(rootPid: number, descendants: number[]): string[][] {
  1433. return [rootPid, ...descendants].map(pid => ['/PID', String(pid), '/T', '/F'])
  1434. }
  1435. /**
  1436. * Walk a process-table snapshot without revisiting duplicate or cyclic PID links.
  1437. * @param root - process whose descendants are collected; excluded from the result.
  1438. * @param rows - observed PID and parent PID pairs.
  1439. * @returns distinct reachable descendants in breadth-first order.
  1440. */
  1441. export function collectDescendants(root: number, rows: Array<[number, number]>): number[] {
  1442. const byParent = new Map<number, number[]>()
  1443. for (const [pid, ppid] of rows) {
  1444. const children = byParent.get(ppid) ?? []
  1445. children.push(pid)
  1446. byParent.set(ppid, children)
  1447. }
  1448. const seen = new Set([root])
  1449. const queue = [root]
  1450. for (const parent of queue) {
  1451. for (const pid of byParent.get(parent) ?? []) {
  1452. if (seen.has(pid)) continue
  1453. seen.add(pid)
  1454. queue.push(pid)
  1455. }
  1456. }
  1457. return queue.slice(1)
  1458. }
  1459. /**
  1460. * Format every independently observed failure fact for the aggregate summary.
  1461. * @param result - unsuccessful gate result.
  1462. * @returns error, exit, and signal facts without allowing one to hide another.
  1463. */
  1464. export function formatGateResultReason(result: GateResult): string {
  1465. const facts: string[] = []
  1466. if (result.error !== undefined) facts.push(result.error)
  1467. if (result.exitCode !== null) facts.push(`exit ${result.exitCode}`)
  1468. if (result.signalCode !== null) facts.push(`signal ${result.signalCode}`)
  1469. return facts.length === 0 ? 'no exit code or signal' : facts.join(', ')
  1470. }
  1471. function printResult(result: GateResult): void {
  1472. const verbose = process.env.DSH_GATE_VERBOSE === '1'
  1473. const seconds = (result.durationMs / 1000).toFixed(2)
  1474. if (result.status === 'passed' && !verbose) {
  1475. console.log(`run-gates: PASS ${result.gate.label} (${seconds}s)`)
  1476. return
  1477. }
  1478. const heading = `${result.status.toUpperCase()} ${result.gate.label} (${seconds}s)`
  1479. const writeHeading = result.status === 'passed' ? console.log : console.error
  1480. writeHeading(`\n== ${heading} ==`)
  1481. if (result.status !== 'passed') {
  1482. console.error(`command: ${result.gate.displayCommand}`)
  1483. console.error(`outcome: ${formatGateResultReason(result)}`)
  1484. }
  1485. if (result.gate.streamOutput !== true) printOutput(result.output)
  1486. }
  1487. function printSummary(results: GateResult[], durationMs: number): void {
  1488. const passed = results.filter(result => result.status === 'passed').length
  1489. const failed = results.filter(result => result.status === 'failed').length
  1490. const skipped = results.filter(result => result.status === 'skipped').length
  1491. const seconds = (durationMs / 1000).toFixed(2)
  1492. console.log(`\nrun-gates: ${passed} passed, ${failed} failed, ${skipped} skipped in ${seconds}s.`)
  1493. const unsuccessful = results.filter(result => result.status === 'failed' || result.status === 'skipped')
  1494. if (unsuccessful.length === 0) return
  1495. console.error('run-gates: unsuccessful gates:')
  1496. for (const result of unsuccessful) {
  1497. const duration = (result.durationMs / 1000).toFixed(2)
  1498. const reason = formatGateResultReason(result)
  1499. const disposition = result.gate.allowFailure === true ? 'NON-BLOCKING ' : ''
  1500. console.error(` - ${disposition}${result.status.toUpperCase()} ${result.gate.label} (${duration}s, ${reason})`)
  1501. console.error(` ${result.gate.displayCommand}`)
  1502. }
  1503. }
  1504. function printOutput(output: GateOutputChunk[]): void {
  1505. for (const chunk of output) {
  1506. if (chunk.stream === 'stdout') process.stdout.write(chunk.text)
  1507. else process.stderr.write(chunk.text)
  1508. }
  1509. }