import { readdirSync, readFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { afterEach, describe, expect, it, vi } from "vitest"; import { createPiSession, type PiSession, } from "../../../test/fixture/create-pi-session.ts"; const extensionPath = fileURLToPath(new URL("../index.ts", import.meta.url)); describe("context-size debug", () => { let session: PiSession | undefined; afterEach(async () => { await session?.dispose(); session = undefined; }); it("writes its lifecycle JSONL through the standalone factory", async () => { // The fixture applies env BEFORE loading, so the debug module reads // PI_CONTEXT_SIZE_DEBUG at import; no withProcessEnv/vi.resetModules needed. session = await createPiSession({ extensionPaths: [extensionPath], env: { PI_CONTEXT_SIZE_DEBUG: "1" }, }); const runner = session.session.extensionRunner; await runner.emit({ type: "session_start", reason: "startup" }); await runner.emit({ type: "session_shutdown", reason: "quit" }); const stateHome = session.env["XDG_STATE_HOME"]; if (!stateHome) throw new Error("missing sandbox state home"); const directory = path.join(stateHome, "pi-ext", "debug", "context-size"); // Debug records flush asynchronously; poll until both events appear. const events = await vi.waitFor(() => { const [file] = readdirSync(directory); if (!file) throw new Error("no debug file yet"); const parsed = readFileSync(path.join(directory, file), "utf8") .trim() .split("\n") .map((line) => JSON.parse(line).event); if ( !parsed.includes("session.start") || !parsed.includes("session.shutdown") ) throw new Error("lifecycle events not flushed yet"); return parsed; }); expect(events).toEqual( expect.arrayContaining(["session.start", "session.shutdown"]), ); }); });