Skip to content

Commit ebfeb7a

Browse files
radek-pacltclaude
andcommitted
feat(memory): add lifecycle hooks and vector memory plugin
Add plugin lifecycle hooks infrastructure: - before_agent_start: inject context before agent loop - agent_end: analyze conversation after completion - 13 hook types total (message, tool, session, gateway hooks) Memory plugin implementation: - LanceDB vector storage with OpenAI embeddings - kind: "memory" to integrate with upstream slot system - Auto-recall: injects <relevant-memories> when context found - Auto-capture: stores preferences, decisions, entities - Rule-based capture filtering with 0.95 similarity dedup - Tools: memory_recall, memory_store, memory_forget - CLI: clawdbot ltm list|search|stats Plugin infrastructure: - api.on() method for hook registration - Global hook runner singleton for cross-module access - Priority ordering and error catching Co-Authored-By: Claude Opus 4.5 <[email protected]>
1 parent ac1b2d8 commit ebfeb7a

11 files changed

Lines changed: 2073 additions & 2 deletions

File tree

‎extensions/memory/index.test.ts‎

Lines changed: 282 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,282 @@
1+
/**
2+
* Memory Plugin E2E Tests
3+
*
4+
* Tests the memory plugin functionality including:
5+
* - Plugin registration and configuration
6+
* - Memory storage and retrieval
7+
* - Auto-recall via hooks
8+
* - Auto-capture filtering
9+
*/
10+
11+
import { describe, test, expect, beforeEach, afterEach } from "vitest";
12+
import { randomUUID } from "node:crypto";
13+
import fs from "node:fs/promises";
14+
import path from "node:path";
15+
import os from "node:os";
16+
17+
// Skip if no OpenAI API key
18+
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
19+
const describeWithKey = OPENAI_API_KEY ? describe : describe.skip;
20+
21+
describeWithKey("memory plugin e2e", () => {
22+
let tmpDir: string;
23+
let dbPath: string;
24+
25+
beforeEach(async () => {
26+
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-memory-test-"));
27+
dbPath = path.join(tmpDir, "lancedb");
28+
});
29+
30+
afterEach(async () => {
31+
if (tmpDir) {
32+
await fs.rm(tmpDir, { recursive: true, force: true });
33+
}
34+
});
35+
36+
test("memory plugin registers and initializes correctly", async () => {
37+
// Dynamic import to avoid loading LanceDB when not testing
38+
const { default: memoryPlugin } = await import("./index.js");
39+
40+
expect(memoryPlugin.id).toBe("memory");
41+
expect(memoryPlugin.name).toBe("Memory (Vector)");
42+
expect(memoryPlugin.kind).toBe("memory");
43+
expect(memoryPlugin.configSchema).toBeDefined();
44+
expect(memoryPlugin.register).toBeInstanceOf(Function);
45+
});
46+
47+
test("config schema parses valid config", async () => {
48+
const { default: memoryPlugin } = await import("./index.js");
49+
50+
const config = memoryPlugin.configSchema?.parse?.({
51+
embedding: {
52+
apiKey: OPENAI_API_KEY,
53+
model: "text-embedding-3-small",
54+
},
55+
dbPath,
56+
autoCapture: true,
57+
autoRecall: true,
58+
});
59+
60+
expect(config).toBeDefined();
61+
expect(config?.embedding?.apiKey).toBe(OPENAI_API_KEY);
62+
expect(config?.dbPath).toBe(dbPath);
63+
});
64+
65+
test("config schema resolves env vars", async () => {
66+
const { default: memoryPlugin } = await import("./index.js");
67+
68+
// Set a test env var
69+
process.env.TEST_MEMORY_API_KEY = "test-key-123";
70+
71+
const config = memoryPlugin.configSchema?.parse?.({
72+
embedding: {
73+
apiKey: "${TEST_MEMORY_API_KEY}",
74+
},
75+
dbPath,
76+
});
77+
78+
expect(config?.embedding?.apiKey).toBe("test-key-123");
79+
80+
delete process.env.TEST_MEMORY_API_KEY;
81+
});
82+
83+
test("config schema rejects missing apiKey", async () => {
84+
const { default: memoryPlugin } = await import("./index.js");
85+
86+
expect(() => {
87+
memoryPlugin.configSchema?.parse?.({
88+
embedding: {},
89+
dbPath,
90+
});
91+
}).toThrow("embedding.apiKey is required");
92+
});
93+
94+
test("shouldCapture filters correctly", async () => {
95+
// Test the capture filtering logic by checking the rules
96+
const triggers = [
97+
{ text: "I prefer dark mode", shouldMatch: true },
98+
{ text: "Remember that my name is John", shouldMatch: true },
99+
{ text: "My email is [email protected]", shouldMatch: true },
100+
{ text: "Call me at +1234567890123", shouldMatch: true },
101+
{ text: "We decided to use TypeScript", shouldMatch: true },
102+
{ text: "I always want verbose output", shouldMatch: true },
103+
{ text: "Just a random short message", shouldMatch: false },
104+
{ text: "x", shouldMatch: false }, // Too short
105+
{ text: "<relevant-memories>injected</relevant-memories>", shouldMatch: false }, // Skip injected
106+
];
107+
108+
// The shouldCapture function is internal, but we can test via the capture behavior
109+
// For now, just verify the patterns we expect to match
110+
for (const { text, shouldMatch } of triggers) {
111+
const hasPreference = /prefer|radši|like|love|hate|want/i.test(text);
112+
const hasRemember = /zapamatuj|pamatuj|remember/i.test(text);
113+
const hasEmail = /[\w.-]+@[\w.-]+\.\w+/.test(text);
114+
const hasPhone = /\+\d{10,}/.test(text);
115+
const hasDecision = /rozhodli|decided|will use|budeme/i.test(text);
116+
const hasAlways = /always|never|important/i.test(text);
117+
const isInjected = text.includes("<relevant-memories>");
118+
const isTooShort = text.length < 10;
119+
120+
const wouldCapture =
121+
!isTooShort &&
122+
!isInjected &&
123+
(hasPreference || hasRemember || hasEmail || hasPhone || hasDecision || hasAlways);
124+
125+
if (shouldMatch) {
126+
expect(wouldCapture).toBe(true);
127+
}
128+
}
129+
});
130+
131+
test("detectCategory classifies correctly", async () => {
132+
// Test category detection patterns
133+
const cases = [
134+
{ text: "I prefer dark mode", expected: "preference" },
135+
{ text: "We decided to use React", expected: "decision" },
136+
{ text: "My email is [email protected]", expected: "entity" },
137+
{ text: "The server is running on port 3000", expected: "fact" },
138+
];
139+
140+
for (const { text, expected } of cases) {
141+
const lower = text.toLowerCase();
142+
let category: string;
143+
144+
if (/prefer|radši|like|love|hate|want/i.test(lower)) {
145+
category = "preference";
146+
} else if (/rozhodli|decided|will use|budeme/i.test(lower)) {
147+
category = "decision";
148+
} else if (/\+\d{10,}|@[\w.-]+\.\w+|is called|jmenuje se/i.test(lower)) {
149+
category = "entity";
150+
} else if (/is|are|has|have|je|má|jsou/i.test(lower)) {
151+
category = "fact";
152+
} else {
153+
category = "other";
154+
}
155+
156+
expect(category).toBe(expected);
157+
}
158+
});
159+
});
160+
161+
// Live tests that require OpenAI API key and actually use LanceDB
162+
describeWithKey("memory plugin live tests", () => {
163+
let tmpDir: string;
164+
let dbPath: string;
165+
166+
beforeEach(async () => {
167+
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-memory-live-"));
168+
dbPath = path.join(tmpDir, "lancedb");
169+
});
170+
171+
afterEach(async () => {
172+
if (tmpDir) {
173+
await fs.rm(tmpDir, { recursive: true, force: true });
174+
}
175+
});
176+
177+
test("memory tools work end-to-end", async () => {
178+
const { default: memoryPlugin } = await import("./index.js");
179+
180+
// Mock plugin API
181+
const registeredTools: any[] = [];
182+
const registeredClis: any[] = [];
183+
const registeredServices: any[] = [];
184+
const registeredHooks: Record<string, any[]> = {};
185+
const logs: string[] = [];
186+
187+
const mockApi = {
188+
id: "memory",
189+
name: "Memory (Vector)",
190+
source: "test",
191+
config: {},
192+
pluginConfig: {
193+
embedding: {
194+
apiKey: OPENAI_API_KEY,
195+
model: "text-embedding-3-small",
196+
},
197+
dbPath,
198+
autoCapture: false,
199+
autoRecall: false,
200+
},
201+
runtime: {},
202+
logger: {
203+
info: (msg: string) => logs.push(`[info] ${msg}`),
204+
warn: (msg: string) => logs.push(`[warn] ${msg}`),
205+
error: (msg: string) => logs.push(`[error] ${msg}`),
206+
debug: (msg: string) => logs.push(`[debug] ${msg}`),
207+
},
208+
registerTool: (tool: any, opts: any) => {
209+
registeredTools.push({ tool, opts });
210+
},
211+
registerCli: (registrar: any, opts: any) => {
212+
registeredClis.push({ registrar, opts });
213+
},
214+
registerService: (service: any) => {
215+
registeredServices.push(service);
216+
},
217+
on: (hookName: string, handler: any) => {
218+
if (!registeredHooks[hookName]) registeredHooks[hookName] = [];
219+
registeredHooks[hookName].push(handler);
220+
},
221+
resolvePath: (p: string) => p,
222+
};
223+
224+
// Register plugin
225+
await memoryPlugin.register(mockApi as any);
226+
227+
// Check registration
228+
expect(registeredTools.length).toBe(3);
229+
expect(registeredTools.map((t) => t.opts?.name)).toContain("memory_recall");
230+
expect(registeredTools.map((t) => t.opts?.name)).toContain("memory_store");
231+
expect(registeredTools.map((t) => t.opts?.name)).toContain("memory_forget");
232+
expect(registeredClis.length).toBe(1);
233+
expect(registeredServices.length).toBe(1);
234+
235+
// Get tool functions
236+
const storeTool = registeredTools.find((t) => t.opts?.name === "memory_store")?.tool;
237+
const recallTool = registeredTools.find((t) => t.opts?.name === "memory_recall")?.tool;
238+
const forgetTool = registeredTools.find((t) => t.opts?.name === "memory_forget")?.tool;
239+
240+
// Test store
241+
const storeResult = await storeTool.execute("test-call-1", {
242+
text: "The user prefers dark mode for all applications",
243+
importance: 0.8,
244+
category: "preference",
245+
});
246+
247+
expect(storeResult.details?.action).toBe("created");
248+
expect(storeResult.details?.id).toBeDefined();
249+
const storedId = storeResult.details?.id;
250+
251+
// Test recall
252+
const recallResult = await recallTool.execute("test-call-2", {
253+
query: "dark mode preference",
254+
limit: 5,
255+
});
256+
257+
expect(recallResult.details?.count).toBeGreaterThan(0);
258+
expect(recallResult.details?.memories?.[0]?.text).toContain("dark mode");
259+
260+
// Test duplicate detection
261+
const duplicateResult = await storeTool.execute("test-call-3", {
262+
text: "The user prefers dark mode for all applications",
263+
});
264+
265+
expect(duplicateResult.details?.action).toBe("duplicate");
266+
267+
// Test forget
268+
const forgetResult = await forgetTool.execute("test-call-4", {
269+
memoryId: storedId,
270+
});
271+
272+
expect(forgetResult.details?.action).toBe("deleted");
273+
274+
// Verify it's gone
275+
const recallAfterForget = await recallTool.execute("test-call-5", {
276+
query: "dark mode preference",
277+
limit: 5,
278+
});
279+
280+
expect(recallAfterForget.details?.count).toBe(0);
281+
}, 60000); // 60s timeout for live API calls
282+
});

0 commit comments

Comments
 (0)