From 093217de811be9b5f35b1d071c96b741e8df883a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 20:28:41 +0000 Subject: [PATCH 1/5] fix(tests): isolate Claude host storage from the invoking home --- docs/process/testing.md | 11 +++ .../tests/confirm-bash.test.ts | 15 +++- .../fixtures/host-storage-isolation.test.ts | 39 +++++++++ .../tests/host-storage-isolation.test.ts | 76 +++++++++++++++++ scripts/test-claude-home-guard.ts | 82 +++++++++++++++++++ scripts/test-home.ts | 42 ++++++++++ scripts/test-network-preload.ts | 11 ++- tests/test-home.test.ts | 40 +++++++++ 8 files changed, 310 insertions(+), 6 deletions(-) create mode 100644 packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts create mode 100644 packages/ui-backend-claude/tests/host-storage-isolation.test.ts create mode 100644 scripts/test-claude-home-guard.ts create mode 100644 scripts/test-home.ts create mode 100644 tests/test-home.test.ts diff --git a/docs/process/testing.md b/docs/process/testing.md index ba9d567ef8..3d4b525fe8 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -56,6 +56,17 @@ inspecting CI on a PR live in the `work-issue` skill's commands and explicitly preloaded child probes. Production invocations keep their own policy. The startup-view copier still refuses concurrent changes. +The shared test preload assigns a fresh disposable `HOME` and +`CLAUDE_CONFIG_DIR`, including when a caller inherited a real Claude config +path. Tests that supply their own profile paths must keep them in owned +fixtures. A process-local guard refuses filesystem write attempts to the invoking +home’s `.claude` tree and inherited Claude config, including canonical aliases. +The regression probe compares path membership and exact file metadata, so +same-size overwrites cannot hide behind an unchanged directory count. +The preload restores both environment descriptors and removes its storage +after all test files finish. Turns must await owned observation saves before +settling so teardown cannot race storage writes. + ### Deliberate offline commands on Linux Use the repository launcher when a manual test command needs OS-level network diff --git a/packages/ui-backend-claude/tests/confirm-bash.test.ts b/packages/ui-backend-claude/tests/confirm-bash.test.ts index c495b0a645..2e8b6303a2 100644 --- a/packages/ui-backend-claude/tests/confirm-bash.test.ts +++ b/packages/ui-backend-claude/tests/confirm-bash.test.ts @@ -13,12 +13,19 @@ import { mockWorkerHostForSdkStream } from "./helpers/worker-host.js"; * alone. A pattern set that fires on `git status` would be turned off within a * day, and then it protects nothing. */ -import { describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import type { Options, query } from "@anthropic-ai/claude-agent-sdk"; import { createClaudeBackend, DEFAULT_CONFIRM_BASH_PATTERNS } from "../src/backend.js"; import { MUTATING_TOOL_MATCHER } from "../src/tool-policy.js"; +let brainPath: string; +beforeEach(() => { brainPath = mkdtempSync(join(tmpdir(), "odysseus-confirm-bash-")); }); +afterEach(() => { rmSync(brainPath, { recursive: true, force: true }); }); + const patterns = DEFAULT_CONFIRM_BASH_PATTERNS.map((p) => new RegExp(p.pattern, "i")); const confirms = (command: string) => patterns.some((re) => re.test(command)); @@ -134,7 +141,7 @@ describe("unparseable patterns", () => { let constructionError: unknown; try { backend = createClaudeBackend({ - brainPath: "/tmp", confirmBashPatterns: ["("], queryFn, log: () => {}, + brainPath, confirmBashPatterns: ["("], queryFn, log: () => {}, }); } catch (error) { constructionError = error; @@ -156,7 +163,7 @@ describe("unparseable patterns", () => { const calls: Array<{ level: string; message: string; attrs?: Record }> = []; createClaudeBackend({ - brainPath: "/tmp", + brainPath, confirmBashPatterns: ["(unclosed", String.raw`\brm\s`], log: (level, message, attrs) => calls.push({ level, message, attrs }), }); @@ -208,7 +215,7 @@ describe("what the card says (#112)", () => { })(); }) as unknown as typeof query; const backend = createClaudeBackend({ - brainPath: "/tmp", + brainPath, queryFn, log: () => {}, ...(confirmBashPatterns ? { confirmBashPatterns } : {}), diff --git a/packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts b/packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts new file mode 100644 index 0000000000..d071e6967a --- /dev/null +++ b/packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts @@ -0,0 +1,39 @@ +/** Spawned only by host-storage-isolation.test.ts; also harmless in full discovery. */ +import { expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createClaudeBackend } from "../../src/backend"; +import { transcriptPaths } from "../../src/transcript-archive"; +import { turnEnv } from "../../src/sdk-options"; +import { mockWorkerHostForSdkStream } from "../helpers/worker-host"; + +mockWorkerHostForSdkStream(); +test("default and explicit profile saves settle in the disposable test home", async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-isolation-turn-")); + const records: number[] = []; + let storageWasInsideTestHome = true; + try { + for (const explicit of [false, true]) { + const brain = join(root, String(explicit)); mkdirSync(brain); + const profile = { id: "voyage", label: "Voyage", billing: "api" as const, requiredEnvKeys: [], buildEnv: () => ({}) }; + const session = "44444444-4444-4444-8444-444444444444"; + const backend = createClaudeBackend({ brainPath: brain, log: () => {}, + ...(explicit ? { profiles: [profile] } : {}), + queryFn: (() => (async function* () { + yield { type: "system", subtype: "init", session_id: session }; + yield { type: "result", subtype: "success", session_id: session, is_error: false, + duration_ms: 1, duration_api_ms: 0, num_turns: 1, result: "", total_cost_usd: 0, usage: {}, modelUsage: {} }; + })()) as never, + }); + await backend.startTurn({ prompt: "Return to Ithaca", signal: new AbortController().signal, + bridge: { emit: () => {}, requestPermission: async () => ({ behavior: "allow" }) } }); + const storage = join(transcriptPaths(brain, explicit ? turnEnv(profile) : undefined).archive, "native-observations"); + records.push(readdirSync(storage).filter(name => name.endsWith(".json")).length); + storageWasInsideTestHome &&= storage.startsWith(join(process.env.HOME!, ".claude") + "/"); + } + expect(records).toEqual([1, 1]); + if (process.env.ODYSSEUS_ISOLATION_REPORT) writeFileSync(process.env.ODYSSEUS_ISOLATION_REPORT, + JSON.stringify({ records, storageWasInsideTestHome, home: process.env.HOME })); + } finally { rmSync(root, { recursive: true, force: true }); } +}); diff --git a/packages/ui-backend-claude/tests/host-storage-isolation.test.ts b/packages/ui-backend-claude/tests/host-storage-isolation.test.ts new file mode 100644 index 0000000000..bc1fe15af8 --- /dev/null +++ b/packages/ui-backend-claude/tests/host-storage-isolation.test.ts @@ -0,0 +1,76 @@ +/** Exercise the actual test preload and turns against a disposable invoking home. */ +import { expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { claudeHomeSnapshot } from "../../../scripts/test-home"; + +const workspace = resolve(import.meta.dir, "../../.."); +test("the shared preload keeps default and explicit-profile turns out of the invoking Claude home", async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-host-isolation-")); + const home = join(root, "invoking-home"), config = join(home, ".claude"); + mkdirSync(config, { recursive: true }); + const sentinel = join(config, "sentinel"); + writeFileSync(sentinel, "Ithaca\n"); + const baseline = claudeHomeSnapshot(home); + try { + const child = Bun.spawn([process.execPath, "test", "--timeout", "30000", "--preload", + join(workspace, "scripts/test-network-preload.ts"), join(import.meta.dir, "fixtures/host-storage-isolation.test.ts")], { + cwd: workspace, env: { ...process.env, HOME: home, CLAUDE_CONFIG_DIR: config, ODYSSEUS_ISOLATION_REPORT: join(root, "report.json") }, + stdout: "pipe", stderr: "pipe", + }); + const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); + expect(exit, stderr + stdout).toBe(0); + expect(claudeHomeSnapshot(home), "INVOKING_CLAUDE_HOME_UNCHANGED").toBe(baseline); + expect(readFileSync(sentinel, "utf8")).toBe("Ithaca\n"); + const report = JSON.parse(readFileSync(join(root, "report.json"), "utf8")); + expect(report.records).toEqual([1, 1]); + expect(report.storageWasInsideTestHome).toBe(true); + expect(existsSync(report.home)).toBe(false); + } finally { rmSync(root, { recursive: true, force: true }); } +}); + +test("the invoking-home guard records swallowed sync, async, Bun and aliased write attempts", async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-host-write-guard-")); + const home = join(root, "invoking-home"), config = join(home, ".claude"); + mkdirSync(config, { recursive: true }); + const sentinel = join(config, "sentinel"); writeFileSync(sentinel, "Ithaca\n"); + const baseline = claudeHomeSnapshot(home); + const probe = join(root, "guard-probe.test.ts"); + const report = join(root, "attempts.json"); + writeFileSync(probe, `import {expect,test} from "bun:test"; +import {writeFileSync,symlinkSync} from "node:fs"; +import {open} from "node:fs/promises"; +test("swallowed host write attempts remain failures", async () => { + const path = ${JSON.stringify(sentinel)}, alias = ${JSON.stringify(join(root, "alias"))}; + symlinkSync(${JSON.stringify(config)}, alias); + const caught = []; + for (const [name, attempt] of [ + ["sync", () => writeFileSync(path, "Troy!!\\n")], + ["async", () => open(path, "w")], + ["bun", () => Bun.write(path, "Troy!!\\n")], + ["file", () => Bun.file(path).write("Troy!!\\n")], + ["writer", () => Bun.file(path).writer()], + ["delete", () => Bun.file(path).delete()], + ["alias", () => writeFileSync(alias + "/sentinel", "Troy!!\\n")], + ]) { + try { await attempt(); } catch(error) { + expect(String(error)).toContain("TEST_WROTE_INVOKING_CLAUDE_HOME"); caught.push(name); + } + } + writeFileSync(${JSON.stringify(report)}, JSON.stringify(caught)); + expect(caught).toEqual(["sync", "async", "bun", "file", "writer", "delete", "alias"]); +});`); + try { + const child = Bun.spawn([process.execPath, "test", "--timeout", "30000", "--preload", + join(workspace, "scripts/test-network-preload.ts"), probe], { + cwd: workspace, env: { ...process.env, HOME: home, CLAUDE_CONFIG_DIR: config }, stdout: "pipe", stderr: "pipe", + }); + const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); + expect(exit, stdout + stderr).toBe(1); + expect(stderr + stdout).toContain("TEST_WROTE_INVOKING_CLAUDE_HOME"); + expect(JSON.parse(readFileSync(report, "utf8"))).toEqual(["sync", "async", "bun", "file", "writer", "delete", "alias"]); + expect(claudeHomeSnapshot(home)).toBe(baseline); + expect(readFileSync(sentinel, "utf8")).toBe("Ithaca\n"); + } finally { rmSync(root, { recursive: true, force: true }); } +}); diff --git a/scripts/test-claude-home-guard.ts b/scripts/test-claude-home-guard.ts new file mode 100644 index 0000000000..f3bba14567 --- /dev/null +++ b/scripts/test-claude-home-guard.ts @@ -0,0 +1,82 @@ +/** Process-local write-attempt guard: other sessions may use their own home. */ +import { spyOn } from "bun:test"; +import * as fs from "node:fs"; +import * as promises from "node:fs/promises"; +import { basename, dirname, resolve, sep } from "node:path"; +import { fileURLToPath } from "node:url"; + +export function installClaudeHomeGuard(home: string, config?: string) { + const roots = [resolve(home, ".claude"), ...(config ? [resolve(config)] : [])]; + const canonical = (path: string): string => { + try { return fs.realpathSync(path); } + catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + const parent = dirname(path); + return parent === path ? path : resolve(canonical(parent), basename(path)); + } + }; + const protectedRoots = roots.flatMap(path => [path, canonical(path)]); + let attempted = false; + const check = (input: unknown) => { + if (typeof input === "number") return; // Writable opens are guarded below. + const path = input instanceof URL ? fileURLToPath(input) + : Buffer.isBuffer(input) ? input.toString() : typeof input === "string" ? input : undefined; + if (path === undefined) return; + const absolute = resolve(path); + const matches = (candidate: string) => protectedRoots.some(root => candidate === root || candidate.startsWith(root + sep)); + if (matches(absolute) || matches(canonical(absolute))) { + attempted = true; + throw new Error("TEST_WROTE_INVOKING_CLAUDE_HOME: test attempted to write invoking Claude storage"); + } + }; + const spies: Array<{ mockRestore(): void }> = []; + const mutators: Record = { + appendFile: [0], chmod: [0], chown: [0], copyFile: [1], cp: [1], + lchmod: [0], lchown: [0], lutimes: [0], link: [1], mkdir: [0], mkdtemp: [0], + rename: [0, 1], rm: [0], rmdir: [0], symlink: [1], truncate: [0], unlink: [0], utimes: [0], writeFile: [0], + }; + const wrap = (target: object, name: string, indices: number[], asynchronous = false, opening = false) => { + const methods = target as Record unknown>; + if (typeof methods[name] !== "function") return; + const original = methods[name]!; + const invoke = (...args: unknown[]) => { + const flags = args[1]; + const writable = !opening || (typeof flags === "number" + ? (flags & (fs.constants.O_WRONLY | fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_TRUNC | fs.constants.O_APPEND)) !== 0 + : typeof flags === "string" && /[wa+]/.test(flags)); + if (writable) for (const index of indices) check(args[index]); + return Reflect.apply(original, target, args); + }; + spies.push(spyOn(methods, name).mockImplementation(asynchronous ? async (...args) => invoke(...args) : invoke)); + }; + for (const [name, indices] of Object.entries(mutators)) { + wrap(fs, name, indices); + wrap(fs, name + "Sync", indices); + wrap(promises, name, indices, true); + } + wrap(fs, "open", [0], false, true); + wrap(fs, "openSync", [0], false, true); + wrap(promises, "open", [0], true, true); + wrap(fs, "createWriteStream", [0]); + const write = Bun.write; + const guardedWrite = ((...args: unknown[]) => { + const destination = args[0]; + check(typeof destination === "object" && destination !== null && "name" in destination ? destination.name : destination); + return Reflect.apply(write, Bun, args); + }) as typeof Bun.write; + spies.push(spyOn(Bun, "write").mockImplementation(guardedWrite)); + const filePrototype = Object.getPrototypeOf(Bun.file(import.meta.path)) as Record unknown>; + for (const name of ["write", "writer", "unlink", "delete"]) { + const native = filePrototype[name]!; + spies.push(spyOn(filePrototype, name).mockImplementation(function (this: { name?: string }, ...args: unknown[]) { + check(this.name); + return Reflect.apply(native, this, args); + })); + } + return { + assertNoEscapes() { + if (attempted) throw new Error("TEST_WROTE_INVOKING_CLAUDE_HOME: a test attempted to write invoking Claude storage"); + }, + dispose() { for (const spy of spies.reverse()) spy.mockRestore(); }, + }; +} diff --git a/scripts/test-home.ts b/scripts/test-home.ts new file mode 100644 index 0000000000..6ea632944d --- /dev/null +++ b/scripts/test-home.ts @@ -0,0 +1,42 @@ +/** Test-owned host storage; production's HOME fallback remains untouched. */ +import { lstatSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +/** Metadata includes ctime/inode, so an equal-size overwrite is still a change. */ +export function claudeHomeSnapshot(home: string): string { + const entries: unknown[] = []; + const visit = (path: string) => { + let stat; + try { stat = lstatSync(path, { bigint: true }); } + catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return; + throw error; + } + entries.push([path, stat.dev, stat.ino, stat.mode, stat.nlink, stat.size, stat.mtimeNs, stat.ctimeNs].map(String)); + // Never follow a user's symlinks outside the guarded tree. + if (stat.isDirectory()) for (const name of readdirSync(path).sort()) visit(join(path, name)); + }; + visit(join(home, ".claude")); + return JSON.stringify(entries); +} + +export function installTestHome() { + const descriptors = new Map(["HOME", "CLAUDE_CONFIG_DIR"].map(name => [name, Object.getOwnPropertyDescriptor(process.env, name)])); + const root = mkdtempSync(join(tmpdir(), "brain-test-home-")); + const home = join(root, "home"); + mkdirSync(home); + process.env.HOME = home; + // Override an inherited host config too, rather than preserving a real path. + process.env.CLAUDE_CONFIG_DIR = join(home, ".claude"); + return { + root, + dispose() { + for (const [name, descriptor] of descriptors) { + if (descriptor) Object.defineProperty(process.env, name, descriptor); + else delete process.env[name]; + } + rmSync(root, { recursive: true, force: true }); + }, + }; +} diff --git a/scripts/test-network-preload.ts b/scripts/test-network-preload.ts index afa60694a5..e9ff68151a 100644 --- a/scripts/test-network-preload.ts +++ b/scripts/test-network-preload.ts @@ -1,14 +1,18 @@ import { afterAll, afterEach } from "bun:test"; import { cleanupCliUtilities } from "../packages/core/tests/cli-harness"; import { installNetworkGuard } from "./test-network-guard"; +import { installTestHome } from "./test-home"; +import { installClaudeHomeGuard } from "./test-claude-home-guard"; import { join, resolve } from "node:path"; import { mkdirSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import { ensureWorkspaceLease, processIdentity, workspaceTestAccess } from "./workspace-lease.mjs"; const guard = installNetworkGuard(); const coordinated = await ensureWorkspaceLease(resolve(import.meta.dir, ".."), workspaceTestAccess(), "test"); if (coordinated !== undefined) process.exit(coordinated); +const homeGuard = installClaudeHomeGuard(process.env.HOME || homedir(), process.env.CLAUDE_CONFIG_DIR); +const testHome = installTestHome(); // Commands a test spawns queue in a ledger private to this test process, never // behind the host's real heavy commands (#2943). The path is testLedgerFor's // convention in scripts/host-admission.mjs, so a descendant whose environment @@ -20,14 +24,17 @@ const privateAdmission = join(tmpdir(), `brain-host-admission-test-${process.getuid?.() ?? "user"}-${process.pid}-${processIdentity(process.pid)?.start ?? "0"}`); mkdirSync(privateAdmission, { mode: 0o700 }); process.env.BRAIN_HOST_ADMISSION_DIR = privateAdmission; -afterEach(() => guard.assertNoEscapes()); +afterEach(() => { guard.assertNoEscapes(); homeGuard.assertNoEscapes(); }); // A preload hook runs after all files; a hook in the cached helper would run // after its first importing file. Bun test does not run the ordinary exit hook. afterAll(() => { try { guard.assertNoEscapes(); + homeGuard.assertNoEscapes(); } finally { cleanupCliUtilities(); rmSync(privateAdmission, { recursive: true, force: true }); + homeGuard.dispose(); + testHome.dispose(); } }); diff --git a/tests/test-home.test.ts b/tests/test-home.test.ts new file mode 100644 index 0000000000..8c6f7ce363 --- /dev/null +++ b/tests/test-home.test.ts @@ -0,0 +1,40 @@ +import { expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { claudeHomeSnapshot, installTestHome } from "../scripts/test-home"; + +for (const configPresent of [false, true]) { + test(`test home restores environment descriptors with config ${configPresent ? "set" : "absent"} and snapshots detect host overwrites`, () => { + const descriptors = new Map(["HOME", "CLAUDE_CONFIG_DIR"].map(name => [name, Object.getOwnPropertyDescriptor(process.env, name)])); + const root = mkdtempSync(join(tmpdir(), "odysseus-test-home-")); + const config = join(root, ".claude"); mkdirSync(config); + const sentinel = join(config, "sentinel"); writeFileSync(sentinel, "Ithaca\n"); + process.env.HOME = root; + if (configPresent) process.env.CLAUDE_CONFIG_DIR = config; + else delete process.env.CLAUDE_CONFIG_DIR; + const before = ["HOME", "CLAUDE_CONFIG_DIR"].map(name => Object.getOwnPropertyDescriptor(process.env, name)); + const isolated = installTestHome(); + try { + expect(process.env.HOME).toBe(join(isolated.root, "home")); + expect(process.env.CLAUDE_CONFIG_DIR).toBe(join(isolated.root, "home/.claude")); + const baseline = claudeHomeSnapshot(root); + // Same path and byte count: a directory-count-only guard misses this. + writeFileSync(sentinel, "Troy!!\n"); + expect(readFileSync(sentinel, "utf8")).toBe("Troy!!\n"); + expect(claudeHomeSnapshot(root)).not.toBe(baseline); + } finally { + isolated.dispose(); + try { + expect(existsSync(isolated.root)).toBe(false); + expect(["HOME", "CLAUDE_CONFIG_DIR"].map(name => Object.getOwnPropertyDescriptor(process.env, name))).toEqual(before); + } finally { + for (const [name, descriptor] of descriptors) { + if (descriptor) Object.defineProperty(process.env, name, descriptor); + else delete process.env[name]; + } + rmSync(root, { recursive: true, force: true }); + } + } + }); +} From ec072ad656b9f6b8135a944967e2564f2b5ee62b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 20:31:47 +0000 Subject: [PATCH 2/5] test: carry home isolation into copied test harnesses --- .../tests/fixtures/host-storage-isolation.test.ts | 15 ++++++++------- .../tests/host-storage-isolation.test.ts | 4 ++-- tests/experiment-tier.test.ts | 2 +- tests/helpers/test-invocation-fixture.ts | 2 +- tests/helpers/unit-worker-fixture.ts | 2 +- tests/local-checks.test.ts | 2 +- tests/test-script.test.ts | 2 +- tests/test-shards.test.ts | 2 +- tests/workspace-lease.test.ts | 2 +- 9 files changed, 17 insertions(+), 16 deletions(-) diff --git a/packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts b/packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts index d071e6967a..19484f3304 100644 --- a/packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts +++ b/packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts @@ -12,11 +12,12 @@ mockWorkerHostForSdkStream(); test("default and explicit profile saves settle in the disposable test home", async () => { const root = mkdtempSync(join(tmpdir(), "odysseus-isolation-turn-")); const records: number[] = []; - let storageWasInsideTestHome = true; + let storageWasOwned = true; try { - for (const explicit of [false, true]) { - const brain = join(root, String(explicit)); mkdirSync(brain); - const profile = { id: "voyage", label: "Voyage", billing: "api" as const, requiredEnvKeys: [], buildEnv: () => ({}) }; + for (const mode of ["default", "empty", "override"]) { + const explicit = mode !== "default"; + const brain = join(root, mode); mkdirSync(brain); + const profile = { id: "voyage", label: "Voyage", billing: "api" as const, requiredEnvKeys: [], buildEnv: () => mode === "override" ? { CLAUDE_CONFIG_DIR: join(root, "config") } : {} }; const session = "44444444-4444-4444-8444-444444444444"; const backend = createClaudeBackend({ brainPath: brain, log: () => {}, ...(explicit ? { profiles: [profile] } : {}), @@ -30,10 +31,10 @@ test("default and explicit profile saves settle in the disposable test home", as bridge: { emit: () => {}, requestPermission: async () => ({ behavior: "allow" }) } }); const storage = join(transcriptPaths(brain, explicit ? turnEnv(profile) : undefined).archive, "native-observations"); records.push(readdirSync(storage).filter(name => name.endsWith(".json")).length); - storageWasInsideTestHome &&= storage.startsWith(join(process.env.HOME!, ".claude") + "/"); + storageWasOwned &&= storage.startsWith((mode === "override" ? join(root, "config") : join(process.env.HOME!, ".claude")) + "/"); } - expect(records).toEqual([1, 1]); + expect(records).toEqual([1, 1, 1]); if (process.env.ODYSSEUS_ISOLATION_REPORT) writeFileSync(process.env.ODYSSEUS_ISOLATION_REPORT, - JSON.stringify({ records, storageWasInsideTestHome, home: process.env.HOME })); + JSON.stringify({ records, storageWasOwned, home: process.env.HOME })); } finally { rmSync(root, { recursive: true, force: true }); } }); diff --git a/packages/ui-backend-claude/tests/host-storage-isolation.test.ts b/packages/ui-backend-claude/tests/host-storage-isolation.test.ts index bc1fe15af8..2ba0471ee0 100644 --- a/packages/ui-backend-claude/tests/host-storage-isolation.test.ts +++ b/packages/ui-backend-claude/tests/host-storage-isolation.test.ts @@ -24,8 +24,8 @@ test("the shared preload keeps default and explicit-profile turns out of the inv expect(claudeHomeSnapshot(home), "INVOKING_CLAUDE_HOME_UNCHANGED").toBe(baseline); expect(readFileSync(sentinel, "utf8")).toBe("Ithaca\n"); const report = JSON.parse(readFileSync(join(root, "report.json"), "utf8")); - expect(report.records).toEqual([1, 1]); - expect(report.storageWasInsideTestHome).toBe(true); + expect(report.records).toEqual([1, 1, 1]); + expect(report.storageWasOwned).toBe(true); expect(existsSync(report.home)).toBe(false); } finally { rmSync(root, { recursive: true, force: true }); } }); diff --git a/tests/experiment-tier.test.ts b/tests/experiment-tier.test.ts index 2fad53a575..36026cd4b0 100644 --- a/tests/experiment-tier.test.ts +++ b/tests/experiment-tier.test.ts @@ -16,7 +16,7 @@ import { } from "../scripts/test-experiments"; const ROOT = join(import.meta.dir, ".."); -const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", +const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-claude-home-guard.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; const passing = (name: string) => `import { expect, test } from "bun:test";\ntest(${JSON.stringify(name)}, () => expect(1).toBe(1));\n`; diff --git a/tests/helpers/test-invocation-fixture.ts b/tests/helpers/test-invocation-fixture.ts index d1dc673fb2..d8748c12c5 100644 --- a/tests/helpers/test-invocation-fixture.ts +++ b/tests/helpers/test-invocation-fixture.ts @@ -10,7 +10,7 @@ export function invocationFixture(parent = tmpdir()) { write("bun.lock", "{}\n"); write(".gitignore", "node_modules/\npackages/*/dist/\ntmp/\n"); write("tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2019", module: "ESNext", moduleResolution: "Bundler", types: [], skipLibCheck: true } })); - for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { + for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-claude-home-guard.ts", "test-network-guard.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { write(`scripts/${file}`, readFileSync(join(source, "scripts", file), "utf8")); } for (const file of ["packages/core/tests/cli-harness.ts", "packages/ui-react/tests/fixtures/runtime-package-build.ts", "packages/ui-react/tests/fixtures/runtime-hook-phases.ts"]) write(file, readFileSync(join(source, file), "utf8")); diff --git a/tests/helpers/unit-worker-fixture.ts b/tests/helpers/unit-worker-fixture.ts index 474a30d410..4ae00e7961 100644 --- a/tests/helpers/unit-worker-fixture.ts +++ b/tests/helpers/unit-worker-fixture.ts @@ -74,7 +74,7 @@ const stop=Date.now()+5000;while((!existsSync(join(shared,"built-1"))||!existsSy ${options.failBuild ? "process.exit(7);" : ""} mkdirSync("dist",{recursive:true});writeFileSync("dist/lease.json",JSON.stringify({lease:JSON.parse(process.env.BRAIN_WORKSPACE_LEASE),nonce:process.env.BRAIN_TEST_INVOCATION_NONCE}));writeFileSync("dist/ready.txt","Odysseus builds the raft.");receipt.packageEnd("raft",true);receipt.finish(0);\n`); for (const file of ["scripts/test.ts", "scripts/runtime-test-builds.ts", "scripts/test-invocation.ts", "scripts/test-invocation-child.ts", "scripts/publishable-packages.ts", - "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "packages/core/tests/cli-harness.ts"]) { + "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-claude-home-guard.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "packages/core/tests/cli-harness.ts"]) { write(file, readFileSync(join(source, file), "utf8")); } const files = ["odysseus", "penelope"].map(name => `tests/${name}.test.ts`); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index 9dda8e5acf..4731e232fb 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -400,7 +400,7 @@ function importFixture() { const dir = fixture(); const root = join(import.meta.dir, ".."); mkdirSync(join(dir, "scripts")); - for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-claude-home-guard.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(root, "scripts", helper), join(dir, "scripts", helper)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/test-script.test.ts b/tests/test-script.test.ts index c8749b7fa8..3c2eb980c2 100644 --- a/tests/test-script.test.ts +++ b/tests/test-script.test.ts @@ -33,7 +33,7 @@ async function run(args: string[], env: Record = {}) { if (existsSync(script)) { mkdirSync(join(dir, "scripts")); cpSync(script, join(dir, "scripts/test.ts")); - for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-claude-home-guard.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", helper), join(dir, "scripts", helper)); } // The actual preload also owns cleanup for the shared CLI harness. diff --git a/tests/test-shards.test.ts b/tests/test-shards.test.ts index fd415d32bd..1f90b63d3e 100644 --- a/tests/test-shards.test.ts +++ b/tests/test-shards.test.ts @@ -59,7 +59,7 @@ describe("balanced shards run the root command for real", () => { mkdirSync(join(dir, "scripts")); const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "fixture", scripts: { test: manifest.scripts.test } })); - for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-claude-home-guard.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/workspace-lease.test.ts b/tests/workspace-lease.test.ts index bccaaa810b..2b587d4d4f 100644 --- a/tests/workspace-lease.test.ts +++ b/tests/workspace-lease.test.ts @@ -281,7 +281,7 @@ test("the real pinned container wrapper waits for host ownership of its mounted test("direct Bun test preserves its selector, timeout and offline preload while waiting", async () => { const root = fixture(); mkdirSync(join(root, "scripts")); mkdirSync(join(root, "packages/core/tests"), { recursive: true }); - for (const name of ["test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const name of ["test-network-preload.ts", "test-home.ts", "test-claude-home-guard.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { copyFileSync(join(project, "scripts", name), join(root, "scripts", name)); } copyFileSync(join(project, "packages/core/tests/cli-harness.ts"), join(root, "packages/core/tests/cli-harness.ts")); From 722c47ce2c1cb23b415b04b4e0ec4cf2be157b6b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 20:36:54 +0000 Subject: [PATCH 3/5] test: type the explicit isolation profile environment --- .../tests/fixtures/host-storage-isolation.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts b/packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts index 19484f3304..ab58ac8fce 100644 --- a/packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts +++ b/packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts @@ -17,7 +17,7 @@ test("default and explicit profile saves settle in the disposable test home", as for (const mode of ["default", "empty", "override"]) { const explicit = mode !== "default"; const brain = join(root, mode); mkdirSync(brain); - const profile = { id: "voyage", label: "Voyage", billing: "api" as const, requiredEnvKeys: [], buildEnv: () => mode === "override" ? { CLAUDE_CONFIG_DIR: join(root, "config") } : {} }; + const profile = { id: "voyage", label: "Voyage", billing: "api" as const, requiredEnvKeys: [], buildEnv: (): Record => mode === "override" ? { CLAUDE_CONFIG_DIR: join(root, "config") } : {} }; const session = "44444444-4444-4444-8444-444444444444"; const backend = createClaudeBackend({ brainPath: brain, log: () => {}, ...(explicit ? { profiles: [profile] } : {}), From 400ebfd8cd0efebfa969ce522de780d946cf2416 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 21:57:57 +0000 Subject: [PATCH 4/5] fix(tests): guard owned homes without filesystem spies --- docs/process/testing.md | 11 ++- .../tests/host-storage-isolation.test.ts | 45 ---------- scripts/test-claude-home-guard.ts | 82 ------------------- scripts/test-home.ts | 22 ++++- scripts/test-network-preload.ts | 8 +- scripts/test.ts | 8 +- tests/experiment-tier.test.ts | 2 +- tests/helpers/test-invocation-fixture.ts | 2 +- tests/helpers/unit-worker-fixture.ts | 2 +- tests/local-checks.test.ts | 2 +- tests/test-home.test.ts | 40 ++++++++- tests/test-script.test.ts | 2 +- tests/test-shards.test.ts | 2 +- tests/workspace-lease.test.ts | 2 +- 14 files changed, 81 insertions(+), 149 deletions(-) delete mode 100644 scripts/test-claude-home-guard.ts diff --git a/docs/process/testing.md b/docs/process/testing.md index 3d4b525fe8..0d7a30381c 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -59,10 +59,13 @@ inspecting CI on a PR live in the `work-issue` skill's The shared test preload assigns a fresh disposable `HOME` and `CLAUDE_CONFIG_DIR`, including when a caller inherited a real Claude config path. Tests that supply their own profile paths must keep them in owned -fixtures. A process-local guard refuses filesystem write attempts to the invoking -home’s `.claude` tree and inherited Claude config, including canonical aliases. -The regression probe compares path membership and exact file metadata, so -same-size overwrites cannot hide behind an unchanged directory count. +fixtures. The test launcher supplies a separate disposable invoking home before +starting Bun, so even a native HOME fallback cannot select user storage. The +preload then assigns the test's working home. After the test process and its +children finish, the launcher compares the invoking home's sentinel tree with +its original path membership and metadata, including nanosecond change times. +This detects retained creations and same-size overwrites without patching +filesystem functions or observing unrelated sessions' storage activity. The preload restores both environment descriptors and removes its storage after all test files finish. Turns must await owned observation saves before settling so teardown cannot race storage writes. diff --git a/packages/ui-backend-claude/tests/host-storage-isolation.test.ts b/packages/ui-backend-claude/tests/host-storage-isolation.test.ts index 2ba0471ee0..7e91fa2d6f 100644 --- a/packages/ui-backend-claude/tests/host-storage-isolation.test.ts +++ b/packages/ui-backend-claude/tests/host-storage-isolation.test.ts @@ -29,48 +29,3 @@ test("the shared preload keeps default and explicit-profile turns out of the inv expect(existsSync(report.home)).toBe(false); } finally { rmSync(root, { recursive: true, force: true }); } }); - -test("the invoking-home guard records swallowed sync, async, Bun and aliased write attempts", async () => { - const root = mkdtempSync(join(tmpdir(), "odysseus-host-write-guard-")); - const home = join(root, "invoking-home"), config = join(home, ".claude"); - mkdirSync(config, { recursive: true }); - const sentinel = join(config, "sentinel"); writeFileSync(sentinel, "Ithaca\n"); - const baseline = claudeHomeSnapshot(home); - const probe = join(root, "guard-probe.test.ts"); - const report = join(root, "attempts.json"); - writeFileSync(probe, `import {expect,test} from "bun:test"; -import {writeFileSync,symlinkSync} from "node:fs"; -import {open} from "node:fs/promises"; -test("swallowed host write attempts remain failures", async () => { - const path = ${JSON.stringify(sentinel)}, alias = ${JSON.stringify(join(root, "alias"))}; - symlinkSync(${JSON.stringify(config)}, alias); - const caught = []; - for (const [name, attempt] of [ - ["sync", () => writeFileSync(path, "Troy!!\\n")], - ["async", () => open(path, "w")], - ["bun", () => Bun.write(path, "Troy!!\\n")], - ["file", () => Bun.file(path).write("Troy!!\\n")], - ["writer", () => Bun.file(path).writer()], - ["delete", () => Bun.file(path).delete()], - ["alias", () => writeFileSync(alias + "/sentinel", "Troy!!\\n")], - ]) { - try { await attempt(); } catch(error) { - expect(String(error)).toContain("TEST_WROTE_INVOKING_CLAUDE_HOME"); caught.push(name); - } - } - writeFileSync(${JSON.stringify(report)}, JSON.stringify(caught)); - expect(caught).toEqual(["sync", "async", "bun", "file", "writer", "delete", "alias"]); -});`); - try { - const child = Bun.spawn([process.execPath, "test", "--timeout", "30000", "--preload", - join(workspace, "scripts/test-network-preload.ts"), probe], { - cwd: workspace, env: { ...process.env, HOME: home, CLAUDE_CONFIG_DIR: config }, stdout: "pipe", stderr: "pipe", - }); - const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); - expect(exit, stdout + stderr).toBe(1); - expect(stderr + stdout).toContain("TEST_WROTE_INVOKING_CLAUDE_HOME"); - expect(JSON.parse(readFileSync(report, "utf8"))).toEqual(["sync", "async", "bun", "file", "writer", "delete", "alias"]); - expect(claudeHomeSnapshot(home)).toBe(baseline); - expect(readFileSync(sentinel, "utf8")).toBe("Ithaca\n"); - } finally { rmSync(root, { recursive: true, force: true }); } -}); diff --git a/scripts/test-claude-home-guard.ts b/scripts/test-claude-home-guard.ts deleted file mode 100644 index f3bba14567..0000000000 --- a/scripts/test-claude-home-guard.ts +++ /dev/null @@ -1,82 +0,0 @@ -/** Process-local write-attempt guard: other sessions may use their own home. */ -import { spyOn } from "bun:test"; -import * as fs from "node:fs"; -import * as promises from "node:fs/promises"; -import { basename, dirname, resolve, sep } from "node:path"; -import { fileURLToPath } from "node:url"; - -export function installClaudeHomeGuard(home: string, config?: string) { - const roots = [resolve(home, ".claude"), ...(config ? [resolve(config)] : [])]; - const canonical = (path: string): string => { - try { return fs.realpathSync(path); } - catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; - const parent = dirname(path); - return parent === path ? path : resolve(canonical(parent), basename(path)); - } - }; - const protectedRoots = roots.flatMap(path => [path, canonical(path)]); - let attempted = false; - const check = (input: unknown) => { - if (typeof input === "number") return; // Writable opens are guarded below. - const path = input instanceof URL ? fileURLToPath(input) - : Buffer.isBuffer(input) ? input.toString() : typeof input === "string" ? input : undefined; - if (path === undefined) return; - const absolute = resolve(path); - const matches = (candidate: string) => protectedRoots.some(root => candidate === root || candidate.startsWith(root + sep)); - if (matches(absolute) || matches(canonical(absolute))) { - attempted = true; - throw new Error("TEST_WROTE_INVOKING_CLAUDE_HOME: test attempted to write invoking Claude storage"); - } - }; - const spies: Array<{ mockRestore(): void }> = []; - const mutators: Record = { - appendFile: [0], chmod: [0], chown: [0], copyFile: [1], cp: [1], - lchmod: [0], lchown: [0], lutimes: [0], link: [1], mkdir: [0], mkdtemp: [0], - rename: [0, 1], rm: [0], rmdir: [0], symlink: [1], truncate: [0], unlink: [0], utimes: [0], writeFile: [0], - }; - const wrap = (target: object, name: string, indices: number[], asynchronous = false, opening = false) => { - const methods = target as Record unknown>; - if (typeof methods[name] !== "function") return; - const original = methods[name]!; - const invoke = (...args: unknown[]) => { - const flags = args[1]; - const writable = !opening || (typeof flags === "number" - ? (flags & (fs.constants.O_WRONLY | fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_TRUNC | fs.constants.O_APPEND)) !== 0 - : typeof flags === "string" && /[wa+]/.test(flags)); - if (writable) for (const index of indices) check(args[index]); - return Reflect.apply(original, target, args); - }; - spies.push(spyOn(methods, name).mockImplementation(asynchronous ? async (...args) => invoke(...args) : invoke)); - }; - for (const [name, indices] of Object.entries(mutators)) { - wrap(fs, name, indices); - wrap(fs, name + "Sync", indices); - wrap(promises, name, indices, true); - } - wrap(fs, "open", [0], false, true); - wrap(fs, "openSync", [0], false, true); - wrap(promises, "open", [0], true, true); - wrap(fs, "createWriteStream", [0]); - const write = Bun.write; - const guardedWrite = ((...args: unknown[]) => { - const destination = args[0]; - check(typeof destination === "object" && destination !== null && "name" in destination ? destination.name : destination); - return Reflect.apply(write, Bun, args); - }) as typeof Bun.write; - spies.push(spyOn(Bun, "write").mockImplementation(guardedWrite)); - const filePrototype = Object.getPrototypeOf(Bun.file(import.meta.path)) as Record unknown>; - for (const name of ["write", "writer", "unlink", "delete"]) { - const native = filePrototype[name]!; - spies.push(spyOn(filePrototype, name).mockImplementation(function (this: { name?: string }, ...args: unknown[]) { - check(this.name); - return Reflect.apply(native, this, args); - })); - } - return { - assertNoEscapes() { - if (attempted) throw new Error("TEST_WROTE_INVOKING_CLAUDE_HOME: a test attempted to write invoking Claude storage"); - }, - dispose() { for (const spy of spies.reverse()) spy.mockRestore(); }, - }; -} diff --git a/scripts/test-home.ts b/scripts/test-home.ts index 6ea632944d..6ffdfe30c1 100644 --- a/scripts/test-home.ts +++ b/scripts/test-home.ts @@ -1,5 +1,5 @@ /** Test-owned host storage; production's HOME fallback remains untouched. */ -import { lstatSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from "node:fs"; +import { lstatSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -40,3 +40,23 @@ export function installTestHome() { }, }; } + +/** A disposable invoking home lets the launcher guard every child filesystem API + * without patching the functions that race/refusal tests must spy on themselves. + * The preload creates a separate working home; this sentinel must stay untouched. + */ +export function createInvokingTestHome() { + const root = mkdtempSync(join(tmpdir(), "brain-test-invoking-home-")); + const home = join(root, "home"), config = join(home, ".claude"); + mkdirSync(config, { recursive: true }); + writeFileSync(join(config, "sentinel"), "Odysseus: invoking storage stays untouched.\n"); + const baseline = claudeHomeSnapshot(home); + return { + root, home, config, + assertUnchanged() { + if (claudeHomeSnapshot(home) !== baseline) + throw new Error("TEST_WROTE_INVOKING_CLAUDE_HOME: a test changed the invoking Claude storage"); + }, + dispose() { rmSync(root, { recursive: true, force: true }); }, + }; +} diff --git a/scripts/test-network-preload.ts b/scripts/test-network-preload.ts index e9ff68151a..ad43c1f120 100644 --- a/scripts/test-network-preload.ts +++ b/scripts/test-network-preload.ts @@ -2,16 +2,14 @@ import { afterAll, afterEach } from "bun:test"; import { cleanupCliUtilities } from "../packages/core/tests/cli-harness"; import { installNetworkGuard } from "./test-network-guard"; import { installTestHome } from "./test-home"; -import { installClaudeHomeGuard } from "./test-claude-home-guard"; import { join, resolve } from "node:path"; import { mkdirSync, rmSync } from "node:fs"; -import { homedir, tmpdir } from "node:os"; +import { tmpdir } from "node:os"; import { ensureWorkspaceLease, processIdentity, workspaceTestAccess } from "./workspace-lease.mjs"; const guard = installNetworkGuard(); const coordinated = await ensureWorkspaceLease(resolve(import.meta.dir, ".."), workspaceTestAccess(), "test"); if (coordinated !== undefined) process.exit(coordinated); -const homeGuard = installClaudeHomeGuard(process.env.HOME || homedir(), process.env.CLAUDE_CONFIG_DIR); const testHome = installTestHome(); // Commands a test spawns queue in a ledger private to this test process, never // behind the host's real heavy commands (#2943). The path is testLedgerFor's @@ -24,17 +22,15 @@ const privateAdmission = join(tmpdir(), `brain-host-admission-test-${process.getuid?.() ?? "user"}-${process.pid}-${processIdentity(process.pid)?.start ?? "0"}`); mkdirSync(privateAdmission, { mode: 0o700 }); process.env.BRAIN_HOST_ADMISSION_DIR = privateAdmission; -afterEach(() => { guard.assertNoEscapes(); homeGuard.assertNoEscapes(); }); +afterEach(() => guard.assertNoEscapes()); // A preload hook runs after all files; a hook in the cached helper would run // after its first importing file. Bun test does not run the ordinary exit hook. afterAll(() => { try { guard.assertNoEscapes(); - homeGuard.assertNoEscapes(); } finally { cleanupCliUtilities(); rmSync(privateAdmission, { recursive: true, force: true }); - homeGuard.dispose(); testHome.dispose(); } }); diff --git a/scripts/test.ts b/scripts/test.ts index e0d22f756b..3e30cacfe5 100644 --- a/scripts/test.ts +++ b/scripts/test.ts @@ -20,6 +20,7 @@ import { constants } from "node:os"; import { isAbsolute, join, resolve } from "node:path"; import { realpathSync } from "node:fs"; import { invocationChild } from "./test-invocation-child"; +import { createInvokingTestHome } from "./test-home"; import { runtimeBuildSelection } from "./runtime-test-builds"; import { acceptsSpeechDelegation, clearInvocation, prepareCopiedInvocation, prepareInvocation, takePreparedTree } from "./test-invocation"; import { ensureWorkspaceLease, workspaceTestAccess } from "./workspace-lease.mjs"; @@ -219,6 +220,7 @@ if (import.meta.main) { const listeners = signals.map(signal => () => { cancelled = signal; stop(signal); }); signals.forEach((signal, index) => process.on(signal, listeners[index]!)); let dispose = () => {}; + let invokingHome: ReturnType | undefined; let result = 1; try { const paths = testPaths(argv); @@ -236,12 +238,14 @@ if (import.meta.main) { if (!cancelled) { const beforeTests = performance.now(); console.error(JSON.stringify({ kind: "test-invocation", event: "tests-start", pid: process.pid, at: Date.now() })); - const tests = invocationChild([process.execPath, "test", "--preload", join(import.meta.dir, "test-network-preload.ts"), ...argv], { stdin: "inherit" }); + invokingHome = createInvokingTestHome(); + const tests = invocationChild([process.execPath, "test", "--preload", join(import.meta.dir, "test-network-preload.ts"), ...argv], { stdin: "inherit", env: { ...process.env, HOME: invokingHome.home, CLAUDE_CONFIG_DIR: invokingHome.config } }); started(tests); await tests.ready; const relay = async (stream: ReadableStream, channel: "stdout" | "stderr") => { for await (const chunk of stream) process[channel].write(chunk); }; const joined = await Promise.allSettled([tests.exited, relay(tests.stdout, "stdout"), relay(tests.stderr, "stderr")]); await tests.finish(); + invokingHome.assertUnchanged(); result = joined[0].status === "fulfilled" ? joined[0].value : 1; if (joined.some(item => item.status === "rejected")) result = result || 1; if (tests.signalCode) result = 128 + (constants.signals[tests.signalCode] ?? 0); @@ -252,7 +256,7 @@ if (import.meta.main) { finally { const stopped = await Promise.allSettled(stopping); if (stopped.some(item => item.status === "rejected")) { console.error("Invocation child cleanup failed", stopped); result = result || 1; } - dispose(); + try { dispose(); } finally { invokingHome?.dispose(); } signals.forEach((signal, index) => process.off(signal, listeners[index]!)); } process.exit(cancelled ? 128 + (constants.signals[cancelled] ?? 0) : result); diff --git a/tests/experiment-tier.test.ts b/tests/experiment-tier.test.ts index 36026cd4b0..e2028980ff 100644 --- a/tests/experiment-tier.test.ts +++ b/tests/experiment-tier.test.ts @@ -16,7 +16,7 @@ import { } from "../scripts/test-experiments"; const ROOT = join(import.meta.dir, ".."); -const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-claude-home-guard.ts", +const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; const passing = (name: string) => `import { expect, test } from "bun:test";\ntest(${JSON.stringify(name)}, () => expect(1).toBe(1));\n`; diff --git a/tests/helpers/test-invocation-fixture.ts b/tests/helpers/test-invocation-fixture.ts index d8748c12c5..2ec8c434bb 100644 --- a/tests/helpers/test-invocation-fixture.ts +++ b/tests/helpers/test-invocation-fixture.ts @@ -10,7 +10,7 @@ export function invocationFixture(parent = tmpdir()) { write("bun.lock", "{}\n"); write(".gitignore", "node_modules/\npackages/*/dist/\ntmp/\n"); write("tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2019", module: "ESNext", moduleResolution: "Bundler", types: [], skipLibCheck: true } })); - for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-claude-home-guard.ts", "test-network-guard.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { + for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { write(`scripts/${file}`, readFileSync(join(source, "scripts", file), "utf8")); } for (const file of ["packages/core/tests/cli-harness.ts", "packages/ui-react/tests/fixtures/runtime-package-build.ts", "packages/ui-react/tests/fixtures/runtime-hook-phases.ts"]) write(file, readFileSync(join(source, file), "utf8")); diff --git a/tests/helpers/unit-worker-fixture.ts b/tests/helpers/unit-worker-fixture.ts index 4ae00e7961..f1ed4f54d3 100644 --- a/tests/helpers/unit-worker-fixture.ts +++ b/tests/helpers/unit-worker-fixture.ts @@ -74,7 +74,7 @@ const stop=Date.now()+5000;while((!existsSync(join(shared,"built-1"))||!existsSy ${options.failBuild ? "process.exit(7);" : ""} mkdirSync("dist",{recursive:true});writeFileSync("dist/lease.json",JSON.stringify({lease:JSON.parse(process.env.BRAIN_WORKSPACE_LEASE),nonce:process.env.BRAIN_TEST_INVOCATION_NONCE}));writeFileSync("dist/ready.txt","Odysseus builds the raft.");receipt.packageEnd("raft",true);receipt.finish(0);\n`); for (const file of ["scripts/test.ts", "scripts/runtime-test-builds.ts", "scripts/test-invocation.ts", "scripts/test-invocation-child.ts", "scripts/publishable-packages.ts", - "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-claude-home-guard.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "packages/core/tests/cli-harness.ts"]) { + "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "packages/core/tests/cli-harness.ts"]) { write(file, readFileSync(join(source, file), "utf8")); } const files = ["odysseus", "penelope"].map(name => `tests/${name}.test.ts`); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index 4731e232fb..2c63f2d581 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -400,7 +400,7 @@ function importFixture() { const dir = fixture(); const root = join(import.meta.dir, ".."); mkdirSync(join(dir, "scripts")); - for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-claude-home-guard.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(root, "scripts", helper), join(dir, "scripts", helper)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/test-home.test.ts b/tests/test-home.test.ts index 8c6f7ce363..d778843478 100644 --- a/tests/test-home.test.ts +++ b/tests/test-home.test.ts @@ -1,8 +1,9 @@ -import { expect, test } from "bun:test"; +import { expect, spyOn, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import * as fs from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { claudeHomeSnapshot, installTestHome } from "../scripts/test-home"; +import { claudeHomeSnapshot, createInvokingTestHome, installTestHome } from "../scripts/test-home"; for (const configPresent of [false, true]) { test(`test home restores environment descriptors with config ${configPresent ? "set" : "absent"} and snapshots detect host overwrites`, () => { @@ -38,3 +39,38 @@ for (const configPresent of [false, true]) { } }); } + +test("the invoking-home guard detects a same-size overwrite without adding paths", () => { + const invoking = createInvokingTestHome(); + try { + const sentinel = join(invoking.config, "sentinel"); + const bytes = readFileSync(sentinel); + expect(bytes.toString()).toBe("Odysseus: invoking storage stays untouched.\n"); + invoking.assertUnchanged(); + writeFileSync(sentinel, Buffer.alloc(bytes.length, 120)); + expect(readFileSync(sentinel).length).toBe(bytes.length); + expect(() => invoking.assertUnchanged()).toThrow("TEST_WROTE_INVOKING_CLAUDE_HOME"); + } finally { invoking.dispose(); } + expect(existsSync(invoking.root)).toBe(false); +}); + +test("home isolation leaves filesystem originals and descriptors available to fixture spies", () => { + const descriptor = Object.getOwnPropertyDescriptor(fs, "mkdtempSync")!; + const original = fs.mkdtempSync; + const created: string[] = []; + const observe = ((...args: Parameters) => { + const path = Reflect.apply(original, fs, args); + created.push(String(path)); + return path; + }) as typeof original; + const spy = spyOn(fs, "mkdtempSync").mockImplementation(observe); + try { + const path = fs.mkdtempSync(join(tmpdir(), "odysseus-home-spy-")); + expect(existsSync(path)).toBe(true); + expect(created).toEqual([path]); + } finally { + spy.mockRestore(); + Object.defineProperty(fs, "mkdtempSync", descriptor); + for (const path of created) rmSync(path, { recursive: true, force: true }); + } +}); diff --git a/tests/test-script.test.ts b/tests/test-script.test.ts index 3c2eb980c2..0c48044114 100644 --- a/tests/test-script.test.ts +++ b/tests/test-script.test.ts @@ -33,7 +33,7 @@ async function run(args: string[], env: Record = {}) { if (existsSync(script)) { mkdirSync(join(dir, "scripts")); cpSync(script, join(dir, "scripts/test.ts")); - for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-claude-home-guard.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", helper), join(dir, "scripts", helper)); } // The actual preload also owns cleanup for the shared CLI harness. diff --git a/tests/test-shards.test.ts b/tests/test-shards.test.ts index 1f90b63d3e..af68c6b9da 100644 --- a/tests/test-shards.test.ts +++ b/tests/test-shards.test.ts @@ -59,7 +59,7 @@ describe("balanced shards run the root command for real", () => { mkdirSync(join(dir, "scripts")); const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "fixture", scripts: { test: manifest.scripts.test } })); - for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-claude-home-guard.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/workspace-lease.test.ts b/tests/workspace-lease.test.ts index 2b587d4d4f..09e487f8dc 100644 --- a/tests/workspace-lease.test.ts +++ b/tests/workspace-lease.test.ts @@ -281,7 +281,7 @@ test("the real pinned container wrapper waits for host ownership of its mounted test("direct Bun test preserves its selector, timeout and offline preload while waiting", async () => { const root = fixture(); mkdirSync(join(root, "scripts")); mkdirSync(join(root, "packages/core/tests"), { recursive: true }); - for (const name of ["test-network-preload.ts", "test-home.ts", "test-claude-home-guard.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { copyFileSync(join(project, "scripts", name), join(root, "scripts", name)); } copyFileSync(join(project, "packages/core/tests/cli-harness.ts"), join(root, "packages/core/tests/cli-harness.ts")); From 0c059885f53c46baa599164fe9c8bb16b2f6d59f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 21:59:29 +0000 Subject: [PATCH 5/5] test: restore filesystem descriptors through a local module handle --- tests/test-home.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test-home.test.ts b/tests/test-home.test.ts index d778843478..c9b5b878c1 100644 --- a/tests/test-home.test.ts +++ b/tests/test-home.test.ts @@ -1,6 +1,5 @@ import { expect, spyOn, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import * as fs from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { claudeHomeSnapshot, createInvokingTestHome, installTestHome } from "../scripts/test-home"; @@ -54,7 +53,8 @@ test("the invoking-home guard detects a same-size overwrite without adding paths expect(existsSync(invoking.root)).toBe(false); }); -test("home isolation leaves filesystem originals and descriptors available to fixture spies", () => { +test("home isolation leaves filesystem originals and descriptors available to fixture spies", async () => { + const fs = await import("node:fs"); const descriptor = Object.getOwnPropertyDescriptor(fs, "mkdtempSync")!; const original = fs.mkdtempSync; const created: string[] = [];