repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

test: isolate extension harness env

611bc6fcff050d7a1885dba0f5c07d16926cb94b

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (34)

extensions/angel/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("angel pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/builtin-tools/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("builtin-tools pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/context-size/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("context-size pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/cost/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
7 4 import { __test } from "../index.ts";
9 6 describe("cost pi-test-harness", () => {

extensions/ctx/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, beforeEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 let t: TestSession | undefined;

extensions/cwd/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("cwd pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/devil/__tests__/harness.test.ts

Modified
1 -import {
2 - createTestSession,
3 - type TestSession,
4 -} from "@marcfargas/pi-test-harness";
5 1 import { afterEach, describe, expect, it } from "vitest";
2 +import { createTestSession, type TestSession } from "../../../test/harness";
7 4 let t: TestSession | undefined;

extensions/diff-review/__tests__/harness.test.ts

Modified
2 2 import { execFile } from "node:child_process";
3 3 import { writeFile } from "node:fs/promises";
4 4 import path from "node:path";
5 5 import { promisify } from "node:util";
6 -import {
7 - createTestSession,
8 - type TestSession,
9 -} from "@marcfargas/pi-test-harness";
10 6 import { afterEach, describe, expect, it } from "vitest";
7 +import { createTestSession, type TestSession } from "../../../test/harness";
12 9 const execFileAsync = promisify(execFile);
13 10 const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

extensions/fast/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("fast pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/footer/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("footer pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/git-safe/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("git-safe pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/leaks/__tests__/harness.test.ts

Modified
1 1 import { mkdirSync, writeFileSync } from "node:fs";
2 2 import os from "node:os";
3 3 import path from "node:path";
4 +import { afterEach, describe, expect, it } from "vitest";
4 5 import {
5 6 createTestSession,
6 7 says,
7 8 type TestSession,
8 9 when,
9 -} from "@marcfargas/pi-test-harness";
10 -import { afterEach, describe, expect, it } from "vitest";
10 +} from "../../../test/harness";
12 12 function extPath() {
13 13 return path.resolve(import.meta.dirname, "../index.ts");

extensions/llmiterate/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("llmiterate pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/model-info/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
7 4 import { __test } from "../index.ts";
9 6 describe("model-info pi-test-harness", () => {

extensions/neko/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("neko pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/nu-bang/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("nu-bang pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/prompt-autopsy/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("prompt-autopsy pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/pulse/__tests__/harness.test.ts

Modified
1 1 import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2 2 import path from "node:path";
3 -import {
4 - createTestSession,
5 - type TestSession,
6 -} from "@marcfargas/pi-test-harness";
7 3 import { afterEach, describe, expect, it } from "vitest";
4 +import { createTestSession, type TestSession } from "../../../test/harness";
9 6 let t: TestSession | undefined;

extensions/q/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("q pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/quota/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
7 4 import { __test } from "../index.ts";
9 6 describe("quota pi-test-harness", () => {

extensions/runtime/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("runtime pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/session-rename/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("session-rename pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/ssh-tools/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("ssh-tools pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/superpowers/__tests__/harness.test.ts

Modified
1 +import { execSync } from "node:child_process";
1 2 import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2 3 import path from "node:path";
4 +import { afterEach, describe, expect, it } from "vitest";
3 5 import {
4 6 createTestSession,
7 + sandboxEnv,
5 8 type TestSession,
6 -} from "@marcfargas/pi-test-harness";
7 -import { afterEach, describe, expect, it } from "vitest";
9 + withProcessEnvSync,
10 +} from "../../../test/harness";
8 11 import { __test } from "../index.ts";
10 13 let t: TestSession | undefined;
27 30 const notices = () =>
28 31 t?.events.uiCallsFor("notify").map((c) => String(c.args[0]));
29 -const tasksPath = () => __test.tasksFile(t?.cwd);
32 +const tasksPath = () => {
33 + if (!t) throw new Error("test session not initialized");
34 + return withProcessEnvSync(t.env, () => __test.tasksFile(t.cwd));
35 +};
30 36 const tasks = () => JSON.parse(readFileSync(tasksPath(), "utf8"));
31 37 const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
38 +function env() {
39 + if (!t) throw new Error("test session not initialized");
40 + return sandboxEnv(t.cwd);
42 +function initGitRepo() {
43 + if (!t) throw new Error("test session not initialized");
44 + const gitEnv = env();
45 + execSync("git init --initial-branch=trunk --quiet", {
46 + cwd: t.cwd,
47 + env: gitEnv,
48 + });
49 + execSync("git config user.email test@test.com", { cwd: t.cwd, env: gitEnv });
50 + execSync("git config user.name Test", { cwd: t.cwd, env: gitEnv });
51 + execSync("git config branch.autoSetupMerge false", {
52 + cwd: t.cwd,
53 + env: gitEnv,
54 + });
55 + writeFileSync(path.join(t.cwd, "file.txt"), "hello");
56 + execSync("git add .", { cwd: t.cwd, env: gitEnv });
57 + execSync("git commit -m init --quiet", { cwd: t.cwd, env: gitEnv });
58 + return gitEnv;
33 61 function fakeCtx(cwd: string, sessionFile: string) {
34 62 const entries: any[] = [];
297 325 it("starts, announces, reannounces, reports, and stops visual session", async () => {
298 326 t = await createTestSession({ extensions: [extPath()] });
299 - const prevNoOpen = process.env.PI_SUPERPOWERS_NO_OPEN;
300 - process.env.PI_SUPERPOWERS_NO_OPEN = "1";
327 + t.env.PI_SUPERPOWERS_NO_OPEN = "1";
302 329 await command().handler("visual start", ctx());
303 330 await waitFor(() =>
359 386 await command().handler("visual stop", ctx());
360 387 expect(notices().at(-1)).toBe("visual stopped");
361 388 } finally {
362 - if (prevNoOpen === undefined) delete process.env.PI_SUPERPOWERS_NO_OPEN;
363 - else process.env.PI_SUPERPOWERS_NO_OPEN = prevNoOpen;
389 + delete t.env.PI_SUPERPOWERS_NO_OPEN;
367 393 it("closes visual server on session shutdown", async () => {
368 394 t = await createTestSession({ extensions: [extPath()] });
369 - const prevNoOpen = process.env.PI_SUPERPOWERS_NO_OPEN;
370 - process.env.PI_SUPERPOWERS_NO_OPEN = "1";
395 + t.env.PI_SUPERPOWERS_NO_OPEN = "1";
372 397 await command().handler("visual start", ctx());
373 398 await waitFor(() =>
394 419 "visual server still accepted requests after shutdown",
396 421 } finally {
397 - if (prevNoOpen === undefined) delete process.env.PI_SUPERPOWERS_NO_OPEN;
398 - else process.env.PI_SUPERPOWERS_NO_OPEN = prevNoOpen;
422 + delete t.env.PI_SUPERPOWERS_NO_OPEN;
500 524 it("detects git standard checkout", async () => {
501 525 t = await createTestSession({ extensions: [extPath()] });
502 - // Initialize a git repo in the test cwd
503 - const { execSync } = await import("node:child_process");
504 - execSync("git init", { cwd: t.cwd });
505 - execSync("git config user.email test@test.com", { cwd: t.cwd });
506 - execSync("git config user.name Test", { cwd: t.cwd });
507 - writeFileSync(path.join(t.cwd, "file.txt"), "hello");
508 - execSync("git add .", { cwd: t.cwd });
509 - execSync("git commit -m init", { cwd: t.cwd });
526 + initGitRepo();
510 527 const repo = __test.detectRepo(t.cwd);
511 528 expect(repo).not.toBeNull();
512 529 expect(repo).toHaveProperty("type", "git");
516 533 it("creates and cleans up git worktree isolate", async () => {
517 534 t = await createTestSession({ extensions: [extPath()] });
518 - const { execSync } = await import("node:child_process");
519 - execSync("git init", { cwd: t.cwd });
520 - execSync("git config user.email test@test.com", { cwd: t.cwd });
521 - execSync("git config user.name Test", { cwd: t.cwd });
522 - writeFileSync(path.join(t.cwd, "file.txt"), "hello");
523 - execSync("git add .", { cwd: t.cwd });
524 - execSync("git commit -m init", { cwd: t.cwd });
535 + const gitEnv = initGitRepo();
525 536 const repo = __test.detectRepo(t.cwd);
526 537 expect(repo).not.toBeNull();
527 538 const piMock = {
528 539 exec: async (_cmd: string, _args: string[]) => {
529 - execSync([_cmd, ..._args].join(" "), { cwd: t.cwd });
540 + execSync([_cmd, ..._args].join(" "), {
541 + cwd: t.cwd,
542 + env: gitEnv,
543 + stdio: "pipe",
544 + });
531 546 } as any;
532 547 if (!repo) throw new Error("expected git repo");
541 556 it("skips isolate when --share is passed", async () => {
542 557 t = await createTestSession({ extensions: [extPath()] });
543 - const { execSync } = await import("node:child_process");
544 - execSync("git init", { cwd: t.cwd });
545 - execSync("git config user.email test@test.com", { cwd: t.cwd });
546 - execSync("git config user.name Test", { cwd: t.cwd });
547 - writeFileSync(path.join(t.cwd, "file.txt"), "hello");
548 - execSync("git add .", { cwd: t.cwd });
549 - execSync("git commit -m init", { cwd: t.cwd });
558 + initGitRepo();
550 559 mkdirSync(path.join(t.cwd, ".pi/prompts"), { recursive: true });
551 560 writeFileSync(
552 561 path.join(t.cwd, ".pi/prompts/echo.md"),

extensions/terminal-notifier/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("terminal-notifier pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/terminal-signals/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("terminal-signals pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/terse/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("terse pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/tldr/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("tldr pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/tps/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("tps pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/usage/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("usage pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/vcs-status/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("vcs-status pi-test-harness", () => {
9 6 let t: TestSession | undefined;

extensions/web/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 -import {
3 - createTestSession,
4 - type TestSession,
5 -} from "@marcfargas/pi-test-harness";
6 2 import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
8 5 describe("web extension harness", () => {
9 6 let t: TestSession | undefined;
10 7 afterEach(() => t?.dispose());
12 - it("registers web_fetch, web_search, and understand_image tools", async () => {
9 + it("registers web_fetch, web_map, web_search, and understand_image tools", async () => {
13 10 const webPath = path.resolve(import.meta.dirname, "../index.ts");
14 11 t = await createTestSession({ extensions: [webPath] });
16 13 const [extension] = t.session.extensionRunner.extensions;
17 14 expect([...extension.tools.keys()]).toContain("web_fetch");
15 + expect([...extension.tools.keys()]).toContain("web_map");
18 16 expect([...extension.tools.keys()]).toContain("web_search");
19 17 expect([...extension.tools.keys()]).toContain("understand_image");

scripts/extensions.py

Modified
191 191 return specs
194 +def is_allowed_test_import(file: Path, resolved: Path) -> bool:
195 + try:
196 + resolved.relative_to((ROOT / "test").resolve())
197 + except ValueError:
198 + return False
199 + return "__tests__" in file.parts
194 202 def err(errors: list[str], ext: Path, msg: str) -> None:
195 203 errors.append(f"{ext.name}: {msg}")
262 270 resolved.relative_to(ext.resolve())
263 271 except ValueError:
264 - err(
265 - errors,
266 - ext,
267 - f"cross-extension relative import {spec} in {file.relative_to(ext)}",
272 + if not is_allowed_test_import(file, resolved):
273 + err(
274 + errors,
275 + ext,
276 + f"cross-extension relative import {spec} in {file.relative_to(ext)}",
269 278 if SECRET_RE.search(text):
270 279 err(errors, ext, f"possible secret in {file.relative_to(ext)}")

test/harness.ts

Added
new file mode 100644
1 +import { mkdtempSync, rmSync } from "node:fs";
2 +import { tmpdir } from "node:os";
3 +import path from "node:path";
4 +import {
5 + type TestSession as BaseTestSession,
6 + type TestSessionOptions as BaseTestSessionOptions,
7 + createTestSession as createBaseTestSession,
8 + type SandboxOptions,
9 + type SandboxResult,
10 + verifySandboxInstall as verifyBaseSandboxInstall,
11 +} from "@marcfargas/pi-test-harness";
13 +export type {
14 + MockPi,
15 + MockPiCall,
16 + MockToolHandler,
17 + MockUIConfig,
18 + PlaybookAction,
19 + SandboxOptions,
20 + SandboxResult,
21 + TestEvents,
22 + ToolCallRecord,
23 + ToolResultRecord,
24 + Turn,
25 + UICallRecord,
26 +} from "@marcfargas/pi-test-harness";
27 +export {
28 + calls,
29 + createMockPi,
30 + safeRmSync,
31 + says,
32 + ToolBlockedError,
33 + when,
34 +} from "@marcfargas/pi-test-harness";
36 +export interface HarnessEnvOptions {
37 + /** Explicit env additions. Undefined deletes the key. */
38 + env?: Record<string, string | undefined>;
39 + /** Ambient env keys to copy intentionally. */
40 + inheritEnv?: string[];
43 +export type HarnessTestSessionOptions = BaseTestSessionOptions &
44 + HarnessEnvOptions;
45 +export type HarnessTestSession = BaseTestSession & { env: NodeJS.ProcessEnv };
46 +export type TestSession = HarnessTestSession;
47 +export type TestSessionOptions = HarnessTestSessionOptions;
49 +const BASE_ENV_KEYS = [
50 + "PATH",
51 + "Path",
52 + "PATHEXT",
53 + "SystemRoot",
54 + "WINDIR",
55 + "COMSPEC",
56 + "TMPDIR",
57 + "TMP",
58 + "TEMP",
59 + "SHELL",
60 + "TERM",
61 + "COLORTERM",
62 + "NO_COLOR",
63 + "FORCE_COLOR",
64 + "CI",
65 + "VITEST",
66 + "VITEST_POOL_ID",
67 + "VITEST_WORKER_ID",
68 + "NODE_OPTIONS",
69 +];
71 +export function sandboxEnv(
72 + root: string,
73 + options: HarnessEnvOptions = {},
74 +): NodeJS.ProcessEnv {
75 + const env: NodeJS.ProcessEnv = {};
76 + for (const key of BASE_ENV_KEYS) copyIfSet(env, process.env, key);
77 + for (const key of options.inheritEnv ?? []) copyIfSet(env, process.env, key);
79 + env.HOME = path.join(root, ".test-home");
80 + env.USERPROFILE = env.HOME;
81 + env.XDG_CONFIG_HOME = path.join(root, ".test-config");
82 + env.XDG_CACHE_HOME = path.join(root, ".test-cache");
83 + env.XDG_STATE_HOME = path.join(root, ".test-state");
84 + env.XDG_DATA_HOME = path.join(root, ".test-data");
86 + for (const [key, value] of Object.entries(options.env ?? {})) {
87 + if (value === undefined) delete env[key];
88 + else env[key] = value;
89 + }
90 + return env;
93 +export async function createTestSession(
94 + options: HarnessTestSessionOptions = {},
95 +): Promise<HarnessTestSession> {
96 + const { env: envOverrides, inheritEnv, ...baseOptions } = options;
97 + const ownsCwd = !baseOptions.cwd;
98 + const cwd =
99 + baseOptions.cwd ?? mkdtempSync(path.join(tmpdir(), "pi-test-harness-"));
100 + const originalEnv = { ...process.env };
101 + const env = sandboxEnv(cwd, { env: envOverrides, inheritEnv });
102 + replaceProcessEnv(env);
103 + let session: BaseTestSession;
104 + try {
105 + session = await createBaseTestSession({ ...baseOptions, cwd });
106 + } catch (error) {
107 + replaceProcessEnv(originalEnv);
108 + if (ownsCwd) rmSync(cwd, { recursive: true, force: true });
109 + throw error;
111 + const wrapped = Object.assign(session, {
112 + env: process.env,
113 + }) as HarnessTestSession;
114 + wrapSessionEnv(wrapped);
115 + const dispose = session.dispose.bind(session);
116 + wrapped.dispose = () => {
117 + dispose();
118 + if (ownsCwd) rmSync(cwd, { recursive: true, force: true });
119 + replaceProcessEnv(originalEnv);
120 + };
121 + return wrapped;
124 +export async function verifySandboxInstall(
125 + options: SandboxOptions & HarnessEnvOptions,
126 +): Promise<SandboxResult> {
127 + const { env, inheritEnv, ...baseOptions } = options;
128 + return await withProcessEnv(
129 + sandboxEnv(baseOptions.packageDir, { env, inheritEnv }),
130 + () => verifyBaseSandboxInstall(baseOptions),
131 + );
134 +function wrapSessionEnv(session: HarnessTestSession): void {
135 + const run = session.run.bind(session);
136 + session.run = (...turns) => withProcessEnv(session.env, () => run(...turns));
138 + const prompt = session.session.prompt?.bind(session.session);
139 + if (prompt) {
140 + session.session.prompt = (...args: unknown[]) =>
141 + withProcessEnv(session.env, () => prompt(...args));
144 + const extensionRunner = session.session.extensionRunner;
145 + const emit = extensionRunner?.emit?.bind(extensionRunner);
146 + if (emit) {
147 + extensionRunner.emit = (...args: unknown[]) =>
148 + withProcessEnv(session.env, () => emit(...args));
151 + for (const extension of extensionRunner?.extensions ?? []) {
152 + for (const command of extension.commands?.values?.() ?? []) {
153 + if (typeof command.handler !== "function") continue;
154 + const handler = command.handler.bind(command);
155 + command.handler = (...args: unknown[]) =>
156 + withProcessEnv(session.env, () => handler(...args));
158 + for (const tool of extension.tools?.values?.() ?? []) {
159 + const definition = tool.definition;
160 + if (typeof definition?.execute !== "function") continue;
161 + const execute = definition.execute.bind(definition);
162 + definition.execute = (...args: unknown[]) =>
163 + withProcessEnv(session.env, () => execute(...args));
168 +export async function withProcessEnv<T>(
169 + env: NodeJS.ProcessEnv,
170 + fn: () => T | Promise<T>,
171 +): Promise<T> {
172 + const original = { ...process.env };
173 + const next = { ...env };
174 + replaceProcessEnv(next);
175 + try {
176 + return await fn();
177 + } finally {
178 + replaceProcessEnv(original);
182 +export function withProcessEnvSync<T>(env: NodeJS.ProcessEnv, fn: () => T): T {
183 + const original = { ...process.env };
184 + const next = { ...env };
185 + replaceProcessEnv(next);
186 + try {
187 + return fn();
188 + } finally {
189 + replaceProcessEnv(original);
193 +function replaceProcessEnv(env: NodeJS.ProcessEnv): void {
194 + for (const key of Object.keys(process.env)) delete process.env[key];
195 + Object.assign(process.env, env);
198 +function copyIfSet(
199 + to: NodeJS.ProcessEnv,
200 + from: NodeJS.ProcessEnv,
201 + key: string,
202 +): void {
203 + const value = from[key];
204 + if (value !== undefined) to[key] = value;