Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✅ test(database): 100% coverage for userMemory models (part 1) (#21779)

Arvin Xu127e68a60d6e
diff --git a/packages/database/src/models/userMemory/__tests__/model.countFallback.test.ts b/packages/database/src/models/userMemory/__tests__/model.countFallback.test.ts
new file mode 100644
index 00000000000..9e20a5fdc34
--- /dev/null
+++ b/packages/database/src/models/userMemory/__tests__/model.countFallback.test.ts
@@ -0,0 +1,93 @@
+// @vitest-environment node
+import { PGlite } from '@electric-sql/pglite';
+import { LayersEnum } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { drizzle as proxyDrizzle } from 'drizzle-orm/pg-proxy';
+import type { Pool } from 'pg';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import * as schema from '../../../schemas';
+import { users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { UserMemoryIdentityModel } from '../identity';
+import { UserMemoryModel } from '../model';
+
+const userId = 'memory-count-fallback-test-user';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const client = (serverDB as unknown as { $client: PGlite | Pool }).$client;
+
+/** Runs a statement on the real test client: PGlite (client-db suite) or node-postgres. */
+const runOnTestDB = async (text: string, values: unknown[], arrayMode: boolean) => {
+ if (client instanceof PGlite) {
+ return client.query(text, values, { rowMode: arrayMode ? 'array' : 'object' });
+ }
+
+ return client.query({ rowMode: arrayMode ? 'array' : undefined, text, values });
+};
+
+/**
+ * Forwards every statement to the real test database, but answers `SELECT COUNT(...)` with no rows,
+ * so the `totalResult[0]?.count ?? 0` fallbacks see an aggregate that produced nothing.
+ */
+const countlessDB = proxyDrizzle(
+ async (text, params, method) => {
+ if (/^select count\(/i.test(text.trim())) return { rows: [] };
+
+ const result = await runOnTestDB(text, params, method === 'all');
+
+ return { rows: result.rows };
+ },
+ { schema },
+) as unknown as LobeChatDatabase;
+
+beforeAll(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.insert(users).values({ id: userId });
+
+ const seed = new UserMemoryModel(serverDB, userId);
+ await seed.createContextMemory({ context: {}, memoryLayer: LayersEnum.Context } as any);
+ await seed.createActivityMemory({
+ activity: { status: 'completed' },
+ memoryLayer: LayersEnum.Activity,
+ } as any);
+ await seed.createExperienceMemory({
+ experience: {},
+ memoryLayer: LayersEnum.Experience,
+ } as any);
+ await seed.createPreferenceMemory({
+ memoryLayer: LayersEnum.Preference,
+ preference: {},
+ } as any);
+ await seed.addIdentityEntry({ identity: { relationship: 'self', type: 'personal' } } as any);
+});
+
+// Memory rows cascade from the user row.
+afterAll(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+});
+
+describe('userMemory paginated queries - aggregate with no rows', () => {
+ it.each([
+ LayersEnum.Context,
+ LayersEnum.Activity,
+ LayersEnum.Experience,
+ LayersEnum.Identity,
+ LayersEnum.Preference,
+ ])('queryMemories(%s) still returns rows and reports total 0', async (layer) => {
+ const result = await new UserMemoryModel(countlessDB, userId).queryMemories({ layer });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0]).toMatchObject({ layer });
+ expect(result).toMatchObject({ page: 1, pageSize: 20, total: 0 });
+ });
+
+ it('identity queryList() still returns rows and reports total 0', async () => {
+ const result = await new UserMemoryIdentityModel(countlessDB, userId).queryList();
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0]).toMatchObject({ relationship: 'self', type: 'personal' });
+ expect(result).toMatchObject({ page: 1, pageSize: 20, total: 0 });
+ });
+});
diff --git a/packages/database/src/models/userMemory/__tests__/model.defaults.test.ts b/packages/database/src/models/userMemory/__tests__/model.defaults.test.ts
new file mode 100644
index 00000000000..f53327084ad
--- /dev/null
+++ b/packages/database/src/models/userMemory/__tests__/model.defaults.test.ts
@@ -0,0 +1,629 @@
+// @vitest-environment node
+import { LayersEnum, MemorySourceType, MergeStrategyEnum } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ userMemories,
+ userMemoriesContexts,
+ userMemoriesIdentities,
+ users,
+} from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { UserMemoryActivityModel } from '../activity';
+import { UserMemoryContextModel } from '../context';
+import { UserMemoryExperienceModel } from '../experience';
+import { UserMemoryIdentityModel } from '../identity';
+import { UserMemoryModel } from '../model';
+
+const userId = 'memory-defaults-test-user';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+let memoryModel: UserMemoryModel;
+
+beforeEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.insert(users).values({ id: userId });
+ memoryModel = new UserMemoryModel(serverDB, userId);
+});
+
+// Memory rows cascade from the user row.
+afterAll(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+});
+
+const BUILDER_METHODS = [
+ 'from',
+ 'groupBy',
+ 'innerJoin',
+ 'leftJoin',
+ 'limit',
+ 'offset',
+ 'onConflictDoNothing',
+ 'onConflictDoUpdate',
+ 'orderBy',
+ 'returning',
+ 'set',
+ 'values',
+ 'where',
+] as const;
+
+/** Chainable fake query builder: every builder method returns itself and awaiting it yields `rows`. */
+const chain = (rows: unknown[]) => {
+ const builder: any = Promise.resolve(rows);
+ for (const method of BUILDER_METHODS) builder[method] = () => builder;
+
+ return builder;
+};
+
+const ftsSource = (candidateIds: string[]) => ({
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates: vi.fn(async () => ({
+ candidates: candidateIds.map((id, index) => ({ id, score: candidateIds.length - index })),
+ total: candidateIds.length,
+ })),
+});
+
+describe('UserMemoryModel static parsers - fallbacks', () => {
+ it('wraps a JSON scalar association extra and drops a missing one', () => {
+ expect(
+ UserMemoryModel.parseAssociatedSubjects([
+ { extra: '42', name: 'Scalar', type: 'person' },
+ { extra: null, name: 'Bare', type: 'person' },
+ ]),
+ ).toEqual([
+ { extra: { value: 42 }, name: 'Scalar', type: 'person' },
+ { name: 'Bare', type: 'person' },
+ ]);
+ });
+
+ it('returns an empty list when no subject survives parsing', () => {
+ expect(UserMemoryModel.parseAssociatedSubjects([42, { name: 7 }])).toEqual([]);
+ });
+
+ it('skips non-object locations', () => {
+ expect(
+ UserMemoryModel.parseAssociatedLocations([null, 'Paris', { name: 'Tokyo' }] as any),
+ ).toEqual([{ address: undefined, name: 'Tokyo', tags: undefined, type: undefined }]);
+ });
+
+ it('returns null for a whitespace-only date string', () => {
+ expect(UserMemoryModel.parseDateFromString(' ')).toBeNull();
+ });
+});
+
+describe('UserMemoryModel.extractSourceMetadata', () => {
+ const extract = (metadata: unknown) => (memoryModel as any).extractSourceMetadata(metadata);
+
+ it('ignores non-object metadata', () => {
+ expect(extract('topic-1')).toEqual({});
+ });
+
+ it('reads string source fields and defaults the type to chat topics', () => {
+ expect(extract({ sourceId: 'topic-1', sourceType: 'custom' })).toEqual({
+ sourceId: 'topic-1',
+ sourceType: 'custom',
+ });
+ expect(extract({ sourceId: 7, sourceType: 7 })).toEqual({
+ sourceId: undefined,
+ sourceType: MemorySourceType.ChatTopic,
+ });
+ });
+});
+
+describe('UserMemoryModel create defaults', () => {
+ it('create() inserts a bare base memory with null optional columns', async () => {
+ const memory = await memoryModel.create({ memoryLayer: LayersEnum.Context } as any);
+
+ expect(memory).toMatchObject({
+ details: null,
+ memoryLayer: LayersEnum.Context,
+ memoryType: null,
+ metadata: null,
+ status: null,
+ summary: null,
+ tags: null,
+ title: null,
+ userId,
+ });
+ });
+
+ it('createContextMemory() fills every omitted context field', async () => {
+ const { context, memory } = await memoryModel.createContextMemory({
+ context: {},
+ memoryLayer: LayersEnum.Context,
+ } as any);
+
+ expect(memory.tags).toBeNull();
+ expect(context).toMatchObject({
+ associatedObjects: [],
+ associatedSubjects: [],
+ description: null,
+ tags: [],
+ title: null,
+ type: null,
+ userMemoryIds: [memory.id],
+ });
+ });
+
+ it('createExperienceMemory() falls back to the memory type, then to null', async () => {
+ const typed = await memoryModel.createExperienceMemory({
+ experience: {},
+ memoryLayer: LayersEnum.Experience,
+ memoryType: 'learning',
+ } as any);
+ const untyped = await memoryModel.createExperienceMemory({
+ experience: {},
+ memoryLayer: LayersEnum.Experience,
+ } as any);
+
+ expect(typed.memory.tags).toBeNull();
+ expect(typed.experience).toMatchObject({
+ action: null,
+ keyLearning: null,
+ possibleOutcome: null,
+ reasoning: null,
+ situation: null,
+ tags: [],
+ type: 'learning',
+ });
+ expect(untyped.experience.type).toBeNull();
+ });
+
+ it('createPreferenceMemory() fills omitted fields and a null type', async () => {
+ const { memory, preference } = await memoryModel.createPreferenceMemory({
+ memoryLayer: LayersEnum.Preference,
+ preference: {},
+ } as any);
+
+ expect(memory).toMatchObject({ metadata: null, tags: null });
+ expect(preference).toMatchObject({
+ conclusionDirectives: null,
+ metadata: null,
+ scorePriority: null,
+ suggestions: null,
+ tags: [],
+ type: null,
+ });
+ });
+});
+
+describe('UserMemoryModel detail lookups', () => {
+ it('findUserMemoryRawById() returns undefined for an unknown id', async () => {
+ await expect(
+ (memoryModel as any).findUserMemoryRawById('missing-memory'),
+ ).resolves.toBeUndefined();
+ });
+
+ it('getMemoryDetail() looks up the source topic through the model', async () => {
+ const { context } = await memoryModel.createContextMemory({
+ context: { metadata: { sourceId: 'missing-topic' } },
+ memoryLayer: LayersEnum.Context,
+ } as any);
+
+ const detail = await memoryModel.getMemoryDetail({ id: context.id, layer: LayersEnum.Context });
+
+ expect(detail).toMatchObject({
+ layer: LayersEnum.Context,
+ source: undefined,
+ sourceType: MemorySourceType.ChatTopic,
+ });
+ });
+});
+
+describe('UserMemoryModel identity entry normalization', () => {
+ const readIdentity = async (identityId: string) => {
+ const [identity] = await serverDB
+ .select()
+ .from(userMemoriesIdentities)
+ .where(eq(userMemoriesIdentities.id, identityId));
+ return identity;
+ };
+
+ it('addIdentityEntry() defaults a missing base and identity', async () => {
+ const { identityId, userMemoryId } = await memoryModel.addIdentityEntry({} as any);
+
+ const identity = await readIdentity(identityId);
+ const [memory] = await serverDB
+ .select()
+ .from(userMemories)
+ .where(eq(userMemories.id, userMemoryId));
+
+ expect(memory).toMatchObject({ memoryLayer: 'identity', status: 'active' });
+ expect(identity).toMatchObject({ episodicDate: null, relationship: null, type: null });
+ });
+
+ it('addIdentityEntry() keeps explicit nulls and drops unknown enum values', async () => {
+ const explicitNull = await memoryModel.addIdentityEntry({
+ base: { status: null },
+ identity: { episodicDate: '2024-05-01', relationship: null, type: null },
+ } as any);
+ const unknownValues = await memoryModel.addIdentityEntry({
+ identity: { relationship: 'stranger', type: 'cosmic' },
+ } as any);
+
+ const [memory] = await serverDB
+ .select()
+ .from(userMemories)
+ .where(eq(userMemories.id, explicitNull.userMemoryId));
+
+ expect(memory.status).toBeNull();
+ expect(await readIdentity(explicitNull.identityId)).toMatchObject({
+ episodicDate: new Date('2024-05-01'),
+ relationship: null,
+ type: null,
+ });
+ expect(await readIdentity(unknownValues.identityId)).toMatchObject({
+ relationship: null,
+ type: null,
+ });
+ });
+
+ it('addIdentityEntry() / updateIdentityEntry() store null for non-string enum values', async () => {
+ // Tool payloads arrive as untyped JSON, so a number can reach the enum normalizers.
+ const { identityId } = await memoryModel.addIdentityEntry({
+ identity: { relationship: 7, type: 7 },
+ } as any);
+
+ expect(await readIdentity(identityId)).toMatchObject({ relationship: null, type: null });
+
+ const typed = await memoryModel.addIdentityEntry({
+ identity: { relationship: 'self', type: 'personal' },
+ } as any);
+ await memoryModel.updateIdentityEntry({
+ identity: { relationship: 7, type: 7 },
+ identityId: typed.identityId,
+ } as any);
+
+ expect(await readIdentity(typed.identityId)).toMatchObject({ relationship: null, type: null });
+ });
+
+ it('updateIdentityEntry() skips writes for empty base and identity payloads', async () => {
+ const { identityId } = await memoryModel.addIdentityEntry({
+ identity: { relationship: 'self', type: 'personal' },
+ } as any);
+ const before = await readIdentity(identityId);
+
+ await expect(memoryModel.updateIdentityEntry({ base: {}, identityId })).resolves.toBe(true);
+ await expect(memoryModel.updateIdentityEntry({ identity: {}, identityId })).resolves.toBe(true);
+
+ expect((await readIdentity(identityId)).updatedAt).toEqual(before.updatedAt);
+ });
+
+ it('updateIdentityEntry() replaces an unparseable lastAccessedAt with now', async () => {
+ const { identityId, userMemoryId } = await memoryModel.addIdentityEntry({
+ base: { lastAccessedAt: new Date('2020-01-01') },
+ } as any);
+
+ await memoryModel.updateIdentityEntry({
+ base: { lastAccessedAt: 'not-a-date' } as any,
+ identityId,
+ });
+
+ const [memory] = await serverDB
+ .select()
+ .from(userMemories)
+ .where(eq(userMemories.id, userMemoryId));
+ expect(memory.lastAccessedAt.getTime()).toBeGreaterThan(new Date('2020-01-02').getTime());
+ });
+
+ it('updateIdentityEntry(replace) normalizes null, unknown and valid enum values', async () => {
+ const { identityId } = await memoryModel.addIdentityEntry({
+ identity: { relationship: 'self', type: 'personal' },
+ } as any);
+
+ await memoryModel.updateIdentityEntry({
+ identity: { episodicDate: '2024-06-01', relationship: null, type: null } as any,
+ identityId,
+ mergeStrategy: MergeStrategyEnum.Replace,
+ });
+ expect(await readIdentity(identityId)).toMatchObject({
+ episodicDate: new Date('2024-06-01'),
+ relationship: null,
+ type: null,
+ });
+
+ await memoryModel.updateIdentityEntry({
+ identity: { relationship: 'stranger', type: 'cosmic' } as any,
+ identityId,
+ mergeStrategy: MergeStrategyEnum.Replace,
+ });
+ expect(await readIdentity(identityId)).toMatchObject({
+ episodicDate: null,
+ relationship: null,
+ type: null,
+ });
+
+ await memoryModel.updateIdentityEntry({
+ identity: { relationship: ' Self ', type: ' Personal ' } as any,
+ identityId,
+ mergeStrategy: MergeStrategyEnum.Replace,
+ });
+ expect(await readIdentity(identityId)).toMatchObject({
+ relationship: 'self',
+ type: 'personal',
+ });
+ });
+
+ it('updateIdentityEntry(merge) normalizes null and unknown enum values and coerces dates', async () => {
+ const { identityId } = await memoryModel.addIdentityEntry({
+ identity: { relationship: 'self', type: 'personal' },
+ } as any);
+
+ await memoryModel.updateIdentityEntry({
+ identity: { episodicDate: '2024-07-01', relationship: null, type: null } as any,
+ identityId,
+ });
+ expect(await readIdentity(identityId)).toMatchObject({
+ episodicDate: new Date('2024-07-01'),
+ relationship: null,
+ type: null,
+ });
+
+ await memoryModel.updateIdentityEntry({
+ identity: { relationship: 'stranger', type: 'cosmic' } as any,
+ identityId,
+ });
+ expect(await readIdentity(identityId)).toMatchObject({ relationship: null, type: null });
+ });
+});
+
+describe('UserMemoryModel.listMemories - parameter fallbacks', () => {
+ it('normalizes null paging, honours ascending order and ignores unsupported layers', async () => {
+ const first = await memoryModel.createContextMemory({
+ context: { title: 'first' },
+ memoryLayer: LayersEnum.Context,
+ } as any);
+ const second = await memoryModel.createContextMemory({
+ context: { title: 'second' },
+ memoryLayer: LayersEnum.Context,
+ } as any);
+ await serverDB
+ .update(userMemoriesContexts)
+ .set({ updatedAt: new Date('2020-01-01') })
+ .where(eq(userMemoriesContexts.id, first.context.id));
+
+ const items = await memoryModel.listMemories({
+ layer: LayersEnum.Context,
+ order: 'asc',
+ page: null,
+ pageSize: null,
+ } as any);
+
+ expect(items.map((item: any) => item.context.id)).toEqual([
+ first.context.id,
+ second.context.id,
+ ]);
+ await expect(memoryModel.listMemories({ layer: LayersEnum.Activity } as any)).resolves.toEqual(
+ [],
+ );
+ });
+});
+
+describe('UserMemoryModel.queryMemories - filters and candidate paths', () => {
+ it('defaults null page, size and layer to the first context page', async () => {
+ await memoryModel.createContextMemory({ context: {}, memoryLayer: LayersEnum.Context } as any);
+
+ const result = await memoryModel.queryMemories({
+ layer: null,
+ page: null,
+ pageSize: null,
+ } as any);
+
+ expect(result).toMatchObject({ page: 1, pageSize: 20, total: 1 });
+ expect(result.items[0].layer).toBe(LayersEnum.Context);
+ });
+
+ it('filters contexts by category and type, forwarding them to the candidate source', async () => {
+ const match = await memoryModel.createContextMemory({
+ context: { scoreImpact: 0.9, scoreUrgency: 0.1, type: 'project' },
+ memoryCategory: 'work',
+ memoryLayer: LayersEnum.Context,
+ } as any);
+ await memoryModel.createContextMemory({
+ context: { type: 'other' },
+ memoryCategory: 'work',
+ memoryLayer: LayersEnum.Context,
+ } as any);
+ const source = ftsSource([match.context.id]);
+ const model = new UserMemoryModel(serverDB, userId, source);
+
+ for (const sort of ['scoreUrgency', 'scoreImpact'] as const) {
+ const result = await model.queryMemories({
+ categories: ['work'],
+ layer: LayersEnum.Context,
+ order: 'asc',
+ q: 'project',
+ sort,
+ types: ['project'],
+ });
+
+ expect(result.items.map((item: any) => item.context.id)).toEqual([match.context.id]);
+ }
+ expect(source.ftsSearchCandidates).toHaveBeenCalledWith(
+ expect.objectContaining({
+ entity: 'memoryContexts',
+ filters: { memoryCategories: ['work'], memoryTypes: ['project'] },
+ }),
+ );
+ });
+
+ it('filters activities by type and status sorted by start time', async () => {
+ const match = await memoryModel.createActivityMemory({
+ activity: { startsAt: new Date('2024-01-01'), status: 'completed', type: 'event' },
+ memoryLayer: LayersEnum.Activity,
+ } as any);
+ await memoryModel.createActivityMemory({
+ activity: { status: 'pending', type: 'event' },
+ memoryLayer: LayersEnum.Activity,
+ } as any);
+
+ const result = await memoryModel.queryMemories({
+ layer: LayersEnum.Activity,
+ sort: 'startsAt',
+ status: ['completed'],
+ types: ['event'],
+ });
+
+ expect(result.items.map((item: any) => item.activity.id)).toEqual([match.activity.id]);
+ });
+
+ it('hydrates experience candidates with type and tag filters', async () => {
+ const match = await memoryModel.createExperienceMemory({
+ experience: { scoreConfidence: 0.8, tags: ['focus'], type: 'learning' },
+ memoryLayer: LayersEnum.Experience,
+ } as any);
+ await memoryModel.createExperienceMemory({
+ experience: { tags: ['other'], type: 'learning' },
+ memoryLayer: LayersEnum.Experience,
+ } as any);
+ const model = new UserMemoryModel(serverDB, userId, ftsSource([match.experience.id]));
+
+ const result = await model.queryMemories({
+ layer: LayersEnum.Experience,
+ q: 'focus',
+ sort: 'scoreConfidence',
+ tags: ['focus'],
+ types: ['learning'],
+ });
+
+ expect(result.items.map((item: any) => item.experience.id)).toEqual([match.experience.id]);
+ expect(result.total).toBe(1);
+ });
+
+ it('hydrates identity candidates with type and tag filters', async () => {
+ const match = await memoryModel.addIdentityEntry({
+ identity: { relationship: 'self', tags: ['core'], type: 'personal' },
+ } as any);
+ await memoryModel.addIdentityEntry({
+ identity: { relationship: 'self', tags: ['core'], type: 'professional' },
+ } as any);
+ const model = new UserMemoryModel(serverDB, userId, ftsSource([match.identityId]));
+
+ const result = await model.queryMemories({
+ layer: LayersEnum.Identity,
+ q: 'core',
+ tags: ['core'],
+ types: ['personal'],
+ });
+
+ expect(result.items.map((item: any) => item.identity.id)).toEqual([match.identityId]);
+ });
+
+ it('hydrates preference candidates with type and tag filters sorted by priority', async () => {
+ const match = await memoryModel.createPreferenceMemory({
+ memoryLayer: LayersEnum.Preference,
+ preference: { scorePriority: 0.5, tags: ['style'], type: 'communication' },
+ } as any);
+ await memoryModel.createPreferenceMemory({
+ memoryLayer: LayersEnum.Preference,
+ preference: { tags: ['style'], type: 'other' },
+ } as any);
+ const model = new UserMemoryModel(serverDB, userId, ftsSource([match.preference.id]));
+
+ const result = await model.queryMemories({
+ layer: LayersEnum.Preference,
+ q: 'style',
+ sort: 'scorePriority',
+ tags: ['style'],
+ types: ['communication'],
+ });
+
+ expect(result.items.map((item: any) => item.preference.id)).toEqual([match.preference.id]);
+ });
+});
+
+describe('context removal without linked memories', () => {
+ const insertUnlinkedContext = async () => {
+ const [context] = await serverDB
+ .insert(userMemoriesContexts)
+ .values({ title: 'unlinked', userId, userMemoryIds: null })
+ .returning();
+ return context;
+ };
+
+ it('UserMemoryModel.removeContextEntry() deletes a context whose memory ids are null', async () => {
+ const context = await insertUnlinkedContext();
+
+ await expect(memoryModel.removeContextEntry(context.id)).resolves.toBe(true);
+ await expect(
+ serverDB.query.userMemoriesContexts.findFirst({
+ where: eq(userMemoriesContexts.id, context.id),
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('UserMemoryContextModel.delete() deletes a context whose memory ids are null', async () => {
+ const context = await insertUnlinkedContext();
+
+ await expect(new UserMemoryContextModel(serverDB, userId).delete(context.id)).resolves.toEqual({
+ success: true,
+ });
+ });
+});
+
+describe('layer models queryList fallbacks', () => {
+ const layerModels = [
+ {
+ Model: UserMemoryActivityModel,
+ entity: 'memoryActivities',
+ filters: { tags: ['t1'], types: ['event'] },
+ expectedFilters: { memoryTagMatch: 'any', memoryTags: ['t1'], memoryTypes: ['event'] },
+ name: 'activity',
+ },
+ {
+ Model: UserMemoryExperienceModel,
+ entity: 'memoryExperiences',
+ filters: {},
+ expectedFilters: {},
+ name: 'experience',
+ },
+ {
+ Model: UserMemoryIdentityModel,
+ entity: 'memoryIdentities',
+ filters: { tags: ['t1'], types: ['personal'] },
+ expectedFilters: {
+ memoryRelationships: ['self'],
+ memoryTagMatch: 'any',
+ memoryTags: ['t1'],
+ memoryTypes: ['personal'],
+ },
+ name: 'identity',
+ },
+ ] as const;
+
+ it.each(layerModels)(
+ '$name forwards only the supplied filters to the candidate source',
+ async ({ Model, entity, expectedFilters, filters }) => {
+ const source = ftsSource([]);
+ const model = new Model(serverDB, userId, source);
+
+ const result = await model.queryList({ q: 'anything', ...filters } as any);
+
+ expect(result.items).toEqual([]);
+ expect(source.ftsSearchCandidates).toHaveBeenCalledWith(
+ expect.objectContaining({ entity, filters: expectedFilters }),
+ );
+ },
+ );
+
+ it.each(layerModels.filter(({ name }) => name !== 'identity'))(
+ '$name queries without a WHERE clause and reports 0 when the count row is missing',
+ async ({ Model }) => {
+ const where = vi.fn((_clause?: unknown) => builder);
+ const builder: any = chain([]);
+ const select = vi.fn(() => ({
+ from: () => ({ innerJoin: () => ({ where }) }),
+ }));
+ const model = new Model({ select } as any, userId);
+ (model as any).memoryWhere = () => undefined;
+
+ const result = await model.queryList();
+
+ expect(result).toEqual({ items: [], page: 1, pageSize: 20, total: 0 });
+ expect(where).toHaveBeenCalledTimes(2);
+ expect(where.mock.calls.every(([clause]) => clause === undefined)).toBe(true);
+ },
+ );
+});
diff --git a/packages/database/src/models/userMemory/__tests__/model.guards.test.ts b/packages/database/src/models/userMemory/__tests__/model.guards.test.ts
new file mode 100644
index 00000000000..5c5e6578e72
--- /dev/null
+++ b/packages/database/src/models/userMemory/__tests__/model.guards.test.ts
@@ -0,0 +1,260 @@
+// @vitest-environment node
+import { ActivityTypeEnum, LayersEnum, MemorySourceType } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { userMemoriesActivities, userMemoriesContexts } from '../../../schemas';
+import { updateAccessMetrics } from '../model/accessMetrics';
+import type { UserMemoryModelContext } from '../model/context';
+import {
+ createActivityMemory,
+ createContextMemory,
+ createExperienceMemory,
+ createPreferenceMemory,
+} from '../model/create';
+import { getMemoryDetail } from '../model/detail';
+import { search } from '../model/search';
+
+const BUILDER_METHODS = [
+ 'from',
+ 'groupBy',
+ 'innerJoin',
+ 'leftJoin',
+ 'limit',
+ 'offset',
+ 'onConflictDoNothing',
+ 'onConflictDoUpdate',
+ 'orderBy',
+ 'returning',
+ 'set',
+ 'values',
+ 'where',
+] as const;
+
+/** Chainable fake query builder: every builder method returns itself and awaiting it yields `rows`. */
+const chain = (rows: unknown[]) => {
+ const builder: any = Promise.resolve(rows);
+ for (const method of BUILDER_METHODS) builder[method] = () => builder;
+
+ return builder;
+};
+
+const createCtx = (overrides: Partial<Record<keyof UserMemoryModelContext, unknown>> = {}) =>
+ ({
+ buildBaseMemoryInsertValues: vi.fn(() => ({ memoryLayer: 'context', userId: 'guard-user' })),
+ extractSourceMetadata: vi.fn(() => ({})),
+ findUserMemoryRawById: vi.fn(),
+ memoryWhere: vi.fn(() => undefined),
+ topicModel: { findById: vi.fn() },
+ updateAccessMetrics: vi.fn(),
+ userId: 'guard-user',
+ ...overrides,
+ }) as unknown as UserMemoryModelContext;
+
+describe('updateAccessMetrics guards', () => {
+ it('skips the transaction when there is nothing to touch', async () => {
+ const transaction = vi.fn();
+ const ctx = createCtx({ db: { transaction } });
+
+ await updateAccessMetrics(ctx, [], {});
+ await updateAccessMetrics(ctx, []);
+
+ expect(transaction).not.toHaveBeenCalled();
+ });
+
+ it('touches only the context rows, in sorted order, when no memory ids are given', async () => {
+ const update = vi.fn(() => chain([]));
+ const select = vi.fn(() => chain([]));
+ const transaction = vi.fn(async (callback: (tx: unknown) => Promise<void>) =>
+ callback({ select, update }),
+ );
+ const ctx = createCtx({ db: { transaction } });
+
+ await updateAccessMetrics(ctx, [], { contextIds: ['ctx-b', 'ctx-a'] });
+
+ expect(transaction).toHaveBeenCalledTimes(1);
+ expect(select).not.toHaveBeenCalled();
+ expect(update).toHaveBeenCalledTimes(1);
+ expect(update).toHaveBeenCalledWith(userMemoriesContexts);
+ });
+});
+
+describe('create* guards', () => {
+ const emptyInsertCtx = () => {
+ const tx = { insert: vi.fn(() => chain([])) };
+ return createCtx({
+ db: { transaction: async (callback: (tx: unknown) => unknown) => callback(tx) },
+ });
+ };
+
+ it('throws when the base context memory insert returns no row', async () => {
+ await expect(
+ createContextMemory(emptyInsertCtx(), {
+ context: {},
+ memoryLayer: LayersEnum.Context,
+ } as any),
+ ).rejects.toThrow('Failed to create user memory context');
+ });
+
+ it('throws when the base experience memory insert returns no row', async () => {
+ await expect(
+ createExperienceMemory(emptyInsertCtx(), {
+ experience: {},
+ memoryLayer: LayersEnum.Experience,
+ } as any),
+ ).rejects.toThrow('Failed to create user memory experience');
+ });
+
+ it('throws when the base activity memory insert returns no row', async () => {
+ await expect(
+ createActivityMemory(emptyInsertCtx(), {
+ activity: {},
+ memoryLayer: LayersEnum.Activity,
+ } as any),
+ ).rejects.toThrow('Failed to create user memory activity');
+ });
+
+ it('fills every omitted activity field, including the nullable status', async () => {
+ // The activity `status` column is NOT NULL, so the `?? null` fallback can only be observed
+ // on the values handed to the insert, not on a persisted row.
+ const inserted: [unknown, Record<string, unknown>][] = [];
+ const tx = {
+ insert: vi.fn((table: unknown) => ({
+ values: (values: Record<string, unknown>) => {
+ inserted.push([table, values]);
+ return { returning: async () => [{ id: 'mem-1', ...values }] };
+ },
+ })),
+ };
+ const ctx = createCtx({
+ db: { transaction: async (callback: (tx: unknown) => unknown) => callback(tx) },
+ });
+
+ await createActivityMemory(ctx, { activity: {}, memoryLayer: LayersEnum.Activity } as any);
+
+ expect(ctx.buildBaseMemoryInsertValues).toHaveBeenCalledWith(expect.anything(), {
+ metadata: null,
+ status: 'pending',
+ tags: null,
+ });
+ expect(inserted[1][0]).toBe(userMemoriesActivities);
+ expect(inserted[1][1]).toMatchObject({
+ associatedLocations: null,
+ associatedObjects: [],
+ associatedSubjects: [],
+ narrative: null,
+ status: null,
+ tags: [],
+ type: ActivityTypeEnum.Other,
+ userMemoryId: 'mem-1',
+ });
+ });
+
+ it('throws when the base preference memory insert returns no row', async () => {
+ await expect(
+ createPreferenceMemory(emptyInsertCtx(), {
+ memoryLayer: LayersEnum.Preference,
+ preference: {},
+ } as any),
+ ).rejects.toThrow('Failed to create user memory preference');
+ });
+});
+
+describe('getMemoryDetail guards', () => {
+ const layerRows = {
+ [LayersEnum.Activity]: { id: 'activity-1', metadata: null, userMemoryId: 'mem-1' },
+ [LayersEnum.Context]: { id: 'context-1', metadata: null, userMemoryIds: ['mem-1'] },
+ [LayersEnum.Experience]: { id: 'experience-1', metadata: null, userMemoryId: 'mem-1' },
+ [LayersEnum.Identity]: { id: 'identity-1', metadata: null, userMemoryId: 'mem-1' },
+ [LayersEnum.Preference]: { id: 'preference-1', metadata: null, userMemoryId: 'mem-1' },
+ } as const;
+ const layers = Object.keys(layerRows) as (keyof typeof layerRows)[];
+
+ const detailCtx = (row: unknown, memory: unknown, sourceId?: string) =>
+ createCtx({
+ db: { select: () => chain(row ? [row] : []) },
+ extractSourceMetadata: vi.fn(() => ({
+ sourceId,
+ sourceType: MemorySourceType.ChatTopic,
+ })),
+ findUserMemoryRawById: vi.fn(async () => memory),
+ topicModel: { findById: vi.fn(async (id: string) => ({ id, title: 'Source topic' })) },
+ });
+
+ it.each(layers)('returns undefined when the %s parent memory is gone', async (layer) => {
+ const ctx = detailCtx(layerRows[layer], undefined);
+
+ await expect(getMemoryDetail(ctx, { id: 'x', layer })).resolves.toBeUndefined();
+ expect(ctx.findUserMemoryRawById).toHaveBeenCalledWith('mem-1');
+ });
+
+ it.each(layers)(
+ 'returns undefined when the %s parent memory belongs to another layer',
+ async (layer) => {
+ const otherLayer = layer === LayersEnum.Context ? LayersEnum.Activity : LayersEnum.Context;
+ const ctx = detailCtx(layerRows[layer], { id: 'mem-1', memoryLayer: otherLayer });
+
+ await expect(getMemoryDetail(ctx, { id: 'x', layer })).resolves.toBeUndefined();
+ expect(ctx.extractSourceMetadata).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(layers)('resolves the source topic for a %s detail with a sourceId', async (layer) => {
+ const memory = { id: 'mem-1', memoryLayer: layer };
+ const ctx = detailCtx(layerRows[layer], memory, 'topic-1');
+
+ const result = await getMemoryDetail(ctx, { id: 'x', layer });
+
+ expect(ctx.topicModel.findById).toHaveBeenCalledWith('topic-1');
+ expect(result).toMatchObject({
+ layer,
+ memory,
+ source: { id: 'topic-1', title: 'Source topic' },
+ sourceType: MemorySourceType.ChatTopic,
+ });
+ });
+
+ it('treats a non-array context userMemoryIds as having no parent', async () => {
+ const ctx = detailCtx({ id: 'context-1', metadata: null, userMemoryIds: null }, undefined);
+
+ await expect(
+ getMemoryDetail(ctx, { id: 'context-1', layer: LayersEnum.Context }),
+ ).resolves.toBeUndefined();
+ expect(ctx.findUserMemoryRawById).not.toHaveBeenCalled();
+ });
+
+ it('returns undefined when the preference row is missing or has no parent id', async () => {
+ const missing = detailCtx(undefined, undefined);
+ const orphan = detailCtx({ id: 'preference-1', userMemoryId: null }, undefined);
+
+ await expect(
+ getMemoryDetail(missing, { id: 'preference-1', layer: LayersEnum.Preference }),
+ ).resolves.toBeUndefined();
+ await expect(
+ getMemoryDetail(orphan, { id: 'preference-1', layer: LayersEnum.Preference }),
+ ).resolves.toBeUndefined();
+ expect(orphan.findUserMemoryRawById).not.toHaveBeenCalled();
+ });
+});
+
+describe('search guards', () => {
+ it('skips rows without parent ids but still records the context links', async () => {
+ const experiences = [{ id: 'experience-1', userMemoryId: null }];
+ const preferences = [{ id: 'preference-1', userMemoryId: null }];
+ const activities = [{ id: 'activity-1', userMemoryId: null }];
+ const contexts = [{ id: 'context-1', userMemoryIds: null }];
+ const ctx = createCtx({
+ searchActivities: vi.fn(async () => activities),
+ searchContexts: vi.fn(async () => contexts),
+ searchExperiences: vi.fn(async () => experiences),
+ searchPreferences: vi.fn(async () => preferences),
+ });
+
+ const result = await search(ctx, { embedding: [0.1] } as any);
+
+ expect(result).toMatchObject({ activities, contexts, experiences, preferences });
+ expect(ctx.updateAccessMetrics).toHaveBeenCalledWith([], {
+ contextIds: ['context-1'],
+ timestamp: expect.any(Date),
+ });
+ });
+});
diff --git a/packages/database/src/models/userMemory/identity.ts b/packages/database/src/models/userMemory/identity.ts
index 059d3eca325..c32f59f9fc6 100644
--- a/packages/database/src/models/userMemory/identity.ts
+++ b/packages/database/src/models/userMemory/identity.ts
@@ -121,7 +121,10 @@ export class UserMemoryIdentityModel {
];
const filters = conditions.filter((condition): condition is SQL => condition !== undefined);
- const whereClause = filters.length > 0 ? and(...filters) : undefined;
+ const whereClause =
+ filters.length > 0
+ ? and(...filters)
+ : /* v8 ignore next -- unreachable: eq()/inArray() always yield SQL, so filters is never empty */ undefined;
// Build ORDER BY
const applyOrder = order === 'asc' ? asc : desc;
diff --git a/packages/database/src/models/userMemory/model/identities.ts b/packages/database/src/models/userMemory/model/identities.ts
index bdc1d56ddd1..0f2c06d3502 100644
--- a/packages/database/src/models/userMemory/model/identities.ts
+++ b/packages/database/src/models/userMemory/model/identities.ts
@@ -17,6 +17,7 @@ import type {
import { coerceDate } from './utils';
const normalizeRelationshipValue = (input: unknown): RelationshipEnum | null => {
+ /* v8 ignore next -- unreachable: every caller maps null to null before normalizing */
if (input === null) return null;
if (typeof input !== 'string') return null;
const normalized = input.trim().toLowerCase();
@@ -26,6 +27,7 @@ const normalizeRelationshipValue = (input: unknown): RelationshipEnum | null =>
};
const normalizeIdentityTypeValue = (input: unknown): IdentityTypeEnum | null => {
+ /* v8 ignore next -- unreachable: every caller maps null to null before normalizing */
if (input === null) return null;
if (typeof input !== 'string') return null;
const normalized = input.trim().toLowerCase();
diff --git a/packages/database/src/models/userMemory/model/listMemories.ts b/packages/database/src/models/userMemory/model/listMemories.ts
index 49c03599d6d..a50f3a297b3 100644
--- a/packages/database/src/models/userMemory/model/listMemories.ts
+++ b/packages/database/src/models/userMemory/model/listMemories.ts
@@ -89,7 +89,9 @@ export const listMemories = async <
);
const contextFilters: Array<SQL | undefined> = [
- baseWhere.length ? and(...baseWhere) : undefined,
+ baseWhere.length
+ ? and(...baseWhere)
+ : /* v8 ignore next -- unreachable: baseWhere always holds the memoryLayer eq() */ undefined,
];
const contextWhere = contextFilters.filter(Boolean) as SQL[];
@@ -100,7 +102,11 @@ export const listMemories = async <
})
.from(userMemories)
.innerJoin(userMemoriesContexts, joinCondition)
- .where(contextWhere.length ? and(...contextWhere) : undefined)
+ .where(
+ contextWhere.length
+ ? and(...contextWhere)
+ : /* v8 ignore next -- unreachable: always holds the non-empty baseWhere and() */ undefined,
+ )
.orderBy(...orderByClauses)
.limit(normalizedPageSize)
.offset(offset);
@@ -122,7 +128,9 @@ export const listMemories = async <
);
const experienceFilters: Array<SQL | undefined> = [
- baseWhere.length ? and(...baseWhere) : undefined,
+ baseWhere.length
+ ? and(...baseWhere)
+ : /* v8 ignore next -- unreachable: baseWhere always holds the memoryLayer eq() */ undefined,
];
const experienceWhere = experienceFilters.filter(Boolean) as SQL[];
@@ -133,7 +141,11 @@ export const listMemories = async <
})
.from(userMemories)
.innerJoin(userMemoriesExperiences, joinCondition)
- .where(experienceWhere.length ? and(...experienceWhere) : undefined)
+ .where(
+ experienceWhere.length
+ ? and(...experienceWhere)
+ : /* v8 ignore next -- unreachable: always holds the non-empty baseWhere and() */ undefined,
+ )
.orderBy(...orderByClauses)
.limit(normalizedPageSize)
.offset(offset);
@@ -155,7 +167,9 @@ export const listMemories = async <
);
const identityFilters: Array<SQL | undefined> = [
- baseWhere.length ? and(...baseWhere) : undefined,
+ baseWhere.length
+ ? and(...baseWhere)
+ : /* v8 ignore next -- unreachable: baseWhere always holds the memoryLayer eq() */ undefined,
];
const identityWhere = identityFilters.filter(Boolean) as SQL[];
@@ -166,7 +180,11 @@ export const listMemories = async <
})
.from(userMemories)
.innerJoin(userMemoriesIdentities, joinCondition)
- .where(identityWhere.length ? and(...identityWhere) : undefined)
+ .where(
+ identityWhere.length
+ ? and(...identityWhere)
+ : /* v8 ignore next -- unreachable: always holds the non-empty baseWhere and() */ undefined,
+ )
.orderBy(...orderByClauses)
.limit(normalizedPageSize)
.offset(offset);
@@ -188,7 +206,9 @@ export const listMemories = async <
);
const preferenceFilters: Array<SQL | undefined> = [
- baseWhere.length ? and(...baseWhere) : undefined,
+ baseWhere.length
+ ? and(...baseWhere)
+ : /* v8 ignore next -- unreachable: baseWhere always holds the memoryLayer eq() */ undefined,
];
const preferenceWhere = preferenceFilters.filter(Boolean) as SQL[];
@@ -199,7 +219,11 @@ export const listMemories = async <
})
.from(userMemories)
.innerJoin(userMemoriesPreferences, joinCondition)
- .where(preferenceWhere.length ? and(...preferenceWhere) : undefined)
+ .where(
+ preferenceWhere.length
+ ? and(...preferenceWhere)
+ : /* v8 ignore next -- unreachable: always holds the non-empty baseWhere and() */ undefined,
+ )
.orderBy(...orderByClauses)
.limit(normalizedPageSize)
.offset(offset);
diff --git a/packages/database/src/models/userMemory/model/queryMemories.ts b/packages/database/src/models/userMemory/model/queryMemories.ts
index 3f27b5e2799..56c67b25051 100644
--- a/packages/database/src/models/userMemory/model/queryMemories.ts
+++ b/packages/database/src/models/userMemory/model/queryMemories.ts
@@ -147,7 +147,10 @@ export const queryMemories = async (
];
const filters = conditions.filter((condition): condition is SQL => condition !== undefined);
- const whereClause = filters.length > 0 ? and(...filters) : undefined;
+ const whereClause =
+ filters.length > 0
+ ? and(...filters)
+ : /* v8 ignore next -- unreachable: eq()/inArray() always yield SQL, so filters is never empty */ undefined;
const applyOrder = order === 'asc' ? asc : desc;
@@ -250,7 +253,7 @@ export const queryMemories = async (
(condition): condition is SQL => condition !== undefined,
) as SQL[]),
)
- : undefined;
+ : /* v8 ignore next -- unreachable: the first filter is the always-defined layer whereClause */ undefined;
const rowsQuery = ctx.db
.select({
@@ -360,7 +363,7 @@ export const queryMemories = async (
(condition): condition is SQL => condition !== undefined,
) as SQL[]),
)
- : undefined;
+ : /* v8 ignore next -- unreachable: the first filter is the always-defined layer whereClause */ undefined;
const rowsQuery = ctx.db
.select({
@@ -468,7 +471,7 @@ export const queryMemories = async (
(condition): condition is SQL => condition !== undefined,
) as SQL[]),
)
- : undefined;
+ : /* v8 ignore next -- unreachable: the first filter is the always-defined layer whereClause */ undefined;
const rowsQuery = ctx.db
.select({
@@ -564,7 +567,7 @@ export const queryMemories = async (
(condition): condition is SQL => condition !== undefined,
) as SQL[]),
)
- : undefined;
+ : /* v8 ignore next -- unreachable: the first filter is the always-defined layer whereClause */ undefined;
const rowsQuery = ctx.db
.select({
@@ -667,7 +670,7 @@ export const queryMemories = async (
(condition): condition is SQL => condition !== undefined,
) as SQL[]),
)
- : undefined;
+ : /* v8 ignore next -- unreachable: the first filter is the always-defined layer whereClause */ undefined;
const rowsQuery = ctx.db
.select({