Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131import assert from "node:assert/strict";import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { dirname, join, relative } from "node:path";import { createEventBus } from "@earendil-works/pi-coding-agent";import test, { type TestContext } from "node:test";import { Type } from "typebox";import { Check } from "typebox/value";import { createMemoryExtension, INDEX_TOKEN_BUDGET } from "../index.ts";
interface TestEvent { systemPromptOptions?: { sections: Record<string, string>; selectedTools: string[] }; toolName?: string; input?: { path: string }; content?: Array<{ type: string; text: string }>;}interface ToolPatch { content: Array<{ text: string }>;}type Handler = ( event: TestEvent, ctx: { cwd: string },) => ToolPatch | undefined | Promise<ToolPatch | undefined>;
const ResolveRequest = Type.Object({ cwd: Type.String() });
async function setup(t: TestContext, activeTools = ["read", "edit", "write"]) { const root = await mkdtemp(join(tmpdir(), "pi-memory-test-")); t.after(() => rm(root, { recursive: true, force: true })); const directory = join(root, "memory"); const checkout = join(root, "checkout"); const workspace = join(root, "workspace"); const handlers = new Map<string, Handler>(); const events = createEventBus(); events.on("workspaces:resolve", (request) => { if (Check(ResolveRequest, request)) { Object.assign(request, { root: checkout }); } }); const pi = { events, on(name: string, handler: Handler) { handlers.set(name, handler); }, }; // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- The fixture provides each extension API member used here. createMemoryExtension(pi as never, directory); const globalIndex = join(directory, "global", "MEMORY.md"); const projectIndex = join( directory, "projects", checkout.replace(/[^\w.-]+/g, "-"), "MEMORY.md", );
async function prompt() { const options = { sections: {} as Record<string, string>, selectedTools: activeTools }; await handlers.get("before_agent_start")?.( { systemPromptOptions: options }, { cwd: workspace }, ); return options.sections; } async function toolResult(toolName: string, path: string) { const content = [{ type: "text", text: "Successfully wrote the file." }]; return handlers.get("tool_result")?.( { toolName, input: { path }, content }, { cwd: workspace }, ); } return { globalIndex, projectIndex, workspace, prompt, toolResult };}
async function writeIndex(path: string, text: string) { await mkdir(dirname(path), { recursive: true }); await writeFile(path, text);}
test("prompt shows the global and project indexes with their paths", async (t) => { const memory = await setup(t); await writeIndex(memory.globalIndex, "## Feedback\n\n- commit-style: Keep subjects short.\n");
const { persistent_memory: section, memory_rules: rules } = await memory.prompt();
assert.ok(section); assert.match(section, new RegExp(`Global memory \\(\`${memory.globalIndex}\`\\)`)); assert.match(section, /- commit-style: Keep subjects short\./); assert.match( section, new RegExp(`Project memory \\(\`${memory.projectIndex}\`\\)\n\nEmpty\\.`), ); assert.ok(rules); assert.match(rules, /Do not save/);});
test("prompt leaves out the save rules without edit and write tools", async (t) => { const memory = await setup(t, ["read", "bash"]); await writeIndex(memory.projectIndex, "- vault: ~/notes\n");
const sections = await memory.prompt();
assert.match(sections.persistent_memory ?? "", /- vault: ~\/notes/); assert.equal(sections.memory_rules, undefined);});
test("prompt cuts an index that exceeds its budget at a line boundary", async (t) => { const memory = await setup(t); const line = `- ${"x".repeat(150)}\n`; await writeIndex(memory.globalIndex, line.repeat(INDEX_TOKEN_BUDGET / 20));
const section = (await memory.prompt()).persistent_memory ?? "";
const kept = section.split("\n").filter((entry) => entry.startsWith("- x")); assert.ok(kept.length > 0 && kept.length < INDEX_TOKEN_BUDGET / 20); assert.ok(kept.every((entry) => entry === line.trimEnd())); assert.match(section, /is over its budget/);});
test("writing an index over its budget adds a warning to the tool result", async (t) => { const memory = await setup(t); await writeIndex(memory.projectIndex, `- ${"x".repeat(150)}\n`.repeat(INDEX_TOKEN_BUDGET / 20)); await writeIndex(memory.globalIndex, "- small: fits\n");
for (const path of [memory.projectIndex, relative(memory.workspace, memory.projectIndex)]) { const over = await memory.toolResult("write", path); assert.match(over?.content.at(-1)?.text ?? "", /over its budget/); } assert.equal(await memory.toolResult("edit", memory.globalIndex), undefined); assert.equal(await memory.toolResult("read", memory.projectIndex), undefined);});