/** * MemoryBackend — injection, route dispatch, and payload normalization. * * Covers the unified `/web/memory/*` contract: * - no backend injected → routes fall back to the sqlite multi-user * adapter (status reports mode='sqlite' with the full status shape, * operations serve the caller's visible memories, not 404) * - backend injected → routes delegate to it (scope/list/write/promote/ * search/governance) * - normalizePayload preserves memory_* meta fields on the SSE wire * - team endpoints surface the backend's own errors (e.g. team disabled) */ import { beforeEach, describe, expect, mock, test } from 'bun:test' import { mockConfigModule } from './helpers/mock-config' // Mock config (apiKeys: ['test-api-key']) mock.module('../config', () => mockConfigModule({})) import { Hono } from 'hono' import { freshDb } from './helpers/db' import { createUserDirectly, type TestUser } from './helpers/fixtures' import { issueSessionToken } from '../auth/session' import { getDb } from '../db/sqlite' import { setMemoryBackend, type MemoryBackend } from '../services/memoryBackend' import memoryRoutes from '../routes/web/memories' import { normalizePayload } from '../services/transport' freshDb() function buildApp(): Hono { const app = new Hono() app.route('/web', memoryRoutes as unknown as Hono) return app } function mockBackend(overrides: Partial = {}): MemoryBackend { return { mode: 'memdir', status: async () => ({ mode: 'memdir' as const, enabled: true, memoryDir: '/tmp/mem', teamEnabled: false, automation: { prefetch: true, extract: false, autoDream: true, mode: 'normal' as const, }, }), listProjects: async () => [], list: async () => [], read: async () => null, write: async () => ({ error: null }), delete: async () => ({ error: null }), create: async () => ({ error: null, path: 'team/x.md' }), promoteToTeam: async () => ({ error: 'team memory is not enabled' }), search: async () => [], recallTest: async () => [], governanceStatus: async () => ({ health: { totalMemories: 0, memoriesByType: {}, memoriesByLayer: {}, avgConfidence: 0, capacity: { total: 0, maxFiles: 0, utilizationPct: 0, tier: 'healthy' as const, }, }, layers: { working: 0, episodic: 0, semantic: 0, procedural: 0 }, alerts: [], conflicts: null, autoDreamSetting: undefined, automation: { prefetch: true, extract: false, autoDream: true, mode: 'normal' as const, }, teamEnabled: false, }), ...overrides, } } describe('memoryBackend', () => { let user: TestUser let authHeaders: Record let userSeq = 0 beforeEach(() => { setMemoryBackend(null) // Unique username per test — users.username has a unique constraint and // createUserDirectly swallows insert errors, so a repeat would silently // produce a userId that fails the session_tokens FK. user = createUserDirectly(getDb(), { username: `memory-tester-${userSeq++}`, }) authHeaders = { Authorization: `Bearer ${issueSessionToken(user.id, getDb()).accessToken}`, } }) test('no backend → status falls back to the sqlite adapter (full shape)', async () => { const res = await buildApp().request('/web/memory/status', { headers: authHeaders, }) expect(res.status).toBe(200) const body = (await res.json()) as { mode: string enabled: boolean teamEnabled: boolean automation: { extract: boolean } } expect(body.mode).toBe('sqlite') expect(body.enabled).toBe(true) expect(body.teamEnabled).toBe(true) expect(body.automation.extract).toBe(true) }) test('no auth → 401', async () => { setMemoryBackend(mockBackend()) const res = await buildApp().request('/web/memory/status') expect(res.status).toBe(401) }) test('no backend → operations serve the sqlite fallback, not 404', async () => { // The caller is a fresh user — the sqlite listing is visible-but-empty. const res = await buildApp().request('/web/memory/list', { headers: authHeaders, }) expect(res.status).toBe(200) expect(await res.json()).toEqual([]) }) test('backend injected → status delegates', async () => { setMemoryBackend(mockBackend()) const res = await buildApp().request('/web/memory/status', { headers: authHeaders, }) expect(res.status).toBe(200) const body = (await res.json()) as { mode: string; memoryDir: string } expect(body.mode).toBe('memdir') expect(body.memoryDir).toBe('/tmp/mem') }) test('backend injected → list passes scope filter', async () => { let receivedScope: string | undefined setMemoryBackend( mockBackend({ list: async scope => { receivedScope = scope return [] }, }), ) const res = await buildApp().request('/web/memory/list?scope=team', { headers: authHeaders, }) expect(res.status).toBe(200) expect(receivedScope).toBe('team') }) test('backend injected → list passes project selector', async () => { let receivedProject: string | undefined setMemoryBackend( mockBackend({ list: async (_scope, project) => { receivedProject = project return [] }, }), ) const res = await buildApp().request('/web/memory/list?project=all', { headers: authHeaders, }) expect(res.status).toBe(200) expect(receivedProject).toBe('all') }) test('backend injected → read passes project selector', async () => { let receivedProject: string | undefined setMemoryBackend( mockBackend({ read: async (_path, project) => { receivedProject = project return '---\nname: x\n---\nbody' }, }), ) const res = await buildApp().request( '/web/memory/file?path=a.md&project=some-project', { headers: authHeaders }, ) expect(res.status).toBe(200) expect(receivedProject).toBe('some-project') }) test('backend injected → projects endpoint delegates', async () => { setMemoryBackend( mockBackend({ listProjects: async () => [ { key: '-home-x-csa', shortName: 'csa', isCurrent: true }, { key: '-home-x-soma', shortName: 'soma', isCurrent: false }, ], }), ) const res = await buildApp().request('/web/memory/projects', { headers: authHeaders, }) expect(res.status).toBe(200) const body = (await res.json()) as { key: string shortName: string isCurrent: boolean }[] expect(body).toHaveLength(2) expect(body[0].isCurrent).toBe(true) expect(body[1].shortName).toBe('soma') }) test('search passes project selector', async () => { let receivedProject: string | undefined setMemoryBackend( mockBackend({ search: async (_pattern, project) => { receivedProject = project return [] }, }), ) const res = await buildApp().request('/web/memory/search?q=x&project=all', { headers: authHeaders, }) expect(res.status).toBe(200) expect(receivedProject).toBe('all') }) test('write requires path and content', async () => { setMemoryBackend(mockBackend()) const res = await buildApp().request('/web/memory/file', { method: 'PUT', headers: { ...authHeaders, 'content-type': 'application/json' }, body: JSON.stringify({ path: '' }), }) expect(res.status).toBe(400) }) test('promote surfaces backend error (team disabled)', async () => { setMemoryBackend(mockBackend()) const res = await buildApp().request('/web/memory/promote', { method: 'POST', headers: { ...authHeaders, 'content-type': 'application/json' }, body: JSON.stringify({ path: 'feedback_x.md' }), }) expect(res.status).toBe(400) const body = (await res.json()) as { error: { message: string } } expect(body.error.message).toContain('team memory is not enabled') }) test('create validates scope/type and delegates to backend', async () => { setMemoryBackend(mockBackend()) const badScope = await buildApp().request('/web/memory/create', { method: 'POST', headers: { ...authHeaders, 'content-type': 'application/json' }, body: JSON.stringify({ scope: 'global', name: 'x', type: 'user', content: 'y', }), }) expect(badScope.status).toBe(400) const badType = await buildApp().request('/web/memory/create', { method: 'POST', headers: { ...authHeaders, 'content-type': 'application/json' }, body: JSON.stringify({ scope: 'team', name: 'x', type: 'episodic', content: 'y', }), }) expect(badType.status).toBe(400) const missingName = await buildApp().request('/web/memory/create', { method: 'POST', headers: { ...authHeaders, 'content-type': 'application/json' }, body: JSON.stringify({ scope: 'personal', type: 'user', content: 'y' }), }) expect(missingName.status).toBe(400) }) test('create returns 201 with path on success', async () => { let received: unknown setMemoryBackend( mockBackend({ create: async input => { received = input return { error: null, path: 'team/project_deploy.md' } }, }), ) const res = await buildApp().request('/web/memory/create', { method: 'POST', headers: { ...authHeaders, 'content-type': 'application/json' }, body: JSON.stringify({ scope: 'team', name: 'Deploy workflow', description: 'How deploys run', type: 'project', content: 'Use bun run deploy.', }), }) expect(res.status).toBe(201) const body = (await res.json()) as { ok: boolean; path: string } expect(body.ok).toBe(true) expect(body.path).toBe('team/project_deploy.md') expect(received).toEqual({ scope: 'team', name: 'Deploy workflow', description: 'How deploys run', type: 'project', content: 'Use bun run deploy.', }) }) test('create surfaces backend error (duplicate path)', async () => { setMemoryBackend( mockBackend({ create: async () => ({ error: 'a memory file already exists at team/x.md', path: 'team/x.md', }), }), ) const res = await buildApp().request('/web/memory/create', { method: 'POST', headers: { ...authHeaders, 'content-type': 'application/json' }, body: JSON.stringify({ scope: 'team', name: 'x', type: 'user', content: 'y', }), }) expect(res.status).toBe(400) const body = (await res.json()) as { error: { message: string } } expect(body.error.message).toContain('already exists') }) test('search requires q', async () => { setMemoryBackend(mockBackend()) const res = await buildApp().request('/web/memory/search', { headers: authHeaders, }) expect(res.status).toBe(400) }) test('search delegates the regex pattern to the backend', async () => { let receivedPattern = '' setMemoryBackend( mockBackend({ search: async pattern => { receivedPattern = pattern return [] }, }), ) const res = await buildApp().request('/web/memory/search?q=bun%7Cnpm', { headers: authHeaders, }) expect(res.status).toBe(200) expect(receivedPattern).toBe('bun|npm') }) test('recall-test delegates and requires q', async () => { setMemoryBackend(mockBackend()) const empty = await buildApp().request('/web/memory/recall-test', { headers: authHeaders, }) expect(empty.status).toBe(400) let receivedQuery = '' let receivedTopK: number | undefined setMemoryBackend( mockBackend({ recallTest: async (query, topK) => { receivedQuery = query receivedTopK = topK return [{ path: 'feedback_bun.md', score: 0.4, mtimeMs: 0 }] }, }), ) const res = await buildApp().request( '/web/memory/recall-test?q=bun&top_k=5', { headers: authHeaders }, ) expect(res.status).toBe(200) expect(receivedQuery).toBe('bun') expect(receivedTopK).toBe(5) const body = (await res.json()) as { path: string }[] expect(body[0].path).toBe('feedback_bun.md') }) test('governance delegates to backend', async () => { setMemoryBackend( mockBackend({ governanceStatus: async () => ({ health: { totalMemories: 7, memoriesByType: { feedback: 7 }, memoriesByLayer: { semantic: 7 }, avgConfidence: 0.8, capacity: { total: 7, maxFiles: 1620, utilizationPct: 0.4, tier: 'healthy' as const, }, }, layers: { working: 0, episodic: 0, semantic: 7, procedural: 0 }, alerts: ['- [t] **write_rejected**: x'], conflicts: null, autoDreamSetting: true, automation: { prefetch: true, extract: false, autoDream: true, mode: 'normal' as const, }, teamEnabled: false, }), }), ) const res = await buildApp().request('/web/memory/governance', { headers: authHeaders, }) expect(res.status).toBe(200) const body = (await res.json()) as { health: { totalMemories: number } } expect(body.health.totalMemories).toBe(7) }) test('normalizePayload preserves memory_changed meta fields', () => { const normalized = normalizePayload('memory_changed', { path: 'feedback_bun.md', name: 'bun', type: 'feedback', layer: 'semantic', scope: 'personal', }) expect(normalized.path).toBe('feedback_bun.md') expect(normalized.scope).toBe('personal') expect(normalized.type).toBe('feedback') }) test('normalizePayload preserves memory_recall hits', () => { const normalized = normalizePayload('memory_recall', { query: 'bun install', sessionId: 's-1', hits: [{ path: 'feedback_bun.md', score: 0.42 }], }) expect(normalized.query).toBe('bun install') expect(normalized.sessionId).toBe('s-1') expect(normalized.hits).toEqual([{ path: 'feedback_bun.md', score: 0.42 }]) }) test('normalizePayload preserves memory_dream_completed summary', () => { const normalized = normalizePayload('memory_dream_completed', { summary: 'merged 3 memories', }) expect(normalized.summary).toBe('merged 3 memories') }) })