repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/lazy/__tests__/unit.test.ts

Raw
File outline
import { mkdirSync, writeFileSync } from "node:fs";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import lazyExtension from "../index.ts";
import {
	loadLazySettingsForCwd,
	mergeLazySettings,
	pickLazy,
	settingsSnippet,
} from "../src/config.ts";
import {
	formatDebt,
	markersFromUnifiedDiff,
	parseLazyMarker,
	scanLazyDebt,
} from "../src/debt.ts";
import {
	buildLazyInstructions,
	injectLazyInstructions,
} from "../src/instructions.ts";
import {
	isStandaloneDeactivation,
	modeFromBareDefault,
	normalizeMode,
	parseLazyCommand,
} from "../src/modes.ts";

let dirs: string[] = [];

afterEach(async () => {
	for (const dir of dirs) await rm(dir, { recursive: true, force: true });
	dirs = [];
});

async function tempDir(): Promise<string> {
	const dir = await mkdtemp(path.join(tmpdir(), "lazy-test-"));
	dirs.push(dir);
	return dir;
}

describe("modes", () => {
	it("normalizes only lazy modes", () => {
		expect(normalizeMode("OFF")).toBe("off");
		expect(normalizeMode("lite")).toBe("lite");
		expect(normalizeMode("review")).toBeUndefined();
	});

	it("falls back from default off to full for bare command", () => {
		expect(modeFromBareDefault("off")).toBe("full");
		expect(parseLazyCommand("", "off")).toEqual({ kind: "set", mode: "full" });
	});

	it("parses status and default", () => {
		expect(parseLazyCommand("status", "full")).toEqual({ kind: "status" });
		expect(parseLazyCommand("/lazy status", "full")).toEqual({
			kind: "status",
		});
		expect(parseLazyCommand("default ultra", "full")).toEqual({
			kind: "default",
			mode: "ultra",
		});
	});

	it("matches only standalone deactivation", () => {
		expect(isStandaloneDeactivation("stop lazy!")).toBe(true);
		expect(isStandaloneDeactivation("normal mode.")).toBe(true);
		expect(isStandaloneDeactivation("add a normal mode toggle")).toBe(false);
	});
});

describe("config", () => {
	it("picks and merges valid lazy settings only", () => {
		expect(
			pickLazy({ lazy: { defaultMode: "ultra", status: false, nope: true } }),
		).toEqual({ defaultMode: "ultra", status: false });
		expect(pickLazy({ lazy: { defaultMode: "review" } })).toEqual({});
		expect(
			mergeLazySettings({ defaultMode: "lite" }, { status: false }),
		).toEqual({
			defaultMode: "lite",
			status: false,
		});
	});

	it("loads runtime Pi settings and ignores workspace-root settings.json", async () => {
		const dir = await tempDir();
		writeFileSync(
			path.join(dir, "settings.json"),
			JSON.stringify({ lazy: { defaultMode: "lite" } }),
		);

		expect(
			loadLazySettingsForCwd(dir, {
				settingsManager: {
					getSettings: () => ({ lazy: { defaultMode: "ultra" } }),
				},
			}).defaultMode,
		).toBe("ultra");

		expect(
			loadLazySettingsForCwd(dir, {
				settingsManager: { getSettings: () => ({}) },
			}).defaultMode,
		).toBe("full");
	});

	it("prints settings snippet", () => {
		expect(settingsSnippet("off")).toContain('"defaultMode": "off"');
	});
});

describe("instructions", () => {
	it("builds active header and excludes inactive mode lines", () => {
		const block = buildLazyInstructions("lite");
		expect(block).toContain("LAZY MODE ACTIVE — level: lite");
		expect(block).toContain("Root-cause bug-fix rule:");
		expect(block).not.toContain("Deletion first");
	});

	it("includes concrete over-engineering guardrails", () => {
		const block = buildLazyInstructions("full");
		expect(block).toContain("No unrequested abstractions");
		expect(block).toContain("same size");
		expect(block).toContain("`lazy:`");
	});

	it("before_agent_start tolerates a missing event or prompt", () => {
		const events = new Map<string, (...args: never[]) => unknown>();
		lazyExtension({
			on: (name: string, handler: (...args: never[]) => unknown) =>
				events.set(name, handler),
			registerCommand: () => undefined,
			appendEntry: () => undefined,
		} as never);
		const ctx = {
			cwd: "/",
			hasUI: false,
			sessionManager: { getBranch: () => [] },
		};
		events.get("session_start")?.({} as never, ctx as never);
		const missingEvent = events.get("before_agent_start")?.(undefined as never);
		const missingPrompt = events.get("before_agent_start")?.({} as never);
		expect(missingEvent).toEqual({
			systemPrompt: expect.stringContaining("LAZY MODE ACTIVE"),
		});
		expect(JSON.stringify(missingEvent)).not.toContain("undefined");
		expect(missingPrompt).toEqual({
			systemPrompt: expect.stringContaining("LAZY MODE ACTIVE"),
		});
	});

	it("injects idempotently", () => {
		const once = injectLazyInstructions("BASE", "full");
		const twice = injectLazyInstructions(once, "ultra");
		expect(twice.match(/LAZY MODE ACTIVE/g)).toHaveLength(1);
		expect(twice).toContain("level: ultra");
		expect(twice).not.toContain("level: full");
	});
});

describe("debt", () => {
	it("parses markers and missing triggers", () => {
		expect(
			parseLazyMarker("// lazy: cap at 10 until > 10 users", "a.ts", 3),
		).toEqual({
			file: "a.ts",
			line: 3,
			ceiling: "cap at 10",
			trigger: "> 10 users",
			noTrigger: false,
		});
		expect(parseLazyMarker("# lazy: ship quick", "a.sh", 1)?.noTrigger).toBe(
			true,
		);
	});

	it("scans repo and skips heavy dirs", async () => {
		const dir = await tempDir();
		mkdirSync(path.join(dir, "src"), { recursive: true });
		mkdirSync(path.join(dir, "node_modules"), { recursive: true });
		writeFileSync(
			path.join(dir, "src", "a.ts"),
			"// lazy: rough until API stable\n",
		);
		writeFileSync(path.join(dir, "node_modules", "b.ts"), "// lazy: nope\n");
		const result = scanLazyDebt(dir);
		expect(result.markers).toHaveLength(1);
		expect(formatDebt(result)).toContain(
			"src/a.ts:1 ceiling: rough trigger: API stable",
		);
	});

	it("extracts added markers from unified diff", () => {
		const diff = [
			"diff --git a/a.ts b/a.ts",
			"+++ b/a.ts",
			"@@ -0,0 +1,2 @@",
			"+const x = 1;",
			"+// lazy: fake until real API",
		].join("\n");
		expect(markersFromUnifiedDiff(diff)).toEqual([
			{
				file: "a.ts",
				line: 2,
				ceiling: "fake",
				trigger: "real API",
				noTrigger: false,
			},
		]);
	});
});