Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/devdocs/__tests__/contract.test.ts

Raw
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, expect, it, vi } from "vitest";
import {
	createPiSession,
	type PiSession,
} from "../../../test/fixture/create-pi-session.ts";

let box: PiSession | undefined;
const owned: string[] = [];
afterEach(async () => {
	await box?.dispose();
	box = undefined;
	vi.restoreAllMocks();
	for (const p of owned.splice(0)) rmSync(p, { recursive: true, force: true });
});
it("searches and reads registered installed docs through a real Pi tool, using personal db path", async () => {
	const root = mkdtempSync(join(tmpdir(), "devdocs-contract-"));
	owned.push(root);
	const path = join(root, "guide.md");
	writeFileSync(
		path,
		"# Example\n\n## Install\n\nInstall command reference.\n\n## Transactions\n\nAtomic transactions preserve prior content.",
	);
	const database = join(root, "personal", "docs.db");
	box = await createPiSession({
		extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
		env: { PI_DEVDOCS_DEBUG: "0", PI_DEVDOCS_DATABASE_PATH: undefined },
		userSettings: {
			devdocs: {
				databasePath: database,
				offline: true,
				enabledSources: ["manual"],
				sources: [{ id: "manual", target: "example", path, version: "1.2.3" }],
			},
		},
	});
	expect(box.errors).toEqual([]);
	const tool = box.extensions[0]?.tools.get("devdocs")?.definition;
	if (!tool) throw new Error("missing devdocs tool");
	const ctx = box.session.extensionRunner.createToolContext(
		"fixture",
		undefined,
	);
	const found = await tool.execute(
		"search",
		{
			action: "search",
			target: "example",
			query: "atomic transactions",
			version: "1.2.3",
		},
		undefined,
		undefined,
		ctx,
	);
	const data = found.details as {
		status: string;
		results: { ref: string; heading: string; source: string }[];
	};
	expect(data.status).toBe("ok");
	expect(data.results[0]?.heading).toContain("Transactions");
	expect(existsSync(database)).toBe(true);
	const read = await tool.execute(
		"read",
		{ action: "read", refs: [data.results[0]?.ref], budget: 1000 },
		undefined,
		undefined,
		ctx,
	);
	expect(read.content[0]).toMatchObject({
		type: "text",
		text: expect.stringContaining("Atomic transactions"),
	});
	expect(JSON.stringify(read.details).length).toBeLessThanOrEqual(1000);
});
it("retrieves a URL-only personal source through normal Pi settings and default engine construction", async () => {
	const remote = vi
		.spyOn(globalThis, "fetch")
		.mockImplementation(async (input) => {
			expect(String(input)).toBe("https://manual.example.test/transactions.md");
			return new Response(
				"# Transactions\n\nAtomic transactions preserve prior revisions.",
				{ headers: { "content-type": "text/markdown", etag: '"v1"' } },
			);
		});
	box = await createPiSession({
		extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
		env: { PI_DEVDOCS_DEBUG: "0", PI_DEVDOCS_DATABASE_PATH: undefined },
		userSettings: {
			devdocs: {
				enabledSources: ["remote-manual"],
				sources: [
					{
						id: "remote-manual",
						target: "example",
						url: "https://manual.example.test/transactions.md",
						format: "markdown",
						version: "1.2.3",
					},
				],
			},
		},
	});
	expect(box.errors).toEqual([]);
	const tool = box.extensions[0]?.tools.get("devdocs")?.definition;
	if (!tool) throw new Error("missing devdocs");
	const ctx = box.session.extensionRunner.createToolContext(
		"fixture",
		undefined,
	);
	const found = await tool.execute(
		"search",
		{
			action: "search",
			target: "example",
			query: "atomic transactions",
			version: "1.2.3",
		},
		undefined,
		undefined,
		ctx,
	);
	const data = found.details as {
		status: string;
		results: { ref: string; source: string }[];
	};
	expect(data.status).toBe("ok");
	expect(data.results[0]?.source).toBe("remote-manual");
	const read = await tool.execute(
		"read",
		{ action: "read", refs: [data.results[0]?.ref], budget: 2000 },
		undefined,
		undefined,
		ctx,
	);
	expect(read.content[0]).toMatchObject({
		type: "text",
		text: expect.stringContaining(
			"Atomic transactions preserve prior revisions",
		),
	});
	expect(remote).toHaveBeenCalledTimes(1);
});

it("rejects a relative personal db override without opening the default", async () => {
	box = await createPiSession({
		extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
		env: { PI_DEVDOCS_DEBUG: "0", PI_DEVDOCS_DATABASE_PATH: undefined },
		userSettings: { devdocs: { databasePath: "relative.db" } },
	});
	const tool = box.extensions[0]?.tools.get("devdocs")?.definition;
	if (!tool) throw new Error("missing devdocs");
	await expect(
		tool.execute(
			"status",
			{ action: "status" },
			undefined,
			undefined,
			box.session.extensionRunner.createToolContext("fixture", undefined),
		),
	).rejects.toThrow(/absolute/);
	expect(existsSync(join(box.cwd, ".cache", "pi", "devdocs", "cache.db"))).toBe(
		false,
	);
});