run-gates.ts 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608
  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. ], {
  741. label: 'documentation site checks',
  742. }),
  743. pnpmScript('package-readme-limitations', 'verify-package-readme-limitations', { label: 'package README limitations', quick: true }),
  744. ]
  745. }
  746. /**
  747. * The quick comprehensive documentation-standard aggregate for `test:docs`.
  748. * It covers the prose, pairing, README, budget, and Agent Note gates
  749. * without builds, generator regeneration, or the VitePress site build.
  750. */
  751. function docQuickLeafGates(): Gate[] {
  752. return docSyncLeafGates({ includeDocTypecheck: false }).filter(gate => gate.quick === true)
  753. }
  754. function builtBinSmokeGate(needs: string[] = ['build']): Gate {
  755. return pnpmExec('built-bin-smoke', [
  756. 'vitest',
  757. 'run',
  758. '--config',
  759. 'vitest.e2e.config.ts',
  760. 'apps/cli/tests/profiles/headless/tests/keyless-smoke.e2e.ts',
  761. 'apps/cli/tests/built-bin.e2e.ts',
  762. 'packages/host/directory-picker-native/tests/built-worker.e2e.ts',
  763. 'packages/sdk/server/tests/built-scope-carrier.e2e.ts',
  764. 'packages/fs/tool-present/tests/built-errors.e2e.ts',
  765. 'packages/subprocess/subprocess-local/tests/spawn-runner-built.e2e.ts',
  766. 'packages/subagent/subagent-codex/tests/loader-composition.e2e.ts',
  767. 'packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts',
  768. 'packages/api/remotes/tests/built-lib.e2e.ts',
  769. 'packages/experimental/agent-team/tests/built-lib.e2e.ts',
  770. // Built execution consumers: the only automated proof that package-name
  771. // imports reach their lib/ entrypoints under plain Node. The e2e lane runs
  772. // unbuilt, so these files self-skip there.
  773. 'packages/workflow/workflow-ptc/tests/built-runtime.e2e.ts',
  774. 'packages/ptc-runtime/ptc-runtime-node/tests/built-lib.e2e.ts',
  775. 'packages/session/session-persistence-jsonl/tests/built-migration-worker.e2e.ts',
  776. 'packages/lsp/lsp-stdio/tests/built-lib.e2e.ts',
  777. ], {
  778. label: 'built-bin smoke',
  779. needs,
  780. env: { DSH_EXAMPLE_MODE: 'lib' },
  781. })
  782. }
  783. /**
  784. * Reject a gate list whose graph cannot be executed unambiguously.
  785. * @param gates - complete aggregate to validate.
  786. */
  787. function validateGateGraph(gates: readonly Gate[]): void {
  788. if (gates.length === 0) throw new Error('run-gates: gate graph has no gates.')
  789. const ids = new Set<string>()
  790. for (const gate of gates) {
  791. if (ids.has(gate.id)) throw new Error(`run-gates: duplicate gate id ${JSON.stringify(gate.id)}.`)
  792. ids.add(gate.id)
  793. }
  794. for (const gate of gates) {
  795. for (const dependency of gate.needs ?? []) {
  796. if (!ids.has(dependency)) {
  797. throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} depends on unknown gate ${JSON.stringify(dependency)}.`)
  798. }
  799. }
  800. for (const predecessor of gate.after ?? []) {
  801. if (!ids.has(predecessor)) {
  802. throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} waits for unknown gate ${JSON.stringify(predecessor)}.`)
  803. }
  804. }
  805. }
  806. const cycle = findDependencyCycle(gates)
  807. if (cycle !== undefined) throw new Error(`run-gates: dependency cycle: ${cycle.join(' -> ')}.`)
  808. }
  809. function findDependencyCycle(gates: readonly Gate[]): string[] | undefined {
  810. const byId = new Map(gates.map(gate => [gate.id, gate]))
  811. const complete = new Set<string>()
  812. const active = new Map<string, number>()
  813. const path: string[] = []
  814. const visit = (id: string): string[] | undefined => {
  815. if (complete.has(id)) return undefined
  816. const cycleStart = active.get(id)
  817. if (cycleStart !== undefined) return [...path.slice(cycleStart), id]
  818. const gate = byId.get(id)
  819. if (gate === undefined) return undefined
  820. active.set(id, path.length)
  821. path.push(id)
  822. for (const predecessor of [...(gate.needs ?? []), ...(gate.after ?? [])]) {
  823. const cycle = visit(predecessor)
  824. if (cycle !== undefined) return cycle
  825. }
  826. path.pop()
  827. active.delete(id)
  828. complete.add(id)
  829. return undefined
  830. }
  831. for (const gate of gates) {
  832. const cycle = visit(gate.id)
  833. if (cycle !== undefined) return cycle
  834. }
  835. return undefined
  836. }
  837. /**
  838. * Scheduling options for one aggregate.
  839. */
  840. export interface RunGatesOptions {
  841. /** Stop the aggregate at the first blocking gate failure. */
  842. failFast?: boolean
  843. /** Forward host SIGINT/SIGTERM to the abort path so detached gate trees are
  844. * terminated when the run itself is interrupted or the runner cancels it.
  845. * Tree termination additionally requires failFast, because only then is the
  846. * abort signal passed to the executor and children detached. */
  847. forwardProcessSignals?: boolean
  848. }
  849. /**
  850. * Validate and run one aggregate before the injected executor can start a child.
  851. * @param gates - complete aggregate to execute.
  852. * @param maxActive - maximum concurrent child count.
  853. * @param execute - child-process executor; receives the abort signal only when
  854. * fail-fast is enabled, so ordinary runs keep their children in the host
  855. * process group.
  856. * @param observe - result observer invoked when each gate settles.
  857. * @param options - scheduling options; fail-fast aborts the aggregate at the
  858. * first blocking gate failure by killing running children and skipping every
  859. * not-yet-run gate.
  860. * @returns results in aggregate order.
  861. */
  862. export async function runGates(
  863. gates: Gate[],
  864. maxActive: number,
  865. execute: GateExecutor,
  866. observe: ResultObserver = () => {},
  867. options: RunGatesOptions = {},
  868. ): Promise<GateResult[]> {
  869. validateGateGraph(gates)
  870. if (!Number.isSafeInteger(maxActive) || maxActive < 1) {
  871. throw new Error(`run-gates: max concurrency must be a positive integer, got ${JSON.stringify(maxActive)}.`)
  872. }
  873. if (options.forwardProcessSignals === true && options.failFast !== true) {
  874. throw new Error('run-gates: forwardProcessSignals requires failFast, otherwise no child is detached or killed.')
  875. }
  876. const states = new Map<string, GateState>(gates.map(gate => [gate.id, 'pending']))
  877. const results = new Map<string, GateResult>()
  878. const running: RunningGate[] = []
  879. const abort = new AbortController()
  880. let abortCause: string | undefined
  881. // Host interruption (terminal Ctrl+C, runner cancellation) drains through
  882. // the same abort path as a gate failure, so detached trees are killed and
  883. // never orphaned. Handlers are removed before returning.
  884. const hostSignals = options.forwardProcessSignals === true ? ['SIGINT', 'SIGTERM'] as const : []
  885. const hostHandlers = hostSignals.map((name) => {
  886. const handler = () => {
  887. abortCause = abortCause ?? 'host interruption'
  888. abort.abort()
  889. }
  890. process.on(name, handler)
  891. return { name, handler }
  892. })
  893. const failFastSignal = options.failFast === true ? abort.signal : undefined
  894. try {
  895. for (;;) {
  896. let madeProgress = false
  897. if (abortCause === undefined) {
  898. while (running.length < maxActive) {
  899. const ready = gates.find(gate => states.get(gate.id) === 'pending' && predecessorsReady(gate, states))
  900. if (ready === undefined) break
  901. states.set(ready.id, 'running')
  902. running.push({ gate: ready, promise: execute(ready, failFastSignal) })
  903. console.log(`run-gates: start ${ready.label}`)
  904. madeProgress = true
  905. }
  906. }
  907. if (running.length === 0) {
  908. if (abortCause !== undefined) {
  909. for (const gate of gates) {
  910. if (states.get(gate.id) !== 'pending') continue
  911. const skipped = skippedByFailFast(gate, abortCause)
  912. states.set(gate.id, 'skipped')
  913. results.set(gate.id, skipped)
  914. observe(skipped)
  915. }
  916. break
  917. }
  918. const pending = gates.filter(gate => states.get(gate.id) === 'pending')
  919. if (pending.length === 0) break
  920. const gate = pending.find(item => (item.needs ?? []).some(id => gateFailed(states.get(id))))
  921. if (gate === undefined) throw new Error('run-gates: validated graph stalled without a failed dependency.')
  922. const failedDeps = (gate.needs ?? []).filter(id => gateFailed(states.get(id)))
  923. const result: GateResult = {
  924. gate,
  925. status: 'skipped',
  926. durationMs: 0,
  927. output: [],
  928. exitCode: null,
  929. signalCode: null,
  930. error: `dependency failed or skipped: ${failedDeps.join(', ')}`,
  931. }
  932. states.set(gate.id, 'skipped')
  933. results.set(gate.id, result)
  934. observe(result)
  935. continue
  936. }
  937. if (!madeProgress) {
  938. const settled = await Promise.race(running.map(async item => ({ item, result: await item.promise })))
  939. running.splice(running.indexOf(settled.item), 1)
  940. const observed = abortCause === undefined || settled.result.aborted !== true
  941. ? settled.result
  942. : skippedByFailFast(settled.item.gate, abortCause)
  943. states.set(settled.item.gate.id, observed.status)
  944. results.set(settled.item.gate.id, observed)
  945. observe(observed)
  946. if (abortCause === undefined && options.failFast === true
  947. && observed.status === 'failed' && settled.item.gate.allowFailure !== true) {
  948. abortCause = `${observed.gate.label} failed`
  949. abort.abort()
  950. console.error(`run-gates: fail-fast aborting: ${abortCause}.`)
  951. for (const gate of gates) {
  952. if (states.get(gate.id) !== 'pending') continue
  953. const skipped = skippedByFailFast(gate, abortCause)
  954. states.set(gate.id, 'skipped')
  955. results.set(gate.id, skipped)
  956. observe(skipped)
  957. }
  958. }
  959. }
  960. }
  961. } finally {
  962. for (const { name, handler } of hostHandlers) process.removeListener(name, handler)
  963. }
  964. return gates.map((gate) => {
  965. const result = results.get(gate.id)
  966. if (result === undefined) throw new Error(`run-gates: missing result for ${gate.id}.`)
  967. return result
  968. })
  969. }
  970. /**
  971. * The result of a gate that produced no evidence because fail-fast aborted.
  972. * A gate whose process settled before the abort took effect keeps its real
  973. * result instead: it did produce evidence, and the summary must say so. Any
  974. * result settling after the abort — including a genuine independent failure
  975. * in the race window, and a child that trapped the signal and exited zero —
  976. * is recorded skipped with its partial output discarded, because on Windows a
  977. * killed process is indistinguishable from a failed one by exit code alone.
  978. * @param gate - the gate that produced no evidence.
  979. * @param cause - the full clause naming what aborted the aggregate, e.g.
  980. * `typecheck failed` or `host interruption`.
  981. * @returns the skipped record with the fail-fast error.
  982. */
  983. function skippedByFailFast(gate: Gate, cause: string): GateResult {
  984. return {
  985. gate,
  986. status: 'skipped',
  987. durationMs: 0,
  988. output: [],
  989. exitCode: null,
  990. signalCode: null,
  991. error: `aborted by fail-fast: ${cause}`,
  992. }
  993. }
  994. function predecessorsReady(gate: Gate, states: Map<string, GateState>): boolean {
  995. return (gate.needs ?? []).every(id => states.get(id) === 'passed')
  996. && (gate.after ?? []).every(id => gateSettled(states.get(id)))
  997. }
  998. function gateSettled(state: GateState | undefined): boolean {
  999. return state === 'passed' || state === 'failed' || state === 'skipped'
  1000. }
  1001. function gateFailed(state: GateState | undefined): boolean {
  1002. return state === 'failed' || state === 'skipped'
  1003. }
  1004. /**
  1005. * Execute one gate through the real shell-free child-process boundary.
  1006. * @param gate - command and scheduler environment to execute.
  1007. * @param signal - abort signal that terminates the whole gate process tree when
  1008. * the aggregate fails fast; an already-aborted signal terminates it
  1009. * immediately. A provided signal spawns the child detached so POSIX can signal
  1010. * its process group and Windows can reach its tree through taskkill.
  1011. * @returns the complete process outcome.
  1012. */
  1013. export async function runGate(gate: Gate, signal?: AbortSignal): Promise<GateResult> {
  1014. const started = performance.now()
  1015. const output: GateOutputChunk[] = []
  1016. let spawnError: string | undefined
  1017. let aborted = false
  1018. const outcome = await new Promise<{
  1019. exitCode: number | null
  1020. signalCode: NodeJS.Signals | null
  1021. }>((resolveExit) => {
  1022. const child = spawn(gate.command, gate.args, {
  1023. cwd: root,
  1024. env: { ...process.env, ...gate.env },
  1025. stdio: ['pipe', 'pipe', 'pipe'],
  1026. detached: signal !== undefined && process.platform !== 'win32',
  1027. })
  1028. child.stdout.setEncoding('utf8')
  1029. child.stderr.setEncoding('utf8')
  1030. child.stdout.on('data', (chunk: string) => {
  1031. if (gate.streamOutput === true) process.stdout.write(chunk)
  1032. else output.push({ stream: 'stdout', text: chunk })
  1033. })
  1034. child.stderr.on('data', (chunk: string) => {
  1035. if (gate.streamOutput === true) process.stderr.write(chunk)
  1036. else output.push({ stream: 'stderr', text: chunk })
  1037. })
  1038. // Deliver one signal to the entire gate tree: the negative pid targets the
  1039. // POSIX process group the detached child leads; Windows has no groups, so
  1040. // taskkill walks the tree rooted at the child and force-terminates (a
  1041. // taskkill without `/F` does not terminate console processes, which is
  1042. // what gate commands are). Outcomes are deliberately unchecked because
  1043. // delivery races tree exit, and a missing taskkill binary is as tolerable
  1044. // as ESRCH. Mirrors the subprocess package's teardown contract
  1045. // (packages/subprocess/subprocess-local/src/spawn.ts).
  1046. const treeKill = (signalToSend: 'SIGTERM' | 'SIGKILL') => {
  1047. const pid = child.pid
  1048. if (pid === undefined) return
  1049. if (process.platform === 'win32') {
  1050. for (const args of taskkillArgs(pid, descendants)) {
  1051. spawnSync('taskkill', args, { stdio: 'ignore' })
  1052. }
  1053. return
  1054. }
  1055. try {
  1056. process.kill(-pid, signalToSend)
  1057. } catch {
  1058. // The group is gone; the direct child may still be alive alone.
  1059. child.kill(signalToSend)
  1060. }
  1061. // The captured list stays valid after the group kill reparents the
  1062. // detached descendants of a nested run-gates (the `check:node-compat`
  1063. // and `check:ci:lint:contracts-ready` gates in ci-consumers): pids do
  1064. // not change on reparenting, so the escalation reaches leaves that
  1065. // ignored SIGTERM without re-enumerating.
  1066. for (const descendantPid of descendants) {
  1067. try {
  1068. process.kill(descendantPid, signalToSend)
  1069. } catch {
  1070. // The descendant exited between the enumeration and the signal.
  1071. }
  1072. }
  1073. }
  1074. let escalation: ReturnType<typeof setTimeout> | undefined
  1075. let terminatedAt = 0
  1076. // Captured once at terminate and re-signalled on escalation: the group
  1077. // kill reaps the direct child, after which its detached descendants are
  1078. // reparented and unreachable by parent id, so the escalation cannot
  1079. // re-enumerate them.
  1080. let descendants: number[] = []
  1081. let pipeDrain: ReturnType<typeof setTimeout> | undefined
  1082. const terminate = () => {
  1083. aborted = true
  1084. const pid = child.pid
  1085. // Merge while the child is still alive: re-enumerating alone would drop
  1086. // a descendant that an exited intermediate reparented out of the parent
  1087. // chain, and replacing the list entirely would lose the sampler's
  1088. // last-known entries when the child already exited. Union preserves both.
  1089. // The sampler runs on every platform (including Windows, where an
  1090. // exited intermediate's table record vanishes and a fresh enumeration
  1091. // cannot cross the gap), so the cache is the source of truth once the
  1092. // child is gone.
  1093. if (pid !== undefined && child.exitCode === null && child.signalCode === null) {
  1094. descendants = [...new Set([...descendants, ...descendantPids(pid)])]
  1095. }
  1096. treeKill('SIGTERM')
  1097. if (escalation === undefined) {
  1098. terminatedAt = Date.now()
  1099. // Force-kill at the deadline regardless of the direct child's exit
  1100. // state: when the wrapper dies but a grandchild ignores SIGTERM and
  1101. // still holds the stdio pipes, `close` has not fired and the tree must
  1102. // still be killed. treeKill swallows an already-absent group.
  1103. escalation = setTimeout(() => { treeKill('SIGKILL') }, 5000)
  1104. }
  1105. if (pipeDrain === undefined) {
  1106. // `close` can stay pending past the direct child's exit when a
  1107. // descendant holds the stdio write ends (escaped process group, or
  1108. // uninterruptible I/O that keeps the SIGKILL pending). Bound the wait
  1109. // past the 5-second SIGKILL grace and force the streams closed so
  1110. // fail-fast settles instead of hanging to the job timeout. Only the
  1111. // abort path arms it: on an ordinary run a gate that outlives its
  1112. // descendants must keep waiting rather than report passed over a live
  1113. // leak. Armed in terminate (not only at `exit`) so the window where
  1114. // the child already exited before the abort is covered too.
  1115. pipeDrain = setTimeout(() => {
  1116. child.stdout.destroy()
  1117. child.stderr.destroy()
  1118. child.stdin.destroy()
  1119. }, 10000)
  1120. }
  1121. }
  1122. if (signal !== undefined) {
  1123. if (signal.aborted) terminate()
  1124. else signal.addEventListener('abort', terminate, { once: true })
  1125. }
  1126. // Refresh the descendant cache while the child runs, so an abort that
  1127. // arrives after the child already exited can still reach a detached
  1128. // descendant the child left behind: once the child is gone, its
  1129. // descendants are reparented (POSIX) or their intermediate's table record
  1130. // is gone (Windows), so a fresh enumeration cannot cross the gap. The
  1131. // cache is primed at spawn and refreshed every 5 seconds, so a descendant
  1132. // is captured once it appears in any enumeration whose parent chain is
  1133. // still fully present in the table; the residual window is a descendant
  1134. // that never appears in such a snapshot — created after one enumeration
  1135. // and orphaned before the next. Enumeration is asynchronous (a slow
  1136. // WMI/CIM call is bounded by its own 10-second timeout), so a gate's
  1137. // output draining and exit handling are never blocked while the sampler
  1138. // reads the process table. Fail-fast runs only; ordinary runs never
  1139. // abort.
  1140. let descendantSampler: ReturnType<typeof setInterval> | undefined
  1141. if (signal !== undefined) {
  1142. let enumerationInFlight: { cancel: () => void } | undefined
  1143. const refreshDescendants = () => {
  1144. const pid = child.pid
  1145. if (pid === undefined || child.exitCode !== null || child.signalCode !== null) return
  1146. if (enumerationInFlight !== undefined) return
  1147. const handle = descendantPidsAsync(pid, process.platform)
  1148. enumerationInFlight = handle
  1149. void handle.promise.then((fresh) => {
  1150. if (enumerationInFlight === handle) enumerationInFlight = undefined
  1151. // Merge regardless of the child's exit state: the enumeration
  1152. // started while the child was alive, so its snapshot is the last
  1153. // reliable view of the tree. The child may exit (its intermediate
  1154. // gone, its table record vanished) before the promise settles while
  1155. // a grandchild still holds the stdio write ends and keeps `close`
  1156. // pending — exactly when terminate needs this list.
  1157. // Merge instead of replacing, like terminate: an intermediate that
  1158. // exited since the last tick reparented its detached descendants
  1159. // out of the parent chain, so a fresh enumeration alone would drop
  1160. // them. Filter the cache to the still-executing so a long gate
  1161. // does not accumulate stale pids; while sampler ticks still run the
  1162. // live filter also keeps the escalation from signalling a reused
  1163. // pid, but once ticks stop (child exited) the cache can go stale,
  1164. // and a pid reused after that is the accepted sampling window.
  1165. descendants = [...new Set([...descendants.filter(processAlive), ...fresh])]
  1166. })
  1167. }
  1168. const cancelInFlightEnumeration = () => {
  1169. if (enumerationInFlight !== undefined) enumerationInFlight.cancel()
  1170. enumerationInFlight = undefined
  1171. }
  1172. refreshDescendants()
  1173. descendantSampler = setInterval(refreshDescendants, 5000)
  1174. // A gate that settles while an enumeration is still running must not
  1175. // leave the PowerShell subprocess holding stdio handles until its own
  1176. // timeout: stop it as soon as the child's outcome is known.
  1177. child.once('close', cancelInFlightEnumeration)
  1178. child.once('error', cancelInFlightEnumeration)
  1179. }
  1180. child.on('error', (error) => {
  1181. if (escalation !== undefined) clearTimeout(escalation)
  1182. if (pipeDrain !== undefined) clearTimeout(pipeDrain)
  1183. if (descendantSampler !== undefined) clearInterval(descendantSampler)
  1184. if (signal !== undefined) signal.removeEventListener('abort', terminate)
  1185. spawnError = `failed to start command: ${error.message}`
  1186. resolveExit({ exitCode: null, signalCode: null })
  1187. })
  1188. child.on('close', (exitCode, signalCode) => {
  1189. if (pipeDrain !== undefined) clearTimeout(pipeDrain)
  1190. if (descendantSampler !== undefined) clearInterval(descendantSampler)
  1191. if (signal !== undefined) signal.removeEventListener('abort', terminate)
  1192. if (escalation !== undefined && process.platform !== 'win32') {
  1193. // `close` only means the direct child's stdio closed; a grandchild
  1194. // that ignored SIGTERM and redirected its stdio can outlive it. Do
  1195. // not settle until the process group and the captured descendants are
  1196. // confirmed gone — the deadline SIGKILL covers members still alive at
  1197. // the grace end — so runGate returns only once the tree is quiescent.
  1198. const confirmGroupGone = () => {
  1199. if (!groupAlive(child.pid) && descendants.every(descendantPid => !processAlive(descendantPid))) {
  1200. clearTimeout(escalation)
  1201. resolveExit({ exitCode, signalCode })
  1202. return
  1203. }
  1204. if (Date.now() - terminatedAt < 8000) {
  1205. setTimeout(confirmGroupGone, 50)
  1206. return
  1207. }
  1208. // The grace ended with members still alive (e.g. uninterruptible
  1209. // I/O that even SIGKILL cannot cut). Fail loud instead of reporting
  1210. // a quiescent tree: the gate is recorded failed either way.
  1211. console.error(`run-gates: gate tree not quiescent after 8s (${gate.label}).`)
  1212. clearTimeout(escalation)
  1213. resolveExit({ exitCode, signalCode })
  1214. }
  1215. confirmGroupGone()
  1216. return
  1217. }
  1218. if (escalation !== undefined) clearTimeout(escalation)
  1219. resolveExit({ exitCode, signalCode })
  1220. })
  1221. child.stdin.end()
  1222. })
  1223. const { exitCode, signalCode } = outcome
  1224. const status: GateResultStatus = exitCode === 0 && signalCode === null && spawnError === undefined ? 'passed' : 'failed'
  1225. const result: GateResult = {
  1226. gate,
  1227. status,
  1228. durationMs: performance.now() - started,
  1229. output,
  1230. exitCode,
  1231. signalCode,
  1232. }
  1233. result.aborted = aborted
  1234. if (spawnError !== undefined) result.error = spawnError
  1235. return result
  1236. }
  1237. /**
  1238. * Parse the state, parent, and process-group fields from a `/proc/<pid>/stat`
  1239. * line. The comm field may contain spaces and parentheses, so the state starts
  1240. * after the last closing parenthesis.
  1241. * @param stat - one `/proc/<pid>/stat` line.
  1242. * @returns state, parent pid, and process-group pid; undefined when truncated.
  1243. */
  1244. function procStatFields(stat: string): { state: string; ppid: number; pgrp: number } | undefined {
  1245. const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ')
  1246. const state = fields[0]
  1247. const ppid = fields[1]
  1248. const pgrp = fields[2]
  1249. if (state === undefined || ppid === undefined || pgrp === undefined) return undefined
  1250. return { state, ppid: Number(ppid), pgrp: Number(pgrp) }
  1251. }
  1252. /**
  1253. * Whether one process is still executing. Zombies (state `Z`) do not count:
  1254. * they are dead records awaiting reaping, and kill(pid, 0) would report them
  1255. * as alive. Linux reads /proc/<pid>/stat to distinguish; other platforms fall
  1256. * back to the signal probe.
  1257. * @param pid - the process to probe.
  1258. */
  1259. function processAlive(pid: number): boolean {
  1260. if (process.platform === 'linux') {
  1261. try {
  1262. const parsed = procStatFields(readFileSync(`/proc/${pid}/stat`, 'utf8'))
  1263. return parsed !== undefined && parsed.state !== 'Z'
  1264. } catch {
  1265. return false
  1266. }
  1267. }
  1268. try {
  1269. process.kill(pid, 0)
  1270. return true
  1271. } catch {
  1272. return false
  1273. }
  1274. }
  1275. /**
  1276. * Whether any member of the child's POSIX process group is still executing.
  1277. * Zombie entries (state `Z`) do not count: they are dead records awaiting
  1278. * reaping, and the kill(-pid, 0) group probe would report them as alive.
  1279. * Linux enumerates /proc to distinguish after a fast-path group probe; other
  1280. * POSIX platforms fall back to the probe alone.
  1281. * @param pid - the group leader's pid; undefined or non-positive means the
  1282. * spawn failed and nothing is alive.
  1283. */
  1284. function groupAlive(pid: number | undefined): boolean {
  1285. if (pid === undefined || pid <= 0) return false
  1286. if (process.platform === 'linux') {
  1287. try {
  1288. process.kill(-pid, 0)
  1289. } catch {
  1290. // ESRCH: the group has no entries at all.
  1291. return false
  1292. }
  1293. try {
  1294. for (const entry of readdirSync('/proc')) {
  1295. if (!/^\d+$/.test(entry)) continue
  1296. try {
  1297. const parsed = procStatFields(readFileSync(`/proc/${entry}/stat`, 'utf8'))
  1298. if (parsed !== undefined && parsed.pgrp === pid && parsed.state !== 'Z') return true
  1299. } catch {
  1300. // The process exited mid-scan; it is not a live member.
  1301. }
  1302. }
  1303. return false
  1304. } catch {
  1305. return false
  1306. }
  1307. }
  1308. try {
  1309. process.kill(-pid, 0)
  1310. return true
  1311. } catch {
  1312. return false
  1313. }
  1314. }
  1315. /**
  1316. * The pids of every transitive descendant of `root`, read from the live
  1317. * process table. Linux walks /proc/<pid>/stat parent fields; other platforms
  1318. * parse `ps` (POSIX) or the CIM process table (Windows) output. This is one
  1319. * snapshot, not the full tree-ownership mechanism: terminate and the sampler
  1320. * rely on the 5-second cache to cross an intermediate that exited between
  1321. * ticks (reparented on POSIX, table record gone on Windows), so a single
  1322. * enumeration reaches only the descendants whose parent chain is still fully
  1323. * present in the table.
  1324. * @param root - the pid whose descendants are wanted.
  1325. * @returns descendant pids in breadth-first order; empty on enumeration failure.
  1326. */
  1327. function descendantPids(root: number): number[] {
  1328. if (root <= 0) return []
  1329. if (process.platform === 'linux') {
  1330. const rows: Array<[number, number]> = []
  1331. try {
  1332. for (const entry of readdirSync('/proc')) {
  1333. if (!/^\d+$/.test(entry)) continue
  1334. try {
  1335. const parsed = procStatFields(readFileSync(`/proc/${entry}/stat`, 'utf8'))
  1336. if (parsed !== undefined) rows.push([Number(entry), parsed.ppid])
  1337. } catch {
  1338. // The process exited mid-scan; skip it.
  1339. }
  1340. }
  1341. } catch {
  1342. return []
  1343. }
  1344. return collectDescendants(root, rows)
  1345. }
  1346. let ps: { error?: Error; stdout: string }
  1347. if (process.platform === 'win32') {
  1348. // taskkill /T covers the tree only while the root is alive; once the
  1349. // direct child exits (a descendant still holding the stdio write ends
  1350. // keeps `close` pending), abort must reach the survivors from a fresh
  1351. // enumeration. Windows keeps the exited parent's pid in its descendants'
  1352. // parent column, so this walk still finds the whole tree. A hung
  1353. // PowerShell (WMI/CIM service trouble) must not stall the abort path
  1354. // indefinitely, so the enumeration is bounded.
  1355. ps = spawnSync('powershell', processTableArgs('win32'), { encoding: 'utf8', timeout: 10000 })
  1356. } else {
  1357. ps = spawnSync('ps', processTableArgs('posix'), { encoding: 'utf8' })
  1358. }
  1359. if (ps.error !== undefined) return []
  1360. return collectDescendants(root, parsePidPpidLines(ps.stdout))
  1361. }
  1362. /**
  1363. * The process-table enumeration command for one platform. Windows queries the
  1364. * CIM provider through PowerShell (each line `pid ppid`); other platforms use
  1365. * `ps -axo pid=,ppid=`.
  1366. * @param platform - the target platform.
  1367. * @returns the command arguments to enumerate every live process's pid/ppid.
  1368. */
  1369. function processTableArgs(platform: 'win32' | 'posix'): string[] {
  1370. if (platform === 'win32') {
  1371. return ['-NoProfile', '-NonInteractive', '-Command', 'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId)" }']
  1372. }
  1373. return ['-axo', 'pid=,ppid=']
  1374. }
  1375. /**
  1376. * Asynchronous descendant enumeration, so a slow WMI/CIM call (bounded by a
  1377. * 10-second timeout) cannot block the event loop: the sampler runs it while
  1378. * the gate's output streams and exit handling must keep flowing. Returns the
  1379. * same descendant list as {@link descendantPids}; used by the fail-fast
  1380. * sampler only, never on the abort path (which needs the synchronous walk to
  1381. * capture the tree before any member exits).
  1382. * @param root - the pid whose descendants are wanted.
  1383. * @param platform - the platform whose table the enumeration reads.
  1384. * @returns a promise of descendant pids in breadth-first order; empty on
  1385. * enumeration failure.
  1386. */
  1387. function descendantPidsAsync(root: number, platform: NodeJS.Platform): { promise: Promise<number[]>; cancel: () => void } {
  1388. if (root <= 0 || platform === 'linux') {
  1389. // The /proc walk is synchronous inside the async wrapper so the sampler
  1390. // keeps the same contract on every platform; /proc reads are fast and
  1391. // need no subprocess, and a completed enumeration needs no cancellation.
  1392. return { promise: Promise.resolve(descendantPids(root)), cancel: () => {} }
  1393. }
  1394. const [command, args] = platform === 'win32'
  1395. ? ['powershell', processTableArgs('win32')]
  1396. : ['ps', processTableArgs('posix')]
  1397. const child = spawn(command, args, {
  1398. stdio: ['ignore', 'pipe', 'ignore'],
  1399. timeout: platform === 'win32' ? 10000 : undefined,
  1400. })
  1401. child.stdout.setEncoding('utf8')
  1402. let stdout = ''
  1403. let settled = false
  1404. let settle!: (value: number[]) => void
  1405. const promise = new Promise<number[]>((resolve) => { settle = resolve })
  1406. const finish = (value: number[]) => {
  1407. if (settled) return
  1408. settled = true
  1409. // The enumeration completed (or was cancelled): stop the subprocess so
  1410. // the gate does not wait on its stdio handles.
  1411. child.kill('SIGTERM')
  1412. settle(value)
  1413. }
  1414. child.stdout.on('data', (chunk: string) => { stdout += chunk })
  1415. child.on('error', () => { finish([]) })
  1416. child.on('close', () => { finish(collectDescendants(root, parsePidPpidLines(stdout))) })
  1417. return {
  1418. promise,
  1419. cancel: () => { finish([]) },
  1420. }
  1421. }
  1422. /** Parse `pid ppid` rows from a process-table dump. Both the POSIX `ps -axo
  1423. * pid=,ppid=` output and the Windows PowerShell `Get-CimInstance Win32_Process`
  1424. * projection emit one `pid ppid` pair per line.
  1425. * @param output - the raw dump text.
  1426. * @returns the parsed pid/ppid rows in line order; blank and malformed lines
  1427. * are dropped.
  1428. */
  1429. export function parsePidPpidLines(output: string): Array<[number, number]> {
  1430. const rows: Array<[number, number]> = []
  1431. for (const line of output.split('\n')) {
  1432. const match = line.trim().match(/^(\d+)\s+(\d+)$/)
  1433. if (match !== null) rows.push([Number(match[1]), Number(match[2])])
  1434. }
  1435. return rows
  1436. }
  1437. /**
  1438. * The taskkill invocations that terminate one Windows gate tree. The direct
  1439. * child leads, because a live `taskkill /T` walks its whole subtree in one
  1440. * call; each captured descendant follows individually, because when the root
  1441. * already exited (a descendant holding the stdio write ends keeps `close`
  1442. * pending) `taskkill /T` rooted at the dead pid finds nothing — Windows never
  1443. * reparents, so the ppid chain captured at terminate still reaches the whole
  1444. * tree, and `/T` lets a surviving intermediate carry its own subtree. A pid
  1445. * that exited between capture and termination is as tolerable as ESRCH on
  1446. * POSIX: taskkill reports a nonzero status that is deliberately unchecked.
  1447. * @param rootPid - the direct child's pid.
  1448. * @param descendants - the captured descendant pids.
  1449. * @returns one `taskkill` argument list per pid, in termination order.
  1450. */
  1451. export function taskkillArgs(rootPid: number, descendants: number[]): string[][] {
  1452. return [rootPid, ...descendants].map(pid => ['/PID', String(pid), '/T', '/F'])
  1453. }
  1454. /**
  1455. * Walk a process-table snapshot without revisiting duplicate or cyclic PID links.
  1456. * @param root - process whose descendants are collected; excluded from the result.
  1457. * @param rows - observed PID and parent PID pairs.
  1458. * @returns distinct reachable descendants in breadth-first order.
  1459. */
  1460. export function collectDescendants(root: number, rows: Array<[number, number]>): number[] {
  1461. const byParent = new Map<number, number[]>()
  1462. for (const [pid, ppid] of rows) {
  1463. const children = byParent.get(ppid) ?? []
  1464. children.push(pid)
  1465. byParent.set(ppid, children)
  1466. }
  1467. const seen = new Set([root])
  1468. const queue = [root]
  1469. for (const parent of queue) {
  1470. for (const pid of byParent.get(parent) ?? []) {
  1471. if (seen.has(pid)) continue
  1472. seen.add(pid)
  1473. queue.push(pid)
  1474. }
  1475. }
  1476. return queue.slice(1)
  1477. }
  1478. /**
  1479. * Format every independently observed failure fact for the aggregate summary.
  1480. * @param result - unsuccessful gate result.
  1481. * @returns error, exit, and signal facts without allowing one to hide another.
  1482. */
  1483. export function formatGateResultReason(result: GateResult): string {
  1484. const facts: string[] = []
  1485. if (result.error !== undefined) facts.push(result.error)
  1486. if (result.exitCode !== null) facts.push(`exit ${result.exitCode}`)
  1487. if (result.signalCode !== null) facts.push(`signal ${result.signalCode}`)
  1488. return facts.length === 0 ? 'no exit code or signal' : facts.join(', ')
  1489. }
  1490. function printResult(result: GateResult): void {
  1491. const verbose = process.env.DSH_GATE_VERBOSE === '1'
  1492. const seconds = (result.durationMs / 1000).toFixed(2)
  1493. if (result.status === 'passed' && !verbose) {
  1494. console.log(`run-gates: PASS ${result.gate.label} (${seconds}s)`)
  1495. return
  1496. }
  1497. const heading = `${result.status.toUpperCase()} ${result.gate.label} (${seconds}s)`
  1498. const writeHeading = result.status === 'passed' ? console.log : console.error
  1499. writeHeading(`\n== ${heading} ==`)
  1500. if (result.status !== 'passed') {
  1501. console.error(`command: ${result.gate.displayCommand}`)
  1502. console.error(`outcome: ${formatGateResultReason(result)}`)
  1503. }
  1504. if (result.gate.streamOutput !== true) printOutput(result.output)
  1505. }
  1506. function printSummary(results: GateResult[], durationMs: number): void {
  1507. const passed = results.filter(result => result.status === 'passed').length
  1508. const failed = results.filter(result => result.status === 'failed').length
  1509. const skipped = results.filter(result => result.status === 'skipped').length
  1510. const seconds = (durationMs / 1000).toFixed(2)
  1511. console.log(`\nrun-gates: ${passed} passed, ${failed} failed, ${skipped} skipped in ${seconds}s.`)
  1512. const unsuccessful = results.filter(result => result.status === 'failed' || result.status === 'skipped')
  1513. if (unsuccessful.length === 0) return
  1514. console.error('run-gates: unsuccessful gates:')
  1515. for (const result of unsuccessful) {
  1516. const duration = (result.durationMs / 1000).toFixed(2)
  1517. const reason = formatGateResultReason(result)
  1518. const disposition = result.gate.allowFailure === true ? 'NON-BLOCKING ' : ''
  1519. console.error(` - ${disposition}${result.status.toUpperCase()} ${result.gate.label} (${duration}s, ${reason})`)
  1520. console.error(` ${result.gate.displayCommand}`)
  1521. }
  1522. }
  1523. function printOutput(output: GateOutputChunk[]): void {
  1524. for (const chunk of output) {
  1525. if (chunk.stream === 'stdout') process.stdout.write(chunk.text)
  1526. else process.stderr.write(chunk.text)
  1527. }
  1528. }