/** * ── ⭐⭐ A BACKGROUND PROCESS WITH A REAL ARGV, AND THE GATE IT GOES THROUGH ── * * MEASURED 2026-08-14, before any of this existed: * * start_process {"command":"npm run serve"} → ok, bg1, pid 19648 * start_process {"command":"node server.mjs --port 3005"} * → REFUSED "--port is not an allowed node flag" * start_process {"command":"node -e console.log(1)"} → REFUSED on "(" * * The middle one is the whole reason this file exists. Every framework dev * server takes a port or a host flag, so the one tool built to start servers * could not start a server on a chosen port; `npm run dev` worked by the * coincidence of having no arguments. `run_program` had already solved exactly * this for one-shot commands, and nothing offered it for a process that keeps * running. * * ⚠️ SO THE TESTS THAT MATTER MOST HERE ARE NOT THE HAPPY ONES. They are the * ones proving the new door has the SAME locks as the old one — because a * second, less-audited way to start a process is a security regression, and this * package has already shipped an RCE that printed a check mark. Every refusal * below is asserted to be `command.mjs`'s OWN sentence, not a lookalike. * * ⭐ Still $0.00 and no key: the subject is `node`, which is already running * this test. */ import { test, after, beforeEach } from 'node:test'; import assert from 'node:assert/strict'; import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { createServer } from 'node:net'; import { startBackground, checkBackground, stopBackground, stopAllBackground, listBackground, backgroundToolSchemas, runBackgroundTool, } from '../lib/background.mjs'; /** * ⚠️ THE REGISTRY IS MODULE-LEVEL AND CAPPED AT FOUR, so one test that leaks a * live process makes the NEXT four refuse with "already running" — a cascade * that reads like five broken features. Found while mutation-testing this file: * breaking the npm gate started a real process and reddened five unrelated * tests, which would have made the mutation signal unreadable. */ beforeEach(() => stopAllBackground()); const made = []; after(() => { stopAllBackground(); for (const d of made) { try { rmSync(d, { recursive: true, force: true }); } catch { /* best effort */ } } }); /** * A server that PRINTS ITS OWN argv. That printout is the evidence: it is the * only way to show that `"hello there"` arrived as ONE slot rather than two, * which is the entire difference between this form and a string. */ const SERVER = ` import { createServer } from 'node:http'; const argv = process.argv.slice(2); const port = Number(argv[argv.indexOf('--port') + 1]); const banner = argv[argv.indexOf('--banner') + 1]; createServer((_q, r) => { r.writeHead(200); r.end('ok'); }) .listen(port, '127.0.0.1', () => { console.log('argv seen: ' + JSON.stringify(argv)); console.log(banner + ' - listening on http://localhost:' + port); }); `; function workspace({ scripts = {}, files = {} } = {}) { const root = mkdtempSync(join(tmpdir(), 'acuvo-bgargv-')); made.push(root); const pkg = JSON.stringify({ name: 'bg', version: '1.0.0', scripts }, null, 2); writeFileSync(join(root, 'package.json'), pkg); writeFileSync(join(root, 'server.mjs'), SERVER); for (const [rel, body] of Object.entries(files)) writeFileSync(join(root, rel), body); /** * ⚠️ A REAL `readFile`, because the npm script-body gate reads package.json * through the executor. A stub that returns null would make the gate fail * closed and the test would pass for the wrong reason. */ return { root, dryRun: false, readFile: (rel) => (rel === 'package.json' ? { ok: true, content: pkg } : { ok: false, error: 'no such file' }), }; } /** A port nothing is using, so `--port N` can be asserted rather than assumed. */ function freePort() { return new Promise((resolve) => { const s = createServer(); s.listen(0, '127.0.0.1', () => { const { port } = s.address(); s.close(() => resolve(port)); }); }); } async function until(fn, { timeoutMs = 20_000, everyMs = 100 } = {}) { const deadline = Date.now() + timeoutMs; for (;;) { const v = await fn(); if (v) return v; if (Date.now() > deadline) return null; await new Promise((r) => setTimeout(r, everyMs)); } } // ── ⭐ THE GAP, CLOSED AND PROVEN AGAINST A REAL PROCESS ──────────────────── test('a server starts on a port chosen by an argument the string form refuses', async () => { const ex = workspace(); const port = await freePort(); // ⚠️ FIRST, THE BASELINE. If this ever starts succeeding, the argv form is no // longer closing a gap and this whole file is measuring nothing. const asString = startBackground({ command: `node server.mjs --port ${port}`, executor: ex }); assert.equal(asString.ok, false, 'the string path must still refuse a program flag'); assert.match(asString.error, /--port is not an allowed node flag/); /** * ── ⚠️ THE PORT RACE, CLOSED AT THE CAUSE RATHER THAN BY WAITING LONGER ──── * * `freePort()` binds port 0, reads the number, CLOSES the socket, and returns. * Between that close and the child binding it, the port belongs to nobody — * so under the full parallel suite another test can take it and this server * never comes up. Measured 2026-08-14: green twice in isolation, failed once * inside a 2,195-test parallel run. That is a race, not a slow machine. * * ⚠️ RAISING THE TIMEOUT WOULD HAVE MADE IT GREENER AND NO MORE CORRECT — the * port is already gone; waiting longer waits for something that will never * happen. This package fixed a flake the same way once before and recorded the * rule: fix the cause, never the number. * * ⭐ So a lost race is RETRIED WITH A FRESH PORT, and only that. A genuine * failure — the argv form not reaching the program at all — still fails on the * last attempt, because the assertion below is unchanged and runs either way. */ let started = null; let up = null; let usedPort = port; for (let attempt = 1; attempt <= 3 && !up; attempt += 1) { if (attempt > 1) usedPort = await freePort(); started = startBackground({ program: 'node', args: ['server.mjs', '--port', String(usedPort), '--banner', 'hello there'], executor: ex, }); assert.equal(started.ok, true, started.error); assert.equal(typeof started.pid, 'number'); /** * ── ⚠️⚠️ REACHABLE IS NOT THE SAME AS "ITS OUTPUT HAS BEEN COLLECTED" ──── * * This waited on `probe.reachable` alone and then asserted on `up.output`, * and the two are not the same event. The child prints its argv, calls * `listen`, and prints "… - listening" from the listen callback — so the * probe can succeed in the very same tick the second line is written, before * that line has been read off the pipe and appended to the record. Measured * on 2026-08-15: 1 pass and 2 failures in three isolated runs, and the * failure output always held the argv line and never the listening one. * That is the whole tell — a truncated tail, not a missing feature. * * ⭐ FIXED AT THE CAUSE, like the port race above it: wait for the thing the * assertions actually read. Raising the timeout would have made it greener * and no more correct, which is this file's own stated rule. * * ⚠️ AND IT STILL FAILS HONESTLY. If the program never receives its * arguments, the output never matches, `up` stays null, and the assertion * below reports it — the wait is narrower, not weaker. */ up = await until(async () => { const s = await checkBackground(started.id); if (!s.probe?.reachable) return null; return /listening/.test(String(s.output ?? '')) ? s : null; }, { timeoutMs: 8_000 }); // ⚠️ SYNCHRONOUS — line 176 reads `.ok` off it directly. `await …catch()` // would throw on a plain object, turning a retry into the failure it exists // to prevent. Reaping the loser matters: a child left holding a port is how // one flake becomes several. if (!up) { try { stopBackground(started.id); } catch { /* already gone */ } } } assert.ok(up, 'the server never became reachable, on three different ports'); /** * ⚠️ `usedPort`, NOT `port` — AND THE RETRY LOOP MADE ITS OWN SUCCESS IMPOSSIBLE. * The loop retries on a FRESH port (`usedPort = await freePort()`), and these * two assertions checked the ORIGINAL one. So the retry that exists to survive * a lost port race would have failed here every time it was needed, reporting * "it bound the wrong port" for a server that bound exactly what it was told. * A recovery path that cannot pass is not a recovery path. */ assert.equal(up.port, usedPort, 'it bound the port WE chose, which is the capability that was missing'); assert.equal(up.probe.status, 200, 'and it really served a request'); /** * ⭐ THE SLOT ASSERTION. The child printed its own argv, so this is not * "we passed an array" — it is "the program received two arguments, and the * second one still had its space in it". */ assert.match(up.output, /argv seen: \["--port","\d+","--banner","hello there"\]/); assert.match(up.output, /hello there - listening/); // The receipt is on the record too, so a later round can read it back. assert.deepEqual(up.argv, ['node', 'server.mjs', '--port', String(usedPort), '--banner', 'hello there']); assert.equal(stopBackground(started.id).ok, true); assert.deepEqual(listBackground(), []); }); test('npm run