Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

test(setup): require an env option on every child spawn in test code

Jack Rudenko0e7e447a77eb
diff --git a/packages/cli/src/hooks-command.test.ts b/packages/cli/src/hooks-command.test.ts
index c35ee490..c00078c0 100644
--- a/packages/cli/src/hooks-command.test.ts
+++ b/packages/cli/src/hooks-command.test.ts
@@ -182,7 +182,10 @@ describe("claudish hooks init", () => {
})
);
const tsc = join(CLI_ROOT, "node_modules", ".bin", "tsc");
- const proc = Bun.spawnSync([tsc, "-p", join(target, "tsconfig.json")], { cwd: target });
+ const proc = Bun.spawnSync([tsc, "-p", join(target, "tsconfig.json")], {
+ env: { ...process.env },
+ cwd: target,
+ });
expect(proc.stdout.toString() + proc.stderr.toString()).toBe("");
expect(proc.exitCode).toBe(0);
});
@@ -208,6 +211,7 @@ describe("claudish hooks telemetry", () => {
describe("generated ambient declaration", () => {
it("src/hooks/ambient-dts.generated.ts matches public.ts", () => {
const proc = Bun.spawnSync(["bun", "run", "scripts/generate-hooks-dts.ts", "--check"], {
+ env: { ...process.env },
cwd: CLI_ROOT,
});
expect(proc.stderr.toString()).toBe("");
diff --git a/packages/cli/src/hooks-docs.test.ts b/packages/cli/src/hooks-docs.test.ts
index 7fa0e702..a070ffe8 100644
--- a/packages/cli/src/hooks-docs.test.ts
+++ b/packages/cli/src/hooks-docs.test.ts
@@ -88,7 +88,10 @@ describe("docs/advanced/hooks.md examples", () => {
})
);
const tsc = join(CLI_ROOT, "node_modules", ".bin", "tsc");
- const proc = Bun.spawnSync([tsc, "-p", join(target, "tsconfig.json")], { cwd: target });
+ const proc = Bun.spawnSync([tsc, "-p", join(target, "tsconfig.json")], {
+ env: { ...process.env },
+ cwd: target,
+ });
expect(proc.stdout.toString() + proc.stderr.toString()).toBe("");
expect(proc.exitCode).toBe(0);
diff --git a/packages/cli/src/hooks/loader.test.ts b/packages/cli/src/hooks/loader.test.ts
index e7cedb2e..3d91961d 100644
--- a/packages/cli/src/hooks/loader.test.ts
+++ b/packages/cli/src/hooks/loader.test.ts
@@ -287,6 +287,7 @@ describe("hook output stays off stdout (spawned process)", () => {
const dir = tempDir();
const mod = write(dir, "noisy.ts", NOISY);
const proc = Bun.spawn(["bun", HELPER, "interactive", mod], {
+ env: { ...process.env },
cwd: dir,
stdout: "pipe",
stderr: "pipe",
@@ -318,7 +319,7 @@ describe("hook output stays off stdout (spawned process)", () => {
const mod = write(dir, "noisy.ts", NOISY);
const proc = Bun.spawn(
["bun", "-e", `await import(${JSON.stringify(mod)}); await Bun.sleep(100);`],
- { cwd: dir, stdout: "pipe", stderr: "pipe" }
+ { env: { ...process.env }, cwd: dir, stdout: "pipe", stderr: "pipe" }
);
const stdout = await new Response(proc.stdout).text();
await proc.exited;
diff --git a/packages/cli/src/hooks/mcp-isolation.test.ts b/packages/cli/src/hooks/mcp-isolation.test.ts
index af36e9a3..c8cef071 100644
--- a/packages/cli/src/hooks/mcp-isolation.test.ts
+++ b/packages/cli/src/hooks/mcp-isolation.test.ts
@@ -186,6 +186,7 @@ describe.skipIf(!SUPPORTED)("MCP protocol stdout with hooks loaded", () => {
writeFileSync(script, `await import(${JSON.stringify(modulePath)});\n`);
const proc = Bun.spawn(["bun", script], {
+ env: { ...process.env },
cwd: layout.cwd,
stdin: "pipe",
stdout: "pipe",
diff --git a/packages/cli/src/hooks/output-capture.test.ts b/packages/cli/src/hooks/output-capture.test.ts
index fa39299f..62b7243a 100644
--- a/packages/cli/src/hooks/output-capture.test.ts
+++ b/packages/cli/src/hooks/output-capture.test.ts
@@ -76,6 +76,7 @@ describe("isolateProtocolStdout (spawned process)", () => {
const mod = join(dir, "user.ts");
writeFileSync(mod, `export default { apiVersion: 1, id: "u", on: { request: () => [] } };`);
const proc = Bun.spawn(["bun", join(HELPERS, "capture-child.ts"), "mcp-unbound", mod], {
+ env: { ...process.env },
cwd: dir,
stdout: "pipe",
stderr: "pipe",
@@ -99,6 +100,7 @@ describe("isolateProtocolStdout (spawned process)", () => {
const dir = tempDir();
const size = 4 * 1024 * 1024;
const proc = Bun.spawn(["bun", join(HELPERS, "isolate-child.ts"), String(size)], {
+ env: { ...process.env },
cwd: dir,
stdout: "pipe",
stderr: "pipe",
diff --git a/packages/cli/src/mcp-session/e2e-sessions.test.ts b/packages/cli/src/mcp-session/e2e-sessions.test.ts
index 0e28a0a0..c324b1ef 100644
--- a/packages/cli/src/mcp-session/e2e-sessions.test.ts
+++ b/packages/cli/src/mcp-session/e2e-sessions.test.ts
@@ -489,10 +489,11 @@ async function runClaudeWithMcp(
let claudeUsable = false;
if (!SKIP_LIVE_E2E) {
try {
- const proc = spawn("claude", ["--version"], { stdio: "pipe" });
+ const proc = spawn("claude", ["--version"], { env: { ...process.env }, stdio: "pipe" });
const versionOk = (await new Promise<number>((r) => proc.on("exit", (c) => r(c ?? 1)))) === 0;
if (versionOk) {
const probe = spawn("claude", ["-p", "--dangerously-skip-permissions", "--bare", "hi"], {
+ env: { ...process.env },
stdio: ["ignore", "pipe", "pipe"],
});
let out = "";
diff --git a/packages/cli/src/mcp-session/host-pid.contract.test.ts b/packages/cli/src/mcp-session/host-pid.contract.test.ts
index 2ad79d31..4292e74a 100644
--- a/packages/cli/src/mcp-session/host-pid.contract.test.ts
+++ b/packages/cli/src/mcp-session/host-pid.contract.test.ts
@@ -156,6 +156,7 @@ describe.skipIf(!MAGMUX_AVAILABLE)("REQ-3 the installed npm path for real (9a)",
beforeAll(() => {
if (!existsSync(distEntry)) {
const build = Bun.spawnSync(["bun", "run", "build"], {
+ env: { ...process.env },
cwd: PACKAGE_DIR,
stdout: "pipe",
stderr: "pipe",
diff --git a/packages/cli/src/mcp-session/session-manager.test.ts b/packages/cli/src/mcp-session/session-manager.test.ts
index 4d42e0ce..9f1aea73 100644
--- a/packages/cli/src/mcp-session/session-manager.test.ts
+++ b/packages/cli/src/mcp-session/session-manager.test.ts
@@ -981,6 +981,7 @@ interface ExitObservation {
async function runSignalChild(signal: "SIGTERM" | "SIGINT"): Promise<ExitObservation> {
const child = spawn(process.execPath, ["run", SIGNAL_CHILD_TS], {
+ env: { ...process.env },
stdio: ["ignore", "pipe", "pipe"],
shell: false,
});
diff --git a/packages/cli/src/pane/pane-registry.test.ts b/packages/cli/src/pane/pane-registry.test.ts
index 5c1251e4..4d4c50bd 100644
--- a/packages/cli/src/pane/pane-registry.test.ts
+++ b/packages/cli/src/pane/pane-registry.test.ts
@@ -114,7 +114,7 @@ async function staleSocket(path: string): Promise<void> {
"-e",
`require("node:net").createServer().listen(${JSON.stringify(path)}, () => console.log("up"));`,
],
- { stdout: "pipe", stderr: "inherit" }
+ { env: { ...process.env }, stdout: "pipe", stderr: "inherit" }
);
await child.stdout.getReader().read(); // "up": bound and listening
child.kill("SIGKILL");
@@ -123,7 +123,7 @@ async function staleSocket(path: string): Promise<void> {
}
function deadPid(): number {
- const p = Bun.spawnSync(["/usr/bin/true"]);
+ const p = Bun.spawnSync(["/usr/bin/true"], { env: { ...process.env } });
return p.pid;
}
@@ -192,7 +192,10 @@ function unixFds(pids: number[]): Map<number, Array<{ fd: string; addr: string;
const out = new Map<number, Array<{ fd: string; addr: string; peer: string }>>();
let text = "";
try {
- text = execFileSync("lsof", ["-a", "-U", "-p", pids.join(",")], { encoding: "utf8" });
+ text = execFileSync("lsof", ["-a", "-U", "-p", pids.join(",")], {
+ env: { ...process.env },
+ encoding: "utf8",
+ });
} catch (e) {
text = String((e as { stdout?: string }).stdout ?? "");
}
@@ -305,7 +308,11 @@ describe.skipIf(!MAGMUX)(`pane registry, real magmux (${MAGMUX ? "" : NO_MAGMUX_
test("decoy: the watcher never signals a pid that fails its identity check", async () => {
const t = env();
ensureSockRoot(t.sockRoot);
- const decoy = spawn("sleep", ["60"], { detached: true, stdio: "ignore" });
+ const decoy = spawn("sleep", ["60"], {
+ env: { ...process.env },
+ detached: true,
+ stdio: "ignore",
+ });
extraProcs.push(decoy);
const ctl = join(t.sockRoot, "launch-DeCoY1");
const turn = join(t.sockRoot, "launch-DeCoY2");
@@ -340,7 +347,11 @@ describe.skipIf(!MAGMUX)(`pane registry, real magmux (${MAGMUX ? "" : NO_MAGMUX_
test("sweep: a dead-owner record is identity-validated; a decoy pid is kept, never signalled", async () => {
const t = env();
ensureSockRoot(t.sockRoot);
- const decoy = spawn("sleep", ["60"], { detached: true, stdio: "ignore" });
+ const decoy = spawn("sleep", ["60"], {
+ env: { ...process.env },
+ detached: true,
+ stdio: "ignore",
+ });
extraProcs.push(decoy);
const ctl = join(t.sockRoot, "launch-SwEeP1");
mkdirSync(ctl, { mode: 0o700 });
@@ -379,7 +390,7 @@ describe.skipIf(!MAGMUX)(`pane registry, real magmux (${MAGMUX ? "" : NO_MAGMUX_
const fakeWatcher = spawn(
"/bin/sh",
["-c", "sleep 30; :", "claudish-pane-watcher", paneId, "x"],
- { stdio: "ignore" }
+ { env: { ...process.env }, stdio: "ignore" }
);
extraProcs.push(fakeWatcher);
await Bun.sleep(100);
@@ -570,7 +581,10 @@ describe.skipIf(!MAGMUX)(`pane registry, real magmux (${MAGMUX ? "" : NO_MAGMUX_
/** `ps -o <field>= -p <pid>`, or null when the pid is gone. */
function psField(pid: number, field: string): number | null {
try {
- const v = execFileSync("ps", ["-o", `${field}=`, "-p", String(pid)], { encoding: "utf8" });
+ const v = execFileSync("ps", ["-o", `${field}=`, "-p", String(pid)], {
+ env: { ...process.env },
+ encoding: "utf8",
+ });
return Number(v.trim());
} catch {
return null;
@@ -683,6 +697,7 @@ describe("records", () => {
const mode =
Bun.file(join(t.sockRoot, "panes", `${rec.paneId}.json`)).size >= 0
? execFileSync("stat", ["-f", "%Lp", join(t.sockRoot, "panes", `${rec.paneId}.json`)], {
+ env: { ...process.env },
encoding: "utf8",
}).trim()
: "";
@@ -1082,7 +1097,9 @@ describe("the pane-socket probe: ENOENT, or ECONNREFUSED with magmux proven dead
const sock = sockPathOf(root, id);
await staleSocket(sock);
// a process whose argv carries the pane's magmux needle, as a busy magmux's would
- const mag = Bun.spawn(["/bin/sh", "-c", "sleep 30; true", "sh", magmuxNeedle(id)]);
+ const mag = Bun.spawn(["/bin/sh", "-c", "sleep 30; true", "sh", magmuxNeedle(id)], {
+ env: { ...process.env },
+ });
try {
expect(await sweepOrphanPanes(root)).toEqual({ reaped: [], cleaned: [], kept: [id] });
expect(existsSync(sock)).toBe(true);
diff --git a/packages/cli/src/pane/pane-session-liveness-exit.test.ts b/packages/cli/src/pane/pane-session-liveness-exit.test.ts
index 3e6bfa43..f8b8f28b 100644
--- a/packages/cli/src/pane/pane-session-liveness-exit.test.ts
+++ b/packages/cli/src/pane/pane-session-liveness-exit.test.ts
@@ -21,7 +21,7 @@ afterEach(async () => {
/** A pid that existed and is gone: spawned, exited and reaped by this process. */
async function deadPid(): Promise<number> {
- const child = spawn("true");
+ const child = spawn("true", [], { env: { ...process.env } });
await new Promise((resolve) => child.once("exit", resolve));
return child.pid!;
}
diff --git a/packages/cli/src/pane/pane-session.integration.test.ts b/packages/cli/src/pane/pane-session.integration.test.ts
index d24e8c0a..c5b12af7 100644
--- a/packages/cli/src/pane/pane-session.integration.test.ts
+++ b/packages/cli/src/pane/pane-session.integration.test.ts
@@ -561,7 +561,10 @@ describe.skipIf(!MAGMUX)(
rmSync(pidFile, { force: true });
try {
const pgid = Number(
- execFileSync("ps", ["-o", "pgid=", "-p", String(pid)], { encoding: "utf8" })
+ execFileSync("ps", ["-o", "pgid=", "-p", String(pid)], {
+ env: { ...process.env },
+ encoding: "utf8",
+ })
);
expect(pgid).toBe(pid); // its own group: a group signal to the pane never reaches it
expect((await finish(r)).state).toBe("COMPLETED");
diff --git a/packages/cli/src/pane/process-identity.test.ts b/packages/cli/src/pane/process-identity.test.ts
index f314ddf2..2a14889f 100644
--- a/packages/cli/src/pane/process-identity.test.ts
+++ b/packages/cli/src/pane/process-identity.test.ts
@@ -224,8 +224,10 @@ function shell(script: string, opts: { ctl?: string; root?: string; rows?: PsRow
describe("the generated watcher shell agrees with the TS predicates on the same table", () => {
test("the script parses under bash's sh and under dash", () => {
- expect(spawnSync("/bin/sh", ["-n", "-c", WATCHER_SCRIPT]).status).toBe(0);
- const dash = spawnSync("dash", ["-n", "-c", WATCHER_SCRIPT]);
+ expect(
+ spawnSync("/bin/sh", ["-n", "-c", WATCHER_SCRIPT], { env: { ...process.env } }).status
+ ).toBe(0);
+ const dash = spawnSync("dash", ["-n", "-c", WATCHER_SCRIPT], { env: { ...process.env } });
if (!dash.error) expect(dash.status).toBe(0);
});
@@ -419,7 +421,7 @@ describe("the process table when ps cannot run (macOS refuses the setuid ps in a
const res = spawnSync(
"/usr/bin/sandbox-exec",
["-p", "(version 1)(allow default)", process.execPath, "--no-env-file", "-e", script],
- { encoding: "utf8", timeout: 20_000 }
+ { env: { ...process.env }, encoding: "utf8", timeout: 20_000 }
);
expect({ status: res.status, stdout: res.stdout.trim() }).toEqual({
status: 0,
diff --git a/packages/cli/src/pane/sweep-untrusted-table.test.ts b/packages/cli/src/pane/sweep-untrusted-table.test.ts
index 5f04edb2..42469d36 100644
--- a/packages/cli/src/pane/sweep-untrusted-table.test.ts
+++ b/packages/cli/src/pane/sweep-untrusted-table.test.ts
@@ -99,7 +99,7 @@ function sandboxSweep(root: string): SandboxSweep {
const stdout = execFileSync(
SANDBOX_EXEC,
["-p", SANDBOX_PROFILE, process.execPath, HELPER, root],
- { encoding: "utf8", timeout: 15_000 }
+ { env: { ...process.env }, encoding: "utf8", timeout: 15_000 }
);
return JSON.parse(stdout) as SandboxSweep;
}
diff --git a/packages/cli/src/pane/test-fixtures/fixtures-redaction.test.ts b/packages/cli/src/pane/test-fixtures/fixtures-redaction.test.ts
index af63e64e..d5736ee8 100644
--- a/packages/cli/src/pane/test-fixtures/fixtures-redaction.test.ts
+++ b/packages/cli/src/pane/test-fixtures/fixtures-redaction.test.ts
@@ -62,7 +62,11 @@ describe("pane test fixtures carry no private content", () => {
});
test("no fixture is git-ignored", () => {
- const r = spawnSync("git", ["check-ignore", ...all], { cwd: ROOT, encoding: "utf8" });
+ const r = spawnSync("git", ["check-ignore", ...all], {
+ env: { ...process.env },
+ cwd: ROOT,
+ encoding: "utf8",
+ });
expect(r.stdout.trim()).toBe("");
});
});
diff --git a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
index 1f6fbbd5..670bdce9 100755
--- a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
+++ b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
@@ -1096,7 +1096,7 @@ async function bgServer(c: string): Promise<void> {
{ template: T.bgBashResult }
);
// a real process in the pane group, so the reap can be seen ending "the shell"
- spawn("sleep", ["300"], { stdio: "ignore" }).unref();
+ spawn("sleep", ["300"], { env: { ...process.env }, stdio: "ignore" }).unref();
return answerTurn(c);
}
@@ -1106,7 +1106,11 @@ async function bgServer(c: string): Promise<void> {
* the fake never ends it on exit, so only claudish's reap can.
*/
async function bgDetached(c: string): Promise<void> {
- const child = spawn("sleep", ["300"], { stdio: "ignore", detached: true });
+ const child = spawn("sleep", ["300"], {
+ env: { ...process.env },
+ stdio: "ignore",
+ detached: true,
+ });
child.unref();
if (env.FAKE_BG_PID_FILE && child.pid) writeFileSync(env.FAKE_BG_PID_FILE, String(child.pid));
return answerTurn(c);
@@ -1354,7 +1358,10 @@ function dropTyping(ch: string): boolean {
if (scenario === "late_reset_swallow" && process.stdin.isTTY) {
process.stdin.setRawMode(false);
// A swallowed burst must not become kernel-echoed box text while cooked.
- spawnSync("stty", ["-echo"], { stdio: ["inherit", "ignore", "ignore"] });
+ spawnSync("stty", ["-echo"], {
+ env: { ...process.env },
+ stdio: ["inherit", "ignore", "ignore"],
+ });
setTimeout(() => process.stdin.setRawMode(true), 120);
}
return true;
@@ -1455,7 +1462,10 @@ function installSignals(): void {
process.on("SIGWINCH", () => {
try {
// Bun's stdout dimensions can still be stale inside SIGWINCH; query the pty.
- const size = spawnSync("stty", ["size"], { stdio: ["inherit", "pipe", "ignore"] });
+ const size = spawnSync("stty", ["size"], {
+ env: { ...process.env },
+ stdio: ["inherit", "pipe", "ignore"],
+ });
const match =
size.status === 0
? size.stdout
@@ -1526,7 +1536,7 @@ async function boot(): Promise<void> {
if (process.stdin.isTTY) process.stdin.setRawMode(true);
process.stdin.on("data", onData);
if (scenario === "orphan_grandchild") {
- spawn("sleep", ["300"], { stdio: "ignore" }).unref();
+ spawn("sleep", ["300"], { env: { ...process.env }, stdio: "ignore" }).unref();
setTimeout(() => process.exit(0), gap("ORPHAN", 3000));
}
if (scenario.startsWith("dialog_")) {
diff --git a/packages/cli/src/process-tree.test.ts b/packages/cli/src/process-tree.test.ts
index 92e42102..2d1cb4c8 100644
--- a/packages/cli/src/process-tree.test.ts
+++ b/packages/cli/src/process-tree.test.ts
@@ -15,6 +15,7 @@ const tempDirs = new Set<string>();
function spawnChild(body: string): ChildProcess {
const child = spawn(process.execPath, ["-e", body], {
+ env: { ...process.env },
detached: KILL_PROCESS_GROUP,
stdio: ["pipe", "pipe", "pipe"],
});
diff --git a/packages/cli/src/providers/onepassword-handshake-lock.test.ts b/packages/cli/src/providers/onepassword-handshake-lock.test.ts
index 60eac3c6..a769face 100644
--- a/packages/cli/src/providers/onepassword-handshake-lock.test.ts
+++ b/packages/cli/src/providers/onepassword-handshake-lock.test.ts
@@ -66,7 +66,7 @@ describe("peerHoldsHandshakeLock", () => {
});
test("returns false when the lock owner has exited", () => {
- const deadProcess = spawnSync(process.execPath, ["-e", ""]);
+ const deadProcess = spawnSync(process.execPath, ["-e", ""], { env: { ...process.env } });
expect(deadProcess.status).toBe(0);
expect(deadProcess.pid).toBeGreaterThan(0);
expect(() => process.kill(deadProcess.pid!, 0)).toThrow();
@@ -226,7 +226,7 @@ describe("withHandshakeLock", () => {
});
test("steals a fresh lock whose owner process has exited", async () => {
- const deadProcess = spawnSync(process.execPath, ["-e", ""]);
+ const deadProcess = spawnSync(process.execPath, ["-e", ""], { env: { ...process.env } });
expect(deadProcess.status).toBe(0);
expect(deadProcess.pid).toBeGreaterThan(0);
writeFileSync(lockPath, `${deadProcess.pid} ${Date.now()}`);
diff --git a/packages/cli/src/recovery-contract/recovery-process-blackbox.test.ts b/packages/cli/src/recovery-contract/recovery-process-blackbox.test.ts
index 1c1e37b2..d7109eed 100644
--- a/packages/cli/src/recovery-contract/recovery-process-blackbox.test.ts
+++ b/packages/cli/src/recovery-contract/recovery-process-blackbox.test.ts
@@ -41,7 +41,7 @@ async function runChild(
String(apiTimeoutMs),
...(abortAfterMs ? [String(abortAfterMs)] : []),
],
- { stdout: "pipe", stderr: "pipe", stdin: "ignore" }
+ { env: { ...process.env }, stdout: "pipe", stderr: "pipe", stdin: "ignore" }
);
const [stdout, stderr] = await Promise.all([
new Response(child.stdout).text(),
@@ -150,7 +150,7 @@ describe("CP-7 — the process itself lets go", () => {
const fixture = startRawFixture(port);
const child = Bun.spawn(
["bun", "run", CHILD, "exhaust", `http://127.0.0.1:${port}/v1`, "120000"],
- { stdout: "pipe", stderr: "pipe", stdin: "ignore" }
+ { env: { ...process.env }, stdout: "pipe", stderr: "pipe", stdin: "ignore" }
);
try {
const deadline = Date.now() + 30_000;
diff --git a/packages/cli/src/recovery/magmux-ui.test.ts b/packages/cli/src/recovery/magmux-ui.test.ts
index 827af664..8a21a233 100644
--- a/packages/cli/src/recovery/magmux-ui.test.ts
+++ b/packages/cli/src/recovery/magmux-ui.test.ts
@@ -378,7 +378,7 @@ async function awaitBanner(
}
function ancestorOf(pid: number): number | null {
- const r = spawnSync("ps", ["-o", "ppid=", "-p", String(pid)]);
+ const r = spawnSync("ps", ["-o", "ppid=", "-p", String(pid)], { env: { ...process.env } });
const n = Number.parseInt(String(r.stdout ?? "").trim(), 10);
return Number.isFinite(n) && n > 1 ? n : null;
}
diff --git a/packages/cli/src/team-grid.e2e.test.ts b/packages/cli/src/team-grid.e2e.test.ts
index 5ffbb781..56d37e7b 100644
--- a/packages/cli/src/team-grid.e2e.test.ts
+++ b/packages/cli/src/team-grid.e2e.test.ts
@@ -54,6 +54,7 @@ let magmuxPath = "";
async function probeClaudeUsable(): Promise<boolean> {
try {
const probe = spawn("claude", ["-p", "--dangerously-skip-permissions", "--bare", "hi"], {
+ env: { ...process.env },
stdio: ["ignore", "pipe", "pipe"],
});
let out = "";
diff --git a/packages/cli/src/test-helpers/contract-records.ts b/packages/cli/src/test-helpers/contract-records.ts
index 27f21373..d5ba7ff7 100644
--- a/packages/cli/src/test-helpers/contract-records.ts
+++ b/packages/cli/src/test-helpers/contract-records.ts
@@ -234,7 +234,7 @@ export function pidAlive(pid: number): boolean {
/** The parent pid of `pid` from the process table, or undefined. */
export function ppidOf(pid: number): number | undefined {
- const out = Bun.spawnSync(["ps", "-o", "ppid=", "-p", String(pid)]);
+ const out = Bun.spawnSync(["ps", "-o", "ppid=", "-p", String(pid)], { env: { ...process.env } });
const n = Number.parseInt(out.stdout.toString().trim(), 10);
return Number.isFinite(n) ? n : undefined;
}
diff --git a/packages/cli/src/tui/runtime/shutdown.test.ts b/packages/cli/src/tui/runtime/shutdown.test.ts
index e58d7dc4..9350fd6e 100644
--- a/packages/cli/src/tui/runtime/shutdown.test.ts
+++ b/packages/cli/src/tui/runtime/shutdown.test.ts
@@ -151,6 +151,7 @@ async function runChild(opts: ChildOpts): Promise<ChildResult> {
].join("\n");
const p = Bun.spawn(["bun", "-e", src], {
+ env: { ...process.env },
cwd: SKILL_ROOT,
stdin: "ignore",
stdout: "ignore",
diff --git a/scripts/spawn-env-scan.ts b/scripts/spawn-env-scan.ts
new file mode 100644
index 00000000..e7fc9be4
--- /dev/null
+++ b/scripts/spawn-env-scan.ts
@@ -0,0 +1,216 @@
+/**
+ * Find every child-process spawn in test code that does not pass an `env` option.
+ *
+ * Why: the bun test preload (`test-preload.ts`) deletes the claudish session-identity
+ * variables from `process.env`, but a child spawned with NO `env` option is handed the
+ * ORIGINAL environment, deletions undone. Measured: `Bun.spawn`/`Bun.spawnSync` on bun
+ * 1.3.10 and 1.4.0, and `node:child_process` on 1.3.10 (the CI pin). Such a child can
+ * append a test's doubles to a real session's records (D5), so test code must say what
+ * environment its children get — `env: { ...process.env }` at minimum.
+ *
+ * The scan parses each file with the TypeScript compiler API (no regex over source), so a
+ * comment or a string that mentions `env` cannot satisfy it.
+ *
+ * Rule: the call's options argument must be an OBJECT LITERAL with an `env` property
+ * (`env: …` or shorthand `env`). A call with no options argument is a violation. A call
+ * whose options are not an object literal (a variable, a call) or whose literal has no
+ * `env` key but spreads something (`{ ...opts }`) cannot be decided statically, and is a
+ * violation unless it is listed in the allowlist the caller passes.
+ */
+import { readdirSync, readFileSync, statSync } from "node:fs";
+import { join, relative, sep } from "node:path";
+import ts from "typescript";
+
+/** The spawn functions `node:child_process` exports. */
+const CHILD_PROCESS_FNS = new Set([
+ "spawn",
+ "spawnSync",
+ "exec",
+ "execSync",
+ "execFile",
+ "execFileSync",
+ "fork",
+]);
+
+export type SpawnFamily = "Bun" | "child_process";
+
+export interface SpawnEnvViolation {
+ /** Path relative to the scan root, `/`-separated. */
+ file: string;
+ /** 1-based. */
+ line: number;
+ /** The callee as written: `Bun.spawn`, `spawnSync`, `cp.execFileSync`. */
+ callee: string;
+ family: SpawnFamily;
+ /** "no options" | "options not an object literal" | "no env key (spread)" | "no env key". */
+ problem: string;
+ /** The trimmed source line, for the allowlist and the failure message. */
+ text: string;
+}
+
+export interface AllowlistEntry {
+ file: string;
+ /** The trimmed source line text (line numbers move; text is what the reviewer reads). */
+ text: string;
+ reason: string;
+}
+
+/** Whether a repo-relative path is test code: a test file, or anything under a test-helpers dir. */
+export function isTestCodePath(relPath: string): boolean {
+ const p = relPath.split(sep).join("/");
+ if (!/\.(ts|tsx)$/.test(p) || p.endsWith(".d.ts")) return false;
+ if (/\.test\.tsx?$/.test(p)) return true;
+ return p.split("/").includes("test-helpers");
+}
+
+/** The directories the suite runs test code from (package.json `test`). */
+export const TEST_CODE_ROOTS = [
+ "packages/cli/src",
+ "packages/cli/scripts",
+ "packages/macos-bridge/src",
+ "scripts",
+];
+
+/** Every test-code file under the roots, relative to `repoRoot`. */
+export function listTestCodeFiles(repoRoot: string, roots: string[] = TEST_CODE_ROOTS): string[] {
+ const out: string[] = [];
+ const walk = (dir: string): void => {
+ let entries: string[];
+ try {
+ entries = readdirSync(dir);
+ } catch {
+ return;
+ }
+ for (const name of entries) {
+ if (name === "node_modules" || name === "dist" || name.startsWith(".")) continue;
+ const abs = join(dir, name);
+ const st = statSync(abs);
+ if (st.isDirectory()) walk(abs);
+ else if (isTestCodePath(relative(repoRoot, abs))) out.push(relative(repoRoot, abs));
+ }
+ };
+ for (const r of roots) walk(join(repoRoot, r));
+ return out.sort();
+}
+
+/** Names bound to `node:child_process` in this file: direct imports and namespace/default. */
+function childProcessBindings(sf: ts.SourceFile): { fns: Map<string, string>; namespaces: Set<string> } {
+ const fns = new Map<string, string>(); // local name → exported name
+ const namespaces = new Set<string>();
+ for (const stmt of sf.statements) {
+ if (!ts.isImportDeclaration(stmt) || !ts.isStringLiteral(stmt.moduleSpecifier)) continue;
+ const mod = stmt.moduleSpecifier.text;
+ if (mod !== "node:child_process" && mod !== "child_process") continue;
+ const clause = stmt.importClause;
+ if (!clause) continue;
+ if (clause.name) namespaces.add(clause.name.text);
+ const bindings = clause.namedBindings;
+ if (!bindings) continue;
+ if (ts.isNamespaceImport(bindings)) namespaces.add(bindings.name.text);
+ else
+ for (const el of bindings.elements) {
+ const exported = (el.propertyName ?? el.name).text;
+ if (CHILD_PROCESS_FNS.has(exported)) fns.set(el.name.text, exported);
+ }
+ }
+ return { fns, namespaces };
+}
+
+/** Which argument carries the options, or undefined when the call has none. */
+function optionsArgument(
+ family: SpawnFamily,
+ fn: string,
+ args: readonly ts.Expression[]
+): ts.Expression | undefined {
+ if (family === "Bun") {
+ // Bun.spawn(opts) or Bun.spawn(cmd, opts).
+ if (args.length >= 1 && ts.isObjectLiteralExpression(args[0])) return args[0];
+ return args[1];
+ }
+ // child_process: the options follow the command and an optional argv array; a trailing
+ // callback (exec/execFile) is not options.
+ const rest = args.slice(1).filter((a) => !ts.isArrowFunction(a) && !ts.isFunctionExpression(a));
+ if (fn === "exec" || fn === "execSync") return rest[0];
+ if (rest.length === 0) return undefined;
+ if (ts.isArrayLiteralExpression(rest[0])) return rest[1];
+ // spawn(cmd, opts) / execFileSync(file, opts) with no argv, or a variable argv.
+ return rest.length >= 2 ? rest[1] : rest[0];
+}
+
+function hasEnvKey(obj: ts.ObjectLiteralExpression): boolean {
+ return obj.properties.some((p) => {
+ if (ts.isShorthandPropertyAssignment(p)) return p.name.text === "env";
+ if (ts.isPropertyAssignment(p)) {
+ const n = p.name;
+ return (ts.isIdentifier(n) || ts.isStringLiteral(n)) && n.text === "env";
+ }
+ return false;
+ });
+}
+
+/** Scan one file's source. `file` is only used to label the result. */
+export function scanSource(file: string, source: string): SpawnEnvViolation[] {
+ const sf = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ const { fns, namespaces } = childProcessBindings(sf);
+ const lines = source.split("\n");
+ const out: SpawnEnvViolation[] = [];
+
+ const visit = (node: ts.Node): void => {
+ if (ts.isCallExpression(node)) {
+ const callee = node.expression;
+ let family: SpawnFamily | null = null;
+ let fn = "";
+ if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression)) {
+ const obj = callee.expression.text;
+ const prop = callee.name.text;
+ if (obj === "Bun" && (prop === "spawn" || prop === "spawnSync")) {
+ family = "Bun";
+ fn = prop;
+ } else if (namespaces.has(obj) && CHILD_PROCESS_FNS.has(prop)) {
+ family = "child_process";
+ fn = prop;
+ }
+ } else if (ts.isIdentifier(callee) && fns.has(callee.text)) {
+ family = "child_process";
+ fn = fns.get(callee.text) ?? callee.text;
+ }
+ if (family) {
+ const opts = optionsArgument(family, fn, node.arguments);
+ let problem: string | null = null;
+ if (!opts) problem = "no options";
+ else if (!ts.isObjectLiteralExpression(opts)) problem = "options not an object literal";
+ else if (!hasEnvKey(opts))
+ problem = opts.properties.some(ts.isSpreadAssignment)
+ ? "no env key (spread)"
+ : "no env key";
+ if (problem) {
+ const line = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
+ out.push({
+ file: file.split(sep).join("/"),
+ line,
+ callee: callee.getText(sf),
+ family,
+ problem,
+ text: (lines[line - 1] ?? "").trim(),
+ });
+ }
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(sf);
+ return out;
+}
+
+/** Scan every test-code file under `repoRoot`, minus the allowlisted sites. */
+export function scanRepo(repoRoot: string, allowlist: AllowlistEntry[] = []): SpawnEnvViolation[] {
+ const out: SpawnEnvViolation[] = [];
+ for (const rel of listTestCodeFiles(repoRoot)) {
+ const source = readFileSync(join(repoRoot, rel), "utf-8");
+ for (const v of scanSource(rel, source)) {
+ if (allowlist.some((a) => a.file === v.file && a.text === v.text)) continue;
+ out.push(v);
+ }
+ }
+ return out;
+}
diff --git a/scripts/spawn-env.test.ts b/scripts/spawn-env.test.ts
new file mode 100644
index 00000000..d20ab2a4
--- /dev/null
+++ b/scripts/spawn-env.test.ts
@@ -0,0 +1,43 @@
+/**
+ * Every child-process spawn in test code passes an `env` option.
+ *
+ * The bun test preload deletes the claudish session-identity variables from
+ * `process.env`, and a child spawned with no `env` option gets them back (Bun.spawn on
+ * 1.3.10 and 1.4.0; node:child_process on 1.3.10, the CI pin). See spawn-env-scan.ts.
+ *
+ * A site whose options cannot be read statically (a variable, a spread-only literal)
+ * goes in ALLOWLIST with the file, the trimmed line text and the reason it is safe.
+ */
+import { describe, expect, test } from "bun:test";
+import { join } from "node:path";
+import { type AllowlistEntry, scanRepo, scanSource } from "./spawn-env-scan.ts";
+
+const REPO_ROOT = join(import.meta.dir, "..");
+
+const ALLOWLIST: AllowlistEntry[] = [];
+
+describe("spawn env rule", () => {
+ test("every Bun.spawn / node:child_process spawn in test code passes env", () => {
+ const violations = scanRepo(REPO_ROOT, ALLOWLIST).map(
+ (v) => `${v.file}:${v.line} ${v.callee} (${v.problem}): ${v.text}`
+ );
+ expect(violations).toEqual([]);
+ });
+
+ test("the scanner reports a spawn without env, with its file and line", () => {
+ const src = [
+ 'import { execFileSync as run } from "node:child_process";',
+ 'Bun.spawn(["a"], { cwd: "/" });',
+ 'Bun.spawnSync(["a"], { env: { ...process.env } });',
+ 'run("ps", ["-o", "pid="]);',
+ 'const o = { env: {} }; Bun.spawn(["a"], o);',
+ "// Bun.spawn(['in a comment'])",
+ ].join("\n");
+ const found = scanSource("x.test.ts", src).map((v) => [v.line, v.callee, v.problem]);
+ expect(found).toEqual([
+ [2, "Bun.spawn", "no env key"],
+ [4, "run", "no options"],
+ [5, "Bun.spawn", "options not an object literal"],
+ ]);
+ });
+});