Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/memory/__tests__/store.test.ts

Raw
import { mkdtempSync, readdirSync, rmSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { afterEach, describe, expect, it } from "vitest";
import { MemoryStore, V1DatabaseError } from "../src/store.ts";

let dir: string | undefined;
afterEach(() => {
	if (dir) {
		rmSync(dir, { recursive: true, force: true });
		dir = undefined;
	}
});
function fresh(): string {
	dir = mkdtempSync(join(tmpdir(), "memory-store-"));
	return join(dir, "memory.sqlite");
}

describe("memory store v2", () => {
	it("seeds guide and schema docs, stamps format, and reopens cleanly", async () => {
		const path = fresh();
		const store = await MemoryStore.open(path);
		const probe = new DatabaseSync(path, { readOnly: true });
		expect(
			(probe.prepare("SELECT count(*) AS n FROM _guide").get() as { n: number })
				.n,
		).toBeGreaterThanOrEqual(10);
		expect(
			(
				probe.prepare("SELECT count(*) AS n FROM _schema_docs").get() as {
					n: number;
				}
			).n,
		).toBeGreaterThanOrEqual(3);
		expect(
			(probe.prepare("PRAGMA user_version").get() as { user_version: number })
				.user_version,
		).toBe(2);
		expect(
			(
				probe.prepare("PRAGMA application_id").get() as {
					application_id: number;
				}
			).application_id,
		).toBe(0x50494d45);
		probe.close();
		const reopened = await MemoryStore.open(path);
		reopened.close();
		store.close();
	});

	it("refuses v1 databases and foreign files with guiding errors", async () => {
		fresh();
		const v1 = join(dir!, "v1.sqlite");
		const v1db = new DatabaseSync(v1);
		v1db.exec("CREATE TABLE memories(id TEXT PRIMARY KEY)");
		v1db.prepare("PRAGMA user_version=1").run();
		v1db.prepare("PRAGMA application_id=1346981189").run();
		v1db.close();
		await expect(MemoryStore.open(v1)).rejects.toThrow(V1DatabaseError);
		unlinkSync(v1);
		const foreign = join(dir!, "foreign.sqlite");
		const foreignDb = new DatabaseSync(foreign);
		foreignDb.exec("CREATE TABLE stuff(a)");
		foreignDb.prepare("PRAGMA user_version=1").run();
		foreignDb.close();
		await expect(MemoryStore.open(foreign)).rejects.toThrow(
			/Not an extension-owned/u,
		);
		unlinkSync(foreign);
		const newer = join(dir!, "newer.sqlite");
		const newerDb = new DatabaseSync(newer);
		newerDb.prepare("PRAGMA user_version=99").run();
		newerDb.close();
		await expect(MemoryStore.open(newer)).rejects.toThrow(
			/newer than this extension/u,
		);
		unlinkSync(newer);
	});

	it("journals entries and prunes by age and count", async () => {
		const store = await MemoryStore.open(fresh());
		for (let index = 0; index < 3; index++) {
			store.appendJournal({
				ts: new Date(
					Date.now() - (index === 0 ? 400 * 86_400_000 : 0),
				).toISOString(),
				actor: "agent",
				mode: "write",
				readonly: false,
				sql: `INSERT ${index}`,
				params: "[]",
				rowsReturned: 0,
				rowsWritten: 1,
				spilledTo: null,
				durationMs: 1,
				ok: true,
				error: null,
				tablesTouched: "[]",
				schemaChanged: false,
				attachedEscaped: false,
				undoPath: null,
			});
		}
		expect(store.recentJournal(10)).toHaveLength(3);
		const pruned = store.pruneRetention(new Date());
		expect(pruned.journal).toBe(1);
		expect(store.recentJournal(10)).toHaveLength(2);
		store.close();
	});

	it("restores tables, drops post-snapshot objects, and rebuilds FTS on undo", async () => {
		const path = fresh();
		const store = await MemoryStore.open(path);
		const raw = new DatabaseSync(path);
		raw.exec("CREATE TABLE facts(a TEXT, b INTEGER)");
		raw.exec("CREATE INDEX facts_a ON facts(a)");
		raw.prepare("INSERT INTO facts VALUES('x', 1), ('y', 2)").run();
		const snapshot = store.snapshotForUndo();
		expect(snapshot).not.toBeNull();
		raw.exec("DROP INDEX facts_a");
		raw.exec("UPDATE facts SET a='z'");
		raw.exec("CREATE TABLE extra(a TEXT)");
		raw.exec("CREATE INDEX idx_facts ON facts(b)");
		raw.exec("CREATE VIEW v AS SELECT * FROM facts");
		const restored = store.restoreSnapshot(snapshot!);
		expect(restored.failed).toEqual([]);
		expect(raw.prepare("SELECT a, b FROM facts ORDER BY a").all()).toEqual([
			{ a: "x", b: 1 },
			{ a: "y", b: 2 },
		]);
		expect(store.userTables()).not.toContain("extra");
		// View must be dropped; the pre-snapshot index must be recreated while
		// the post-snapshot index disappears with the undo.
		expect(() => raw.prepare("SELECT * FROM v").all()).toThrow();
		const indexNames = (name: string) =>
			raw
				.prepare("SELECT name FROM sqlite_master WHERE type='index' AND name=?")
				.all(name);
		expect(indexNames("facts_a")).toHaveLength(1);
		expect(indexNames("idx_facts")).toHaveLength(0);

		raw.exec("CREATE VIRTUAL TABLE ft USING fts5(body)");
		raw.prepare("INSERT INTO ft VALUES('hello world')").run();
		const ftsSnapshot = store.snapshotForUndo();
		raw.prepare("INSERT INTO ft VALUES('more text')").run();
		const ftsRestored = store.restoreSnapshot(ftsSnapshot!);
		expect(ftsRestored.failed).toEqual([]);
		expect(
			Number(raw.prepare("SELECT count(*) AS n FROM ft").get()?.["n"]),
		).toBe(1);
		expect(store.userTables()).toContain("facts");
		// Extension-owned tables survive every restore untouched.
		expect(store.recentJournal(10)).toHaveLength(0);
		raw.close();
		store.close();
	});

	it("bounds snapshots by count and reports capacity honestly", async () => {
		const path = fresh();
		const store = await MemoryStore.open(path);
		expect(store.undoCapacity().allowed).toBe(true);
		for (let index = 0; index < 25; index++) {
			expect(store.snapshotForUndo()).not.toBeNull();
		}
		expect(readdirSync(store.undoDir()).length).toBeLessThanOrEqual(20);
		store.close();
	});

	it("aggregates usage, size, and health for the viewer", async () => {
		const store = await MemoryStore.open(fresh());
		store.appendJournal({
			ts: new Date().toISOString(),
			actor: "agent",
			mode: "write",
			readonly: false,
			sql: "CREATE TABLE facts(a)",
			params: "[]",
			rowsReturned: 0,
			rowsWritten: 0,
			spilledTo: null,
			durationMs: 1,
			ok: true,
			error: null,
			tablesTouched: JSON.stringify(["facts"]),
			schemaChanged: true,
			attachedEscaped: false,
			undoPath: null,
		});
		store.sampleSizes();
		const usage = store.usageTableRows();
		expect(usage.length).toBeGreaterThanOrEqual(1);
		const facts = usage.find((row) => row.name === "facts");
		expect(facts?.writes).toBe(1);
		expect(facts?.flag).toBe("ZOMBIE");
		expect(store.callsPerDay(14).length).toBe(1);
		const totals = store.journalTotals(14);
		expect(totals.calls).toBe(1);
		const size = store.sizeOverview();
		expect(size.totalBytes).toBeGreaterThan(0);
		expect(size.pageCount).toBeGreaterThan(0);
		expect(size.objects.length).toBeGreaterThan(3);
		expect(store.growth().length).toBe(1);
		const health = await store.healthChecks(true);
		expect(health.verdict).toBe("ok");
		expect(health.checks.map((check) => check.status)).not.toContain("error");
		store.close();
	});
});