run-gates.ts 64 KB

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