repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/overkill/__tests__/optimizer.test.ts
RawFile outline
- frozen line 8
- fakeSession line 10
- subscribe line 18
- prompt line 22
- abort line 33
- dispose line 36
- isolated optimizer sessions line 42
- creates a fresh frozen session with only terminating structured output line 43
- optimizer step line 105
- elides empty partitions and calls reflection, merge, then ranking in order line 106
- persists attempted-call accounting before a failed model prompt line 136
- retries one malformed proposal before continuing line 166
- uses fixed empty proposals without calls and rejects malformed terminating output line 192
- retains proposal and rejection context when a valid body exceeds ranking context budget line 220
- disposes the fresh session on cancellation and session failures line 244
import { describe, expect, it } from "vitest";
import {
createOptimizerSession,
type OptimizerSession,
runOptimizerStep,
} from "../lib/optimizer.ts";
const frozen = { provider: "test", id: "frozen", thinking: "high" };
function fakeSession(
outputs: unknown[],
): OptimizerSession & { prompts: string[]; disposed: number; aborted: number } {
const listeners = new Set<(event: any) => void>();
return {
prompts: [],
disposed: 0,
aborted: 0,
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
async prompt(prompt) {
this.prompts.push(prompt);
const output = outputs.shift();
for (const listener of listeners)
listener({
type: "tool_execution_end",
toolName: "structured_output",
result: { details: output },
isError: false,
});
},
async abort() {
this.aborted += 1;
},
dispose() {
this.disposed += 1;
},
};
}
describe("isolated optimizer sessions", () => {
it("creates a fresh frozen session with only terminating structured output", async () => {
const created: Array<Record<string, unknown>> = [];
const loaderOptions: Array<Record<string, unknown>> = [];
class Loader {
constructor(options: Record<string, unknown>) {
loaderOptions.push(options);
}
async reload() {}
}
const session = fakeSession([]);
const result = await createOptimizerSession(
{
cwd: "/project",
agentDir: "/agent",
model: frozen,
targetModel: { provider: "test", id: "frozen" },
},
{
DefaultResourceLoader: Loader,
SettingsManager: { inMemory: (value: unknown) => value },
SessionManager: {
inMemory: (cwd: string) => ({ kind: "memory", cwd }),
},
async createAgentSession(options: Record<string, unknown>) {
created.push(options);
return { session };
},
},
);
expect(result).toBe(session);
expect(loaderOptions).toEqual([
expect.objectContaining({
noExtensions: true,
noSkills: true,
noPromptTemplates: true,
noThemes: true,
noContextFiles: true,
}),
]);
expect(created).toEqual([
expect.objectContaining({
model: { provider: "test", id: "frozen" },
thinkingLevel: "high",
tools: ["structured_output"],
sessionManager: { kind: "memory", cwd: "/project" },
customTools: [
expect.objectContaining({
name: "structured_output",
execute: expect.any(Function),
}),
],
}),
]);
const tool = created[0]?.customTools?.[0];
if (!tool) throw new Error("missing structured output tool");
expect(await tool.execute("call", { proposal: "done" })).toMatchObject({
terminate: true,
details: { proposal: "done" },
});
});
});
describe("optimizer step", () => {
it("elides empty partitions and calls reflection, merge, then ranking in order", async () => {
const session = fakeSession([
{ proposal: "success proposal" },
{ proposal: "merged" },
{ edits: [{ op: "append", content: "improve" }] },
]);
const result = await runOptimizerStep(
{
body: "body",
failures: [],
successes: [{ id: "train-1", score: 1, feedback: "good" }],
rejections: [{ reason: "tie", delta: 0 }],
},
{
async createSession() {
return session;
},
},
);
expect(session.prompts).toHaveLength(3);
expect(
session.prompts.map((prompt) => prompt.match(/^phase:(\w+)/)?.[1]),
).toEqual(["success", "merge", "ranking"]);
expect(result).toEqual({
patch: { edits: [{ op: "append", content: "improve" }] },
calls: 3,
});
expect(session.disposed).toBe(1);
});
it("persists attempted-call accounting before a failed model prompt", async () => {
const order: string[] = [];
const session = fakeSession([]);
session.prompt = async () => {
order.push("prompt");
throw new Error("model failed");
};
await expect(
runOptimizerStep(
{
body: "body",
failures: [{ id: "f", score: 0 }],
successes: [],
rejections: [],
},
{
async createSession() {
return session;
},
},
undefined,
{},
async () => {
order.push("persist");
},
),
).rejects.toThrow("model failed");
expect(order).toEqual(["persist", "prompt"]);
});
it("retries one malformed proposal before continuing", async () => {
const session = fakeSession([
{ proposal: "failure proposal", edits: [] },
{ proposal: "failure proposal" },
{ proposal: "merged" },
{ edits: [{ op: "append", content: "improve" }] },
]);
const result = await runOptimizerStep(
{
body: "body",
failures: [{ id: "f", score: 0 }],
successes: [],
rejections: [],
},
{
async createSession() {
return session;
},
},
);
expect(result.calls).toBe(4);
expect(session.prompts[1]).toContain(
"previous structured output was malformed",
);
});
it("uses fixed empty proposals without calls and rejects malformed terminating output", async () => {
const session = fakeSession([
{ proposal: "failure proposal" },
{ proposal: "merged" },
{ edits: [] },
{ edits: [] },
]);
await expect(
runOptimizerStep(
{
body: "body",
failures: [{ id: "f", score: 0 }],
successes: [],
rejections: [],
},
{
async createSession() {
return session;
},
},
),
).rejects.toThrow("one to four");
expect(
session.prompts.map((prompt) => prompt.match(/^phase:(\w+)/)?.[1]),
).toEqual(["failure", "merge", "ranking", "ranking"]);
expect(session.disposed).toBe(1);
});
it("retains proposal and rejection context when a valid body exceeds ranking context budget", async () => {
const session = fakeSession([
{ proposal: "failure" },
{ proposal: "merged proposal" },
{ edits: [{ op: "append", content: "improve" }] },
]);
await runOptimizerStep(
{
body: "x".repeat(80 * 1024),
failures: [{ id: "f", trajectory: { response: "failed" } }],
successes: [],
rejections: [{ reason: "prior rejected edit", delta: -0.5 }],
},
{
async createSession() {
return session;
},
},
);
const ranking = session.prompts.at(-1) ?? "";
expect(ranking).toContain("merged proposal");
expect(ranking).toContain("prior rejected edit");
});
it("disposes the fresh session on cancellation and session failures", async () => {
const controller = new AbortController();
const cancelled = fakeSession([]);
controller.abort();
await expect(
runOptimizerStep(
{
body: "body",
failures: [{ id: "f", score: 0 }],
successes: [],
rejections: [],
},
{
async createSession() {
return cancelled;
},
},
controller.signal,
),
).rejects.toThrow("cancelled");
expect({
aborted: cancelled.aborted,
disposed: cancelled.disposed,
}).toEqual({ aborted: 1, disposed: 1 });
const failed = fakeSession([]);
failed.prompt = async () => {
throw new Error("fake model failure");
};
await expect(
runOptimizerStep(
{
body: "body",
failures: [{ id: "f", score: 0 }],
successes: [],
rejections: [],
},
{
async createSession() {
return failed;
},
},
),
).rejects.toThrow("fake model failure");
expect(failed.disposed).toBe(1);
});
});