Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix(import): reject malformed sections and rows before a replace import deletes the store (#1576)

Dmitrii Zhukov1c995081c45d
diff --git a/src/functions/export-import.ts b/src/functions/export-import.ts
index 7acc12cd..80cef8f2 100644
--- a/src/functions/export-import.ts
+++ b/src/functions/export-import.ts
@@ -407,6 +407,35 @@ export function registerExportImportFunction(sdk: IIIClient, state: StateKV): vo
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : String(error) };
}
+ const badRow = (rows: readonly unknown[], key: string) =>
+ rows.findIndex((row) => {
+ const id = row && typeof row === "object" ? (row as Record<string, unknown>)[key] : undefined;
+ return typeof id !== "string" || id.length === 0;
+ });
+ for (const [sessionId, obs] of Object.entries(importData.observations)) {
+ const index = badRow(obs, "id");
+ if (index >= 0) {
+ return { success: false, error: `observations.${sessionId}[${index}] must be an object with a string id` };
+ }
+ }
+ const rowKeys: Record<string, string> = { summaries: "sessionId", profiles: "project", accessLogs: "memoryId" };
+ for (const section of ["sessions", "memories", "summaries", "profiles", ...EXPORT_COLLECTIONS.map(([field]) => field)] as const) {
+ const rows = importData[section];
+ if (rows !== undefined && !Array.isArray(rows)) {
+ return { success: false, error: `${section} must be an array` };
+ }
+ const key = rowKeys[section] ?? "id";
+ const index = badRow(rows ?? [], key);
+ if (index >= 0) {
+ return { success: false, error: `${section}[${index}] must be an object with a string ${key}` };
+ }
+ }
+ if ((importData.accessLogs?.length ?? 0) > MAX_ACCESS_LOGS) {
+ return {
+ success: false,
+ error: `Too many access logs (max ${MAX_ACCESS_LOGS})`,
+ };
+ }
const stats = {
sessions: 0,
@@ -746,15 +775,6 @@ export function registerExportImportFunction(sdk: IIIClient, state: StateKV): vo
});
}
if (importData.accessLogs) {
- if (!Array.isArray(importData.accessLogs)) {
- return { success: false, error: "accessLogs must be an array" };
- }
- if (importData.accessLogs.length > MAX_ACCESS_LOGS) {
- return {
- success: false,
- error: `Too many access logs (max ${MAX_ACCESS_LOGS})`,
- };
- }
const memoryIds = new Set<string>(
importData.memories.map((m) => m.id),
);
diff --git a/test/export-import.test.ts b/test/export-import.test.ts
index 4ed46449..e034f196 100644
--- a/test/export-import.test.ts
+++ b/test/export-import.test.ts
@@ -105,6 +105,10 @@ const testSummary: SessionSummary = {
observationCount: 1,
};
+const testLesson = { id: "les_1", content: "Validate tokens" };
+
+const testAccessLog = { memoryId: "mem_1", count: 3, lastAt: "2026-02-01T00:00:00Z", recent: [] };
+
describe("Export/Import Functions", () => {
let sdk: ReturnType<typeof mockSdk>;
let kv: ReturnType<typeof mockKV>;
@@ -122,6 +126,8 @@ describe("Export/Import Functions", () => {
await kv.set("mem:obs:ses_1", "obs_1", testObs);
await kv.set("mem:memories", "mem_1", testMemory);
await kv.set("mem:summaries", "ses_1", testSummary);
+ await kv.set("mem:lessons", "les_1", testLesson);
+ await kv.set("mem:access", "mem_1", testAccessLog);
});
it("export produces valid ExportData structure", async () => {
@@ -322,6 +328,58 @@ describe("Export/Import Functions", () => {
expect(await kv.get(KV.summaryRepairs, testSession.id)).toBeNull();
});
+ it.each([
+ { section: "lessons", shape: "an object", value: { les_1: { id: "les_1" } }, error: "lessons must be an array" },
+ { section: "profiles", shape: "a string", value: "ab", error: "profiles must be an array" },
+ { section: "accessLogs", shape: "a string", value: "oops", error: "accessLogs must be an array" },
+ { section: "lessons", shape: "null", value: null, error: "lessons must be an array" },
+ { section: "profiles", shape: "null", value: null, error: "profiles must be an array" },
+ { section: "accessLogs", shape: "null", value: null, error: "accessLogs must be an array" },
+ { section: "graphNodes", shape: "null", value: null, error: "graphNodes must be an array" },
+ {
+ section: "accessLogs",
+ shape: "over the cap",
+ value: Array.from({ length: 50_001 }, () => ({ memoryId: testMemory.id })),
+ error: "Too many access logs (max 50000)",
+ },
+ { section: "lessons", shape: "a null row", value: [null], error: "lessons[0] must be an object with a string id" },
+ { section: "facets", shape: "a null row", value: [null], error: "facets[0] must be an object with a string id" },
+ { section: "memories", shape: "a null row", value: [null], error: "memories[0] must be an object with a string id" },
+ { section: "accessLogs", shape: "a null row", value: [null], error: "accessLogs[0] must be an object with a string memoryId" },
+ { section: "lessons", shape: "a row without id", value: [{ content: "x" }], error: "lessons[0] must be an object with a string id" },
+ { section: "lessons", shape: "a row with an empty id", value: [{ id: "" }], error: "lessons[0] must be an object with a string id" },
+ { section: "profiles", shape: "a row without project", value: [{ id: "my-project" }], error: "profiles[0] must be an object with a string project" },
+ { section: "sessions", shape: "a row without id", value: [{}], error: "sessions[0] must be an object with a string id" },
+ { section: "summaries", shape: "a row without sessionId", value: [{ id: "ses_1" }], error: "summaries[0] must be an object with a string sessionId" },
+ {
+ section: "observations",
+ shape: "a row without id",
+ value: { ses_1: [{ sessionId: "ses_1" }] },
+ error: "observations.ses_1[0] must be an object with a string id",
+ },
+ ])("replace import leaves the store intact when $section is $shape", async ({ section, value, error }) => {
+ const exportData = {
+ version: VERSION,
+ exportedAt: new Date().toISOString(),
+ sessions: [],
+ observations: {},
+ memories: [],
+ summaries: [],
+ [section]: value,
+ } as unknown as ExportData;
+
+ const result = await sdk
+ .trigger("mem::import", { exportData, strategy: "replace" })
+ .catch((thrown: unknown) => thrown);
+
+ expect(result).not.toBeInstanceOf(Error);
+ expect(result).toMatchObject({ success: false, error });
+ expect(await kv.get(KV.sessions, testSession.id)).toEqual(testSession);
+ expect(await kv.get(KV.memories, testMemory.id)).toEqual(testMemory);
+ expect(await kv.get(KV.lessons, testLesson.id)).toEqual(testLesson);
+ expect(await kv.get(KV.accessLog, testAccessLog.memoryId)).toEqual(testAccessLog);
+ });
+
it("export then import round-trip preserves data", async () => {
const exported = (await sdk.trigger("mem::export", {})) as ExportData;