repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/iq/__tests__/core.test.ts

Raw
File outline
import {
	mkdirSync,
	mkdtempSync,
	rmSync,
	statSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
	aggregateModels,
	DIMENSIONS,
	defaultModelReference,
	eligibilityFor,
	prepareSession,
	readIqSettings,
	reduceScore,
	SESSION_SETTLE_MS,
	type SessionScoreRecord,
} from "../core";

let root: string | undefined;

afterEach(() => {
	if (root) rmSync(root, { recursive: true, force: true });
	root = undefined;
});

function tempRoot(): string {
	root = mkdtempSync(join(tmpdir(), "pi-iq-core-"));
	return root;
}

function entry(value: unknown): string {
	return JSON.stringify(value);
}

function record(model: string, score: number, at: string): SessionScoreRecord {
	const dimensions = Object.fromEntries(
		DIMENSIONS.map((dimension) => [
			dimension.name,
			{ score, meanRating: 4, evidence: 1, evidenceWeight: 2 },
		]),
	) as SessionScoreRecord["score"]["dimensions"];
	return {
		version: 1,
		rubricVersion: 1,
		promptVersion: 1,
		source: {
			path: `/sessions/${at}.jsonl`,
			size: 10,
			mtimeMs: 1,
			sha256: at,
			sessionId: at,
			name: at,
			cwd: "/repo",
			model,
			userMessages: 3,
			assistantMessages: 3,
			toolResults: 1,
			models: [model],
		},
		judge: "openai/judge",
		score: { overall: score, observedDimensionWeight: 1, dimensions },
		observations: [],
		usage: {
			input: 0,
			output: 0,
			cacheRead: 0,
			cacheWrite: 0,
			totalTokens: 0,
			cost: 0,
			calls: 0,
			retries: 0,
		},
		chunkCount: 1,
		elapsedMs: 1,
		scoredAt: at,
	};
}

describe("IQ core", () => {
	it("merges judge settings and resolves Pi's configured default", () => {
		expect(
			readIqSettings(
				{ iq: { judgeModel: "openai/old" } },
				{ iq: { judgeModel: null } },
			),
		).toEqual({ judgeModel: null });
		expect(
			defaultModelReference(
				{ defaultProvider: "openai", defaultModel: "global" },
				{ defaultModel: "project" },
			),
		).toBe("openai/project");
		expect(() => readIqSettings({ iq: { judgeModel: "" } }, {})).toThrow(
			/provider\/model or null/,
		);
	});

	it("normalizes an ordered session without hidden thinking", async () => {
		const directory = tempRoot();
		const path = join(directory, "session.jsonl");
		mkdirSync(directory, { recursive: true });
		writeFileSync(
			path,
			[
				entry({
					type: "session",
					version: 3,
					id: "session-id",
					timestamp: "2026-01-01T00:00:00Z",
					cwd: "/repo",
				}),
				entry({
					type: "message",
					id: "u1",
					parentId: null,
					timestamp: "2026-01-01T00:00:01Z",
					message: { role: "user", content: "Fix it" },
				}),
				entry({
					type: "message",
					id: "a1",
					parentId: "u1",
					timestamp: "2026-01-01T00:00:02Z",
					message: {
						role: "assistant",
						provider: "openai",
						model: "worker",
						content: [
							{ type: "thinking", thinking: "private chain" },
							{ type: "text", text: "Inspect callers" },
							{ type: "toolCall", name: "grep", arguments: { pattern: "x" } },
						],
					},
				}),
				entry({
					type: "message",
					id: "t1",
					parentId: "a1",
					timestamp: "2026-01-01T00:00:03Z",
					message: {
						role: "toolResult",
						toolName: "grep",
						isError: false,
						content: [{ type: "text", text: "found" }],
					},
				}),
				entry({
					type: "message",
					id: "u2",
					parentId: "t1",
					timestamp: "2026-01-01T00:00:04Z",
					message: { role: "user", content: "continue" },
				}),
				entry({
					type: "message",
					id: "u3",
					parentId: "u2",
					timestamp: "2026-01-01T00:00:05Z",
					message: { role: "user", content: "done" },
				}),
			].join("\n") + "\n",
			"utf8",
		);
		const prepared = await prepareSession(
			path,
			statSync(path).mtimeMs + SESSION_SETTLE_MS,
		);
		expect(prepared.source.sessionId).toBe("session-id");
		expect(prepared.source.models).toEqual(["openai/worker"]);
		expect(prepared.eligibility).toEqual({ ranked: true });
		expect(JSON.stringify(prepared.events)).not.toContain("private chain");
		expect(prepared.events.map((event) => event.id)).toEqual([
			"u1",
			"a1",
			"t1",
			"u2",
			"u3",
		]);
	});

	it("keeps trivial, mixed, missing-model, and unsettled sessions unranked", () => {
		const old = Date.now() - SESSION_SETTLE_MS - 1;
		expect(
			eligibilityFor({
				userMessages: 2,
				toolResults: 1,
				models: ["p/m"],
				mtimeMs: old,
			}),
		).toEqual({ ranked: false, reason: "trivial" });
		expect(
			eligibilityFor({
				userMessages: 3,
				toolResults: 1,
				models: ["a/x", "b/y"],
				mtimeMs: old,
			}),
		).toEqual({ ranked: false, reason: "mixed-model" });
		expect(
			eligibilityFor({
				userMessages: 3,
				toolResults: 1,
				models: [],
				mtimeMs: old,
			}),
		).toEqual({ ranked: false, reason: "model-missing" });
		expect(
			eligibilityFor({
				userMessages: 3,
				toolResults: 1,
				models: ["p/m"],
				mtimeMs: Date.now(),
			}),
		).toEqual({ ranked: false, reason: "settling" });
	});

	it("reduces cited observations and gives sessions equal model weight", () => {
		const score = reduceScore([
			{
				dimension: "comprehension_judgment",
				rating: 5,
				importance: 3,
				confidence: 1,
				eventIds: ["a"],
				observation: "root cause",
				sourceChunk: 1,
			},
		]);
		expect(score.overall).toBe(115);
		expect(score.dimensions.context_management.score).toBeNull();

		const aggregate = aggregateModels([
			record("openai/worker", 120, "2026-01-01T00:00:00Z"),
			record("openai/worker", 100, "2026-01-02T00:00:00Z"),
		]);
		expect(aggregate[0]).toMatchObject({
			model: "openai/worker",
			score: 110,
			sessions: 2,
			minimum: 100,
			maximum: 120,
		});
	});
});