run-gates.ts 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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. // The prepared typecheck and build both drive Client tsc, while build also
  289. // repeats the Host contract pass. Wait for all three consumers so build
  290. // neither races tsbuildinfo nor replaces declarations while they are read.
  291. ciBuildGate('build', { needs: ['typecheck', 'lint', 'doc-typecheck'] }),
  292. pnpmScript('publint', 'publint', { needs: ['build'] }),
  293. pnpmScript('node-next-types', 'verify-node-next-types', {
  294. label: 'node-next types',
  295. needs: ['build'],
  296. }),
  297. builtPackageInvariantsGate(['build']),
  298. builtBinSmokeGate(),
  299. ]
  300. }
  301. function nodeCompatGates(): Gate[] {
  302. const typecheck = flagEnabled('DSH_NODE_COMPAT_SKIP_TYPECHECK')
  303. ? []
  304. : [pnpmScript('typecheck', 'typecheck')]
  305. if (runningNodeMajor() !== 22) {
  306. return [...typecheck, ...nodeCompatSmokeGates()]
  307. }
  308. return [
  309. ...typecheck,
  310. pnpmScript('build', 'build', {
  311. ...typecheck.length === 0 ? {} : { needs: ['typecheck'] },
  312. }),
  313. pnpmScript('build:web', 'build:web', {
  314. label: 'Web frontend build',
  315. needs: ['build'],
  316. }),
  317. ...nodeCompatSmokeGates({ cliSmoke: true }),
  318. ]
  319. }
  320. function nodeCompatSmokeGates(options: { cliSmoke?: boolean } = {}): Gate[] {
  321. const gates: Gate[] = [
  322. pnpmExec('source-worker-smoke', [
  323. 'vitest',
  324. 'run',
  325. 'packages/workflow/workflow-worker-thread/tests/source-worker.compat.spec.ts',
  326. ], { label: 'source worker smoke' }),
  327. pnpmExec('jsonl-zstd-smoke', [
  328. 'vitest',
  329. 'run',
  330. 'packages/session/session-persistence-jsonl/tests/zstd.compat.spec.ts',
  331. ], { label: 'JSONL Zstandard smoke' }),
  332. pnpmExec('dsh-source-launch-smoke', [
  333. 'vitest',
  334. 'run',
  335. 'apps/cli/tests/source-launch.compat.spec.ts',
  336. ], { label: 'dsh source-launch smoke' }),
  337. pnpmExec('vitest-jsdom-smoke', [
  338. 'vitest',
  339. 'run',
  340. 'scripts/vitest-environment.compat.spec.ts',
  341. ], { label: 'Vitest jsdom smoke' }),
  342. ]
  343. if (options.cliSmoke) {
  344. gates.push(
  345. pnpmExec('cli-lazy-search-startup-smoke', [
  346. 'vitest',
  347. 'run',
  348. 'apps/cli/tests/lazy-search-startup.compat.spec.ts',
  349. ], {
  350. label: 'CLI lazy-search startup smoke',
  351. env: { DSH_REQUIRE_BUILT_CLI_SMOKE: '1' },
  352. needs: ['build:web'],
  353. }),
  354. )
  355. }
  356. return gates
  357. }
  358. /** Active Node major used to select version-specific compatibility checks. */
  359. function runningNodeMajor(): number {
  360. const major = Number.parseInt(process.versions.node.split('.')[0] ?? '', 10)
  361. if (!Number.isSafeInteger(major)) {
  362. throw new Error(`run-gates: cannot parse Node version ${JSON.stringify(process.versions.node)}.`)
  363. }
  364. return major
  365. }
  366. function ciStaticGates(options: { ownsBuild: boolean }): Gate[] {
  367. return [
  368. ...ciSharedStaticGates(),
  369. ...options.ownsBuild ? [ciBuildGate()] : [],
  370. ...docSyncLeafGates({
  371. includeDocTypecheck: options.ownsBuild,
  372. ...options.ownsBuild
  373. ? {
  374. docTypecheckNeeds: ['build'],
  375. docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  376. docTypecheckScript: 'doc-typecheck:contracts-ready',
  377. }
  378. : {},
  379. docsBuildScript: 'docs:build:mpa',
  380. }),
  381. pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
  382. ]
  383. }
  384. function ciArtifactGates(): Gate[] {
  385. return [
  386. ciBuildGate(),
  387. pnpmScript('publint', 'publint', { needs: ['build'] }),
  388. pnpmScript('node-next-types', 'verify-node-next-types', {
  389. label: 'node-next types',
  390. needs: ['build'],
  391. }),
  392. builtPackageInvariantsGate(['build']),
  393. builtBinSmokeGate(),
  394. ]
  395. }
  396. function ciConsumerGates(): Gate[] {
  397. const builtTree = ['build']
  398. const validatedBuild = ['built-package-invariants']
  399. // The HMR web test starts `dev:web`, which rewrites the shared `lib/` and
  400. // `apps/web/dist/` trees. Let every build-artifact reader settle before that
  401. // writer starts; `after` preserves the web diagnostic even if a reader fails.
  402. const buildArtifactReaders = [
  403. 'publint',
  404. 'lint-and-duplication',
  405. 'snapshot',
  406. 'expected-output',
  407. 'doc-typecheck',
  408. 'node-next-types',
  409. 'built-bin-smoke',
  410. ]
  411. return [
  412. ciBuildGate(),
  413. pnpmScript('node-compat', 'check:node-compat', {
  414. label: 'Node compatibility',
  415. env: { [CLIENT_BUILD_PROFILE_SELECTOR]: 'official' },
  416. }),
  417. pnpmScript('publint', 'publint', { needs: builtTree }),
  418. builtPackageInvariantsGate(builtTree),
  419. pnpmScript('lint-and-duplication', 'check:ci:lint:contracts-ready', {
  420. label: 'lint and duplication',
  421. needs: validatedBuild,
  422. }),
  423. snapshotGate(validatedBuild),
  424. expectedOutputGate(validatedBuild),
  425. webSnapshotGate(validatedBuild, buildArtifactReaders),
  426. pnpmScript('doc-typecheck', 'doc-typecheck:contracts-ready', {
  427. needs: validatedBuild,
  428. env: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' },
  429. }),
  430. pnpmScript('node-next-types', 'verify-node-next-types', {
  431. label: 'node-next types',
  432. needs: validatedBuild,
  433. }),
  434. builtBinSmokeGate(validatedBuild),
  435. ]
  436. }
  437. function webSnapshotGate(needs: string[], after?: string[]): Gate {
  438. const order = after === undefined ? { needs } : { needs, after }
  439. const workerRaw = process.env.DSH_WEB_SNAPSHOT_WORKERS
  440. if (workerRaw !== undefined && workerRaw !== '') {
  441. const workers = Number.parseInt(workerRaw, 10)
  442. if (!Number.isSafeInteger(workers) || workers < 2 || String(workers) !== workerRaw) {
  443. throw new Error(`run-gates: DSH_WEB_SNAPSHOT_WORKERS must be an integer greater than 1, got ${JSON.stringify(workerRaw)}.`)
  444. }
  445. return pnpmScript('web-snapshot', 'test:web:ci', {
  446. label: 'web browser snapshot',
  447. displayCommand: `DSH_SNAPSHOT=replay DSH_WEB_SNAPSHOT_WORKERS=${workers} pnpm run test:web:ci`,
  448. env: { DSH_SNAPSHOT: 'replay' },
  449. ...order,
  450. streamOutput: true,
  451. })
  452. }
  453. return pnpmScript('web-snapshot', 'test:web:built', {
  454. label: 'web browser snapshot',
  455. displayCommand: 'DSH_SNAPSHOT=replay pnpm run test:web:built',
  456. env: { DSH_SNAPSHOT: 'replay' },
  457. ...order,
  458. })
  459. }
  460. function ciWindowsBlockingGates(): Gate[] {
  461. return [
  462. ciBuildGate('windows-build', { label: 'build' }),
  463. pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
  464. ]
  465. }
  466. function ciWindowsCompleteGates(): Gate[] {
  467. const coverage = coverageGates().map(gate => ({
  468. ...gate,
  469. needs: [...new Set(['build', ...(gate.needs ?? [])])],
  470. }))
  471. const coverageAfter = coverage.map(gate => gate.id)
  472. const observational = ciWindowsObservationalGates()
  473. // The required production site replaces the observational MPA build; both
  474. // VitePress modes write the same output directory and cannot overlap.
  475. .filter(gate => gate.id !== 'build' && gate.id !== 'docs-site-build')
  476. .map(gate => ({
  477. ...gate,
  478. allowFailure: true,
  479. after: [...new Set([
  480. ...coverageAfter,
  481. ...(gate.after ?? []).map(id => id === 'docs-site-build' ? 'windows-site' : id),
  482. ])],
  483. }))
  484. return [
  485. ciBuildGate(),
  486. pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
  487. ...coverage,
  488. ...observational,
  489. ]
  490. }
  491. function ciWindowsObservationalGates(): Gate[] {
  492. const predecessors = [
  493. ...ciStaticGates({ ownsBuild: true }),
  494. // Linux owns required lint and snapshots; Windows omits those duplicates.
  495. pnpmScript('duplication', 'duplication'),
  496. pnpmScript('publint', 'publint', { needs: ['build'] }),
  497. pnpmScript('node-next-types', 'verify-node-next-types', {
  498. label: 'node-next types',
  499. needs: ['build'],
  500. }),
  501. builtPackageInvariantsGate(['build']),
  502. ]
  503. return [
  504. ...predecessors,
  505. {
  506. ...builtBinSmokeGate(),
  507. // This smoke starts real application children with bounded startup
  508. // deadlines. Let other Windows processes settle before measuring startup.
  509. after: predecessors.map(gate => gate.id),
  510. },
  511. ]
  512. }
  513. function typertContractsGate(): Gate {
  514. return pnpmScript('typert-contracts', 'build:lib:host', { label: 'Typert contracts' })
  515. }
  516. function lintGate(options: { needs?: string[] } = {}): Gate {
  517. const raw = process.env.DSH_OXLINT_THREADS
  518. const script = 'lint:contracts-ready'
  519. return pnpmScript('lint', script, {
  520. ...raw === undefined || raw === ''
  521. ? {}
  522. : { displayCommand: `DSH_OXLINT_THREADS=${raw} pnpm run ${script}` },
  523. ...options.needs === undefined ? {} : { needs: options.needs },
  524. })
  525. }
  526. // The heavy suites run uninstrumented beside the thresholded gate: their
  527. // compiler- and subprocess-bound fixtures pay a multiple of their runtime
  528. // under v8 instrumentation while contributing nothing the thresholds need
  529. // (membership rules in scripts/coverage-exempt.ts).
  530. //
  531. // DSH_COVERAGE_MAX_WORKERS is the ordinary lane's worker budget, so the two
  532. // parallel gates split it instead of each claiming it whole. When
  533. // DSH_COVERAGE_PARTITIONS is set, its single-worker processes replace the
  534. // instrumented share while this budget still sizes the exempt gate. The exempt
  535. // gate's wall clock is dominated by its longest single file, so it takes the
  536. // small share. A budget of 1 gives each gate 1 worker; lanes that need a strict
  537. // total of one (the serial reference jobs) also set DSH_GATE_CONCURRENCY=1,
  538. // which keeps the gates from overlapping at all.
  539. // DSH_COVERAGE_TEST_TIMEOUT_MS raises Vitest's per-test and expect.poll
  540. // defaults together for instrumented lanes whose scheduling overhead exceeds
  541. // those defaults. Explicit fixture timeouts remain authoritative.
  542. function coverageWorkerArgs(): { instrumented: string[]; exempt: string[] } {
  543. const [flag] = positiveIntArg('DSH_COVERAGE_MAX_WORKERS', '--maxWorkers')
  544. if (flag === undefined) return { instrumented: [], exempt: [] }
  545. const total = Number.parseInt(flag.split('=')[1] ?? '', 10)
  546. const exempt = Math.max(1, Math.floor(total / 3))
  547. const instrumented = Math.max(1, total - exempt)
  548. return {
  549. instrumented: [`--maxWorkers=${String(instrumented)}`],
  550. exempt: [`--maxWorkers=${String(exempt)}`],
  551. }
  552. }
  553. function coverageGates(): Gate[] {
  554. const workers = coverageWorkerArgs()
  555. const timeouts = coverageTestTimeoutArgs(process.env[COVERAGE_TEST_TIMEOUT_ENV])
  556. const partitions = parseCoveragePartitionCount(process.env[COVERAGE_PARTITIONS_ENV])
  557. const instrumented = partitions === undefined
  558. ? pnpmExec('coverage', [
  559. 'vitest',
  560. 'run',
  561. '--coverage',
  562. ...workers.instrumented,
  563. ...timeouts,
  564. ], {
  565. label: 'test:coverage',
  566. env: { [COVERAGE_EXEMPT_ENV]: '1' },
  567. })
  568. : pnpmScript('coverage', 'test:coverage:partitioned', {
  569. label: 'test:coverage',
  570. displayCommand: `${COVERAGE_PARTITIONS_ENV}=${partitions} pnpm run test:coverage:partitioned`,
  571. env: { [COVERAGE_EXEMPT_ENV]: '1' },
  572. streamOutput: true,
  573. })
  574. return [
  575. instrumented,
  576. pnpmExec('coverage-exempt-heavy', [
  577. 'vitest',
  578. 'run',
  579. ...coverageExemptHeavySuites.map(suite => suite.filter),
  580. ...workers.exempt,
  581. ...timeouts,
  582. ], {
  583. label: 'test:coverage-exempt-heavy',
  584. }),
  585. ]
  586. }
  587. // Recorded-session adapters boot process scenarios in `lib` mode. Callers wait
  588. // either on `build` or on a validation gate that transitively owns that build.
  589. function snapshotGate(needs: string[] = ['build']): Gate {
  590. return pnpmScript('snapshot', 'test:snapshot', {
  591. env: { DSH_EXAMPLE_MODE: 'lib' },
  592. needs,
  593. })
  594. }
  595. // Owner-local process expectations consume built package exports without entering
  596. // the recorded-session corpus or the credentialed provider lane.
  597. function expectedOutputGate(needs: string[] = ['build']): Gate {
  598. return pnpmScript('expected-output', 'test:expected', {
  599. env: { DSH_EXAMPLE_MODE: 'lib' },
  600. needs,
  601. })
  602. }
  603. function builtPackageInvariantsGate(needs?: string[]): Gate {
  604. return pnpmScript('built-package-invariants', 'verify-built-package-invariants', {
  605. label: 'built package invariants',
  606. ...needs === undefined ? {} : { needs },
  607. })
  608. }
  609. function positiveIntArg(envName: string, flag: string): string[] {
  610. const raw = process.env[envName]
  611. if (raw === undefined || raw === '') return []
  612. const parsed = Number.parseInt(raw, 10)
  613. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  614. throw new Error(`run-gates: ${envName} must be a positive integer, got ${JSON.stringify(raw)}.`)
  615. }
  616. return [`${flag}=${raw}`]
  617. }
  618. function flagEnabled(envName: string): boolean {
  619. const raw = process.env[envName]
  620. if (raw === undefined || raw === '') return false
  621. if (raw !== '1') throw new Error(`run-gates: ${envName} must be 1 when set, got ${JSON.stringify(raw)}.`)
  622. return true
  623. }
  624. function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] {
  625. const artifactOptions = options.artifactNeeds === undefined ? {} : { needs: options.artifactNeeds }
  626. return [
  627. pnpmScript('rescope-vendor', 'rescope-vendor:check', { label: 'vendor rescope' }),
  628. pnpmScript('publint', 'publint', artifactOptions),
  629. pnpmScript('constraints', 'constraints'),
  630. pnpmScript('application-entrypoints', 'verify-application-entrypoints', { label: 'application entrypoints' }),
  631. pnpmScript('dsh-package-licenses', 'verify-dsh-package-licenses', { label: 'DSH package licenses' }),
  632. pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
  633. builtPackageInvariantsGate(options.artifactNeeds),
  634. pnpmScript('node-next-types', 'verify-node-next-types', {
  635. label: 'node-next types',
  636. ...artifactOptions,
  637. }),
  638. pnpmScript('optional-dependency-imports', 'verify-optional-dependency-imports', {
  639. label: 'optional dependency imports',
  640. }),
  641. pnpmScript('client-packages', 'verify-client-packages', { label: 'client packages' }),
  642. pnpmScript('client-ui-i18n', 'verify-client-ui-i18n', { label: 'client UI i18n' }),
  643. ]
  644. }
  645. function docSyncLeafGates(options: {
  646. includeDocTypecheck?: boolean
  647. docTypecheckNeeds?: string[]
  648. docTypecheckEnv?: Record<string, string | undefined>
  649. docTypecheckScript?: 'doc-typecheck' | 'doc-typecheck:contracts-ready'
  650. docsBuildScript?: 'docs:build' | 'docs:build:mpa'
  651. } = {}): Gate[] {
  652. const docTypecheckOptions: Partial<Gate> = {}
  653. if (options.docTypecheckNeeds !== undefined) docTypecheckOptions.needs = options.docTypecheckNeeds
  654. if (options.docTypecheckEnv !== undefined) docTypecheckOptions.env = options.docTypecheckEnv
  655. return [
  656. // Stable FIFO starts the longest leaves first; only docs-site-build writes website/.generated.
  657. ...options.includeDocTypecheck === false
  658. ? []
  659. : [pnpmScript('doc-typecheck', options.docTypecheckScript ?? 'doc-typecheck', docTypecheckOptions)],
  660. pnpmScript('docs-site-build', options.docsBuildScript ?? 'docs:build', { label: 'documentation build' }),
  661. pnpmScript('doc-graphs', 'verify-doc-graphs', { label: 'doc graphs' }),
  662. pnpmScript('markdown-links', 'verify-md-links', { label: 'markdown links', quick: true }),
  663. pnpmScript('type-equivalence', 'verify-type-equiv', { label: 'type equivalence', quick: true }),
  664. pnpmScript('cordis-catalog', 'verify-cordis-catalog', { label: 'cordis catalog' }),
  665. pnpmScript('cordis-inspect-catalog', 'verify-cordis-inspect-catalog', { label: 'Cordis inspect catalog' }),
  666. pnpmScript('mermaid', 'verify-mermaid'),
  667. pnpmScript('scoped-events', 'verify-scoped-events', { label: 'scoped events' }),
  668. pnpmScript('translation-pairing', 'verify-translation-pairing', { label: 'translation pairing', quick: true }),
  669. pnpmScript('markdown-wrap', 'verify-md-wrap', { label: 'markdown wrap', quick: true }),
  670. pnpmScript('client-catalog', 'verify-client-catalog', { label: 'client catalog' }),
  671. pnpmScript('export-jsdoc', 'verify-export-jsdoc', { label: 'export jsdoc' }),
  672. pnpmScript('tool-catalog', 'verify-tool-catalog', { label: 'tool catalog' }),
  673. pnpmScript('config-catalog', 'verify-config-catalog', { label: 'config catalog' }),
  674. pnpmScript('persistence-catalog', 'verify-persistence-catalog', { label: 'persistence catalog' }),
  675. pnpmScript('public-repository-links', 'verify-public-repository-links', { label: 'public repository links', quick: true }),
  676. pnpmScript('doc-refs', 'verify-doc-refs', { label: 'doc refs', quick: true }),
  677. pnpmScript('subsystem-pages', 'verify-subsystem-pages', { label: 'subsystem pages' }),
  678. pnpmScript('package-paths', 'verify-package-paths', { label: 'package paths' }),
  679. pnpmScript('tsconfig-paths', 'verify-tsconfig-paths', { label: 'tsconfig paths' }),
  680. pnpmScript('config-source-ownership', 'verify-config-source-ownership', { label: 'config source ownership' }),
  681. pnpmScript('package-readme-model-experience', 'verify-package-readme-model-experience', { label: 'package README model experience', quick: true }),
  682. pnpmScript('agent-note-classification', 'verify-agent-note-classification', { label: 'agent note classification', quick: true }),
  683. pnpmScript('agent-note-format', 'verify-agent-note-format', { label: 'agent note format', quick: true }),
  684. pnpmScript('archived-agent-notes', 'verify-archived-agent-notes', { label: 'archived agent notes', quick: true }),
  685. pnpmScript('skill-invocation-metadata', 'verify-skill-invocation-metadata', { label: 'skill invocation metadata', quick: true }),
  686. pnpmScript('translation-prompt', 'verify-translation-prompt', { label: 'translation prompt', quick: true }),
  687. pnpmScript('doc-budgets', 'verify-doc-budgets', { label: 'doc budgets', quick: true }),
  688. pnpmExec('doc-standard-tests', ['vitest', 'run', 'scripts/doc-standard.spec.ts'], {
  689. label: 'documentation standard tests',
  690. quick: true,
  691. }),
  692. pnpmExec('docs-site-projection', ['vitest', 'run', 'scripts/project-doc-site.spec.ts', 'scripts/verify-doc-site-fragments.spec.ts'], {
  693. label: 'documentation site checks',
  694. }),
  695. pnpmScript('package-readme-limitations', 'verify-package-readme-limitations', { label: 'package README limitations', quick: true }),
  696. ]
  697. }
  698. /**
  699. * The quick comprehensive documentation-standard aggregate for `test:docs`.
  700. * It covers the prose, pairing, README, budget, and Agent Note gates
  701. * without builds, generator regeneration, or the VitePress site build.
  702. */
  703. function docQuickLeafGates(): Gate[] {
  704. return docSyncLeafGates({ includeDocTypecheck: false }).filter(gate => gate.quick === true)
  705. }
  706. function builtBinSmokeGate(needs: string[] = ['build']): Gate {
  707. return pnpmExec('built-bin-smoke', [
  708. 'vitest',
  709. 'run',
  710. '--config',
  711. 'vitest.e2e.config.ts',
  712. 'apps/cli/tests/profiles/headless/tests/keyless-smoke.e2e.ts',
  713. 'apps/cli/tests/built-bin.e2e.ts',
  714. 'packages/host/directory-picker-native/tests/built-worker.e2e.ts',
  715. 'packages/sdk/server/tests/built-scope-carrier.e2e.ts',
  716. 'packages/subagent/subagent-codex/tests/loader-composition.e2e.ts',
  717. 'packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts',
  718. 'packages/api/remotes/tests/built-lib.e2e.ts',
  719. 'packages/experimental/agent-team/tests/built-lib.e2e.ts',
  720. // Built execution consumers: the only automated proof that package-name
  721. // imports reach their lib/ entrypoints under plain Node. The e2e lane runs
  722. // unbuilt, so these files self-skip there.
  723. 'packages/workflow/workflow-worker-thread/tests/built-worker.e2e.ts',
  724. 'packages/code-runtime/code-runtime-worker-thread/tests/built-lib.e2e.ts',
  725. 'packages/lsp/lsp-stdio/tests/built-lib.e2e.ts',
  726. ], {
  727. label: 'built-bin smoke',
  728. needs,
  729. env: { DSH_EXAMPLE_MODE: 'lib' },
  730. })
  731. }
  732. /**
  733. * Reject a gate list whose graph cannot be executed unambiguously.
  734. * @param gates - complete aggregate to validate.
  735. */
  736. function validateGateGraph(gates: readonly Gate[]): void {
  737. if (gates.length === 0) throw new Error('run-gates: gate graph has no gates.')
  738. const ids = new Set<string>()
  739. for (const gate of gates) {
  740. if (ids.has(gate.id)) throw new Error(`run-gates: duplicate gate id ${JSON.stringify(gate.id)}.`)
  741. ids.add(gate.id)
  742. }
  743. for (const gate of gates) {
  744. for (const dependency of gate.needs ?? []) {
  745. if (!ids.has(dependency)) {
  746. throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} depends on unknown gate ${JSON.stringify(dependency)}.`)
  747. }
  748. }
  749. for (const predecessor of gate.after ?? []) {
  750. if (!ids.has(predecessor)) {
  751. throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} waits for unknown gate ${JSON.stringify(predecessor)}.`)
  752. }
  753. }
  754. }
  755. const cycle = findDependencyCycle(gates)
  756. if (cycle !== undefined) throw new Error(`run-gates: dependency cycle: ${cycle.join(' -> ')}.`)
  757. }
  758. function findDependencyCycle(gates: readonly Gate[]): string[] | undefined {
  759. const byId = new Map(gates.map(gate => [gate.id, gate]))
  760. const complete = new Set<string>()
  761. const active = new Map<string, number>()
  762. const path: string[] = []
  763. const visit = (id: string): string[] | undefined => {
  764. if (complete.has(id)) return undefined
  765. const cycleStart = active.get(id)
  766. if (cycleStart !== undefined) return [...path.slice(cycleStart), id]
  767. const gate = byId.get(id)
  768. if (gate === undefined) return undefined
  769. active.set(id, path.length)
  770. path.push(id)
  771. for (const predecessor of [...(gate.needs ?? []), ...(gate.after ?? [])]) {
  772. const cycle = visit(predecessor)
  773. if (cycle !== undefined) return cycle
  774. }
  775. path.pop()
  776. active.delete(id)
  777. complete.add(id)
  778. return undefined
  779. }
  780. for (const gate of gates) {
  781. const cycle = visit(gate.id)
  782. if (cycle !== undefined) return cycle
  783. }
  784. return undefined
  785. }
  786. /**
  787. * Validate and run one aggregate before the injected executor can start a child.
  788. * @param gates - complete aggregate to execute.
  789. * @param maxActive - maximum concurrent child count.
  790. * @param execute - child-process executor.
  791. * @param observe - result observer invoked when each gate settles.
  792. * @returns results in aggregate order.
  793. */
  794. export async function runGates(
  795. gates: Gate[],
  796. maxActive: number,
  797. execute: GateExecutor,
  798. observe: ResultObserver = () => {},
  799. ): Promise<GateResult[]> {
  800. validateGateGraph(gates)
  801. if (!Number.isSafeInteger(maxActive) || maxActive < 1) {
  802. throw new Error(`run-gates: max concurrency must be a positive integer, got ${JSON.stringify(maxActive)}.`)
  803. }
  804. const states = new Map<string, GateState>(gates.map(gate => [gate.id, 'pending']))
  805. const results = new Map<string, GateResult>()
  806. const running: RunningGate[] = []
  807. for (;;) {
  808. let madeProgress = false
  809. while (running.length < maxActive) {
  810. const ready = gates.find(gate => states.get(gate.id) === 'pending' && predecessorsReady(gate, states))
  811. if (ready === undefined) break
  812. states.set(ready.id, 'running')
  813. running.push({ gate: ready, promise: execute(ready) })
  814. console.log(`run-gates: start ${ready.label}`)
  815. madeProgress = true
  816. }
  817. if (running.length === 0) {
  818. const pending = gates.filter(gate => states.get(gate.id) === 'pending')
  819. if (pending.length === 0) break
  820. const gate = pending.find(item => (item.needs ?? []).some(id => gateFailed(states.get(id))))
  821. if (gate === undefined) throw new Error('run-gates: validated graph stalled without a failed dependency.')
  822. const failedDeps = (gate.needs ?? []).filter(id => gateFailed(states.get(id)))
  823. const result: GateResult = {
  824. gate,
  825. status: 'skipped',
  826. durationMs: 0,
  827. output: [],
  828. exitCode: null,
  829. signalCode: null,
  830. error: `dependency failed or skipped: ${failedDeps.join(', ')}`,
  831. }
  832. states.set(gate.id, 'skipped')
  833. results.set(gate.id, result)
  834. observe(result)
  835. continue
  836. }
  837. if (!madeProgress) {
  838. const settled = await Promise.race(running.map(async item => ({ item, result: await item.promise })))
  839. running.splice(running.indexOf(settled.item), 1)
  840. states.set(settled.item.gate.id, settled.result.status)
  841. results.set(settled.item.gate.id, settled.result)
  842. observe(settled.result)
  843. }
  844. }
  845. return gates.map((gate) => {
  846. const result = results.get(gate.id)
  847. if (result === undefined) throw new Error(`run-gates: missing result for ${gate.id}.`)
  848. return result
  849. })
  850. }
  851. function predecessorsReady(gate: Gate, states: Map<string, GateState>): boolean {
  852. return (gate.needs ?? []).every(id => states.get(id) === 'passed')
  853. && (gate.after ?? []).every(id => gateSettled(states.get(id)))
  854. }
  855. function gateSettled(state: GateState | undefined): boolean {
  856. return state === 'passed' || state === 'failed' || state === 'skipped'
  857. }
  858. function gateFailed(state: GateState | undefined): boolean {
  859. return state === 'failed' || state === 'skipped'
  860. }
  861. /**
  862. * Execute one gate through the real shell-free child-process boundary.
  863. * @param gate - command and scheduler environment to execute.
  864. * @returns the complete process outcome.
  865. */
  866. export async function runGate(gate: Gate): Promise<GateResult> {
  867. const started = performance.now()
  868. const output: GateOutputChunk[] = []
  869. let spawnError: string | undefined
  870. const outcome = await new Promise<{
  871. exitCode: number | null
  872. signalCode: NodeJS.Signals | null
  873. }>((resolveExit) => {
  874. const child = spawn(gate.command, gate.args, {
  875. cwd: root,
  876. env: { ...process.env, ...gate.env },
  877. stdio: ['pipe', 'pipe', 'pipe'],
  878. })
  879. child.stdout.setEncoding('utf8')
  880. child.stderr.setEncoding('utf8')
  881. child.stdout.on('data', (chunk: string) => {
  882. if (gate.streamOutput === true) process.stdout.write(chunk)
  883. else output.push({ stream: 'stdout', text: chunk })
  884. })
  885. child.stderr.on('data', (chunk: string) => {
  886. if (gate.streamOutput === true) process.stderr.write(chunk)
  887. else output.push({ stream: 'stderr', text: chunk })
  888. })
  889. child.on('error', (error) => {
  890. spawnError = `failed to start command: ${error.message}`
  891. resolveExit({ exitCode: null, signalCode: null })
  892. })
  893. child.on('close', (exitCode, signalCode) => {
  894. resolveExit({ exitCode, signalCode })
  895. })
  896. child.stdin.end()
  897. })
  898. const { exitCode, signalCode } = outcome
  899. const status: GateResultStatus = exitCode === 0 && signalCode === null && spawnError === undefined ? 'passed' : 'failed'
  900. const result: GateResult = {
  901. gate,
  902. status,
  903. durationMs: performance.now() - started,
  904. output,
  905. exitCode,
  906. signalCode,
  907. }
  908. if (spawnError !== undefined) result.error = spawnError
  909. return result
  910. }
  911. /**
  912. * Format every independently observed failure fact for the aggregate summary.
  913. * @param result - unsuccessful gate result.
  914. * @returns error, exit, and signal facts without allowing one to hide another.
  915. */
  916. export function formatGateResultReason(result: GateResult): string {
  917. const facts: string[] = []
  918. if (result.error !== undefined) facts.push(result.error)
  919. if (result.exitCode !== null) facts.push(`exit ${result.exitCode}`)
  920. if (result.signalCode !== null) facts.push(`signal ${result.signalCode}`)
  921. return facts.length === 0 ? 'no exit code or signal' : facts.join(', ')
  922. }
  923. function printResult(result: GateResult): void {
  924. const verbose = process.env.DSH_GATE_VERBOSE === '1'
  925. const seconds = (result.durationMs / 1000).toFixed(2)
  926. if (result.status === 'passed' && !verbose) {
  927. console.log(`run-gates: PASS ${result.gate.label} (${seconds}s)`)
  928. return
  929. }
  930. const heading = `${result.status.toUpperCase()} ${result.gate.label} (${seconds}s)`
  931. const writeHeading = result.status === 'passed' ? console.log : console.error
  932. writeHeading(`\n== ${heading} ==`)
  933. if (result.status !== 'passed') {
  934. console.error(`command: ${result.gate.displayCommand}`)
  935. console.error(`outcome: ${formatGateResultReason(result)}`)
  936. }
  937. if (result.gate.streamOutput !== true) printOutput(result.output)
  938. }
  939. function printSummary(results: GateResult[], durationMs: number): void {
  940. const passed = results.filter(result => result.status === 'passed').length
  941. const failed = results.filter(result => result.status === 'failed').length
  942. const skipped = results.filter(result => result.status === 'skipped').length
  943. const seconds = (durationMs / 1000).toFixed(2)
  944. console.log(`\nrun-gates: ${passed} passed, ${failed} failed, ${skipped} skipped in ${seconds}s.`)
  945. const unsuccessful = results.filter(result => result.status === 'failed' || result.status === 'skipped')
  946. if (unsuccessful.length === 0) return
  947. console.error('run-gates: unsuccessful gates:')
  948. for (const result of unsuccessful) {
  949. const duration = (result.durationMs / 1000).toFixed(2)
  950. const reason = formatGateResultReason(result)
  951. const disposition = result.gate.allowFailure === true ? 'NON-BLOCKING ' : ''
  952. console.error(` - ${disposition}${result.status.toUpperCase()} ${result.gate.label} (${duration}s, ${reason})`)
  953. console.error(` ${result.gate.displayCommand}`)
  954. }
  955. }
  956. function printOutput(output: GateOutputChunk[]): void {
  957. for (const chunk of output) {
  958. if (chunk.stream === 'stdout') process.stdout.write(chunk.text)
  959. else process.stderr.write(chunk.text)
  960. }
  961. }