repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/iq/__tests__/harness.test.ts
RawFile outline
- judgment line 23
- theme line 43
- IQ pi-test-harness line 48
- t line 49
- root line 50
- afterEach line 51
- loads in the real Pi extension runtime line 59
- lazy-loads the command without requiring a UI line 69
- rejects non-TUI command execution without opening custom UI line 77
- scans, confirms, judges, and persists through the command path line 92
import {
mkdirSync,
mkdtempSync,
readdirSync,
rmSync,
utimesSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
fauxAssistantMessage,
fauxProvider,
fauxToolCall,
} from "@earendil-works/pi-ai";
import { SettingsManager, type Theme } from "@earendil-works/pi-coding-agent";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createTestSession, type TestSession } from "../../../test/harness";
import { runIqCommand } from "../implementation";
import iqExtension from "../index";
import { loadRecords } from "../storage";
function judgment() {
return fauxAssistantMessage(
fauxToolCall("record_judgment", {
chunk: 1,
observations: [
{
dimension: "comprehension_judgment",
rating: 4,
importance: 2,
confidence: 1,
eventIds: ["a1"],
observation: "Inspected the shared route before changing it.",
},
],
chunkSummary: "Sound root-cause work.",
}),
{ stopReason: "toolUse" },
);
}
const theme = {
fg: (_color: string, text: string) => text,
bold: (text: string) => text,
} as Theme;
describe("IQ pi-test-harness", () => {
let t: TestSession | undefined;
let root: string | undefined;
afterEach(() => {
t?.dispose();
if (root) rmSync(root, { recursive: true, force: true });
t = undefined;
root = undefined;
vi.restoreAllMocks();
});
it("loads in the real Pi extension runtime", async () => {
t = await createTestSession({ extensionFactories: [iqExtension] });
expect(t.session.extensionRunner.extensions).toHaveLength(1);
const command = t.session.extensionRunner.extensions[0]?.commands.get("iq");
expect(command).toBeDefined();
expect(command?.getArgumentCompletions?.("s")).toEqual([
expect.objectContaining({ value: "scan" }),
]);
});
it("lazy-loads the command without requiring a UI", async () => {
t = await createTestSession({ extensionFactories: [iqExtension] });
const command = t.session.extensionRunner.extensions[0]?.commands.get("iq");
await expect(
command?.handler("", { hasUI: false } as never),
).resolves.toBeUndefined();
});
it("rejects non-TUI command execution without opening custom UI", async () => {
t = await createTestSession({ extensionFactories: [iqExtension] });
const command = t.session.extensionRunner.extensions[0]?.commands.get("iq");
const notify = vi.fn();
await command?.handler("", {
hasUI: true,
mode: "rpc",
ui: { notify },
} as never);
expect(notify).toHaveBeenCalledWith(
"IQ requires interactive TUI mode",
"error",
);
});
it("scans, confirms, judges, and persists through the command path", async () => {
root = mkdtempSync(join(tmpdir(), "pi-iq-harness-"));
const sessionDir = join(root, "sessions");
const source = join(sessionDir, "representative.jsonl");
mkdirSync(sessionDir);
writeFileSync(
source,
[
{
type: "session",
version: 3,
id: "source-session",
timestamp: "2026-01-01T00:00:00Z",
cwd: "/repo",
},
{
type: "message",
id: "u1",
parentId: null,
timestamp: "2026-01-01T00:00:01Z",
message: { role: "user", content: "Fix the shared route." },
},
{
type: "message",
id: "a1",
parentId: "u1",
timestamp: "2026-01-01T00:00:02Z",
message: {
role: "assistant",
provider: "worker-provider",
model: "worker",
content: [{ type: "text", text: "Inspect callers first." }],
},
},
{
type: "message",
id: "t1",
parentId: "a1",
timestamp: "2026-01-01T00:00:03Z",
message: {
role: "toolResult",
toolName: "grep",
isError: false,
content: [{ type: "text", text: "three callers" }],
},
},
{
type: "message",
id: "u2",
parentId: "t1",
timestamp: "2026-01-01T00:00:04Z",
message: { role: "user", content: "continue" },
},
{
type: "message",
id: "u3",
parentId: "u2",
timestamp: "2026-01-01T00:00:05Z",
message: { role: "user", content: "finish" },
},
]
.map(JSON.stringify)
.join("\n") + "\n",
{ encoding: "utf8", mode: 0o600, flush: true },
);
const old = new Date(Date.now() - 10 * 60 * 1_000);
utimesSync(source, old, old);
t = await createTestSession({ extensionFactories: [iqExtension] });
const faux = fauxProvider({
provider: "judge-test",
models: [{ id: "medium", maxTokens: 4_096 }],
});
faux.setResponses([judgment()]);
const runner = t.session.extensionRunner;
const base = runner.createContext();
base.modelRegistry.registerProvider(faux.provider);
vi.spyOn(SettingsManager, "create").mockReturnValue(
SettingsManager.inMemory({
iq: { judgeModel: "judge-test/medium" },
defaultProvider: "judge-test",
defaultModel: "medium",
}),
);
const confirm = vi.fn(async () => true);
const notify = vi.fn();
const sessionManager = Object.create(
base.sessionManager,
) as typeof base.sessionManager;
sessionManager.getSessionDir = () => sessionDir;
sessionManager.getSessionFile = () => undefined;
const custom = async <T>(factory: Function): Promise<T> =>
new Promise<T>((done) => {
factory(
{ requestRender: vi.fn(), terminal: { rows: 30 } },
theme,
{},
done,
);
});
const ctx = {
...base,
mode: "tui",
hasUI: true,
sessionManager,
ui: { ...base.ui, confirm, notify, custom },
};
await runIqCommand("scan", ctx as never, join(root, "state", "pi", "iq"));
expect(confirm).toHaveBeenCalledOnce();
expect(notify).toHaveBeenCalledWith("IQ scored 1 session", "info");
const files = readdirSync(root, { recursive: true }).map(String);
expect(files.some((file) => file.endsWith(".json"))).toBe(true);
const loaded = await loadRecords(join(root, "state", "pi", "iq"));
expect(loaded.errors).toEqual([]);
expect(loaded.records).toHaveLength(1);
expect(loaded.records[0]?.judge).toBe("judge-test/medium");
expect(loaded.records[0]?.source.model).toBe("worker-provider/worker");
expect(loaded.records[0]?.score.overall).toBeGreaterThan(100);
});
});