Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/memory/__tests__/contract.test.ts

Raw
import { existsSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { fileURLToPath } from "node:url";
import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";
import { initTheme, type Theme } from "@earendil-works/pi-coding-agent";
import { afterEach, describe, expect, it } from "vitest";
import {
	createPiSession,
	type PiSession,
} from "../../../test/fixture/create-pi-session.ts";
import { MemoryStore } from "../src/store.ts";

const extensionPath = fileURLToPath(new URL("../index.ts", import.meta.url));
let box: PiSession | undefined;
afterEach(async () => {
	await box?.dispose();
	box = undefined;
});
async function start(options: { databasePath?: string } = {}) {
	box = await createPiSession({
		extensionPaths: [extensionPath],
		env: {
			PI_MEMORY_DATABASE_PATH: options.databasePath,
			PI_MEMORY_DEBUG: "0",
		},
	});
	expect(box.errors).toEqual([]);
	const extension = box.extensions[0];
	const tool = extension?.tools.get("memory")?.definition;
	if (!tool) throw new Error("missing memory tool");
	return {
		box,
		extension,
		tool,
		ctx: box.session.extensionRunner.createToolContext("fixture", undefined),
	};
}
const STORE_FACTS =
	"CREATE TABLE facts(entity TEXT, value TEXT, observed_at TEXT)";

describe("real Pi memory contract", () => {
	it("executes SQL through the real agent tool and records schema change", async () => {
		const { box } = await start();
		box.setResponses([
			fauxAssistantMessage(fauxToolCall("memory", { sql: STORE_FACTS }), {
				stopReason: "toolUse",
			}),
			fauxAssistantMessage("Table created."),
		]);
		await box.session.prompt("Create the synthetic fixture table only.");
		const result = box.session.messages.find(
			(message) =>
				message.role === "toolResult" && message.toolName === "memory",
		);
		expect(result).toMatchObject({
			isError: false,
			details: {
				schemaChanged: true,
				journalSeq: 1,
			},
		});
		expect(box.errors).toEqual([]);
	});

	it("validates arguments before opening any database", async () => {
		const { box, tool, ctx } = await start();
		await expect(
			tool.execute("test", { query: "SELECT 1" }, undefined, undefined, ctx),
		).rejects.toThrow(/invalid field/u);
		await expect(
			tool.execute("test", "not an object", undefined, undefined, ctx),
		).rejects.toThrow(/expected object/u);
		const defaultPath = join(box.cwd, ".data");
		expect(existsSync(defaultPath)).toBe(false);
	});

	it("surfaces guard denials as guiding failures", async () => {
		const { tool, ctx } = await start();
		await expect(
			tool.execute(
				"test",
				{ sql: "ATTACH '/tmp/evil.db' AS evil" },
				undefined,
				undefined,
				ctx,
			),
		).rejects.toThrow(/audit boundary/u);
		await expect(
			tool.execute(
				"test",
				{ sql: "INSERT INTO _journal VALUES(1)" },
				undefined,
				undefined,
				ctx,
			),
		).rejects.toThrow(/reserved/u);
	});

	it("reads reserved tables without denials", async () => {
		const { tool, ctx } = await start();
		const result = await tool.execute(
			"test",
			{ sql: "SELECT count(*) AS n FROM _guide", readonly: true },
			undefined,
			undefined,
			ctx,
		);
		// Direct execute returns an AgentToolResult; isError is only present on failures.
		expect(result.isError ?? false).toBe(false);
		const data = result.details as { rows: number[][] };
		expect(Number(data.rows[0]?.[0])).toBeGreaterThanOrEqual(10);
	});

	it("registers tool and command, no review shortcut, no polling state", async () => {
		const { extension } = await start();
		expect(extension?.tools.has("memory")).toBe(true);
		expect(extension?.commands.has("memory")).toBe(true);
		expect(extension?.shortcuts.size).toBe(0);
	});

	it("keeps data durable across sessions and journals every call", async () => {
		const owned = mkdtempSync(join(tmpdir(), "memory-contract-"));
		const databasePath = join(owned, "memory.sqlite");
		try {
			const first = await start({ databasePath });
			await first.tool.execute(
				"test",
				{ sql: STORE_FACTS },
				undefined,
				undefined,
				first.ctx,
			);
			await first.tool.execute(
				"test",
				{
					sql: "INSERT INTO facts VALUES('node', 'needs 26', '2026-10-30')",
				},
				undefined,
				undefined,
				first.ctx,
			);
			await first.box.dispose();
			box = undefined;
			// The fixture wipes its sandbox on dispose; the test-owned file survives.
			const reopened = await MemoryStore.open(databasePath);
			try {
				const journal = reopened.recentJournal(10);
				expect(journal).toHaveLength(2);
				expect(journal.map((row) => row.mode)).toEqual(["write", "ddl"]);
				const probe = new DatabaseSync(databasePath, { readOnly: true });
				const rows = probe
					.prepare("SELECT value FROM facts WHERE entity='node'")
					.all() as Array<{ value: string }>;
				expect(rows[0]?.value).toBe("needs 26");
				probe.close();
			} finally {
				reopened.close();
			}
		} finally {
			rmSync(owned, { recursive: true, force: true });
		}
	});

	it("renders compact calls/results with native expansion", async () => {
		const { tool, ctx } = await start();
		const result = await tool.execute(
			"test",
			{ sql: "SELECT 1 AS one" },
			undefined,
			undefined,
			ctx,
		);
		initTheme("dark", false);
		const theme = {
			fg: (_color: unknown, text: string) => text,
		} as unknown as Theme;
		const renderContext = {
			keyHint: () => "HOST-EXPAND",
			args: {},
			toolCallId: "fixture",
			invalidate: () => {},
			lastComponent: undefined,
			state: undefined,
			cwd: "/tmp",
		} as unknown as Parameters<NonNullable<typeof tool.renderCall>>[2];
		const call = tool.renderCall?.(
			{ sql: "SELECT 1 AS one" },
			theme,
			renderContext,
		);
		const callLines = (call as { render: (width: number) => string[] }).render(
			80,
		);
		expect(callLines.join("\n")).toContain("HOST-EXPAND");
		const expandedCall = tool.renderCall?.(
			{ sql: "SELECT 1 AS one" },
			theme,
			renderContext,
		);
		const expandedLines = (
			expandedCall as { render: (width: number) => string[] }
		).render(80);
		expect(expandedLines.join("\n")).toContain("SELECT 1 AS one");
		const rendered = tool.renderResult?.(
			result,
			{ expanded: false, isPartial: false },
			theme,
			renderContext,
		);
		const renderedLines = (
			rendered as { render: (width: number) => string[] }
		).render(80);
		expect(renderedLines.join("\n")).toContain("1 row(s)");
		const legacy = tool.renderCall?.({ sql: "SELECT 1 AS one" }, theme, {
			...renderContext,
			keyHint: undefined,
		} as never);
		expect(
			(legacy as { render: (width: number) => string[] }).render(80).join("\n"),
		).toContain("to expand");
	});
});