diff --git a/docs/process/testing.md b/docs/process/testing.md index ba9d567ef8..0d7a30381c 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -56,6 +56,20 @@ 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. 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. + ### 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..ab58ac8fce --- /dev/null +++ b/packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts @@ -0,0 +1,40 @@ +/** 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 storageWasOwned = true; + try { + 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: (): 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] } : {}), + 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); + storageWasOwned &&= storage.startsWith((mode === "override" ? join(root, "config") : join(process.env.HOME!, ".claude")) + "/"); + } + expect(records).toEqual([1, 1, 1]); + if (process.env.ODYSSEUS_ISOLATION_REPORT) writeFileSync(process.env.ODYSSEUS_ISOLATION_REPORT, + 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 new file mode 100644 index 0000000000..7e91fa2d6f --- /dev/null +++ b/packages/ui-backend-claude/tests/host-storage-isolation.test.ts @@ -0,0 +1,31 @@ +/** 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, 1]); + expect(report.storageWasOwned).toBe(true); + expect(existsSync(report.home)).toBe(false); + } finally { rmSync(root, { recursive: true, force: true }); } +}); diff --git a/scripts/test-home.ts b/scripts/test-home.ts new file mode 100644 index 0000000000..6ffdfe30c1 --- /dev/null +++ b/scripts/test-home.ts @@ -0,0 +1,62 @@ +/** Test-owned host storage; production's HOME fallback remains untouched. */ +import { lstatSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } 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 }); + }, + }; +} + +/** 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 afa60694a5..ad43c1f120 100644 --- a/scripts/test-network-preload.ts +++ b/scripts/test-network-preload.ts @@ -1,6 +1,7 @@ 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 { join, resolve } from "node:path"; import { mkdirSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -9,6 +10,7 @@ import { ensureWorkspaceLease, processIdentity, workspaceTestAccess } from "./wo const guard = installNetworkGuard(); const coordinated = await ensureWorkspaceLease(resolve(import.meta.dir, ".."), workspaceTestAccess(), "test"); if (coordinated !== undefined) process.exit(coordinated); +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 @@ -29,5 +31,6 @@ afterAll(() => { } finally { cleanupCliUtilities(); rmSync(privateAdmission, { recursive: true, force: true }); + 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 620daa0acf..ce6404a43c 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-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..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-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 474a30d410..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-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 9dda8e5acf..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-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 new file mode 100644 index 0000000000..c9b5b878c1 --- /dev/null +++ b/tests/test-home.test.ts @@ -0,0 +1,76 @@ +import { expect, spyOn, 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, 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`, () => { + 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 }); + } + } + }); +} + +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", async () => { + const fs = await import("node:fs"); + 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 c8749b7fa8..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-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 fd415d32bd..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-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 bccaaa810b..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-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"));