Skip to content

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

fix(hooks): ignore claudish control variables set by cwd env files

Jack Rudenko7be22b4c0a07
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 5f2821df..3f58b9a4 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -91,7 +91,7 @@ jobs:
VERSION="${GITHUB_REF#refs/tags/v}"
sed -i.bak "s/VERSION = \".*\"/VERSION = \"$VERSION\"/" packages/cli/src/cli.ts
# Build from root to preserve workspace resolution
- bun build packages/cli/src/index.ts --compile --target=${{ matrix.target }} --outfile ${{ matrix.artifact }}
+ bun build packages/cli/src/index.ts --compile --no-compile-autoload-dotenv --target=${{ matrix.target }} --outfile ${{ matrix.artifact }}
- name: Ad-hoc sign binary (macOS Gatekeeper compatibility)
if: startsWith(matrix.target, 'bun-darwin')
diff --git a/ai-docs/architecture/testing.md b/ai-docs/architecture/testing.md
index c4e3c3ad..b007489f 100644
--- a/ai-docs/architecture/testing.md
+++ b/ai-docs/architecture/testing.md
@@ -221,8 +221,8 @@ MCP `team` slots and `create_session` run as interactive Claude Code in headless
magmux would test our model of it instead.
**The child is the fake, never Claude Code.** `pane/test-helpers/fake-interactive-child.ts` is
-started through `CLAUDISH_BIN` (a `*.ts` value becomes `bun run <file>`). It draws the REPL with
-lines copied from the phase-2 screen fixtures, reads raw keystrokes with the key semantics measured
+started through `CLAUDISH_BIN` (a `*.ts` value becomes `bun --no-env-file run <file>`). It draws
+the REPL with lines copied from the phase-2 screen fixtures, reads raw keystrokes with the key semantics measured
from the real REPL, and writes its transcript by TEMPLATING real records — never hand-written ones.
A scenario is chosen by `--model fake-<scenario>`, or, in the contract suites' marker mode
(`contract-fake-model`), by markers in the prompt: `@@TOOL@@`, `@@HANG@@` (accepted, never
diff --git a/package.json b/package.json
index a22bb323..e0dbbf35 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,7 @@
"packages/*"
],
"scripts": {
- "dev": "cd packages/cli && exec bun run src/index.ts",
+ "dev": "cd packages/cli && exec bun --no-env-file run src/index.ts",
"dev:mcp": "bun run --cwd packages/cli dev:mcp",
"dev:grok": "bun run --cwd packages/cli dev:grok",
"dev:grok:debug": "bun run --cwd packages/cli dev:grok:debug",
diff --git a/packages/cli/bin/claudish.cjs b/packages/cli/bin/claudish.cjs
index e804fcf5..d2eb6c15 100755
--- a/packages/cli/bin/claudish.cjs
+++ b/packages/cli/bin/claudish.cjs
@@ -36,6 +36,13 @@
const { execFileSync, execSync, spawn } = require("node:child_process");
const { resolve } = require("node:path");
+const { NO_ENV_FILE_FLAG, envFileKeys, probeFailedNotice } = require("./env-files.cjs");
+
+/**
+ * The names `childEnv` left out, handed to the child so it prints ONE line for
+ * everything ignored, after its own `.env` load (src/launch-env.ts reads and deletes it).
+ */
+const LAUNCHER_DROPPED_VAR = "CLAUDISH_LAUNCHER_DROPPED";
/**
* The shell command that asks PATH where bun is.
@@ -90,6 +97,44 @@ function findBun(platform = process.platform, env = process.env) {
return null;
}
+/**
+ * The arguments Bun is started with. `--no-env-file` comes first: without it Bun
+ * loads `.env`, `.env.local`, `.env.<NODE_ENV>` and `.env.<NODE_ENV>.local` from the
+ * caller's working directory into the environment before claudish runs, and that
+ * directory is often a checkout nobody has reviewed. claudish reads the provider API
+ * keys in `.env` itself, and nothing else (src/dotenv-allowlist.ts).
+ */
+function bunArgv(entry, argv) {
+ return [NO_ENV_FILE_FLAG, entry, ...argv];
+}
+
+/**
+ * The environment the Bun child is given, or null when it cannot be built safely.
+ *
+ * Node never loads env files, so under Node this is the launcher's own environment.
+ * Bun does, unless it was started with `--no-env-file`: `bun <path>/claudish.cjs`
+ * puts the checkout's env files into THIS process, and the child's `--no-env-file`
+ * would then vouch for them as the real environment. So under such a Bun every name
+ * those files set is left out (env-files.cjs asks Bun which). A real value sharing a
+ * name with a file's is left out too, the safe direction; the child still reads the
+ * provider API keys and model settings in `.env`. When Bun cannot answer, there is no child.
+ */
+function childEnv({ isBun, execArgv, bunPath, cwd, env }) {
+ const out = { ...env };
+ delete out[LAUNCHER_DROPPED_VAR];
+ if (!isBun || execArgv.includes(NO_ENV_FILE_FLAG)) return { env: out, dropped: [] };
+ const fileKeys = envFileKeys({ bunPath, execArgv, cwd, env });
+ if (fileKeys === null) return null;
+ const dropped = [];
+ for (const key of fileKeys) {
+ if (out[key] === undefined) continue;
+ delete out[key];
+ dropped.push(key);
+ }
+ if (dropped.length > 0) out[LAUNCHER_DROPPED_VAR] = dropped.join(",");
+ return { env: out, dropped };
+}
+
function main() {
const bun = findBun();
if (!bun) {
@@ -107,9 +152,21 @@ Learn more: https://bun.sh`);
const entry = resolve(__dirname, "..", "dist", "index.js");
+ const base = childEnv({
+ isBun: process.versions.bun !== undefined,
+ execArgv: process.execArgv,
+ bunPath: process.execPath,
+ cwd: process.cwd(),
+ env: process.env,
+ });
+ if (base === null) {
+ console.error(probeFailedNotice());
+ process.exit(1);
+ }
+
let child;
try {
- child = spawn(bun, [entry, ...process.argv.slice(2)], {
+ child = spawn(bun, bunArgv(entry, process.argv.slice(2)), {
stdio: "inherit",
// The pid pair tells the Bun child who launched it: this launcher, and the
// launcher's own parent (Claude Code, for an MCP server). The child
@@ -117,7 +174,7 @@ Learn more: https://bun.sh`);
// (channel/parent-session.ts `hostPidFrom`), so a value leaked into a
// nested claudish is inert.
env: {
- ...process.env,
+ ...base.env,
CLAUDISH_LAUNCHER_PID: String(process.pid),
CLAUDISH_LAUNCHER_PPID: String(process.ppid),
},
@@ -180,5 +237,5 @@ Learn more: https://bun.sh`);
if (require.main === module) {
main();
} else {
- module.exports = { findBun, lookupCommand, bunCandidates, installHint };
+ module.exports = { findBun, lookupCommand, bunCandidates, installHint, bunArgv, childEnv };
}
diff --git a/packages/cli/src/config-override.ts b/packages/cli/src/config-override.ts
index 2ffa6fa5..8dc8169c 100644
--- a/packages/cli/src/config-override.ts
+++ b/packages/cli/src/config-override.ts
@@ -133,6 +133,8 @@ export function planConfigOverride(
}
path = flag.value;
} else {
+ // Trusted as the real environment's: no env file in the working directory can
+ // set a control variable (launch-env.ts).
path = env.CLAUDISH_CONFIG || undefined;
}
if (!path) return { kind: "none" };
diff --git a/packages/cli/src/cwd-env-control.test.ts b/packages/cli/src/cwd-env-control.test.ts
new file mode 100644
index 00000000..54428d25
--- /dev/null
+++ b/packages/cli/src/cwd-env-control.test.ts
@@ -0,0 +1,181 @@
+/**
+ * A repository cannot set claudish's control variables: nothing in a checkout's env
+ * files may choose the config file (and so which hook modules are imported) or mark
+ * the process as a pane child.
+ *
+ * Each row spawns the real CLI entry in a scratch checkout with a throwaway HOME,
+ * twice: with the exact argv the npm launcher gives Bun (`bunArgv` in
+ * `bin/claudish.cjs`), and as a bare `bun <entry>`, where Bun loads the cwd env files
+ * before any claudish code runs. The checkout's `evil.ts` writes a marker file when
+ * imported, so "the module was never imported" is observed, not inferred.
+ *
+ * The positive controls show each check can fail: the same config named by the real
+ * environment IS imported, and a real pane marker DOES refuse `-p`.
+ */
+
+import { afterAll, describe, expect, it } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const ENTRY = join(import.meta.dir, "index.ts");
+const BUN = process.execPath;
+const require = createRequire(import.meta.url);
+const { bunArgv } = require("../bin/claudish.cjs") as {
+ bunArgv: (entry: string, argv: string[]) => string[];
+};
+
+const root = realpathSync(mkdtempSync(join(tmpdir(), "claudish-cwd-env-")));
+const home = join(root, "home");
+mkdirSync(home);
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+const GLOBAL_CONFIG = join(home, ".claudish", "config.json");
+
+type Launch = (args: string[]) => string[];
+const LAUNCHES: [string, Launch][] = [
+ ["the npm launcher's argv", (args) => [BUN, ...bunArgv(ENTRY, args)]],
+ ["a bare `bun <entry>`", (args) => [BUN, ENTRY, ...args]],
+];
+
+/** A checkout holding `evil.json`, whose one hook module `evil.ts` marks its import. */
+function hostileCheckout(files: Record<string, string>) {
+ const repo = mkdtempSync(join(root, "repo-"));
+ const marker = join(repo, "IMPORTED");
+ writeFileSync(
+ join(repo, "evil.ts"),
+ `import { writeFileSync } from "node:fs";
+writeFileSync(${JSON.stringify(marker)}, "imported");
+export default { apiVersion: 1, id: "evil", on: { responseEnd: () => [] } };`
+ );
+ writeFileSync(join(repo, "evil.json"), JSON.stringify({ hooks: { modules: ["./evil.ts"] } }));
+ for (const [name, text] of Object.entries(files)) writeFileSync(join(repo, name), text);
+ return { repo, marker };
+}
+
+const BASE_ENV = {
+ PATH: process.env.PATH ?? "",
+ HOME: home,
+ CLAUDISH_DISABLE_KEYCHAIN: "1",
+ CLAUDISH_DISABLE_OP: "1",
+ NO_COLOR: "1",
+};
+
+function run(argv: string[], cwd: string, env: Record<string, string> = {}) {
+ const proc = Bun.spawnSync(argv, {
+ cwd,
+ env: { ...BASE_ENV, ...env },
+ stdin: "ignore",
+ });
+ return { code: proc.exitCode, stdout: proc.stdout.toString(), stderr: proc.stderr.toString() };
+}
+
+function listHooks(launch: Launch, cwd: string, env: Record<string, string> = {}) {
+ const r = run(launch(["hooks", "list", "--json"]), cwd, env);
+ if (r.code !== 0) throw new Error(`hooks list exited ${r.code}: ${r.stderr}`);
+ return { ...r, out: JSON.parse(r.stdout) as { configFile: string; hooks: { id: string }[] } };
+}
+
+/** Env files that try to choose the config file, directly or through a pane snapshot. */
+const CONFIG_VECTORS: [string, Record<string, string>, Record<string, string>][] = [
+ [".env names CLAUDISH_CONFIG", { ".env": "CLAUDISH_CONFIG=./evil.json\n" }, {}],
+ [
+ ".env.development.local names CLAUDISH_CONFIG",
+ { ".env.development.local": "CLAUDISH_CONFIG=./evil.json\n" },
+ {},
+ ],
+ [
+ ".env.production.local names CLAUDISH_CONFIG under NODE_ENV=production",
+ { ".env.production.local": "CLAUDISH_CONFIG=./evil.json\n" },
+ { NODE_ENV: "production" },
+ ],
+ [
+ ".env.test.local names CLAUDISH_CONFIG under NODE_ENV=test",
+ { ".env.test.local": "CLAUDISH_CONFIG=./evil.json\n" },
+ { NODE_ENV: "test" },
+ ],
+ [
+ "a quoted value Bun and dotenv parse differently",
+ { ".env": 'CLAUDISH_CONFIG="./evil.json"x\n' },
+ {},
+ ],
+ [
+ "pane markers whose snapshot carries CLAUDISH_CONFIG",
+ {
+ ".env":
+ 'CLAUDISH_PANE_CHILD=1\nCLAUDISH_PANE_ENV={"CLAUDISH_CONFIG":"./evil.json","PATH":"$PATH","HOME":"$HOME"}\n',
+ },
+ {},
+ ],
+];
+
+describe("a checkout's env files cannot choose the config hooks load from", () => {
+ for (const [launchName, launch] of LAUNCHES) {
+ describe(launchName, () => {
+ it.each(CONFIG_VECTORS)("%s: the module is never imported", (_name, files, env) => {
+ const { repo, marker } = hostileCheckout(files);
+ const r = listHooks(launch, repo, env);
+ expect(existsSync(marker)).toBe(false);
+ expect(r.out.configFile).toBe(GLOBAL_CONFIG);
+ expect(r.out.hooks.map((h) => h.id)).not.toContain("hook:evil/evil");
+ });
+ });
+ }
+
+ for (const [launchName, launch] of LAUNCHES) {
+ it(`${launchName}: one stderr line names the variable it ignored`, () => {
+ const { repo } = hostileCheckout({ ".env": "CLAUDISH_CONFIG=./evil.json\n" });
+ const r = listHooks(launch, repo);
+ expect(r.stderr.match(/ignoring CLAUDISH_CONFIG/g)?.length).toBe(1);
+ });
+ }
+
+ it("control: the same config named by the real environment is imported", () => {
+ const { repo, marker } = hostileCheckout({});
+ const launch = LAUNCHES[0][1];
+ const r = listHooks(launch, repo, { CLAUDISH_CONFIG: join(repo, "evil.json") });
+ expect(existsSync(marker)).toBe(true);
+ expect(r.out.hooks.map((h) => h.id)).toContain("hook:evil/evil");
+ });
+});
+
+describe("a checkout's env files cannot mark the process as a pane child", () => {
+ // `-p` is refused with exit 64 only in a pane child; anywhere else this run fails
+ // fast with exit 1 on the missing OpenRouter key.
+ const PRINT = ["-p", "hi", "--model", "openrouter@x/y"];
+
+ for (const [launchName, launch] of LAUNCHES) {
+ it(`${launchName}: CLAUDISH_PANE_CHILD=1 in .env does not refuse -p`, () => {
+ const { repo } = hostileCheckout({ ".env": "CLAUDISH_PANE_CHILD=1\n" });
+ const r = run(launch(PRINT), repo);
+ expect(r.stderr).not.toContain("pane child refused");
+ expect(r.code).toBe(1);
+ });
+ }
+
+ it("control: the marker in the real environment refuses -p with exit 64", () => {
+ const { repo } = hostileCheckout({});
+ const r = run(LAUNCHES[0][1](PRINT), repo, { CLAUDISH_PANE_CHILD: "1" });
+ expect(r.stderr).toContain("pane child refused");
+ expect(r.code).toBe(64);
+ });
+});
+
+describe("a pane child keeps the config its parent passed", () => {
+ it("the snapshot's CLAUDISH_CONFIG wins over an expanded .env assignment in the checkout", () => {
+ const { repo, marker } = hostileCheckout({ ".env": "CLAUDISH_CONFIG=$PWD/evil.json\n" });
+ const trusted = join(repo, "..", `trusted-${Date.now()}.json`);
+ writeFileSync(trusted, JSON.stringify({}));
+ // What buildPaneEnv hands a child of a parent started with `--config <trusted>`.
+ const snapshot = { ...BASE_ENV, CLAUDISH_CONFIG: trusted, CLAUDISH_PANE_CHILD: "1" };
+ const r = listHooks(LAUNCHES[0][1], repo, {
+ CLAUDISH_PANE_CHILD: "1",
+ CLAUDISH_PANE_CWD: repo,
+ CLAUDISH_PANE_ENV: JSON.stringify(snapshot),
+ });
+ expect(r.stderr).not.toContain("ignoring CLAUDISH_CONFIG");
+ expect(r.out.configFile).toBe(trusted);
+ expect(existsSync(marker)).toBe(false);
+ });
+});
diff --git a/packages/cli/src/default-provider.test.ts b/packages/cli/src/default-provider.test.ts
index 51dc495c..2bd2c8a7 100644
--- a/packages/cli/src/default-provider.test.ts
+++ b/packages/cli/src/default-provider.test.ts
@@ -210,7 +210,7 @@ function sandboxedProbe(flagBeforeProbe: boolean, provider: string): ProbeJson {
};
try {
- const result = Bun.spawnSync([process.execPath, ...args], {
+ const result = Bun.spawnSync([process.execPath, "--no-env-file", ...args], {
cwd: join(import.meta.dir, "../../.."),
env,
stdout: "pipe",
diff --git a/packages/cli/src/hooks/mcp-isolation.test.ts b/packages/cli/src/hooks/mcp-isolation.test.ts
index e91cacc3..af36e9a3 100644
--- a/packages/cli/src/hooks/mcp-isolation.test.ts
+++ b/packages/cli/src/hooks/mcp-isolation.test.ts
@@ -78,7 +78,7 @@ describe.skipIf(!SUPPORTED)("MCP protocol stdout with hooks loaded", () => {
const configPath = join(layout.root, "config.json");
writeFileSync(configPath, JSON.stringify({ hooks: { modules: [modulePath] } }));
- const proc = Bun.spawn(["bun", ENTRY, "--mcp"], {
+ const proc = Bun.spawn(["bun", "--no-env-file", ENTRY, "--mcp"], {
cwd: layout.cwd,
env: serverEnv(layout, { CLAUDISH_CONFIG: configPath, CLAUDISH_DEBUG: "1" }),
stdin: "pipe",
diff --git a/packages/cli/src/launch-env.test.ts b/packages/cli/src/launch-env.test.ts
new file mode 100644
index 00000000..42d96c6d
--- /dev/null
+++ b/packages/cli/src/launch-env.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { join } from "node:path";
+import { loadDotenvText } from "./dotenv-allowlist.js";
+import {
+ CONTROL_VARS,
+ NO_ENV_FILE_FLAG,
+ bunLoadedCwdEnvFiles,
+ dropControlVars,
+ isCompiledEntry,
+} from "./launch-env.js";
+
+const CLI_ROOT = join(import.meta.dir, "..");
+const REPO_ROOT = join(CLI_ROOT, "..", "..");
+
+describe("bunLoadedCwdEnvFiles", () => {
+ test("only --no-env-file on Bun's own argv turns the autoload off", () => {
+ expect(bunLoadedCwdEnvFiles([], "/x/dist/index.js")).toBe(true);
+ expect(bunLoadedCwdEnvFiles([NO_ENV_FILE_FLAG], "/x/dist/index.js")).toBe(false);
+ // `--env-file=<x>` loads <x>, which can be a file in the checkout.
+ expect(bunLoadedCwdEnvFiles(["--env-file=.env.local"], "/x/dist/index.js")).toBe(true);
+ });
+
+ test("a compiled binary, built with --no-compile-autoload-dotenv, loads none", () => {
+ expect(bunLoadedCwdEnvFiles([], "/$bunfs/root/claudish")).toBe(false);
+ expect(bunLoadedCwdEnvFiles([], "B:\\~BUN\\root\\claudish.exe")).toBe(false);
+ });
+
+ test("isCompiledEntry recognises only Bun's embedded file system", () => {
+ expect(isCompiledEntry("/$bunfs/root/claudish")).toBe(true);
+ expect(isCompiledEntry("B:/~BUN/root/claudish.exe")).toBe(true);
+ expect(isCompiledEntry("/usr/lib/node_modules/claudish/dist/index.js")).toBe(false);
+ expect(isCompiledEntry("/home/u/$bunfs/index.js")).toBe(false);
+ });
+});
+
+describe("dropControlVars", () => {
+ test("deletes every control variable present and keeps everything else", () => {
+ const env: Record<string, string | undefined> = {
+ CLAUDISH_CONFIG: "./evil.json",
+ CLAUDISH_PANE_CHILD: "1",
+ CLAUDISH_HOOK_INBOX: "/x",
+ CLAUDISH_MODEL: "grok-4",
+ OPENROUTER_API_KEY: "k",
+ };
+ expect(dropControlVars(env)).toEqual([
+ "CLAUDISH_CONFIG",
+ "CLAUDISH_PANE_CHILD",
+ "CLAUDISH_HOOK_INBOX",
+ ]);
+ expect(env).toEqual({ CLAUDISH_MODEL: "grok-4", OPENROUTER_API_KEY: "k" });
+ });
+
+ test("the control set names the config, the pane markers, the hook inbox and the child binary", () => {
+ expect([...CONTROL_VARS].sort()).toEqual([
+ "CLAUDISH_BIN",
+ "CLAUDISH_CONFIG",
+ "CLAUDISH_HOOK_INBOX",
+ "CLAUDISH_HOOK_SESSION",
+ "CLAUDISH_PANE_CHILD",
+ "CLAUDISH_PANE_CWD",
+ "CLAUDISH_PANE_ENV",
+ ]);
+ });
+});
+
+describe("loadDotenvText", () => {
+ test("sets ordinary keys, never a control variable, and never overwrites", () => {
+ const env: Record<string, string | undefined> = { KEEP: "shell" };
+ const refused = loadDotenvText(
+ env,
+ [
+ "OPENROUTER_API_KEY=k",
+ "KEEP=file",
+ "CLAUDISH_CONFIG=./evil.json",
+ "CLAUDISH_PANE_CHILD=1",
+ 'CLAUDISH_PANE_ENV={"CLAUDISH_CONFIG":"./evil.json"}',
+ "CLAUDISH_HOOK_INBOX=/tmp/x",
+ "CLAUDISH_BIN=./evil.ts",
+ ].join("\n")
+ );
+ expect(env).toEqual({ KEEP: "shell", OPENROUTER_API_KEY: "k" });
+ expect(refused).toEqual([
+ "CLAUDISH_CONFIG",
+ "CLAUDISH_PANE_CHILD",
+ "CLAUDISH_PANE_ENV",
+ "CLAUDISH_HOOK_INBOX",
+ "CLAUDISH_BIN",
+ ]);
+ });
+
+ test("a control variable already in the real environment is kept and not reported", () => {
+ const env: Record<string, string | undefined> = { CLAUDISH_CONFIG: "/mine.json" };
+ expect(loadDotenvText(env, "CLAUDISH_CONFIG=./evil.json\n")).toEqual([]);
+ expect(env.CLAUDISH_CONFIG).toBe("/mine.json");
+ });
+});
+
+describe("every claudish launch path turns Bun's env-file autoload off", () => {
+ test("the npm launcher starts Bun with --no-env-file before the entry", () => {
+ const require = createRequire(import.meta.url);
+ const { bunArgv } = require("../bin/claudish.cjs") as {
+ bunArgv: (entry: string, argv: string[]) => string[];
+ };
+ expect(bunArgv("/pkg/dist/index.js", ["--mcp"])).toEqual([
+ NO_ENV_FILE_FLAG,
+ "/pkg/dist/index.js",
+ "--mcp",
+ ]);
+ });
+
+ test("the entry's shebang (kept in dist/index.js) passes --no-env-file", () => {
+ const first = readFileSync(join(import.meta.dir, "index.ts"), "utf-8").split("\n")[0];
+ expect(first).toBe(`#!/usr/bin/env -S bun ${NO_ENV_FILE_FLAG}`);
+ });
+
+ test("both compiled-binary builds pass --no-compile-autoload-dotenv", () => {
+ const pkg = JSON.parse(readFileSync(join(CLI_ROOT, "package.json"), "utf-8"));
+ expect(pkg.scripts["build:binary"]).toContain("--compile --no-compile-autoload-dotenv");
+ const release = readFileSync(join(REPO_ROOT, ".github", "workflows", "release.yml"), "utf-8");
+ const compileLines = release.split("\n").filter((l) => l.includes("--compile"));
+ expect(compileLines.length).toBeGreaterThan(0);
+ for (const line of compileLines) expect(line).toContain("--no-compile-autoload-dotenv");
+ });
+});
diff --git a/packages/cli/src/launch-env.ts b/packages/cli/src/launch-env.ts
new file mode 100644
index 00000000..09acdc4e
--- /dev/null
+++ b/packages/cli/src/launch-env.ts
@@ -0,0 +1,160 @@
+/**
+ * Which environment values may steer claudish itself.
+ *
+ * A handful of variables decide what code claudish runs or what role the process
+ * plays: the config file (it names the hook modules claudish imports, the endpoints
+ * keys are sent to, and the 1Password sources), the pane-child markers and the
+ * snapshot that re-creates the parent's environment, the hook inbox, and the claudish
+ * binary a child is spawned from. These are the CONTROL VARIABLES. Their one rule:
+ *
+ * a control variable comes from the real environment of the process — the user's
+ * shell, an MCP host's `env`, or the parent claudish that spawned it — and NEVER
+ * from an env file in the working directory.
+ *
+ * The working directory is often a checkout the user has not reviewed, and Claude
+ * Code starts the claudish MCP server there before its folder-trust dialog. Two
+ * loaders read env files from it, and each is closed at its source:
+ *
+ * - Bun loads `.env`, `.env.<NODE_ENV>`, `.env.<NODE_ENV>.local` and `.env.local`
+ * before any claudish code runs, merged into `process.env` with nothing marking
+ * which values came from a file. Every launch path therefore turns that off: the
+ * npm launcher and the `dist/index.js` shebang pass `--no-env-file`, the compiled
+ * binary is built with `--no-compile-autoload-dotenv`, and a claudish child under
+ * `CLAUDISH_BIN=<file>.ts` runs `bun --no-env-file run <file>`. A launch that left it
+ * on (a hand-typed `bun <entry>`) is detected by `bunLoadedCwdEnvFiles`. Then every
+ * control variable is dropped, since none of them can be told apart from a file's,
+ * and so is every other name Bun's env files set in this directory
+ * (`bin/env-files.cjs` asks Bun which). The npm launcher does the same for itself
+ * when Bun, not Node, runs it.
+ * - claudish's own `.env` load sets provider API keys and model settings only
+ * (`dotenv-allowlist.ts`).
+ *
+ * Matching Bun's file list or its parser is NOT the rule: both differ from dotenv's
+ * and change between Bun releases, and an earlier version of this check that compared
+ * values was bypassed by `.env.development.local`, by a quoting difference, and by a
+ * pane snapshot carrying the variable. Bun itself is asked for the names.
+ *
+ * Imports nothing from claudish, so `launch-guard.ts` can run it before any module
+ * that reads the environment while it is being evaluated.
+ */
+
+import { createRequire } from "node:module";
+
+/** The control variables. Spelled out rather than imported, to keep this module a leaf. */
+export const CONTROL_VARS = [
+ "CLAUDISH_CONFIG",
+ "CLAUDISH_PANE_CHILD",
+ "CLAUDISH_PANE_ENV",
+ "CLAUDISH_PANE_CWD",
+ "CLAUDISH_HOOK_INBOX",
+ "CLAUDISH_HOOK_SESSION",
+ "CLAUDISH_BIN",
+] as const;
+
+/** Bun's flag that turns off its env-file autoload. */
+export const NO_ENV_FILE_FLAG = "--no-env-file";
+
+type Env = Record<string, string | undefined>;
+
+/**
+ * True when `entryPath` is inside a `bun build --compile` executable: Bun serves the
+ * embedded module graph from `/$bunfs/` (POSIX) or `B:\~BUN\` (Windows). The drive
+ * is always `B:`; any other drive is a real directory someone could name `~BUN`.
+ */
+export function isCompiledEntry(entryPath: string): boolean {
+ return entryPath.startsWith("/$bunfs/") || /^B:[\\/]~BUN[\\/]/.test(entryPath);
+}
+
+/**
+ * True when Bun loaded the working directory's env files before claudish ran.
+ *
+ * Off only with `--no-env-file` on Bun's own argv (`process.execArgv`; `--env-file=<x>`
+ * is not enough, since `<x>` can be a file in the checkout), or in a compiled binary,
+ * which `build:binary` and `release.yml` build with `--no-compile-autoload-dotenv`
+ * (pinned by `launch-env.test.ts`). A compiled binary reports an empty `execArgv`, so
+ * it is recognised by its entry path instead.
+ */
+export function bunLoadedCwdEnvFiles(execArgv: readonly string[], entryPath: string): boolean {
+ if (isCompiledEntry(entryPath)) return false;
+ return !execArgv.includes(NO_ENV_FILE_FLAG);
+}
+
+/** Delete every control variable present in `env`; returns the names deleted. */
+export function dropControlVars(env: Env): string[] {
+ return dropNames(env, CONTROL_VARS);
+}
+
+/** Delete each of `names` present in `env`; returns the names deleted, in order. */
+function dropNames(env: Env, names: readonly string[]): string[] {
+ const dropped: string[] = [];
+ for (const key of names) {
+ if (env[key] === undefined) continue;
+ delete env[key];
+ dropped.push(key);
+ }
+ return dropped;
+}
+
+/**
+ * Set by the npm launcher (`bin/claudish.cjs`) when Bun ran it with the env-file
+ * autoload on: the comma-separated names it left out of this process's environment.
+ * It only feeds the stderr notice, and it is read once and deleted, so no child
+ * inherits it.
+ */
+export const LAUNCHER_DROPPED_VAR = "CLAUDISH_LAUNCHER_DROPPED";
+
+/** Read and delete `LAUNCHER_DROPPED_VAR`; returns the names it carried. */
+export function takeLauncherDropped(env: Env): string[] {
+ const raw = env[LAUNCHER_DROPPED_VAR];
+ delete env[LAUNCHER_DROPPED_VAR];
+ return raw ? raw.split(",").filter((name) => name.length > 0) : [];
+}
+
+/** `bin/env-files.cjs`: one implementation, shared with the npm launcher. */
+interface EnvFilesModule {
+ envFileKeys(opts: {
+ bunPath: string;
+ execArgv: readonly string[];
+ cwd: string;
+ env: Env;
+ }): string[] | null;
+ droppedByAutoloadNotice(names: readonly string[]): string;
+ probeFailedNotice(): string;
+}
+
+/**
+ * Loaded only on the unsupported launch. The path holds from `src/` and from the
+ * bundled `dist/`, both one level below the package root that ships `bin/`.
+ */
+function envFilesModule(): EnvFilesModule {
+ return createRequire(import.meta.url)("../bin/env-files.cjs") as EnvFilesModule;
+}
+
+/** What `dropEnvFileValues` did: the names dropped, or that Bun could not answer. */
+export type EnvFileDrop = { ok: true; dropped: string[] } | { ok: false };
+
+/**
+ * For a Bun that loaded the working directory's env files: delete every control
+ * variable, and every other name those files set, from `env`. A real value that shares
+ * a name with a file's is lost too, which is the safe direction.
+ */
+export function dropEnvFileValues(
+ env: Env,
+ probe: { bunPath: string; execArgv: readonly string[]; cwd: string }
+): EnvFileDrop {
+ const fileKeys = envFilesModule().envFileKeys({ ...probe, env });
+ if (fileKeys === null) return { ok: false };
+ const dropped = dropControlVars(env);
+ for (const key of dropNames(env, fileKeys)) dropped.push(key);
+ return { ok: true, dropped };
+}
+
+/** The one stderr line for names dropped because Bun's env-file autoload was on. */
+export function droppedByAutoloadNotice(names: readonly string[]): string {
+ return envFilesModule().droppedByAutoloadNotice(names);
+}
+
+/** The one stderr line when Bun could not say which names its env files set. */
+export function probeFailedNotice(): string {
+ return envFilesModule().probeFailedNotice();
+}
diff --git a/packages/cli/src/launch-guard.ts b/packages/cli/src/launch-guard.ts
new file mode 100644
index 00000000..1bf1457f
--- /dev/null
+++ b/packages/cli/src/launch-guard.ts
@@ -0,0 +1,29 @@
+/**
+ * The CLI entry's FIRST import: before the pane child applies its parent's
+ * environment (`pane/child-env.ts`) and before any module reads the environment while
+ * it is being evaluated, drop every control variable, and every other name the working
+ * directory's env files set, when Bun loaded those files for this process. See
+ * `launch-env.ts` for the rule. When Bun cannot say which names its files set, claudish
+ * does not start.
+ *
+ * A side effect at import time is the point of this module; only `index.ts` imports it.
+ * The stderr line naming what was dropped is printed by `index.ts`, after its own
+ * `.env` load, so a provider key that load sets again is not reported as ignored.
+ */
+
+import { bunLoadedCwdEnvFiles, dropEnvFileValues, probeFailedNotice } from "./launch-env.js";
+
+function dropAtLaunch(): string[] {
+ if (!bunLoadedCwdEnvFiles(process.execArgv, import.meta.path)) return [];
+ const result = dropEnvFileValues(process.env, {
+ bunPath: process.execPath,
+ execArgv: process.execArgv,
+ cwd: process.cwd(),
+ });
+ if (result.ok) return result.dropped;
+ process.stderr.write(`${probeFailedNotice()}\n`);
+ process.exit(1);
+}
+
+/** The names dropped here; `index.ts` reports them and keeps its `.env` notice off them. */
+export const droppedAtLaunch: readonly string[] = dropAtLaunch();
diff --git a/packages/cli/src/madbench/session.ts b/packages/cli/src/madbench/session.ts
index fbe6aa84..21e1c793 100644
--- a/packages/cli/src/madbench/session.ts
+++ b/packages/cli/src/madbench/session.ts
@@ -71,7 +71,7 @@ export function writeMcpConfig(opts: SessionOptions): string {
mcpServers: {
claudish: {
command: "/usr/bin/env",
- args: ["-i", ...serverEnv, "bun", "run", opts.serverEntry, "--mcp"],
+ args: ["-i", ...serverEnv, "bun", "--no-env-file", "run", opts.serverEntry, "--mcp"],
},
},
};
diff --git a/packages/cli/src/mcp-blackbox/tool-surface.blackbox.test.ts b/packages/cli/src/mcp-blackbox/tool-surface.blackbox.test.ts
index 0e1da051..3fdba8f1 100644
--- a/packages/cli/src/mcp-blackbox/tool-surface.blackbox.test.ts
+++ b/packages/cli/src/mcp-blackbox/tool-surface.blackbox.test.ts
@@ -108,7 +108,7 @@ function contractError(r: ToolResult, code: string): void {
* an unsupported MCP lifecycle rather than the contract's initialization.
*/
async function initializeOnce(env: Record<string, string>): Promise<Json> {
- const child = Bun.spawn([process.execPath, SERVER_ENTRY, "--mcp"], {
+ const child = Bun.spawn([process.execPath, "--no-env-file", SERVER_ENTRY, "--mcp"], {
env,
cwd: layout.cwd,
stdin: "pipe",
@@ -437,7 +437,7 @@ describe("nested MCP server over stdio", () => {
async function connect(mode: string | undefined, nested = true): Promise<Client> {
transport = new StdioClientTransport({
command: process.execPath,
- args: ["run", SERVER_ENTRY, "--mcp"],
+ args: ["--no-env-file", "run", SERVER_ENTRY, "--mcp"],
cwd: layout.cwd,
env: serverEnv(layout, {
CLAUDISH_PANE_CHILD: nested ? "1" : undefined,
diff --git a/packages/cli/src/mcp-e2e/jsonrpc-client.ts b/packages/cli/src/mcp-e2e/jsonrpc-client.ts
index 8867afad..ee9f746f 100644
--- a/packages/cli/src/mcp-e2e/jsonrpc-client.ts
+++ b/packages/cli/src/mcp-e2e/jsonrpc-client.ts
@@ -109,7 +109,7 @@ export async function driveServer(opts: DriveOptions): Promise<DriveResult> {
// scenario loses every result that came before it.
let proc: ReturnType<typeof spawn>;
try {
- proc = spawn("bun", ["run", opts.serverEntry, "--mcp"], {
+ proc = spawn("bun", ["--no-env-file", "run", opts.serverEntry, "--mcp"], {
stdio: ["pipe", "pipe", "pipe"],
cwd: opts.cwd,
env: opts.env,
diff --git a/packages/cli/src/mcp-session/e2e-sessions.test.ts b/packages/cli/src/mcp-session/e2e-sessions.test.ts
index a299fb10..0e28a0a0 100644
--- a/packages/cli/src/mcp-session/e2e-sessions.test.ts
+++ b/packages/cli/src/mcp-session/e2e-sessions.test.ts
@@ -49,7 +49,7 @@ describe("Group 1: MCP Protocol — session tools", () => {
beforeAll(async () => {
transport = new StdioClientTransport({
command: "bun",
- args: ["run", SERVER_ENTRY, "--mcp"],
+ args: ["--no-env-file", "run", SERVER_ENTRY, "--mcp"],
env: Object.fromEntries(
Object.entries({
...process.env,
@@ -234,7 +234,7 @@ describe("Group 1b: MCP Protocol — session-only tools", () => {
beforeAll(async () => {
transport = new StdioClientTransport({
command: "bun",
- args: ["run", SERVER_ENTRY, "--mcp"],
+ args: ["--no-env-file", "run", SERVER_ENTRY, "--mcp"],
env: Object.fromEntries(
Object.entries({
...process.env,
@@ -278,7 +278,7 @@ describe("Group 1b: MCP Protocol — low-level-only tools", () => {
beforeAll(async () => {
transport = new StdioClientTransport({
command: "bun",
- args: ["run", SERVER_ENTRY, "--mcp"],
+ args: ["--no-env-file", "run", SERVER_ENTRY, "--mcp"],
env: Object.fromEntries(
Object.entries({
...process.env,
@@ -336,7 +336,7 @@ for (const [toolMode, expected] of [
beforeAll(async () => {
transport = new StdioClientTransport({
command: "bun",
- args: ["run", SERVER_ENTRY, "--mcp"],
+ args: ["--no-env-file", "run", SERVER_ENTRY, "--mcp"],
env: Object.fromEntries(
Object.entries({
...process.env,
@@ -399,7 +399,7 @@ async function runClaudeWithMcp(
mcpServers: {
claudish: {
command: "bun",
- args: ["run", SERVER_ENTRY, "--mcp"],
+ args: ["--no-env-file", "run", SERVER_ENTRY, "--mcp"],
env: {
CLAUDISH_MCP_TOOLS: "all",
CLAUDISH_SESSIONS_DIR: SESSIONS_DIR,
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 ea6e7e1a..2ad79d31 100644
--- a/packages/cli/src/mcp-session/host-pid.contract.test.ts
+++ b/packages/cli/src/mcp-session/host-pid.contract.test.ts
@@ -122,7 +122,7 @@ describe.skipIf(!MAGMUX_AVAILABLE)(
writeFileSync(
launcher,
[
- `const child = Bun.spawn([process.execPath, ${JSON.stringify(SERVER_ENTRY)}, "--mcp"], {`,
+ `const child = Bun.spawn([process.execPath, "--no-env-file", ${JSON.stringify(SERVER_ENTRY)}, "--mcp"], {`,
` stdin: "inherit", stdout: "inherit", stderr: "inherit",`,
" env: { ...process.env, CLAUDISH_PANE_CHILD: undefined, CLAUDISH_LAUNCHER_PID: String(process.pid), CLAUDISH_LAUNCHER_PPID: String(process.ppid) },",
"});",
diff --git a/packages/cli/src/mcp-session/session-wire-format.test.ts b/packages/cli/src/mcp-session/session-wire-format.test.ts
index 171b058f..72ce8869 100644
--- a/packages/cli/src/mcp-session/session-wire-format.test.ts
+++ b/packages/cli/src/mcp-session/session-wire-format.test.ts
@@ -29,7 +29,7 @@ describe("MCP capability declaration", () => {
const layout = makeTempLayout("wirecaps");
layouts.push(layout);
// Drive only the initialize handshake — no session needed.
- const proc: ChildProcess = spawn(process.execPath, [SERVER_ENTRY, "--mcp"], {
+ const proc: ChildProcess = spawn(process.execPath, ["--no-env-file", SERVER_ENTRY, "--mcp"], {
stdio: ["pipe", "pipe", "pipe"],
env: serverEnv(layout, { CLAUDISH_MCP_TOOLS: toolMode }),
cwd: layout.cwd,
diff --git a/packages/cli/src/pane/child-env.test.ts b/packages/cli/src/pane/child-env.test.ts
index 495e2ab2..d9ad98e6 100644
--- a/packages/cli/src/pane/child-env.test.ts
+++ b/packages/cli/src/pane/child-env.test.ts
@@ -367,7 +367,7 @@ describe("nested CLI launches", () => {
["T-CLI-4", "team run before argument validation", ["team", "run"]],
] as const) {
test(`${id}: ${name} exits 64 with the exact nested refusal line`, () => {
- const r = Bun.spawnSync([process.execPath, "run", "src/index.ts", ...argv], {
+ const r = Bun.spawnSync([process.execPath, "--no-env-file", "run", "src/index.ts", ...argv], {
cwd: cliDir,
env: hermeticEnv({ CLAUDISH_PANE_CHILD: "1" }),
stdin: "ignore",
@@ -383,11 +383,14 @@ describe("nested CLI launches", () => {
}
test("T-CLI-5: --version still succeeds inside an MCP session", () => {
- const r = Bun.spawnSync([process.execPath, "run", "src/index.ts", "--version"], {
- cwd: cliDir,
- env: hermeticEnv({ CLAUDISH_PANE_CHILD: "1" }),
- timeout: 60_000,
- });
+ const r = Bun.spawnSync(
+ [process.execPath, "--no-env-file", "run", "src/index.ts", "--version"],
+ {
+ cwd: cliDir,
+ env: hermeticEnv({ CLAUDISH_PANE_CHILD: "1" }),
+ timeout: 60_000,
+ }
+ );
expect(r.exitCode).toBe(0);
expect(r.stdout.toString()).toMatch(/\b\d+\.\d+\.\d+\b/);
expect(r.stderr.toString()).not.toContain("refused");
@@ -397,7 +400,16 @@ describe("nested CLI launches", () => {
const statusPath = mkdtempSync(join(cliDir, ".nested-team-status-"));
try {
const r = Bun.spawnSync(
- [process.execPath, "run", "src/index.ts", "team", "status", "--path", statusPath],
+ [
+ process.execPath,
+ "--no-env-file",
+ "run",
+ "src/index.ts",
+ "team",
+ "status",
+ "--path",
+ statusPath,
+ ],
{
cwd: cliDir,
env: hermeticEnv({ CLAUDISH_PANE_CHILD: "1" }),
diff --git a/packages/cli/src/probe/probe-chain.test.ts b/packages/cli/src/probe/probe-chain.test.ts
index 26eb3ef1..f29f52a1 100644
--- a/packages/cli/src/probe/probe-chain.test.ts
+++ b/packages/cli/src/probe/probe-chain.test.ts
@@ -57,7 +57,7 @@ function sandboxedProbe(model: string, keys: Record<string, string> = {}): Probe
try {
const child = Bun.spawnSync(
- [process.execPath, CLI_ENTRY, "--probe", model, "--json", "--no-probe"],
+ [process.execPath, "--no-env-file", CLI_ENTRY, "--probe", model, "--json", "--no-probe"],
{
cwd: REPO_ROOT,
env,
diff --git a/packages/cli/src/spawn-claudish.test.ts b/packages/cli/src/spawn-claudish.test.ts
index e86ba3fb..45aab3c2 100644
--- a/packages/cli/src/spawn-claudish.test.ts
+++ b/packages/cli/src/spawn-claudish.test.ts
@@ -19,7 +19,7 @@ describe("resolveClaudishSpawn", () => {
expect(resolveClaudishSpawn({ [CLAUDISH_BIN_ENV]: entry })).toEqual({
command: process.execPath,
- prefixArgs: ["run", entry],
+ prefixArgs: ["--no-env-file", "run", entry],
});
}
);
@@ -36,7 +36,7 @@ describe("resolveClaudishSpawn", () => {
expect(resolveClaudishSpawn({ [CLAUDISH_BIN_ENV]: entry })).toEqual({
command: process.execPath,
- prefixArgs: ["run", entry],
+ prefixArgs: ["--no-env-file", "run", entry],
});
});
diff --git a/packages/cli/src/spawn-claudish.ts b/packages/cli/src/spawn-claudish.ts
index 4864b2b3..e83d6fa9 100644
--- a/packages/cli/src/spawn-claudish.ts
+++ b/packages/cli/src/spawn-claudish.ts
@@ -26,6 +26,8 @@
* exactly `spawn("claudish", args)`.
*/
+import { NO_ENV_FILE_FLAG } from "./launch-env.js";
+
/** How to spawn claudish: an executable plus any arguments that must precede argv. */
export interface ClaudishSpawnTarget {
command: string;
@@ -41,7 +43,9 @@ export const CLAUDISH_BIN_ENV = "CLAUDISH_BIN";
* A `.ts`/`.js` value is run through the CURRENT runtime (`process.execPath`, i.e.
* the same bun that is executing the parent) rather than requiring the harness to
* write an executable shim — pointing straight at `packages/cli/src/index.ts` is
- * the thing a test actually wants to say. Anything else is treated as an
+ * the thing a test actually wants to say. It runs with `--no-env-file`, as the npm
+ * launcher does: the child starts in the session's cwd, and Bun must not load that
+ * directory's env files (launch-env.ts). Anything else is treated as an
* executable path or a PATH-resolvable name.
*
* `spawn` is always called with `shell: false` at the call sites, so no quoting or
@@ -51,7 +55,7 @@ export function resolveClaudishSpawn(env: NodeJS.ProcessEnv = process.env): Clau
const bin = env[CLAUDISH_BIN_ENV]?.trim();
if (!bin) return { command: "claudish", prefixArgs: [] };
if (/\.(ts|tsx|js|mjs|cjs)$/.test(bin)) {
- return { command: process.execPath, prefixArgs: ["run", bin] };
+ return { command: process.execPath, prefixArgs: [NO_ENV_FILE_FLAG, "run", bin] };
}
return { command: bin, prefixArgs: [] };
}
diff --git a/packages/cli/src/team-cli-signal.test.ts b/packages/cli/src/team-cli-signal.test.ts
index 90e6b729..35cade26 100644
--- a/packages/cli/src/team-cli-signal.test.ts
+++ b/packages/cli/src/team-cli-signal.test.ts
@@ -59,6 +59,7 @@ describe.skipIf(!MAGMUX)("claudish team run — signals", () => {
const proc = Bun.spawn(
[
process.execPath,
+ "--no-env-file",
ENTRY,
"team",
"run",
diff --git a/packages/cli/src/team-mcp-shape-contract.e2e.test.ts b/packages/cli/src/team-mcp-shape-contract.e2e.test.ts
index de2c690d..90689b78 100644
--- a/packages/cli/src/team-mcp-shape-contract.e2e.test.ts
+++ b/packages/cli/src/team-mcp-shape-contract.e2e.test.ts
@@ -144,7 +144,7 @@ describe.skipIf(!MAGMUX)("MCP team shape contract", () => {
}
writeFileSync(configPath, "{}\n");
- server = spawn(process.execPath, ["run", SERVER_ENTRY, "--mcp"], {
+ server = spawn(process.execPath, ["--no-env-file", "run", SERVER_ENTRY, "--mcp"], {
cwd: REPO_ROOT,
stdio: ["pipe", "pipe", "pipe"],
env: {
diff --git a/packages/cli/src/test-helpers/contract-mcp.ts b/packages/cli/src/test-helpers/contract-mcp.ts
index 88c83a44..31d1614a 100644
--- a/packages/cli/src/test-helpers/contract-mcp.ts
+++ b/packages/cli/src/test-helpers/contract-mcp.ts
@@ -146,7 +146,7 @@ export class McpServer {
command?: string[];
}): Promise<McpServer> {
const server = new McpServer(
- opts.command ?? [process.execPath, SERVER_ENTRY, "--mcp"],
+ opts.command ?? [process.execPath, "--no-env-file", SERVER_ENTRY, "--mcp"],
opts.env,
opts.cwd
);