packstruct 0.9.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # packstruct 0.9.0
1
+ # packstruct 1.0.0
2
2
 
3
3
  The shared `/packs` spec. **One manifest + entry + lifecycle contract, many
4
4
  hosts**, currently [crashtest](https://github.com/dhaupin/crashtest)
@@ -65,18 +65,21 @@ Therefore crashtest hosts v1 with **zero runtime changes**, and poststruct
65
65
  adopts v1 fresh. Neither host shares an implementation with the other. They
66
66
  share only this file convention.
67
67
 
68
- ## Status (0.9.0)
68
+ ## Status (1.0.0)
69
69
 
70
70
  Version ladder follows [prestruct](https://github.com/dhaupin/prestruct)'s
71
- convention: 0.9.x is the manual `npm publish` ladder (0.9.0 is this
72
- release); 1.0.0 flips on the CI publish lane - publish.yml refuses 0.x,
73
- verifies the tag matches the version, and publishes with `--provenance`,
74
- so v1.0.0 carries provenance by construction.
71
+ convention: 0.9.x is the manual `npm publish` ladder (0.9.0 was the manual
72
+ release that seeded the package); 1.0.0 and later flip on the CI publish
73
+ lane - tag v1.0.0 and publish.yml runs (refuses 0.x, verifies the tag
74
+ matches the version, and publishes with `--provenance`, so v1.0.0 carries
75
+ provenance by construction).
75
76
 
76
77
  ## Related
77
78
 
78
79
  - [crashtest](https://github.com/dhaupin/crashtest) (scenario-profile host)
79
80
  - [poststruct](https://github.com/dhaupin/poststruct) (check-profile host)
81
+ - **The workshop** -> [Creadev.org](https://creadev.org) (the same home as the
82
+ docs, npm, and site surfaces above)
80
83
 
81
84
  ## Landing & docs
82
85
 
package/bin/cli.mjs CHANGED
@@ -8,14 +8,16 @@
8
8
  // `packstruct <dir>` keeps working (the dir positionally implies lint; a
9
9
  // target dir genuinely named 'lint' must not break the parser either way).
10
10
  //
11
- // lint --deep (packstruct#2): after the manifest pass, imports each declared
12
- // entry once in-process, checks the default export exists, and censuses
13
- // ids (module/attack/check/step names across the corpus) - mirrors the
14
- // engine's shared-`seen` collision refusal (crashtest fc93ca6
15
- // src/packs/loader.js :389-391) at author time. Probe only: host contract
16
- // shapes stay host-owned (SPEC section 3). Importing runs the entry's
17
- // top-level code; data modules are inert, and hostile modules are the
18
- // host's isolation domain, not the linter's.
11
+ // lint --deep (packstruct#2): after the manifest pass, probes each declared
12
+ // entry in a DISPOSABLE CHILD PROCESS (pack code runs nowhere near the
13
+ // linter's own process or exit code - the QC finding: a top-level exit()
14
+ // used to hijack the wire exit and a spin-lock entry hung the CLI), checks
15
+ // the default export exists, and censuses ids (module/attack/check/step
16
+ // names across the corpus) - mirrors the engine's shared-`seen` collision
17
+ // refusal (crashtest fc93ca6 src/packs/loader.js :389-391) at author time.
18
+ // Probe only: host contract shapes stay host-owned (SPEC section 3).
19
+ // Probing runs the entry's top-level code - in the child's domain, not
20
+ // the linter's; a 5s probe timeout makes stalls honest refusals.
19
21
  //
20
22
  // lint --against <file-or-dir> (packstruct#2, requires --deep): seed the
21
23
  // census with the HOST LIBRARY ids so pack-vs-library collisions refuse at
@@ -62,7 +64,7 @@ if (verb === 'audit-conformance') {
62
64
  }
63
65
  const repo = positional[0] ?? '.'
64
66
  const json = args.includes('--json')
65
- const r = auditConformance({ loader, repo, json })
67
+ const r = await auditConformance({ loader, repo, json })
66
68
  if (json) {
67
69
  console.log(JSON.stringify({ schema: 1, mode: 'audit', repo, cases: r.caseCount, honored: r.honored, violations: r.violations }, null, 2))
68
70
  } else {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "packstruct",
3
- "version": "0.9.0",
3
+ "version": "1.0.0",
4
4
  "description": "The shared /packs spec: one manifest, entry, and lifecycle contract for crashtest and poststruct packs - plus a zero-dependency lint CLI that kills broken pack manifests at author time.",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",
package/src/audit.mjs CHANGED
@@ -10,11 +10,23 @@
10
10
  // refusal its own way, so the audit matches identity, not jargon). Any other
11
11
  // outcome is an audit violation naming the case - the harness refuses to
12
12
  // grade, it only reports what the loader actually did.
13
+ //
14
+ // Loader caps (QC hardening): a HOST loader is arbitrary code in the shell
15
+ // it owns, and a refusal is instant - so a loader that HANGS is killed at
16
+ // the 120s audit timeout (neither verdict), and output past the 1MB cap is
17
+ // unverifiable output (neither verdict). Both surface as audit violations
18
+ // naming the case. The spawn is runCapped (async, exit-event-closed, no
19
+ // pipe-EOF hostage and no unaccounted scratch-file growth) - the two caps
20
+ // are the ONLY things that can end a loader early, and both are reported
21
+ // honestly, not graded through.
13
22
  import { cpSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'
14
23
  import { join, resolve } from 'node:path'
15
24
  import { tmpdir } from 'node:os'
16
25
  import { fileURLToPath } from 'node:url'
17
- import { spawnSync } from 'node:child_process'
26
+ import { runCapped } from './run-capped.mjs'
27
+
28
+ export const AUDIT_TIMEOUT_MS = 120000
29
+ export const AUDIT_MAXBUFFER_BYTES = 1024 * 1024
18
30
 
19
31
  export const CASES_DIR = fileURLToPath(new URL('../conformance/cases/', import.meta.url))
20
32
 
@@ -43,7 +55,7 @@ function casePackIdentities(root) {
43
55
  return ids
44
56
  }
45
57
 
46
- export function auditConformance(opts = {}) {
58
+ export async function auditConformance(opts = {}) {
47
59
  if (typeof opts.loader !== 'string' || !opts.loader.includes('{packs}')) {
48
60
  return { caseCount: 0, honored: 0, violations: [{ pack: 'usage', norm: 'usage', message: 'audit-conformance needs --loader "<cmd> {packs}" - {packs} is replaced by each materialized bundle root' }] }
49
61
  }
@@ -58,22 +70,42 @@ export function auditConformance(opts = {}) {
58
70
  cpSync(join(CASES_DIR, c), tmp, { recursive: true })
59
71
  const ids = casePackIdentities(tmp)
60
72
  const cmd = opts.loader.split('{packs}').join(`"${tmp}"`)
61
- const r = spawnSync(cmd, { shell: true, cwd: repo, encoding: 'utf8' })
62
- const out = `${r.stdout ?? ''}\n${r.stderr ?? ''}`
63
- const claimed = r.status === 0
64
- let ok = expect === 'accept' ? claimed : !claimed
73
+ const auditTimeoutMs = Number.isFinite(opts.auditTimeoutMs) ? opts.auditTimeoutMs : AUDIT_TIMEOUT_MS
74
+ const r = await runCapped({ cmd, shell: true, cwd: repo, timeoutMs: auditTimeoutMs, maxBuffer: AUDIT_MAXBUFFER_BYTES, killSignal: 'SIGKILL' })
75
+ if (r.spawnError) throw r.spawnError
76
+ const out = `${r.stdout}\n${r.stderr}`
77
+ let ok
65
78
  let why = ''
66
- if (ok && expect === 'refuse' && ![...ids].some(id => out.includes(id))) {
79
+ if (r.capped) {
80
+ ok = false
81
+ why = `loader output exceeded the audit buffer (${AUDIT_MAXBUFFER_BYTES} bytes) - no verdict is observable past the cap, so the case carries no claim`
82
+ } else if (r.timedOut) {
67
83
  ok = false
68
- why = 'refused but did not name the pack (SPEC section 5: nameable refusals)'
84
+ why = `loader hung past the audit timeout (${auditTimeoutMs}ms, killed with ${r.signal ?? 'SIGKILL'}) - writes no verdict; a refusal is instant, hangs are neither accept nor refuse`
85
+ } else {
86
+ const claimed = r.status === 0
87
+ if (expect === 'accept') {
88
+ ok = claimed
89
+ } else {
90
+ ok = !claimed
91
+ if (!ok) why = '' // exit 0 on a refuse case: the main message covers it
92
+ else if (![...ids].some(id => out.includes(id))) {
93
+ ok = false
94
+ why = 'refused but did not name the pack (SPEC section 5: nameable refusals)'
95
+ }
96
+ }
69
97
  }
70
98
  if (ok) honored++
71
99
  else {
72
- const got = claimed ? 'exit 0 (loader accepted)' : `exit ${r.status}`
100
+ const got = r.capped ? `output capped at ${AUDIT_MAXBUFFER_BYTES} bytes`
101
+ : r.timedOut ? `killed at the ${auditTimeoutMs}ms timeout (${r.signal ?? 'SIGKILL'})`
102
+ : r.status === null ? `killed on signal ${r.signal ?? '?'}`
103
+ : r.status === 0 ? 'exit 0 (loader accepted)'
104
+ : `exit ${r.status}`
73
105
  violations.push({
74
106
  pack: c,
75
107
  norm: `audit-${expect}`,
76
- message: `loader ${got} on case "${c}" - the spec verdict is ${expect === 'accept' ? 'accept' : 'refuse'}${why ? ` - ${why}` : ''}`,
108
+ message: `loader ${got} on case "${c}" - the spec verdict is ${expect}${why ? ` - ${why}` : ''}`,
77
109
  })
78
110
  }
79
111
  } finally {
package/src/lint.mjs CHANGED
@@ -9,9 +9,10 @@
9
9
  // (crashtest `fc93ca6` src/packs/loader.js:389-391) at author time.
10
10
  // PROBE ONLY: host module-shape norms stay host-owned (SPEC section 3) -
11
11
  // deep censes ids, it does not police the host's contract shapes.
12
- import { readFileSync, existsSync, readdirSync } from 'node:fs'
12
+ import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs'
13
13
  import { join, resolve } from 'node:path'
14
14
  import { pathToFileURL } from 'node:url'
15
+ import { runCapped } from './run-capped.mjs'
15
16
 
16
17
  export function lintPacks(dir) {
17
18
  const violations = []
@@ -61,9 +62,12 @@ export function lintPacks(dir) {
61
62
  return { packsChecked, violations }
62
63
  }
63
64
 
64
- // Ids a deep probe extracts from ONE default export (generic over the two
65
- // house profiles: scenario `attacks[]/steps[]`, check `checks[]` - host
66
- // shapes stay host-owned, this never assigns shared meaning to them).
65
+ // Ids ONE default export carries (generic over the two house profiles:
66
+ // scenario `attacks[]/steps[]`, check `checks[]` - host shapes stay
67
+ // host-owned, this never assigns shared meaning to them). Runs in-process
68
+ // ONLY on inert data (JSON libraries); code modules are probed in a child
69
+ // process via childProbe below - their top-level code must never run inside
70
+ // the linter (it could exit() the CLI or spin it forever).
67
71
  function probeIds(def, pack) {
68
72
  const out = []
69
73
  const push = (id, at) => { if (typeof id === 'string' && id) out.push({ id, pack, at }) }
@@ -89,38 +93,114 @@ function probeIds(def, pack) {
89
93
 
90
94
  const DEEP_LIB_TAG = '(host-library)'
91
95
 
92
- // Load the host-library census reference (--against, packstruct#2 ask: the
93
- // id-vs-host-library census). Accepts a file or a directory: .json parses
94
- // directly, code modules import in-process and default-export ids in one of
95
- // the house profile shapes (generically probed - the library's internal
96
- // shapes stay the host's business).
97
- async function loadLibraryAgainst(ref) {
98
- if (ref.endsWith('.json')) return JSON.parse(readFileSync(ref, 'utf8'))
99
- if (existsSync(ref) && (await import('node:fs')).statSync(ref).isDirectory()) {
100
- const entries = readdirSync(ref).filter(f => f.endsWith('.js') || f.endsWith('.mjs')).sort()
101
- let merged = null
102
- for (const f of entries) {
103
- const mod = (await import(pathToFileURL(resolve(ref, f)).href)).default
104
- merged = { parts: (merged?.parts ?? []).concat([{ file: f, mod }]) }
96
+ // QC finding (crash class, fixed): deep used to import entries in-process,
97
+ // so an entry and its own top-level code could drive the probe's process -
98
+ // process.exit(7) made the CLI wire-exit 7 with no output, and an infinite
99
+ // top-level loop hung it forever. Probes now run in a disposable child
100
+ // (no shared module cache/no shared process). Kill on the timeout: a
101
+ // refusal is instant, and a pack that stalls the exit-code contract is an
102
+ // entry-import violation, not a hint.
103
+ export const PROBE_TIMEOUT_MS = 5000
104
+ const PROBE_MARKER = 'PROBE::'
105
+
106
+ function childProbeScript(fileUrl) {
107
+ return `
108
+ try {
109
+ const m = await import(${JSON.stringify(fileUrl)});
110
+ const d = m && m.default;
111
+ const out = { defaultExport: d !== undefined && d !== null, ids: [] };
112
+ const push = (id, at) => { if (typeof id === 'string' && id) out.ids.push({ id, at }) };
113
+ if (d && typeof d === 'object') {
114
+ push(d.name, 'module name');
115
+ for (const key of ['attacks', 'checks', 'scenarios']) {
116
+ const arr = d[key];
117
+ if (!Array.isArray(arr)) continue;
118
+ for (const item of arr) {
119
+ if (!item || typeof item !== 'object') continue;
120
+ push(item.id ?? item.name, key + '[]');
121
+ for (const sub of ['steps', 'phases']) {
122
+ if (!Array.isArray(item[sub])) continue;
123
+ for (const s of item[sub]) {
124
+ if (!s || typeof s !== 'object') continue;
125
+ push(s.id ?? s.name, key + '[].' + sub + '[]');
126
+ }
127
+ }
128
+ }
105
129
  }
106
- return merged
107
130
  }
108
- return (await import(pathToFileURL(resolve(ref)).href)).default
131
+ process.stdout.write(${JSON.stringify(PROBE_MARKER)} + JSON.stringify(out));
132
+ } catch (e) {
133
+ process.stdout.write(${JSON.stringify(PROBE_MARKER)} + JSON.stringify({ importError: String((e && e.message) || e) }));
134
+ }
135
+ `
109
136
  }
110
137
 
111
- // Merge a dir-shaped library into one probeUnits list: [{id, at, from}].
112
- function libraryProbeUnits(lib, ref) {
113
- if (lib?.parts) {
114
- const out = []
115
- for (const { file, mod } of lib.parts) {
116
- for (const u of probeIds(mod, DEEP_LIB_TAG)) out.push({ ...u, at: `${file}: ${u.at}` })
138
+ // Probe one code module in the child. Returns the probe report or throws a
139
+ // plain Error carrying the reason the probe could not report.
140
+ //
141
+ // Stdio through runCapped (async): a killed probe must never wait on
142
+ // pipe-EOF that an orphaned grandchild spawned by the entry can hold
143
+ // forever, and an output-flooding entry hits the 1MB cap (an honest
144
+ // entry-import refusal), not a scratch-file flood that fills the disk.
145
+ async function childProbe(absPath, timeoutMs = PROBE_TIMEOUT_MS) {
146
+ const fileUrl = pathToFileURL(absPath).href
147
+ const r = await runCapped({
148
+ cmd: process.execPath,
149
+ args: ['--input-type=module', '--no-warnings', '-e', childProbeScript(fileUrl)],
150
+ timeoutMs,
151
+ maxBuffer: 1024 * 1024,
152
+ killSignal: 'SIGKILL',
153
+ })
154
+ if (r.spawnError && r.spawnError.code === 'ENOENT') throw new Error(`no node runtime to probe with`)
155
+ const out = r.stdout
156
+ const idx = out.lastIndexOf(PROBE_MARKER)
157
+ if (idx === -1) {
158
+ if (r.capped) throw new Error(`probe output hit the ${1 << 20}B cap before the probe reported (an entry flooding its own stdout) - a pack that floods the probe is refusing the exit-code contract, and a refusal is instant`)
159
+ if (r.timedOut) throw new Error(`probe killed after the ${timeoutMs}ms timeout (signal ${r.signal ?? 'SIGKILL'}) - a pack stalling the probe is refusing the exit-code contract, and a refusal is instant`)
160
+ throw new Error(`entry terminated the probe process (exit ${r.status ?? 'null'}) before the probe could report`)
161
+ }
162
+ let report
163
+ try {
164
+ report = JSON.parse(out.slice(idx + PROBE_MARKER.length).trim())
165
+ } catch {
166
+ throw new Error('probe output was not parseable as a probe report')
167
+ }
168
+ return report
169
+ }
170
+
171
+ // Load the host-library census reference (--against, packstruct#2 ask: the
172
+ // id-vs-host-library census). Accepts a file or a directory: .json parses
173
+ // in-process (inert data - no code execution needed); code modules are
174
+ // child-probed one by one, same as pack entries. The library's internal
175
+ // shapes stay the host's business.
176
+ async function collectLibraryUnits(ref, timeoutMs) {
177
+ const units = []
178
+ if (ref.endsWith('.json')) {
179
+ const obj = JSON.parse(readFileSync(ref, 'utf8'))
180
+ for (const u of probeIds(obj, DEEP_LIB_TAG)) units.push({ id: u.id, at: `json ref: ${u.at}` })
181
+ return units
182
+ }
183
+ let files
184
+ if (existsSync(ref) && statSync(ref).isDirectory()) {
185
+ files = readdirSync(ref).filter(f => f.endsWith('.js') || f.endsWith('.mjs')).sort().map(f => join(ref, f))
186
+ } else {
187
+ files = [resolve(ref)]
188
+ }
189
+ for (const file of files) {
190
+ let report
191
+ try {
192
+ report = await childProbe(file, timeoutMs)
193
+ } catch (err) {
194
+ throw new Error(`${file}: ${err.message}`)
117
195
  }
118
- return out
196
+ if (report.importError !== undefined) throw new Error(`${file}: failed to import: ${report.importError}`)
197
+ for (const { id, at } of report.ids) units.push({ id, at: `${file}: ${at}` })
119
198
  }
120
- return probeIds(lib, DEEP_LIB_TAG).map(u => ({ ...u, at: `ref: ${u.at}` }))
199
+ return units
121
200
  }
122
201
 
123
202
  export async function deepLintPacks(dir, opts = {}) {
203
+ const timeoutMs = Number.isFinite(opts.probeTimeoutMs) ? opts.probeTimeoutMs : PROBE_TIMEOUT_MS
124
204
  const shallow = lintPacks(dir)
125
205
  const violations = [...shallow.violations]
126
206
  const publicDir = join(dir, 'public')
@@ -140,14 +220,14 @@ export async function deepLintPacks(dir, opts = {}) {
140
220
  // namespaced-ids norm, engine side: the #19 44-vs-49 zero-collision claim).
141
221
  if (opts.against !== undefined) {
142
222
  try {
143
- const lib = await loadLibraryAgainst(opts.against)
144
- for (const { id, at } of libraryProbeUnits(lib, opts.against)) {
223
+ const lib = await collectLibraryUnits(opts.against, timeoutMs)
224
+ for (const { id, at } of lib) {
145
225
  if (idSeen.has(id)) continue // the library's own internals: not ours to judge
146
226
  idSeen.set(id, { pack: DEEP_LIB_TAG, at: `--against (${at})` })
147
227
  libraryIds++
148
228
  }
149
229
  } catch (err) {
150
- violations.push({ pack: DEEP_LIB_TAG, norm: 'library-ref', message: `--against "${opts.against}": failed to load the host library: ${err.message}` })
230
+ violations.push({ pack: DEEP_LIB_TAG, norm: 'library-ref', message: `--against "${opts.against}": ${err.message}` })
151
231
  }
152
232
  }
153
233
  for (const name of readdirSync(publicDir).sort()) {
@@ -171,21 +251,25 @@ export async function deepLintPacks(dir, opts = {}) {
171
251
  // Entry probe (packstruct#2 ask 1): import once, in-process.
172
252
  if (flagged === 'entry') continue // missing/invalid entry: shallow already refused
173
253
  if (typeof m.entry !== 'string' || !existsSync(join(packDir, m.entry))) continue
174
- let mod = null
254
+ let report
175
255
  try {
176
- mod = await import(pathToFileURL(resolve(packDir, m.entry)).href)
256
+ report = await childProbe(resolve(packDir, m.entry), timeoutMs)
177
257
  } catch (err) {
178
- violations.push({ pack: name, norm: 'entry-import', message: `entry "${m.entry}" failed to import: ${err.message}` })
258
+ violations.push({ pack: name, norm: 'entry-import', message: `entry "${m.entry}": ${err.message}` })
259
+ continue
260
+ }
261
+ if (report.importError !== undefined) {
262
+ violations.push({ pack: name, norm: 'entry-import', message: `entry "${m.entry}" failed to import: ${report.importError}` })
179
263
  continue
180
264
  }
181
- if (mod === null || typeof mod !== 'object' || mod.default === undefined) {
265
+ if (!report.defaultExport) {
182
266
  violations.push({ pack: name, norm: 'entry-default-export', message: `entry "${m.entry}" has no default export - the loader would report it as an entry failure (SPEC section 3)` })
183
267
  continue
184
268
  }
185
269
  modulesProbed++
186
270
  // Census (packstruct#2 ask 2): raw ids across the pack corpus, plus
187
271
  // within-pack duplicates - engine parity before the host ever loads.
188
- for (const { id, at } of probeIds(mod.default, name)) {
272
+ for (const { id, at } of report.ids) {
189
273
  idsCensused++
190
274
  if (idsCensused > MAX_IDS) {
191
275
  violations.push({ pack: name, norm: 'deep-floor', message: `census floor exceeded (>${MAX_IDS} ids) - refusing to walk further rather than pretending` })
@@ -0,0 +1,95 @@
1
+ // src/run-capped.mjs - the one gated child runner both spawned surfaces use
2
+ // (the audit's HOST loader and the deep probe's entry reader). Zero deps.
3
+ //
4
+ // Why async spawn and not spawnSync pipes (the QC finding, CI-reproduced):
5
+ // a sync pipe read waits for EOF on stdout, and EOF needs every writer gone -
6
+ // a timeout-killed loader that leaves an ORPHANED grandchild holding the
7
+ // pipe makes spawnSync block forever. Killing is fine; waiting on the
8
+ // orphan's EOF is not. This runner resolves on the direct child's `exit`
9
+ // event - never on EOF - so an orphan can't hold the harness hostage.
10
+ //
11
+ // Caps, both hard (kill on exceed, no soft drift):
12
+ // timeoutMs - the child is SIGKILLed at the deadline; `timedOut` reports it
13
+ // maxBuffer - accumulated stdout+stderr bytes; past the cap the child is
14
+ // killed and `capped` reports it (the cap is an honesty cap:
15
+ // output beyond it is unverifiable output)
16
+ // After `exit` (or a kill), later data events from orphans are ignored and
17
+ // only the bytes captured before exit are returned.
18
+ //
19
+ // Group kill (2026-10-25 leak finding): caps that kill the child alone
20
+ // leaked /bin/sh's node grandchildren when the shell forked instead of
21
+ // exec'ing - a flood loader that survives its own death keeps console.log
22
+ // buffering into a pipe nobody reads, gigabytes per child in seconds (4
23
+ // leaked children ballooned this workspace 104MB -> 3.3GB and starved CI
24
+ // runners mid-suite). The child now spawns detached - its own process
25
+ // group - and every kill path signals the NEGATIVE pid: the direct child,
26
+ // any forked shell, and every grandchild, in one shot.
27
+ //
28
+ // Battlefield note (2026-10-24 QC): the predecessor of this file was the
29
+ // audit's sync spawn with file-stdio scratch - under an output-flooding
30
+ // loader there was NO cap on file growth, and a 20GB scratch file filled the
31
+ // disk before the 120s deadline. The flood name in the tests is the same,
32
+ // but the killer is now the cap, not the clock.
33
+ import { spawn } from 'node:child_process'
34
+
35
+ function makeKill(p, killSignal) {
36
+ // Negated pid = the whole process group (the child is a group leader
37
+ // because the spawn is detached). Falls back to the direct-child kill
38
+ // when the group is already gone; both no-op if the child never spawned.
39
+ return () => {
40
+ if (!p.pid) return
41
+ try { process.kill(-p.pid, killSignal) }
42
+ catch { try { p.kill(killSignal) } catch { /* already gone */ } }
43
+ }
44
+ }
45
+
46
+ export function runCapped({ cmd, args = [], shell = false, cwd, timeoutMs = 5000, maxBuffer = 1024 * 1024, killSignal = 'SIGKILL' }) {
47
+ return new Promise((resolve) => {
48
+ let done = false
49
+ let total = 0
50
+ let capped = false
51
+ let timedOut = false
52
+ let spawnError = null
53
+ const chunks = []
54
+ const stderrChunks = []
55
+ // detached on POSIX: the child leads its own process group, which is
56
+ // what makes the negated-pid group kill total (shell forks die too).
57
+ const p = spawn(cmd, args, { shell, cwd, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] })
58
+ const killTree = makeKill(p, killSignal)
59
+ const timer = setTimeout(() => {
60
+ timedOut = true
61
+ killTree()
62
+ }, timeoutMs)
63
+ const finish = () => {
64
+ if (done) return
65
+ done = true
66
+ clearTimeout(timer)
67
+ try { p.stdout.destroy(); p.stderr.destroy() } catch { /* already dead */ }
68
+ resolve({
69
+ status: p.exitCode,
70
+ signal: p.signalCode,
71
+ stdout: Buffer.concat(chunks).toString('utf8'),
72
+ stderr: stderrChunks.join(''),
73
+ capped,
74
+ timedOut,
75
+ spawnError,
76
+ })
77
+ }
78
+ // stdout is capped hard: past maxBuffer the child dies. stderr counts
79
+ // against the same gate so a stderr flood cannot OOM the harness either.
80
+ p.stdout.on('data', (d) => {
81
+ if (done || capped) return
82
+ total += d.length
83
+ chunks.push(d)
84
+ if (total > maxBuffer) { capped = true; killTree() }
85
+ })
86
+ p.stderr.on('data', (d) => {
87
+ if (done) return
88
+ total += d.length
89
+ stderrChunks.push(d)
90
+ if (total > maxBuffer) { capped = true; killTree() }
91
+ })
92
+ p.on('error', (e) => { spawnError = e; finish() })
93
+ p.on('exit', finish)
94
+ })
95
+ }