run-gates.ts 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  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 } from 'node:child_process'
  9. import { availableParallelism } from 'node:os'
  10. import { resolve } from 'node:path'
  11. import { performance } from 'node:perf_hooks'
  12. import { CLIENT_BUILD_PROFILE_SELECTOR } from './client-build-environment.ts'
  13. import { COVERAGE_EXEMPT_ENV, coverageExemptHeavySuites } from './coverage-exempt.ts'
  14. import {
  15. COVERAGE_PARTITIONS_ENV,
  16. COVERAGE_TEST_TIMEOUT_ENV,
  17. coverageTestTimeoutArgs,
  18. parseCoveragePartitionCount,
  19. } from './coverage-partitions.ts'
  20. import { pnpmInvocation } from './pnpm-invocation.ts'
  21. /** A named aggregate exposed by the gate runner. */
  22. export type Mode =
  23. | 'ci-primary'
  24. | 'ci-linux-primary'
  25. | 'ci-static'
  26. | 'ci-lint-contracts-ready'
  27. | 'ci-coverage'
  28. | 'ci-snapshot'
  29. | 'ci-artifacts'
  30. | 'ci-consumers'
  31. | 'ci-windows-blocking'
  32. | 'ci-windows-complete'
  33. | 'ci-windows-observational'
  34. | 'node-compat'
  35. | 'check-all'
  36. | 'hygiene'
  37. | 'doc-sync'
  38. | 'doc-quick'
  39. type GateResultStatus = 'passed' | 'failed' | 'skipped'
  40. type GateState = 'pending' | 'running' | GateResultStatus
  41. /** A command and its dependency metadata inside one aggregate. */
  42. export interface Gate {
  43. id: string
  44. label: string
  45. displayCommand: string
  46. command: string
  47. args: string[]
  48. needs?: string[]
  49. /** Gate ids that must settle, regardless of outcome, before this gate starts. */
  50. after?: string[]
  51. env?: Record<string, string | undefined>
  52. /** Include this leaf in the build-free documentation aggregate. */
  53. quick?: boolean
  54. /** Keep a failure visible without failing the aggregate. */
  55. allowFailure?: boolean
  56. /** Write child output as it arrives instead of buffering it until completion. */
  57. streamOutput?: boolean
  58. }
  59. /** The observed outcome of one gate process. */
  60. export interface GateResult {
  61. gate: Gate
  62. status: GateResultStatus
  63. durationMs: number
  64. output: GateOutputChunk[]
  65. exitCode: number | null
  66. signalCode: NodeJS.Signals | null
  67. error?: string
  68. }
  69. interface GateOutputChunk {
  70. stream: 'stdout' | 'stderr'
  71. text: string
  72. }
  73. interface RunningGate {
  74. gate: Gate
  75. promise: Promise<GateResult>
  76. }
  77. interface ConcurrencyDefault {
  78. workers: number
  79. source: string
  80. }
  81. type GateExecutor = (gate: Gate) => Promise<GateResult>
  82. type ResultObserver = (result: GateResult) => void
  83. const root = resolve(import.meta.dirname, '..')
  84. if (import.meta.main) {
  85. process.exitCode = await main(process.argv.slice(2))
  86. }
  87. async function main(args: string[]): Promise<number> {
  88. const mode = parseMode(args[0])
  89. const gates = gatesForMode(mode)
  90. const concurrencyDefault = defaultConcurrency(mode, gates.length)
  91. const concurrencyOverride = process.env.DSH_GATE_CONCURRENCY
  92. const maxConcurrency = concurrencyFromEnv('DSH_GATE_CONCURRENCY', concurrencyDefault.workers)
  93. const concurrencySource = concurrencyOverride === undefined || concurrencyOverride === ''
  94. ? concurrencyDefault.source
  95. : '$DSH_GATE_CONCURRENCY'
  96. const startedAt = performance.now()
  97. console.log(`run-gates: ${mode} running ${gates.length} gate(s) with ${maxConcurrency} worker(s) from ${concurrencySource}.`)
  98. const results = await runGates(gates, maxConcurrency, runGate, printResult)
  99. printSummary(results, performance.now() - startedAt)
  100. return results.some(result => result.gate.allowFailure !== true && (result.status === 'failed' || result.status === 'skipped'))
  101. ? 1
  102. : 0
  103. }
  104. function parseMode(raw: string | undefined): Mode {
  105. switch (raw) {
  106. case 'ci-primary':
  107. case 'ci-linux-primary':
  108. case 'ci-static':
  109. case 'ci-lint-contracts-ready':
  110. case 'ci-coverage':
  111. case 'ci-snapshot':
  112. case 'ci-artifacts':
  113. case 'ci-consumers':
  114. case 'ci-windows-blocking':
  115. case 'ci-windows-complete':
  116. case 'ci-windows-observational':
  117. case 'node-compat':
  118. case 'check-all':
  119. case 'hygiene':
  120. case 'doc-sync':
  121. case 'doc-quick':
  122. return raw
  123. default:
  124. throw new Error(
  125. `run-gates: expected mode ci-primary | ci-linux-primary | ci-static | ci-lint-contracts-ready | ci-coverage | 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)}.`,
  126. )
  127. }
  128. }
  129. /**
  130. * Resolve the default worker count for one aggregate.
  131. * @param selectedMode - aggregate whose resource posture applies.
  132. * @param total - number of gates in the aggregate.
  133. * @param available - host CPU availability for ordinary modes.
  134. * @returns the default worker count and its diagnostic source.
  135. */
  136. export function defaultConcurrency(
  137. selectedMode: Mode,
  138. total: number,
  139. available = availableParallelism(),
  140. ): ConcurrencyDefault {
  141. if (selectedMode === 'ci-consumers') return { workers: total, source: 'ci-consumers gate count' }
  142. // Local modes cap workers: several doc gates each build a full ts.Program,
  143. // so an uncapped default on a large host trades wall clock for memory blowups.
  144. const localCap = selectedMode === 'check-all'
  145. || selectedMode === 'hygiene'
  146. || selectedMode === 'doc-sync'
  147. || selectedMode === 'doc-quick'
  148. const modeLimit = localCap ? Math.min(4, available) : available
  149. return {
  150. workers: Math.min(total, modeLimit),
  151. source: localCap
  152. ? `${available} available CPU(s), ${selectedMode} cap 4`
  153. : `${available} available CPU(s)`,
  154. }
  155. }
  156. function concurrencyFromEnv(name: string, fallback: number): number {
  157. const raw = process.env[name]
  158. if (raw === undefined || raw === '') return fallback
  159. const parsed = Number.parseInt(raw, 10)
  160. if (!Number.isSafeInteger(parsed) || parsed < 1) {
  161. throw new Error(`run-gates: ${name} must be a positive integer, got ${JSON.stringify(raw)}.`)
  162. }
  163. return parsed
  164. }
  165. function pnpmScript(id: string, script: string, options: Partial<Gate> = {}): Gate {
  166. return {
  167. id,
  168. label: options.label ?? script,
  169. displayCommand: `pnpm run ${script}`,
  170. ...pnpmInvocation(['run', script]),
  171. ...options,
  172. }
  173. }
  174. /** Build official client artifacts inside a CI aggregate without changing sibling gate environments. */
  175. function ciBuildGate(id = 'build', options: Partial<Gate> = {}): Gate {
  176. return pnpmScript(id, 'build', {
  177. ...options,
  178. env: { ...options.env, [CLIENT_BUILD_PROFILE_SELECTOR]: 'official' },
  179. })
  180. }
  181. function pnpmExec(id: string, args: string[], options: Partial<Gate> = {}): Gate {
  182. return {
  183. id,
  184. label: options.label ?? `pnpm exec ${args.join(' ')}`,
  185. displayCommand: `pnpm exec ${args.join(' ')}`,
  186. ...pnpmInvocation(['exec', ...args]),
  187. ...options,
  188. }
  189. }
  190. /**
  191. * Construct the complete gate list for a named aggregate.
  192. * @param selected - aggregate mode to construct.
  193. * @returns the aggregate's gate graph.
  194. */
  195. export function gatesForMode(selected: Mode): Gate[] {
  196. switch (selected) {
  197. case 'ci-primary':
  198. return ciPrimaryGates()
  199. case 'ci-linux-primary':
  200. return [...ciPrimaryGates(), webSnapshotGate(['built-package-invariants'])]
  201. case 'ci-static':
  202. return ciStaticGates({ ownsBuild: false })
  203. case 'ci-lint-contracts-ready':
  204. return [
  205. lintGate(),
  206. pnpmScript('duplication', 'duplication'),
  207. ]
  208. case 'ci-coverage':
  209. return coverageGates()
  210. case 'ci-snapshot':
  211. return [ciBuildGate(), snapshotGate()]
  212. case 'ci-artifacts':
  213. return ciArtifactGates()
  214. case 'ci-consumers':
  215. return ciConsumerGates()
  216. case 'ci-windows-blocking':
  217. return ciWindowsBlockingGates()
  218. case 'ci-windows-complete':
  219. return ciWindowsCompleteGates()
  220. case 'ci-windows-observational':
  221. return ciWindowsObservationalGates()
  222. case 'node-compat':
  223. return nodeCompatGates()
  224. case 'check-all':
  225. return [
  226. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  227. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  228. pnpmScript('client-domain-graph', 'verify-client-domain-graph', { label: 'client domain graph' }),
  229. pnpmScript('test', 'test'),
  230. pnpmScript('issue-management', 'test:issue-management', { label: 'Issue management policy' }),
  231. pnpmScript('duplication', 'duplication'),
  232. snapshotGate(),
  233. expectedOutputGate(),
  234. pnpmScript('build', 'build'),
  235. pnpmScript('build:web', 'build:web'),
  236. ...hygieneLeafGates({ artifactNeeds: ['build'] }),
  237. ...docSyncLeafGates({
  238. docTypecheckNeeds: ['build'],
  239. docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  240. docTypecheckScript: 'doc-typecheck:contracts-ready',
  241. }),
  242. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  243. ]
  244. case 'hygiene':
  245. return [
  246. ...hygieneLeafGates(),
  247. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  248. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  249. pnpmScript('vendored-links', 'verify-vendored-links', { label: 'vendored links' }),
  250. ]
  251. case 'doc-sync':
  252. return docSyncLeafGates()
  253. case 'doc-quick':
  254. return docQuickLeafGates()
  255. }
  256. }
  257. function ciSharedStaticGates(): Gate[] {
  258. return [
  259. pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
  260. pnpmScript('application-entrypoints', 'verify-application-entrypoints', { label: 'application entrypoints' }),
  261. pnpmScript('constraints', 'constraints'),
  262. pnpmScript('dsh-package-licenses', 'verify-dsh-package-licenses', { label: 'DSH package licenses' }),
  263. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  264. pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
  265. pnpmScript('optional-dependency-imports', 'verify-optional-dependency-imports', {
  266. label: 'optional dependency imports',
  267. }),
  268. pnpmScript('client-packages', 'verify-client-packages', { label: 'client packages' }),
  269. pnpmScript('client-ui-i18n', 'verify-client-ui-i18n', { label: 'client UI i18n' }),
  270. pnpmScript('issue-management', 'test:issue-management', { label: 'Issue management policy' }),
  271. ]
  272. }
  273. function ciPrimaryGates(): Gate[] {
  274. return [
  275. ...ciSharedStaticGates(),
  276. typertContractsGate(),
  277. pnpmScript('typecheck', 'typecheck:contracts-ready', { needs: ['typert-contracts'] }),
  278. lintGate({ needs: ['typert-contracts'] }),
  279. pnpmScript('duplication', 'duplication'),
  280. ...coverageGates(),
  281. ...nodeCompatSmokeGates(),
  282. snapshotGate(),
  283. ...docSyncLeafGates({
  284. docTypecheckNeeds: ['typert-contracts'],
  285. docTypecheckScript: 'doc-typecheck:contracts-ready',
  286. }),
  287. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  288. pnpmScript('knip', 'knip'),
  289. // The prepared typecheck and build both drive Client tsc, while build also
  290. // repeats the Host contract pass. Wait for all three consumers so build
  291. // neither races tsbuildinfo nor replaces declarations while they are read.
  292. ciBuildGate('build', { needs: ['typecheck', 'lint', 'doc-typecheck'] }),
  293. pnpmScript('publint', 'publint', { needs: ['build'] }),
  294. pnpmScript('node-next-types', 'verify-node-next-types', {
  295. label: 'node-next types',
  296. needs: ['build'],
  297. }),
  298. builtPackageInvariantsGate(['build']),
  299. builtBinSmokeGate(),
  300. ]
  301. }
  302. function nodeCompatGates(): Gate[] {
  303. const typecheck = flagEnabled('DSH_NODE_COMPAT_SKIP_TYPECHECK')
  304. ? []
  305. : [pnpmScript('typecheck', 'typecheck')]
  306. if (runningNodeMajor() !== 22) {
  307. return [...typecheck, ...nodeCompatSmokeGates()]
  308. }
  309. return [
  310. ...typecheck,
  311. pnpmScript('build', 'build', {
  312. ...typecheck.length === 0 ? {} : { needs: ['typecheck'] },
  313. }),
  314. pnpmScript('build:web', 'build:web', {
  315. label: 'Web frontend build',
  316. needs: ['build'],
  317. }),
  318. ...nodeCompatSmokeGates({ cliSmoke: true }),
  319. ]
  320. }
  321. function nodeCompatSmokeGates(options: { cliSmoke?: boolean } = {}): Gate[] {
  322. const gates: Gate[] = [
  323. pnpmExec('source-worker-smoke', [
  324. 'vitest',
  325. 'run',
  326. 'packages/workflow/workflow-worker-thread/tests/source-worker.compat.spec.ts',
  327. ], { label: 'source worker smoke' }),
  328. pnpmExec('jsonl-zstd-smoke', [
  329. 'vitest',
  330. 'run',
  331. 'packages/session/session-persistence-jsonl/tests/zstd.compat.spec.ts',
  332. ], { label: 'JSONL Zstandard smoke' }),
  333. pnpmExec('dsh-source-launch-smoke', [
  334. 'vitest',
  335. 'run',
  336. 'apps/cli/tests/source-launch.compat.spec.ts',
  337. ], { label: 'dsh source-launch smoke' }),
  338. pnpmExec('vitest-jsdom-smoke', [
  339. 'vitest',
  340. 'run',
  341. 'scripts/vitest-environment.compat.spec.ts',
  342. ], { label: 'Vitest jsdom smoke' }),
  343. ]
  344. if (options.cliSmoke) {
  345. gates.push(
  346. pnpmExec('cli-lazy-search-startup-smoke', [
  347. 'vitest',
  348. 'run',
  349. 'apps/cli/tests/lazy-search-startup.compat.spec.ts',
  350. ], {
  351. label: 'CLI lazy-search startup smoke',
  352. env: { DSH_REQUIRE_BUILT_CLI_SMOKE: '1' },
  353. needs: ['build:web'],
  354. }),
  355. )
  356. }
  357. return gates
  358. }
  359. /** Active Node major used to select version-specific compatibility checks. */
  360. function runningNodeMajor(): number {
  361. const major = Number.parseInt(process.versions.node.split('.')[0] ?? '', 10)
  362. if (!Number.isSafeInteger(major)) {
  363. throw new Error(`run-gates: cannot parse Node version ${JSON.stringify(process.versions.node)}.`)
  364. }
  365. return major
  366. }
  367. function ciStaticGates(options: { ownsBuild: boolean }): Gate[] {
  368. return [
  369. ...ciSharedStaticGates(),
  370. ...options.ownsBuild ? [ciBuildGate()] : [],
  371. ...docSyncLeafGates({
  372. includeDocTypecheck: options.ownsBuild,
  373. ...options.ownsBuild
  374. ? {
  375. docTypecheckNeeds: ['build'],
  376. docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  377. docTypecheckScript: 'doc-typecheck:contracts-ready',
  378. }
  379. : {},
  380. docsBuildScript: 'docs:build:mpa',
  381. }),
  382. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  383. pnpmScript('knip', 'knip'),
  384. ]
  385. }
  386. function ciArtifactGates(): Gate[] {
  387. return [
  388. ciBuildGate(),
  389. pnpmScript('publint', 'publint', { needs: ['build'] }),
  390. pnpmScript('node-next-types', 'verify-node-next-types', {
  391. label: 'node-next types',
  392. needs: ['build'],
  393. }),
  394. builtPackageInvariantsGate(['build']),
  395. builtBinSmokeGate(),
  396. ]
  397. }
  398. function ciConsumerGates(): Gate[] {
  399. const builtTree = ['build']
  400. const validatedBuild = ['built-package-invariants']
  401. // The HMR web test starts `dev:web`, which rewrites the shared `lib/` and
  402. // `apps/web/dist/` trees. Let every build-artifact reader settle before that
  403. // writer starts; `after` preserves the web diagnostic even if a reader fails.
  404. const buildArtifactReaders = [
  405. 'publint',
  406. 'lint-and-duplication',
  407. 'snapshot',
  408. 'expected-output',
  409. 'doc-typecheck',
  410. 'node-next-types',
  411. 'built-bin-smoke',
  412. ]
  413. return [
  414. ciBuildGate(),
  415. pnpmScript('node-compat', 'check:node-compat', {
  416. label: 'Node compatibility',
  417. env: { [CLIENT_BUILD_PROFILE_SELECTOR]: 'official' },
  418. }),
  419. pnpmScript('publint', 'publint', { needs: builtTree }),
  420. builtPackageInvariantsGate(builtTree),
  421. pnpmScript('lint-and-duplication', 'check:ci:lint:contracts-ready', {
  422. label: 'lint and duplication',
  423. needs: validatedBuild,
  424. }),
  425. snapshotGate(validatedBuild),
  426. expectedOutputGate(validatedBuild),
  427. webSnapshotGate(validatedBuild, buildArtifactReaders),
  428. pnpmScript('doc-typecheck', 'doc-typecheck:contracts-ready', {
  429. needs: validatedBuild,
  430. env: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  431. }),
  432. pnpmScript('node-next-types', 'verify-node-next-types', {
  433. label: 'node-next types',
  434. needs: validatedBuild,
  435. }),
  436. builtBinSmokeGate(validatedBuild),
  437. ]
  438. }
  439. function webSnapshotGate(needs: string[], after?: string[]): Gate {
  440. const order = after === undefined ? { needs } : { needs, after }
  441. const workerRaw = process.env.DSH_WEB_SNAPSHOT_WORKERS
  442. if (workerRaw !== undefined && workerRaw !== '') {
  443. const workers = Number.parseInt(workerRaw, 10)
  444. if (!Number.isSafeInteger(workers) || workers < 2 || String(workers) !== workerRaw) {
  445. throw new Error(`run-gates: DSH_WEB_SNAPSHOT_WORKERS must be an integer greater than 1, got ${JSON.stringify(workerRaw)}.`)
  446. }
  447. return pnpmScript('web-snapshot', 'test:web:ci', {
  448. label: 'web browser snapshot',
  449. displayCommand: `DSH_SNAPSHOT=replay DSH_WEB_SNAPSHOT_WORKERS=${workers} pnpm run test:web:ci`,
  450. env: { DSH_SNAPSHOT: 'replay' },
  451. ...order,
  452. streamOutput: true,
  453. })
  454. }
  455. return pnpmScript('web-snapshot', 'test:web:built', {
  456. label: 'web browser snapshot',
  457. displayCommand: 'DSH_SNAPSHOT=replay pnpm run test:web:built',
  458. env: { DSH_SNAPSHOT: 'replay' },
  459. ...order,
  460. })
  461. }
  462. function ciWindowsBlockingGates(): Gate[] {
  463. return [
  464. ciBuildGate('windows-build', { label: 'build' }),
  465. pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
  466. ]
  467. }
  468. function ciWindowsCompleteGates(): Gate[] {
  469. const coverage = coverageGates().map(gate => ({
  470. ...gate,
  471. needs: [...new Set(['build', ...(gate.needs ?? [])])],
  472. }))
  473. const coverageAfter = coverage.map(gate => gate.id)
  474. const observational = ciWindowsObservationalGates()
  475. // The required production site replaces the observational MPA build; both
  476. // VitePress modes write the same output directory and cannot overlap.
  477. .filter(gate => gate.id !== 'build' && gate.id !== 'docs-site-build')
  478. .map(gate => ({
  479. ...gate,
  480. allowFailure: true,
  481. after: [...new Set([
  482. ...coverageAfter,
  483. ...(gate.after ?? []).map(id => id === 'docs-site-build' ? 'windows-site' : id),
  484. ])],
  485. }))
  486. return [
  487. ciBuildGate(),
  488. pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
  489. ...coverage,
  490. ...observational,
  491. ]
  492. }
  493. function ciWindowsObservationalGates(): Gate[] {
  494. const predecessors = [
  495. ...ciStaticGates({ ownsBuild: true }),
  496. // Linux owns required lint and snapshots; Windows omits those duplicates.
  497. pnpmScript('duplication', 'duplication'),
  498. pnpmScript('publint', 'publint', { needs: ['build'] }),
  499. pnpmScript('node-next-types', 'verify-node-next-types', {
  500. label: 'node-next types',
  501. needs: ['build'],
  502. }),
  503. builtPackageInvariantsGate(['build']),
  504. ]
  505. return [
  506. ...predecessors,
  507. {
  508. ...builtBinSmokeGate(),
  509. // This smoke starts real application children with bounded startup
  510. // deadlines. Let other Windows processes settle before measuring startup.
  511. after: predecessors.map(gate => gate.id),
  512. },
  513. ]
  514. }
  515. function typertContractsGate(): Gate {
  516. return pnpmScript('typert-contracts', 'build:lib:host', { label: 'Typert contracts' })
  517. }
  518. function lintGate(options: { needs?: string[] } = {}): Gate {
  519. const raw = process.env.DSH_OXLINT_THREADS
  520. const script = 'lint:contracts-ready'
  521. return pnpmScript('lint', script, {
  522. ...raw === undefined || raw === ''
  523. ? {}
  524. : { displayCommand: `DSH_OXLINT_THREADS=${raw} pnpm run ${script}` },
  525. ...options.needs === undefined ? {} : { needs: options.needs },
  526. })
  527. }
  528. // The heavy suites run uninstrumented beside the thresholded gate: their
  529. // compiler- and subprocess-bound fixtures pay a multiple of their runtime
  530. // under v8 instrumentation while contributing nothing the thresholds need
  531. // (membership rules in scripts/coverage-exempt.ts).
  532. //
  533. // DSH_COVERAGE_MAX_WORKERS is the ordinary lane's worker budget, so the two
  534. // parallel gates split it instead of each claiming it whole. When
  535. // DSH_COVERAGE_PARTITIONS is set, its single-worker processes replace the
  536. // instrumented share while this budget still sizes the exempt gate. The exempt
  537. // gate's wall clock is dominated by its longest single file, so it takes the
  538. // small share. A budget of 1 gives each gate 1 worker; lanes that need a strict
  539. // total of one (the serial reference jobs) also set DSH_GATE_CONCURRENCY=1,
  540. // which keeps the gates from overlapping at all.
  541. // DSH_COVERAGE_TEST_TIMEOUT_MS raises Vitest's per-test and expect.poll
  542. // defaults together for instrumented lanes whose scheduling overhead exceeds
  543. // those defaults. Explicit fixture timeouts remain authoritative.
  544. function coverageWorkerArgs(): { instrumented: string[]; exempt: string[] } {
  545. const [flag] = positiveIntArg('DSH_COVERAGE_MAX_WORKERS', '--maxWorkers')
  546. if (flag === undefined) return { instrumented: [], exempt: [] }
  547. const total = Number.parseInt(flag.split('=')[1] ?? '', 10)
  548. const exempt = Math.max(1, Math.floor(total / 3))
  549. const instrumented = Math.max(1, total - exempt)
  550. return {
  551. instrumented: [`--maxWorkers=${String(instrumented)}`],
  552. exempt: [`--maxWorkers=${String(exempt)}`],
  553. }
  554. }
  555. function coverageGates(): Gate[] {
  556. const workers = coverageWorkerArgs()
  557. const timeouts = coverageTestTimeoutArgs(process.env[COVERAGE_TEST_TIMEOUT_ENV])
  558. const partitions = parseCoveragePartitionCount(process.env[COVERAGE_PARTITIONS_ENV])
  559. const instrumented = partitions === undefined
  560. ? pnpmExec('coverage', [
  561. 'vitest',
  562. 'run',
  563. '--coverage',
  564. ...workers.instrumented,
  565. ...timeouts,
  566. ], {
  567. label: 'test:coverage',
  568. env: { [COVERAGE_EXEMPT_ENV]: '1' },
  569. })
  570. : pnpmScript('coverage', 'test:coverage:partitioned', {
  571. label: 'test:coverage',
  572. displayCommand: `${COVERAGE_PARTITIONS_ENV}=${partitions} pnpm run test:coverage:partitioned`,
  573. env: { [COVERAGE_EXEMPT_ENV]: '1' },
  574. streamOutput: true,
  575. })
  576. return [
  577. instrumented,
  578. pnpmExec('coverage-exempt-heavy', [
  579. 'vitest',
  580. 'run',
  581. ...coverageExemptHeavySuites.map(suite => suite.filter),
  582. ...workers.exempt,
  583. ...timeouts,
  584. ], {
  585. label: 'test:coverage-exempt-heavy',
  586. }),
  587. ]
  588. }
  589. // Recorded-session adapters boot process scenarios in `lib` mode. Callers wait
  590. // either on `build` or on a validation gate that transitively owns that build.
  591. function snapshotGate(needs: string[] = ['build']): Gate {
  592. return pnpmScript('snapshot', 'test:snapshot', {
  593. env: { DSH_EXAMPLE_MODE: 'lib' },
  594. needs,
  595. })
  596. }
  597. // Owner-local process expectations consume built package exports without entering
  598. // the recorded-session corpus or the credentialed provider lane.
  599. function expectedOutputGate(needs: string[] = ['build']): Gate {
  600. return pnpmScript('expected-output', 'test:expected', {
  601. env: { DSH_EXAMPLE_MODE: 'lib' },
  602. needs,
  603. })
  604. }
  605. function builtPackageInvariantsGate(needs?: string[]): Gate {
  606. return pnpmScript('built-package-invariants', 'verify-built-package-invariants', {
  607. label: 'built package invariants',
  608. ...needs === undefined ? {} : { needs },
  609. })
  610. }
  611. function positiveIntArg(envName: string, flag: string): string[] {
  612. const raw = process.env[envName]
  613. if (raw === undefined || raw === '') return []
  614. const parsed = Number.parseInt(raw, 10)
  615. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  616. throw new Error(`run-gates: ${envName} must be a positive integer, got ${JSON.stringify(raw)}.`)
  617. }
  618. return [`${flag}=${raw}`]
  619. }
  620. function flagEnabled(envName: string): boolean {
  621. const raw = process.env[envName]
  622. if (raw === undefined || raw === '') return false
  623. if (raw !== '1') throw new Error(`run-gates: ${envName} must be 1 when set, got ${JSON.stringify(raw)}.`)
  624. return true
  625. }
  626. function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] {
  627. const artifactOptions = options.artifactNeeds === undefined ? {} : { needs: options.artifactNeeds }
  628. return [
  629. pnpmScript('rescope-vendor', 'rescope-vendor:check', { label: 'vendor rescope' }),
  630. pnpmScript('knip', 'knip'),
  631. pnpmScript('publint', 'publint', artifactOptions),
  632. pnpmScript('constraints', 'constraints'),
  633. pnpmScript('application-entrypoints', 'verify-application-entrypoints', { label: 'application entrypoints' }),
  634. pnpmScript('dsh-package-licenses', 'verify-dsh-package-licenses', { label: 'DSH package licenses' }),
  635. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  636. builtPackageInvariantsGate(options.artifactNeeds),
  637. pnpmScript('node-next-types', 'verify-node-next-types', {
  638. label: 'node-next types',
  639. ...artifactOptions,
  640. }),
  641. pnpmScript('optional-dependency-imports', 'verify-optional-dependency-imports', {
  642. label: 'optional dependency imports',
  643. }),
  644. pnpmScript('client-packages', 'verify-client-packages', { label: 'client packages' }),
  645. pnpmScript('client-ui-i18n', 'verify-client-ui-i18n', { label: 'client UI i18n' }),
  646. ]
  647. }
  648. function docSyncLeafGates(options: {
  649. includeDocTypecheck?: boolean
  650. docTypecheckNeeds?: string[]
  651. docTypecheckEnv?: Record<string, string | undefined>
  652. docTypecheckScript?: 'doc-typecheck' | 'doc-typecheck:contracts-ready'
  653. docsBuildScript?: 'docs:build' | 'docs:build:mpa'
  654. } = {}): Gate[] {
  655. const docTypecheckOptions: Partial<Gate> = {}
  656. if (options.docTypecheckNeeds !== undefined) docTypecheckOptions.needs = options.docTypecheckNeeds
  657. if (options.docTypecheckEnv !== undefined) docTypecheckOptions.env = options.docTypecheckEnv
  658. return [
  659. // Stable FIFO starts the longest leaves first; only docs-site-build writes website/.generated.
  660. ...options.includeDocTypecheck === false
  661. ? []
  662. : [pnpmScript('doc-typecheck', options.docTypecheckScript ?? 'doc-typecheck', docTypecheckOptions)],
  663. pnpmScript('docs-site-build', options.docsBuildScript ?? 'docs:build', { label: 'documentation build' }),
  664. pnpmScript('doc-graphs', 'verify-doc-graphs', { label: 'doc graphs' }),
  665. pnpmScript('markdown-links', 'verify-md-links', { label: 'markdown links', quick: true }),
  666. pnpmScript('type-equivalence', 'verify-type-equiv', { label: 'type equivalence', quick: true }),
  667. pnpmScript('cordis-catalog', 'verify-cordis-catalog', { label: 'cordis catalog' }),
  668. pnpmScript('cordis-inspect-catalog', 'verify-cordis-inspect-catalog', { label: 'Cordis inspect catalog' }),
  669. pnpmScript('mermaid', 'verify-mermaid'),
  670. pnpmScript('scoped-events', 'verify-scoped-events', { label: 'scoped events' }),
  671. pnpmScript('translation-pairing', 'verify-translation-pairing', { label: 'translation pairing', quick: true }),
  672. pnpmScript('markdown-wrap', 'verify-md-wrap', { label: 'markdown wrap', quick: true }),
  673. pnpmScript('client-catalog', 'verify-client-catalog', { label: 'client catalog' }),
  674. pnpmScript('export-jsdoc', 'verify-export-jsdoc', { label: 'export jsdoc' }),
  675. pnpmScript('tool-catalog', 'verify-tool-catalog', { label: 'tool catalog' }),
  676. pnpmScript('config-catalog', 'verify-config-catalog', { label: 'config catalog' }),
  677. pnpmScript('persistence-catalog', 'verify-persistence-catalog', { label: 'persistence catalog' }),
  678. pnpmScript('public-repository-links', 'verify-public-repository-links', { label: 'public repository links', quick: true }),
  679. pnpmScript('doc-refs', 'verify-doc-refs', { label: 'doc refs', quick: true }),
  680. pnpmScript('subsystem-pages', 'verify-subsystem-pages', { label: 'subsystem pages' }),
  681. pnpmScript('package-paths', 'verify-package-paths', { label: 'package paths' }),
  682. pnpmScript('config-source-ownership', 'verify-config-source-ownership', { label: 'config source ownership' }),
  683. pnpmScript('package-readme-model-experience', 'verify-package-readme-model-experience', { label: 'package README model experience', quick: true }),
  684. pnpmScript('agent-note-classification', 'verify-agent-note-classification', { label: 'agent note classification', quick: true }),
  685. pnpmScript('agent-note-format', 'verify-agent-note-format', { label: 'agent note format', quick: true }),
  686. pnpmScript('archived-agent-notes', 'verify-archived-agent-notes', { label: 'archived agent notes', quick: true }),
  687. pnpmScript('skill-invocation-metadata', 'verify-skill-invocation-metadata', { label: 'skill invocation metadata', quick: true }),
  688. pnpmScript('translation-prompt', 'verify-translation-prompt', { label: 'translation prompt', quick: true }),
  689. pnpmScript('doc-budgets', 'verify-doc-budgets', { label: 'doc budgets', quick: true }),
  690. pnpmExec('doc-standard-tests', ['vitest', 'run', 'scripts/doc-standard.spec.ts'], {
  691. label: 'documentation standard tests',
  692. quick: true,
  693. }),
  694. pnpmExec('docs-site-projection', ['vitest', 'run', 'scripts/project-doc-site.spec.ts', 'scripts/verify-doc-site-fragments.spec.ts'], {
  695. label: 'documentation site checks',
  696. }),
  697. pnpmScript('package-readme-limitations', 'verify-package-readme-limitations', { label: 'package README limitations', quick: true }),
  698. ]
  699. }
  700. /**
  701. * The quick comprehensive documentation-standard aggregate for `test:docs`.
  702. * It covers the prose, pairing, README, budget, and Agent Note gates
  703. * without builds, generator regeneration, or the VitePress site build.
  704. */
  705. function docQuickLeafGates(): Gate[] {
  706. return docSyncLeafGates({ includeDocTypecheck: false }).filter(gate => gate.quick === true)
  707. }
  708. function builtBinSmokeGate(needs: string[] = ['build']): Gate {
  709. return pnpmExec('built-bin-smoke', [
  710. 'vitest',
  711. 'run',
  712. '--config',
  713. 'vitest.e2e.config.ts',
  714. 'apps/cli/tests/profiles/headless/tests/keyless-smoke.e2e.ts',
  715. 'apps/cli/tests/built-bin.e2e.ts',
  716. 'packages/host/directory-picker-native/tests/built-worker.e2e.ts',
  717. 'packages/sdk/server/tests/built-scope-carrier.e2e.ts',
  718. 'packages/subagent/subagent-codex/tests/loader-composition.e2e.ts',
  719. 'packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts',
  720. 'packages/api/remotes/tests/built-lib.e2e.ts',
  721. 'packages/experimental/agent-team/tests/built-lib.e2e.ts',
  722. // Built execution consumers: the only automated proof that package-name
  723. // imports reach their lib/ entrypoints under plain Node. The e2e lane runs
  724. // unbuilt, so these files self-skip there.
  725. 'packages/workflow/workflow-worker-thread/tests/built-worker.e2e.ts',
  726. 'packages/code-runtime/code-runtime-worker-thread/tests/built-lib.e2e.ts',
  727. 'packages/lsp/lsp-stdio/tests/built-lib.e2e.ts',
  728. ], {
  729. label: 'built-bin smoke',
  730. needs,
  731. env: { DSH_EXAMPLE_MODE: 'lib' },
  732. })
  733. }
  734. /**
  735. * Reject a gate list whose graph cannot be executed unambiguously.
  736. * @param gates - complete aggregate to validate.
  737. */
  738. function validateGateGraph(gates: readonly Gate[]): void {
  739. if (gates.length === 0) throw new Error('run-gates: gate graph has no gates.')
  740. const ids = new Set<string>()
  741. for (const gate of gates) {
  742. if (ids.has(gate.id)) throw new Error(`run-gates: duplicate gate id ${JSON.stringify(gate.id)}.`)
  743. ids.add(gate.id)
  744. }
  745. for (const gate of gates) {
  746. for (const dependency of gate.needs ?? []) {
  747. if (!ids.has(dependency)) {
  748. throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} depends on unknown gate ${JSON.stringify(dependency)}.`)
  749. }
  750. }
  751. for (const predecessor of gate.after ?? []) {
  752. if (!ids.has(predecessor)) {
  753. throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} waits for unknown gate ${JSON.stringify(predecessor)}.`)
  754. }
  755. }
  756. }
  757. const cycle = findDependencyCycle(gates)
  758. if (cycle !== undefined) throw new Error(`run-gates: dependency cycle: ${cycle.join(' -> ')}.`)
  759. }
  760. function findDependencyCycle(gates: readonly Gate[]): string[] | undefined {
  761. const byId = new Map(gates.map(gate => [gate.id, gate]))
  762. const complete = new Set<string>()
  763. const active = new Map<string, number>()
  764. const path: string[] = []
  765. const visit = (id: string): string[] | undefined => {
  766. if (complete.has(id)) return undefined
  767. const cycleStart = active.get(id)
  768. if (cycleStart !== undefined) return [...path.slice(cycleStart), id]
  769. const gate = byId.get(id)
  770. if (gate === undefined) return undefined
  771. active.set(id, path.length)
  772. path.push(id)
  773. for (const predecessor of [...(gate.needs ?? []), ...(gate.after ?? [])]) {
  774. const cycle = visit(predecessor)
  775. if (cycle !== undefined) return cycle
  776. }
  777. path.pop()
  778. active.delete(id)
  779. complete.add(id)
  780. return undefined
  781. }
  782. for (const gate of gates) {
  783. const cycle = visit(gate.id)
  784. if (cycle !== undefined) return cycle
  785. }
  786. return undefined
  787. }
  788. /**
  789. * Validate and run one aggregate before the injected executor can start a child.
  790. * @param gates - complete aggregate to execute.
  791. * @param maxActive - maximum concurrent child count.
  792. * @param execute - child-process executor.
  793. * @param observe - result observer invoked when each gate settles.
  794. * @returns results in aggregate order.
  795. */
  796. export async function runGates(
  797. gates: Gate[],
  798. maxActive: number,
  799. execute: GateExecutor,
  800. observe: ResultObserver = () => {},
  801. ): Promise<GateResult[]> {
  802. validateGateGraph(gates)
  803. if (!Number.isSafeInteger(maxActive) || maxActive < 1) {
  804. throw new Error(`run-gates: max concurrency must be a positive integer, got ${JSON.stringify(maxActive)}.`)
  805. }
  806. const states = new Map<string, GateState>(gates.map(gate => [gate.id, 'pending']))
  807. const results = new Map<string, GateResult>()
  808. const running: RunningGate[] = []
  809. for (;;) {
  810. let madeProgress = false
  811. while (running.length < maxActive) {
  812. const ready = gates.find(gate => states.get(gate.id) === 'pending' && predecessorsReady(gate, states))
  813. if (ready === undefined) break
  814. states.set(ready.id, 'running')
  815. running.push({ gate: ready, promise: execute(ready) })
  816. console.log(`run-gates: start ${ready.label}`)
  817. madeProgress = true
  818. }
  819. if (running.length === 0) {
  820. const pending = gates.filter(gate => states.get(gate.id) === 'pending')
  821. if (pending.length === 0) break
  822. const gate = pending.find(item => (item.needs ?? []).some(id => gateFailed(states.get(id))))
  823. if (gate === undefined) throw new Error('run-gates: validated graph stalled without a failed dependency.')
  824. const failedDeps = (gate.needs ?? []).filter(id => gateFailed(states.get(id)))
  825. const result: GateResult = {
  826. gate,
  827. status: 'skipped',
  828. durationMs: 0,
  829. output: [],
  830. exitCode: null,
  831. signalCode: null,
  832. error: `dependency failed or skipped: ${failedDeps.join(', ')}`,
  833. }
  834. states.set(gate.id, 'skipped')
  835. results.set(gate.id, result)
  836. observe(result)
  837. continue
  838. }
  839. if (!madeProgress) {
  840. const settled = await Promise.race(running.map(async item => ({ item, result: await item.promise })))
  841. running.splice(running.indexOf(settled.item), 1)
  842. states.set(settled.item.gate.id, settled.result.status)
  843. results.set(settled.item.gate.id, settled.result)
  844. observe(settled.result)
  845. }
  846. }
  847. return gates.map((gate) => {
  848. const result = results.get(gate.id)
  849. if (result === undefined) throw new Error(`run-gates: missing result for ${gate.id}.`)
  850. return result
  851. })
  852. }
  853. function predecessorsReady(gate: Gate, states: Map<string, GateState>): boolean {
  854. return (gate.needs ?? []).every(id => states.get(id) === 'passed')
  855. && (gate.after ?? []).every(id => gateSettled(states.get(id)))
  856. }
  857. function gateSettled(state: GateState | undefined): boolean {
  858. return state === 'passed' || state === 'failed' || state === 'skipped'
  859. }
  860. function gateFailed(state: GateState | undefined): boolean {
  861. return state === 'failed' || state === 'skipped'
  862. }
  863. /**
  864. * Execute one gate through the real shell-free child-process boundary.
  865. * @param gate - command and scheduler environment to execute.
  866. * @returns the complete process outcome.
  867. */
  868. export async function runGate(gate: Gate): Promise<GateResult> {
  869. const started = performance.now()
  870. const output: GateOutputChunk[] = []
  871. let spawnError: string | undefined
  872. const outcome = await new Promise<{
  873. exitCode: number | null
  874. signalCode: NodeJS.Signals | null
  875. }>((resolveExit) => {
  876. const child = spawn(gate.command, gate.args, {
  877. cwd: root,
  878. env: { ...process.env, ...gate.env },
  879. stdio: ['pipe', 'pipe', 'pipe'],
  880. })
  881. child.stdout.setEncoding('utf8')
  882. child.stderr.setEncoding('utf8')
  883. child.stdout.on('data', (chunk: string) => {
  884. if (gate.streamOutput === true) process.stdout.write(chunk)
  885. else output.push({ stream: 'stdout', text: chunk })
  886. })
  887. child.stderr.on('data', (chunk: string) => {
  888. if (gate.streamOutput === true) process.stderr.write(chunk)
  889. else output.push({ stream: 'stderr', text: chunk })
  890. })
  891. child.on('error', (error) => {
  892. spawnError = `failed to start command: ${error.message}`
  893. resolveExit({ exitCode: null, signalCode: null })
  894. })
  895. child.on('close', (exitCode, signalCode) => {
  896. resolveExit({ exitCode, signalCode })
  897. })
  898. child.stdin.end()
  899. })
  900. const { exitCode, signalCode } = outcome
  901. const status: GateResultStatus = exitCode === 0 && signalCode === null && spawnError === undefined ? 'passed' : 'failed'
  902. const result: GateResult = {
  903. gate,
  904. status,
  905. durationMs: performance.now() - started,
  906. output,
  907. exitCode,
  908. signalCode,
  909. }
  910. if (spawnError !== undefined) result.error = spawnError
  911. return result
  912. }
  913. /**
  914. * Format every independently observed failure fact for the aggregate summary.
  915. * @param result - unsuccessful gate result.
  916. * @returns error, exit, and signal facts without allowing one to hide another.
  917. */
  918. export function formatGateResultReason(result: GateResult): string {
  919. const facts: string[] = []
  920. if (result.error !== undefined) facts.push(result.error)
  921. if (result.exitCode !== null) facts.push(`exit ${result.exitCode}`)
  922. if (result.signalCode !== null) facts.push(`signal ${result.signalCode}`)
  923. return facts.length === 0 ? 'no exit code or signal' : facts.join(', ')
  924. }
  925. function printResult(result: GateResult): void {
  926. const verbose = process.env.DSH_GATE_VERBOSE === '1'
  927. const seconds = (result.durationMs / 1000).toFixed(2)
  928. if (result.status === 'passed' && !verbose) {
  929. console.log(`run-gates: PASS ${result.gate.label} (${seconds}s)`)
  930. return
  931. }
  932. const heading = `${result.status.toUpperCase()} ${result.gate.label} (${seconds}s)`
  933. const writeHeading = result.status === 'passed' ? console.log : console.error
  934. writeHeading(`\n== ${heading} ==`)
  935. if (result.status !== 'passed') {
  936. console.error(`command: ${result.gate.displayCommand}`)
  937. console.error(`outcome: ${formatGateResultReason(result)}`)
  938. }
  939. if (result.gate.streamOutput !== true) printOutput(result.output)
  940. }
  941. function printSummary(results: GateResult[], durationMs: number): void {
  942. const passed = results.filter(result => result.status === 'passed').length
  943. const failed = results.filter(result => result.status === 'failed').length
  944. const skipped = results.filter(result => result.status === 'skipped').length
  945. const seconds = (durationMs / 1000).toFixed(2)
  946. console.log(`\nrun-gates: ${passed} passed, ${failed} failed, ${skipped} skipped in ${seconds}s.`)
  947. const unsuccessful = results.filter(result => result.status === 'failed' || result.status === 'skipped')
  948. if (unsuccessful.length === 0) return
  949. console.error('run-gates: unsuccessful gates:')
  950. for (const result of unsuccessful) {
  951. const duration = (result.durationMs / 1000).toFixed(2)
  952. const reason = formatGateResultReason(result)
  953. const disposition = result.gate.allowFailure === true ? 'NON-BLOCKING ' : ''
  954. console.error(` - ${disposition}${result.status.toUpperCase()} ${result.gate.label} (${duration}s, ${reason})`)
  955. console.error(` ${result.gate.displayCommand}`)
  956. }
  957. }
  958. function printOutput(output: GateOutputChunk[]): void {
  959. for (const chunk of output) {
  960. if (chunk.stream === 'stdout') process.stdout.write(chunk.text)
  961. else process.stderr.write(chunk.text)
  962. }
  963. }