Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/process/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 11 additions & 4 deletions packages/ui-backend-claude/tests/confirm-bash.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));

Expand Down Expand Up @@ -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;
Expand All @@ -156,7 +163,7 @@ describe("unparseable patterns", () => {
const calls: Array<{ level: string; message: string; attrs?: Record<string, unknown> }> = [];

createClaudeBackend({
brainPath: "/tmp",
brainPath,
confirmBashPatterns: ["(unclosed", String.raw`\brm\s`],
log: (level, message, attrs) => calls.push({ level, message, attrs }),
});
Expand Down Expand Up @@ -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 } : {}),
Expand Down
Original file line number Diff line number Diff line change
@@ -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<string, string> => 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 }); }
});
31 changes: 31 additions & 0 deletions packages/ui-backend-claude/tests/host-storage-isolation.test.ts
Original file line number Diff line number Diff line change
@@ -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 }); }
});
62 changes: 62 additions & 0 deletions scripts/test-home.ts
Original file line number Diff line number Diff line change
@@ -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 }); },
};
}
3 changes: 3 additions & 0 deletions scripts/test-network-preload.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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
Expand All @@ -29,5 +31,6 @@ afterAll(() => {
} finally {
cleanupCliUtilities();
rmSync(privateAdmission, { recursive: true, force: true });
testHome.dispose();
}
});
8 changes: 6 additions & 2 deletions scripts/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<typeof createInvokingTestHome> | undefined;
let result = 1;
try {
const paths = testPaths(argv);
Expand All @@ -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<Uint8Array>, 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);
Expand All @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion tests/experiment-tier.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`;
Expand Down
2 changes: 1 addition & 1 deletion tests/helpers/test-invocation-fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
Expand Down
2 changes: 1 addition & 1 deletion tests/helpers/unit-worker-fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`);
Expand Down
2 changes: 1 addition & 1 deletion tests/local-checks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down
Loading
Loading