import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { CtxStore, defaultDbPath, executeCtxOperation, handleBashToolResult, registerCtxExtension, type CtxToolParams } from "../index.js"; let dir: string; let dbPath: string; beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "pi-ctx-test-")); dbPath = join(dir, "ctx.db"); process.env.PI_CTX_DB_PATH = dbPath; }); afterEach(() => { delete process.env.PI_CTX_DB_PATH; rmSync(dir, { recursive: true, force: true }); }); describe("ctx DB path", () => { test("defaults under current Pi session dir", () => { delete process.env.PI_CTX_DB_PATH; const sessionFile = join(dir, "sessions", "session.jsonl"); const path = defaultDbPath("/repo/project", { sessionManager: { getSessionFile: () => sessionFile }, }); expect(path).toStartWith(join(dir, "sessions", "ctx")); expect(path).toEndWith(".db"); }); test("uses SessionManager sessionDir when no session file exists", () => { delete process.env.PI_CTX_DB_PATH; const path = defaultDbPath("/repo/project", { sessionManager: { getSessionDir: () => join(dir, "session-dir") }, }); expect(path).toStartWith(join(dir, "session-dir", "ctx")); expect(path).toEndWith(".db"); }); }); describe("CtxStore", () => { test("indexes and searches chunks", () => { const store = new CtxStore(dbPath); const indexed = store.indexText({ kind: "test", label: "sample", text: "alpha beta\npanic stack trace\nomega" }); expect(indexed.chunkCount).toBeGreaterThan(0); const hits = store.search(["panic trace"], { limit: 3 }); expect(hits).toContain("panic stack trace"); store.close(); }); test("purges project DB content", () => { const store = new CtxStore(dbPath); store.indexText({ kind: "test", label: "sample", text: "alpha beta" }); expect(store.stats().sources).toBe(1); store.purge(); expect(store.stats().sources).toBe(0); store.close(); }); }); describe("ctx operations", () => { test("run-js returns printed findings", async () => { const store = new CtxStore(dbPath); const result = await executeCtxOperation(store, { op: "run-js", code: "console.log('answer', 41 + 1)", } satisfies CtxToolParams, dir); expect(result.isError).toBeFalsy(); expect(result.content[0].text).toContain("answer 42"); store.close(); }); test("file-py reads file as text", async () => { const file = join(dir, "data.txt"); writeFileSync(file, "one\ntwo\nthree\n", "utf8"); const store = new CtxStore(dbPath); const result = await executeCtxOperation(store, { op: "file-py", path: file, code: "print(len(text.splitlines()))", } satisfies CtxToolParams, dir); expect(result.content[0].text.trim()).toBe("3"); store.close(); }); test("large run output is indexed and returns pointer", async () => { const store = new CtxStore(dbPath); const result = await executeCtxOperation(store, { op: "run-js", code: "console.log('x'.repeat(110_000))", } satisfies CtxToolParams, dir); expect(result.content[0].text).toContain("ctx:stored"); expect(result.content[0].text).toContain("Use ctx search"); expect(store.stats().sources).toBe(1); store.close(); }); }); describe("bash auto-collapse", () => { test("uses fullOutputPath, stores raw, returns bounded replacement", () => { const full = join(dir, "bash.log"); const raw = "CTX_RAW_SENTINEL ".repeat(10_000); writeFileSync(full, raw, "utf8"); const store = new CtxStore(dbPath); const patch = handleBashToolResult(store, { toolName: "bash", input: { command: "python noisy.py" }, content: [{ type: "text", text: "[truncated]" }], details: { fullOutputPath: full, truncation: { truncated: true } }, isError: false, }); expect(patch).toBeDefined(); const text = patch!.content[0].text; expect(text).toContain("ctx:stored"); expect(text).not.toContain("CTX_RAW_SENTINEL"); expect(store.search(["CTX_RAW_SENTINEL"], { limit: 1 })).toContain("CTX_RAW_SENTINEL"); store.close(); }); test("large error output is searched for failures", () => { const full = join(dir, "bash-error.log"); writeFileSync(full, `${"noise\n".repeat(1000)}panic: exploded\nstack trace here\n`, "utf8"); const store = new CtxStore(dbPath); const patch = handleBashToolResult(store, { toolName: "bash", input: { command: "failing" }, content: [{ type: "text", text: "[truncated]" }], details: { fullOutputPath: full }, isError: true, }); expect(patch?.content[0].text).toContain("matched"); expect(patch?.content[0].text).toContain("panic"); store.close(); }); }); describe("extension registration", () => { test("registers one tool and one command", () => { const tools: any[] = []; const commands: Record = {}; const handlers: Record = {}; registerCtxExtension({ registerTool: (tool: any) => tools.push(tool), registerCommand: (name: string, command: any) => { commands[name] = command; }, on: (name: string, handler: Function) => { (handlers[name] ??= []).push(handler); }, }); expect(tools.map(t => t.name)).toEqual(["ctx"]); expect(Object.keys(commands)).toEqual(["ctx"]); expect(Object.keys(handlers)).toContain("tool_result"); }); });