-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathagent-memory.test.js
More file actions
457 lines (402 loc) · 13 KB
/
agent-memory.test.js
File metadata and controls
457 lines (402 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
import { describe, it, expect, beforeEach, vi } from 'vitest';
// ── Mocks ─────────────────────────────────────────────────────────────────
const sqlMock = vi.fn();
vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock }));
const getSessionUserMock = vi.fn();
const authenticateBearerMock = vi.fn();
const extractBearerMock = vi.fn();
vi.mock('../../api/_lib/auth.js', () => ({
getSessionUser: (...a) => getSessionUserMock(...a),
authenticateBearer: (...a) => authenticateBearerMock(...a),
extractBearer: (...a) => extractBearerMock(...a),
}));
vi.mock('../../api/_lib/env.js', () => ({
env: {
APP_ORIGIN: 'http://localhost:3000',
ISSUER: 'http://test',
MCP_RESOURCE: 'http://test',
},
}));
const { default: handler } = await import('../../api/agent-memory.js');
// ── Helpers ───────────────────────────────────────────────────────────────
function mkReq({ method = 'GET', url = '/api/agent-memory', headers = {}, body = null } = {}) {
const req = {
method,
url,
headers: { ...headers },
on(event, cb) {
if (event === 'data' && body != null) {
const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));
queueMicrotask(() => {
cb(buf);
this._endCb?.();
});
} else if (event === 'end') {
this._endCb = cb;
if (body == null) queueMicrotask(() => cb());
} else if (event === 'error') {
// no-op
}
},
destroy() {},
};
return req;
}
function mkRes() {
return {
statusCode: 200,
headers: {},
body: undefined,
writableEnded: false,
setHeader(k, v) {
this.headers[k.toLowerCase()] = v;
},
end(b) {
this.body = b;
this.writableEnded = true;
},
};
}
function parse(res) {
return res.body ? JSON.parse(res.body) : undefined;
}
// Queue sql results FIFO. Each sql`...` call consumes one.
let sqlQueue = [];
function queueSql(...results) {
sqlQueue.push(...results);
}
async function invoke(reqOpts) {
const req = mkReq(reqOpts);
const res = mkRes();
await handler(req, res);
return { res, status: res.statusCode, body: parse(res) };
}
// ── Reset ─────────────────────────────────────────────────────────────────
beforeEach(() => {
sqlQueue = [];
sqlMock.mockReset();
sqlMock.mockImplementation(() => {
if (sqlQueue.length === 0) throw new Error('unexpected sql call — queue is empty');
return Promise.resolve(sqlQueue.shift());
});
getSessionUserMock.mockReset().mockResolvedValue(null);
authenticateBearerMock.mockReset().mockResolvedValue(null);
extractBearerMock.mockReset().mockReturnValue(null);
});
// ── Auth ──────────────────────────────────────────────────────────────────
describe('auth', () => {
it('GET without session or bearer returns empty list (200)', async () => {
// Public embeds boot this fetch on every page load. Returning an empty
// list (instead of 401) keeps the console clean for anonymous viewers.
const { status, body } = await invoke({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
expect(status).toBe(200);
expect(body.entries).toEqual([]);
});
it('POST without auth returns 401', async () => {
const { status } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
body: { agentId: 'a1', entry: { content: 'x' } },
});
expect(status).toBe(401);
});
it('DELETE without auth returns 401', async () => {
const { status } = await invoke({ method: 'DELETE', url: '/api/agent-memory/mem-1' });
expect(status).toBe(401);
});
it('accepts bearer token when session is absent', async () => {
extractBearerMock.mockReturnValue('tok');
authenticateBearerMock.mockResolvedValue({ userId: 'u1' });
queueSql([{ user_id: 'u1' }], []); // ownership row, then memory rows
const { status, body } = await invoke({
method: 'GET',
url: '/api/agent-memory?agentId=a1',
});
expect(status).toBe(200);
expect(body.entries).toEqual([]);
});
});
// ── GET (list) ────────────────────────────────────────────────────────────
describe('GET /api/agent-memory', () => {
beforeEach(() => {
getSessionUserMock.mockResolvedValue({ id: 'u1' });
});
it('returns entries for the authenticated agent owner', async () => {
const createdAt = new Date('2024-06-01T00:00:00Z');
queueSql(
[{ user_id: 'u1' }],
[
{
id: 'm1',
agent_id: 'a1',
type: 'project',
content: 'test note',
tags: ['alpha'],
context: { k: 1 },
salience: 0.8,
created_at: createdAt,
expires_at: null,
},
],
);
const { status, body } = await invoke({
method: 'GET',
url: '/api/agent-memory?agentId=a1',
});
expect(status).toBe(200);
expect(body.entries).toHaveLength(1);
expect(body.entries[0]).toMatchObject({
id: 'm1',
agent_id: 'a1',
type: 'project',
content: 'test note',
tags: ['alpha'],
salience: 0.8,
createdAt: createdAt.getTime(),
expiresAt: null,
});
});
it('returns 400 when agentId is missing', async () => {
const { status, body } = await invoke({ method: 'GET', url: '/api/agent-memory' });
expect(status).toBe(400);
expect(body.error).toBe('validation_error');
});
it('returns empty list (200) when agent does not exist', async () => {
queueSql([]); // no ownership row
const { status, body } = await invoke({ method: 'GET', url: '/api/agent-memory?agentId=nope' });
expect(status).toBe(200);
expect(body.entries).toEqual([]);
});
it('returns empty list (200) when agent is owned by another user', async () => {
queueSql([{ user_id: 'other-user' }]);
const { status, body } = await invoke({
method: 'GET',
url: '/api/agent-memory?agentId=a1',
});
expect(status).toBe(200);
expect(body.entries).toEqual([]);
});
it('handles null tags/context with safe defaults in response', async () => {
queueSql(
[{ user_id: 'u1' }],
[
{
id: 'm2',
agent_id: 'a1',
type: 'user',
content: '',
tags: null,
context: null,
salience: 0.5,
created_at: new Date(),
expires_at: null,
},
],
);
const { body } = await invoke({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
expect(body.entries[0].tags).toEqual([]);
expect(body.entries[0].context).toEqual({});
});
});
// ── POST (upsert) ─────────────────────────────────────────────────────────
describe('POST /api/agent-memory', () => {
beforeEach(() => {
getSessionUserMock.mockResolvedValue({ id: 'u1' });
});
it('creates a new entry (no client id) and returns it with an id', async () => {
const createdAt = new Date();
queueSql(
[{ user_id: 'u1' }],
[
{
id: 'server-gen-id',
agent_id: 'a1',
type: 'project',
content: 'new memory',
tags: [],
context: {},
salience: 0.5,
created_at: createdAt,
expires_at: null,
},
],
);
const { status, body } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
body: { agentId: 'a1', entry: { content: 'new memory' } },
});
expect(status).toBe(201);
expect(body.entry.id).toBe('server-gen-id');
expect(body.entry.content).toBe('new memory');
});
it('returns 400 when agentId is missing', async () => {
const { status, body } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
body: { entry: { content: 'x' } },
});
expect(status).toBe(400);
expect(body.error_description).toMatch(/agentId/);
});
it('returns 400 when entry is missing', async () => {
const { status, body } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
body: { agentId: 'a1' },
});
expect(status).toBe(400);
expect(body.error_description).toMatch(/entry/);
});
it('returns 403 when agent belongs to another user', async () => {
queueSql([{ user_id: 'other' }]);
const { status } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
body: { agentId: 'a1', entry: { content: 'steal' } },
});
expect(status).toBe(403);
});
it('upserts an entry when a client-supplied id is provided', async () => {
queueSql(
[{ user_id: 'u1' }],
[
{
id: 'client-id',
agent_id: 'a1',
type: 'user',
content: 'updated',
tags: [],
context: {},
salience: 0.9,
created_at: new Date(),
expires_at: null,
},
],
);
const { status, body } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
body: {
agentId: 'a1',
entry: { id: 'client-id', type: 'user', content: 'updated', salience: 0.9 },
},
});
expect(status).toBe(201);
expect(body.entry.id).toBe('client-id');
expect(body.entry.salience).toBe(0.9);
});
it('returns 409 when id collides with another agent\'s memory', async () => {
// ON CONFLICT WHERE guard fires — SQL returns no rows.
queueSql([{ user_id: 'u1' }], []);
const { status, body } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
body: { agentId: 'a1', entry: { id: 'stolen-id', content: 'x' } },
});
expect(status).toBe(409);
expect(body.error).toBe('id_conflict');
});
it('normalizes unknown entry.type to "project"', async () => {
queueSql(
[{ user_id: 'u1' }],
[
{
id: 'm1',
agent_id: 'a1',
type: 'project',
content: 'x',
tags: [],
context: {},
salience: 0.5,
created_at: new Date(),
expires_at: null,
},
],
);
const { status, body } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
body: { agentId: 'a1', entry: { type: 'bogus-type', content: 'x' } },
});
expect(status).toBe(201);
expect(body.entry.type).toBe('project');
});
it('truncates content longer than 10,000 characters', async () => {
const huge = 'x'.repeat(20_000);
let capturedContent;
sqlMock.mockReset();
let call = 0;
sqlMock.mockImplementation((_strings, ...values) => {
call += 1;
if (call === 1) return Promise.resolve([{ user_id: 'u1' }]);
capturedContent = values.find((v) => typeof v === 'string' && v.length >= 10_000);
return Promise.resolve([
{
id: 'x',
agent_id: 'a1',
type: 'project',
content: capturedContent,
tags: [],
context: {},
salience: 0.5,
created_at: new Date(),
expires_at: null,
},
]);
});
const { status } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
body: { agentId: 'a1', entry: { content: huge } },
});
expect(status).toBe(201);
expect(capturedContent).toBeDefined();
expect(capturedContent.length).toBe(10_000);
});
});
// ── DELETE ────────────────────────────────────────────────────────────────
describe('DELETE /api/agent-memory/:id', () => {
beforeEach(() => {
getSessionUserMock.mockResolvedValue({ id: 'u1' });
});
it('deletes the memory row and returns { ok: true }', async () => {
queueSql([{ id: 'mem-1', user_id: 'u1' }], []); // lookup, delete
const { status, body } = await invoke({
method: 'DELETE',
url: '/api/agent-memory/mem-1',
});
expect(status).toBe(200);
expect(body).toEqual({ ok: true });
});
it('returns 404 when the memory does not exist', async () => {
queueSql([]); // no row found
const { status } = await invoke({ method: 'DELETE', url: '/api/agent-memory/ghost' });
expect(status).toBe(404);
});
it('returns 403 when memory belongs to another user', async () => {
queueSql([{ id: 'mem-1', user_id: 'other' }]);
const { status, body } = await invoke({
method: 'DELETE',
url: '/api/agent-memory/mem-1',
});
expect(status).toBe(403);
expect(body.error).toBe('forbidden');
});
});
// ── Method routing ────────────────────────────────────────────────────────
describe('method routing', () => {
it('PUT returns 405', async () => {
const { status } = await invoke({ method: 'PUT', url: '/api/agent-memory' });
expect(status).toBe(405);
});
it('OPTIONS returns 204 with CORS headers', async () => {
const { status, res } = await invoke({
method: 'OPTIONS',
headers: { origin: 'http://localhost:3000' },
});
expect(status).toBe(204);
expect(res.headers['access-control-allow-methods']).toMatch(/GET/);
expect(res.headers['access-control-allow-methods']).toMatch(/DELETE/);
});
});