repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/decay/__tests__/core.test.ts
RawFile outline
- user line 22
- record line 26
- memory line 47
- chunk line 61
- zeroUsage line 77
- decay settings line 86
- merges project models over global and preserves explicit null line 87
- marks invalid configured values instead of silently selecting models line 118
- source chunking line 133
- keeps legacy summary, history, and split prefix in distinct ordered chunks line 134
- never splits one oversized message line 153
- classifier records line 164
- strictly validates schema and rejects unknown fields line 165
- sorts complete out-of-order records line 184
- rejects duplicates, missing chunks, wrong totals, and invalid indexes line 190
- structured memory line 206
- migrates legacy summary at epoch zero and counts semantic recurrence line 207
- does not count duplicate atoms inside one chunk as recurrence line 231
- updates prior atoms and lets latest current status supersede line 240
- weights recency and logarithmically bounded recurrence line 257
- records recency inside the current discarded history line 264
- always allocates protected active atoms and favors newer ordinary atoms line 280
- reads only valid details from the latest compaction boundary line 299
- deterministic appendices and usage line 327
- merges files, moves later modifications out of read-only, and sorts line 328
- combines every usage and cost field line 346
import { describe, expect, it } from "vitest";
import {
allocateAtoms,
atomWeight,
combineUsage,
createSourceChunks,
type DecayDetails,
findPreviousDecayDetails,
formatFileAppendix,
type MemoryAtom,
mergeFileLists,
mergeMemory,
parseDecayDetails,
parseModelReference,
type RecordChunk,
readDecaySettings,
reconcileRecords,
type SourceChunk,
validateRecordChunk,
} from "../core";
function user(text: string) {
return { role: "user", content: [{ type: "text", text }], timestamp: 1 };
}
function record(
chunk: number,
of: number,
key: string,
overrides: Partial<RecordChunk["atoms"][number]> = {},
): RecordChunk {
return {
chunk,
of,
atoms: [
{
key,
text: `fact ${key}`,
kind: "context",
status: "active",
...overrides,
},
],
};
}
function memory(overrides: Partial<MemoryAtom> = {}): MemoryAtom {
return {
key: "fact",
text: "fact",
kind: "context",
firstSeen: 1,
lastSeen: 1,
seenCount: 1,
status: "active",
sourcePosition: 1,
...overrides,
};
}
function chunk(
chunkNumber: number,
of: number,
source: SourceChunk["source"] = "history",
): SourceChunk {
return {
chunk: chunkNumber,
of,
source,
firstPosition: chunkNumber,
lastPosition: chunkNumber,
text: "source",
estimatedTokens: 1,
};
}
const zeroUsage = {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
totalTokens: 0,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
};
describe("decay settings", () => {
it("merges project models over global and preserves explicit null", () => {
expect(
readDecaySettings(
{
decay: {
model: "global/model",
summarizerModel: "global/summarizer",
},
},
{ decay: { model: "project/model" } },
),
).toEqual({
model: "project/model",
summarizerModel: "global/summarizer",
});
expect(
readDecaySettings(
{
decay: {
model: "global/model",
summarizerModel: "global/summarizer",
},
},
{
decay: { model: null, summarizerModel: null },
},
),
).toEqual({ model: null, summarizerModel: null });
expect(readDecaySettings({}, {})).toEqual({});
});
it("marks invalid configured values instead of silently selecting models", () => {
expect(
readDecaySettings({ decay: { model: 42, summarizerModel: false } }, {}),
).toEqual({
model: "",
summarizerModel: "",
});
expect(parseModelReference("provider/model/variant")).toEqual({
provider: "provider",
modelId: "model/variant",
});
expect(parseModelReference("broken")).toBeUndefined();
});
});
describe("source chunking", () => {
it("keeps legacy summary, history, and split prefix in distinct ordered chunks", () => {
const chunks = createSourceChunks({
legacySummary: "old checkpoint",
messages: [user("history one"), user("history two")] as never,
turnPrefixMessages: [user("split") as never],
targetTokens: 100,
});
expect(chunks.map((item) => item.source)).toEqual([
"legacy-summary",
"history",
"split-prefix",
]);
expect(chunks.map((item) => item.chunk)).toEqual([1, 2, 3]);
expect(chunks.every((item) => item.of === 3)).toBe(true);
expect(chunks[1].text).toContain("MESSAGE 1 SOURCE history");
expect(chunks[1].text).toContain("MESSAGE 2 SOURCE history");
});
it("never splits one oversized message", () => {
const chunks = createSourceChunks({
messages: [user("x".repeat(1_000))] as never,
turnPrefixMessages: [],
targetTokens: 10,
});
expect(chunks).toHaveLength(1);
expect(chunks[0].text).toContain("x".repeat(1_000));
});
});
describe("classifier records", () => {
it("strictly validates schema and rejects unknown fields", () => {
expect(validateRecordChunk(record(1, 1, "one"))).toBeDefined();
expect(
validateRecordChunk({ ...record(1, 1, "one"), extra: true }),
).toBeUndefined();
expect(
validateRecordChunk({
...record(1, 1, "one"),
atoms: [{ ...record(1, 1, "one").atoms[0], extra: true }],
}),
).toBeUndefined();
expect(
validateRecordChunk({
...record(1, 1, "one"),
atoms: [{ ...record(1, 1, "one").atoms[0], sourcePosition: 99 }],
}),
).toBeUndefined();
});
it("sorts complete out-of-order records", () => {
expect(
reconcileRecords([record(2, 2, "two"), record(1, 2, "one")], 2),
).toEqual([record(1, 2, "one"), record(2, 2, "two")]);
});
it("rejects duplicates, missing chunks, wrong totals, and invalid indexes", () => {
expect(() =>
reconcileRecords([record(1, 2, "one"), record(1, 2, "again")], 2),
).toThrow("duplicated chunk 1");
expect(() => reconcileRecords([record(1, 2, "one")], 2)).toThrow(
"omitted chunks: 2",
);
expect(() => reconcileRecords([record(1, 3, "one")], 2)).toThrow(
"reported 3 chunks, expected 2",
);
expect(() => reconcileRecords([record(3, 2, "three")], 2)).toThrow(
"invalid chunk 3",
);
});
});
describe("structured memory", () => {
it("migrates legacy summary at epoch zero and counts semantic recurrence", () => {
const records = [
record(1, 3, "same", { text: "old wording" }),
record(2, 3, "same", { text: "new wording" }),
record(3, 3, "same", { text: "newest wording", kind: "decision" }),
];
const atoms = mergeMemory([], records, [
chunk(1, 3, "legacy-summary"),
chunk(2, 3),
chunk(3, 3),
]);
expect(atoms).toEqual([
expect.objectContaining({
key: "same",
text: "newest wording",
kind: "decision",
firstSeen: 0,
lastSeen: 2,
seenCount: 3,
sourcePosition: 3,
}),
]);
});
it("does not count duplicate atoms inside one chunk as recurrence", () => {
const duplicated = record(1, 1, "same");
duplicated.atoms.push({ ...duplicated.atoms[0], text: "latest" });
const atoms = mergeMemory([], [duplicated], [chunk(1, 1)]);
expect(atoms[0]).toEqual(
expect.objectContaining({ seenCount: 1, text: "latest" }),
);
});
it("updates prior atoms and lets latest current status supersede", () => {
const atoms = mergeMemory(
[memory({ key: " Rule ", seenCount: 2, lastSeen: 4 })],
[record(1, 1, "rule", { status: "superseded", text: "replaced" })],
[chunk(1, 1)],
);
expect(atoms[0]).toEqual(
expect.objectContaining({
key: "rule",
text: "replaced",
seenCount: 3,
lastSeen: 5,
status: "superseded",
}),
);
});
it("weights recency and logarithmically bounded recurrence", () => {
const newest = memory({ lastSeen: 4, seenCount: 1 });
const oldRecurring = memory({ lastSeen: 1, seenCount: 16 });
expect(atomWeight(newest, 4)).toBe(1);
expect(atomWeight(oldRecurring, 4)).toBe(0.75);
});
it("records recency inside the current discarded history", () => {
const atoms = mergeMemory(
[],
[record(1, 2, "old"), record(2, 2, "new")],
[chunk(1, 2), chunk(2, 2)],
);
expect(atoms.map((atom) => [atom.key, atom.lastSeen])).toEqual([
["old", 1],
["new", 2],
]);
const allocated = new Map(
allocateAtoms(atoms, 200).map((atom) => [atom.key, atom.allocation]),
);
expect(allocated.get("new")).toBeGreaterThan(allocated.get("old") ?? 0);
});
it("always allocates protected active atoms and favors newer ordinary atoms", () => {
const allocated = allocateAtoms(
[
memory({ key: "law", kind: "constraint", lastSeen: 1 }),
memory({ key: "old", lastSeen: 1 }),
memory({ key: "new", lastSeen: 3 }),
memory({ key: "gone", status: "superseded", lastSeen: 4 }),
],
200,
);
const byKey = new Map(allocated.map((atom) => [atom.key, atom]));
expect(byKey.get("law")?.protected).toBe(true);
expect(byKey.get("law")?.allocation).toBeGreaterThanOrEqual(24);
expect(byKey.get("new")?.allocation).toBeGreaterThan(
byKey.get("old")?.allocation ?? 0,
);
expect(byKey.has("gone")).toBe(false);
});
it("reads only valid details from the latest compaction boundary", () => {
const details: DecayDetails = {
decay: {
version: 1,
model: "p/m",
elapsedMs: 10,
chunkCount: 1,
keepRecentTokens: 20_000,
atoms: [memory()],
readFiles: ["read"],
modifiedFiles: ["write"],
},
};
expect(parseDecayDetails(details)).toEqual(details);
expect(
findPreviousDecayDetails([
{ type: "compaction", details, id: "1", parentId: null } as never,
]),
).toEqual(details.decay);
expect(
findPreviousDecayDetails([
{ type: "compaction", details, id: "1", parentId: null } as never,
{ type: "compaction", details: {}, id: "2", parentId: "1" } as never,
]),
).toBeUndefined();
});
});
describe("deterministic appendices and usage", () => {
it("merges files, moves later modifications out of read-only, and sorts", () => {
const files = mergeFileLists(
{ readFiles: ["z", "both"], modifiedFiles: ["old"] },
{
read: new Set(["a"]),
written: new Set(["both"]),
edited: new Set(["new"]),
},
);
expect(files).toEqual({
readFiles: ["a", "z"],
modifiedFiles: ["both", "new", "old"],
});
expect(formatFileAppendix(files.readFiles, files.modifiedFiles)).toBe(
"\n\n<read-files>\na\nz\n</read-files>\n\n<modified-files>\nboth\nnew\nold\n</modified-files>",
);
});
it("combines every usage and cost field", () => {
const combined = combineUsage(
{ ...zeroUsage, input: 2, totalTokens: 2, reasoning: 1 },
{
...zeroUsage,
output: 3,
totalTokens: 3,
cacheWrite1h: 2,
cost: { ...zeroUsage.cost, output: 0.2, total: 0.2 },
},
);
expect(combined).toEqual(
expect.objectContaining({
input: 2,
output: 3,
totalTokens: 5,
reasoning: 1,
cacheWrite1h: 2,
cost: expect.objectContaining({ output: 0.2, total: 0.2 }),
}),
);
});
});