run-gates.ts 66 KB

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