🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✅ test(database): 100% coverage for userMemory models (part 2) (#21853)
Arvin Xu5d65df8fdc22
diff --git a/packages/database/src/models/userMemory/__tests__/persona.guards.test.ts b/packages/database/src/models/userMemory/__tests__/persona.guards.test.tsnew file mode 100644index 00000000000..cca51fc047c--- /dev/null+++ b/packages/database/src/models/userMemory/__tests__/persona.guards.test.ts@@ -0,0 +1,108 @@+// @vitest-environment node+import { inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { userPersonaDocuments, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { UserPersonaModel } from '../persona';++const userId = 'persona-guards-user';+const otherUserId = 'persona-guards-other-user';+const missingUserId = 'persona-guards-missing-user';++const serverDB: LobeChatDatabase = await getTestDB();++const cleanup = () =>+ serverDB.delete(users).where(inArray(users.id, [userId, otherUserId, missingUserId]));++beforeEach(async () => {+ await cleanup();+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+});++afterEach(cleanup);++describe('UserPersonaModel guards', () => {+ it('refuses to write a persona for a user that does not exist', async () => {+ const model = new UserPersonaModel(serverDB, missingUserId);++ await expect(model.upsertPersona({ persona: 'ghost' })).rejects.toThrow(+ 'User persona owner was not found',+ );+ expect(+ await serverDB+ .select()+ .from(userPersonaDocuments)+ .where(inArray(userPersonaDocuments.userId, [missingUserId])),+ ).toEqual([]);+ });++ it('records a diff when only source ids are provided', async () => {+ const model = new UserPersonaModel(serverDB, userId);++ const { diff, document } = await model.upsertPersona({+ persona: 'sourced persona',+ sourceIds: ['source-1'],+ });++ expect(document.sourceIds).toEqual(['source-1']);+ expect(diff).toMatchObject({+ editedBy: 'agent',+ nextVersion: 1,+ personaId: document.id,+ snapshot: 'sourced persona',+ sourceIds: ['source-1'],+ });+ });++ it('reads the default profile through the getLatestDocument alias', async () => {+ const model = new UserPersonaModel(serverDB, userId);+ await model.upsertPersona({ persona: 'default persona' });+ await model.upsertPersona({ persona: 'work persona', profile: 'work' });++ expect((await model.getLatestDocument())?.persona).toBe('default persona');+ expect((await model.getLatestDocument('work'))?.persona).toBe('work persona');+ expect(await new UserPersonaModel(serverDB, otherUserId).getLatestDocument()).toBeUndefined();+ });++ it('lists default-profile versions of the user with the default limit', async () => {+ const model = new UserPersonaModel(serverDB, userId);+ await model.upsertPersona({ persona: 'v1', snapshot: 'v1' });+ await model.upsertPersona({ persona: 'v2', snapshot: 'v2' });+ await model.upsertPersona({ persona: 'work', profile: 'work', snapshot: 'work' });+ await new UserPersonaModel(serverDB, otherUserId).upsertPersona({+ persona: 'theirs',+ snapshot: 'theirs',+ });++ const versions = await model.listVersions();++ expect(versions.map(({ snapshotPersona }) => snapshotPersona).sort()).toEqual(['v1', 'v2']);+ });++ describe('deletePersona', () => {+ it('is a no-op when the profile has no persona', async () => {+ const model = new UserPersonaModel(serverDB, userId);+ await model.upsertPersona({ persona: 'work persona', profile: 'work' });++ await expect(model.deletePersona()).resolves.toBeUndefined();++ expect((await model.getLatestDocument('work'))?.persona).toBe('work persona');+ });++ it('deletes the default profile of the user only', async () => {+ const model = new UserPersonaModel(serverDB, userId);+ const otherModel = new UserPersonaModel(serverDB, otherUserId);+ await model.upsertPersona({ persona: 'mine' });+ await model.upsertPersona({ persona: 'work persona', profile: 'work' });+ await otherModel.upsertPersona({ persona: 'theirs' });++ await model.deletePersona();++ expect(await model.getLatestDocument()).toBeUndefined();+ expect((await model.getLatestDocument('work'))?.persona).toBe('work persona');+ expect((await otherModel.getLatestDocument())?.persona).toBe('theirs');+ });+ });+});diff --git a/packages/database/src/models/userMemory/__tests__/query.helpers.test.ts b/packages/database/src/models/userMemory/__tests__/query.helpers.test.tsnew file mode 100644index 00000000000..7134084d23d--- /dev/null+++ b/packages/database/src/models/userMemory/__tests__/query.helpers.test.ts@@ -0,0 +1,205 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import type { LobeChatDatabase } from '../../../type';+import type { LayerBaseMemorySignals } from '../query';+import { buildBm25MatchCondition, scoreHybridCandidates, UserMemoryQueryModel } from '../query';+import { DEFAULT_HYBRID_SEARCH_LIMIT } from '../query/constants';+import { coerceDate, combineEmbeddings } from '../query/utils';++interface QueryContextHelpers {+ buildCandidateFilters: (entity: string, params: Record<string, unknown>) => unknown;+ collectCandidateMemoryIds: (item: {+ userMemoryId?: string | null;+ userMemoryIds?: string[] | null;+ }) => string[];+ fetchFtsSearchCandidates: (params: {+ entity: string;+ fields: string[];+ limit: number;+ query: string;+ searchParams: Record<string, unknown>;+ }) => Promise<string[] | undefined>;+ getSearchLimit: (key: string, params: Record<string, unknown>) => number;+ getSearchOverfetchLimit: (key: string, params: Record<string, unknown>) => number;+}++const createContext = (ftsSearchCandidateSource?: unknown) =>+ Reflect.get(+ new UserMemoryQueryModel(+ {} as LobeChatDatabase,+ 'query-helpers-user',+ ftsSearchCandidateSource as never,+ ),+ 'context',+ ) as QueryContextHelpers;++const emptySignals = new Map<string, LayerBaseMemorySignals>();++describe('user memory query helpers', () => {+ describe('combineEmbeddings', () => {+ it('gives up when the first of several embeddings is empty', () => {+ expect(combineEmbeddings([[], [1, 2]])).toBeUndefined();+ });++ it('treats missing dimensions of shorter embeddings as zero', () => {+ expect(combineEmbeddings([[2, 4], [2]])).toEqual([2, 2]);+ });+ });++ describe('coerceDate', () => {+ it('rejects invalid Date instances and unparsable strings', () => {+ expect(coerceDate(new Date('not a date'))).toBeNull();+ expect(coerceDate('not a date')).toBeNull();+ });+ });++ describe('buildBm25MatchCondition', () => {+ it('returns no condition when every group has no fields', () => {+ expect(+ buildBm25MatchCondition('atlas', [{ fields: [], keyColumn: {} as never }]),+ ).toBeUndefined();+ });+ });++ describe('search limits', () => {+ it('falls back to the default limit for a layer without topK', () => {+ const ctx = createContext();++ expect(ctx.getSearchLimit('activities', {})).toBe(DEFAULT_HYBRID_SEARCH_LIMIT);+ expect(ctx.getSearchOverfetchLimit('activities', {})).toBe(DEFAULT_HYBRID_SEARCH_LIMIT * 3);+ });++ it('does not overfetch a layer whose topK is zero', () => {+ expect(createContext().getSearchOverfetchLimit('contexts', { topK: { contexts: 0 } })).toBe(+ 0,+ );+ });+ });++ describe('collectCandidateMemoryIds', () => {+ it('returns no ids for an item without a linked memory', () => {+ const ctx = createContext();++ expect(ctx.collectCandidateMemoryIds({ userMemoryId: null })).toEqual([]);+ expect(ctx.collectCandidateMemoryIds({})).toEqual([]);+ });+ });++ describe('buildCandidateFilters', () => {+ const fullParams = {+ categories: ['work'],+ labels: ['label-a'],+ relationships: ['friend'],+ status: ['active'],+ tags: ['tag-a'],+ timeRange: { end: new Date('2026-02-01'), start: new Date('2026-01-01') },+ types: ['project'],+ };++ it('forwards every filter the entity supports', () => {+ const ctx = createContext();++ expect(ctx.buildCandidateFilters('memoryIdentities', fullParams)).toEqual({+ memoryCategories: ['work'],+ memoryRelationships: ['friend'],+ memoryTags: ['tag-a', 'label-a'],+ memoryTimeRange: fullParams.timeRange,+ memoryTypes: ['project'],+ });+ expect(ctx.buildCandidateFilters('memoryContexts', fullParams)).toEqual({+ memoryCategories: ['work'],+ memoryStatus: ['active'],+ memoryTags: ['tag-a', 'label-a'],+ memoryTimeRange: fullParams.timeRange,+ memoryTypes: ['project'],+ });+ expect(ctx.buildCandidateFilters('memoryActivities', fullParams)).toMatchObject({+ memoryStatus: ['active'],+ });+ });++ it('omits filters that are empty or not supported by the entity', () => {+ expect(createContext().buildCandidateFilters('memoryPreferences', fullParams)).toEqual({+ memoryCategories: ['work'],+ memoryTags: ['tag-a', 'label-a'],+ memoryTimeRange: fullParams.timeRange,+ memoryTypes: ['project'],+ });+ expect(createContext().buildCandidateFilters('memoryActivities', {})).toEqual({});+ });+ });++ describe('fetchFtsSearchCandidates', () => {+ const request = {+ entity: 'memoryActivities',+ fields: ['narrative'],+ limit: 3,+ query: 'atlas',+ searchParams: {},+ };++ it('returns undefined without a candidate source', async () => {+ await expect(createContext().fetchFtsSearchCandidates(request)).resolves.toBeUndefined();+ });++ it('returns undefined when the candidate source is disabled', async () => {+ const ftsSearchCandidates = vi.fn();+ const ctx = createContext({ ftsSearchCandidateEnabled: false, ftsSearchCandidates });++ await expect(ctx.fetchFtsSearchCandidates(request)).resolves.toBeUndefined();+ expect(ftsSearchCandidates).not.toHaveBeenCalled();+ });+ });++ describe('scoreHybridCandidates', () => {+ it('scores fuzzy similarity as zero for an item with no searchable text', () => {+ const [ranked] = scoreHybridCandidates({+ baseSignals: emptySignals,+ items: [{ id: ' ' }],+ lexicalLists: [[{ id: ' ' }]],+ queries: ['atlas'],+ queryParams: {},+ semanticLists: [],+ });++ expect(ranked.score.fuzzy).toBe(0);+ expect(ranked.score.keyword).toBe(1);+ });++ it('scores a separator-only query as no token overlap', () => {+ const [ranked] = scoreHybridCandidates({+ baseSignals: emptySignals,+ items: [{ id: 'mem1', tags: ['atlas'] }],+ lexicalLists: [[{ id: 'mem1', tags: ['atlas'] }]],+ queries: ['/'],+ queryParams: {},+ semanticLists: [],+ });++ expect(ranked.score.fuzzy).toBe(0);+ });++ it('scores blank tags as no affinity between candidates', () => {+ const items = [+ { id: 'mem-a', tags: [' '] },+ { id: 'mem-b', tags: [' '] },+ ];++ const ranked = scoreHybridCandidates({+ baseSignals: emptySignals,+ items,+ lexicalLists: [items],+ queries: [],+ queryParams: {},+ semanticLists: [],+ });++ expect(ranked).toHaveLength(2);+ for (const { score } of ranked) {+ expect(score.tagAffinity).toBe(0);+ expect(score.clusterBoost).toBe(0);+ }+ });+ });+});diff --git a/packages/database/src/models/userMemory/__tests__/query.layers.test.ts b/packages/database/src/models/userMemory/__tests__/query.layers.test.tsnew file mode 100644index 00000000000..f432bc9b884--- /dev/null+++ b/packages/database/src/models/userMemory/__tests__/query.layers.test.ts@@ -0,0 +1,397 @@+// @vitest-environment node+import { LayersEnum } from '@lobechat/types';+import { eq, inArray } from 'drizzle-orm';+import { drizzle as drizzleProxy } from 'drizzle-orm/pg-proxy';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import * as schema from '../../../schemas';+import {+ userMemories,+ userMemoriesActivities,+ userMemoriesContexts,+ userMemoriesExperiences,+ userMemoriesIdentities,+ userMemoriesPreferences,+ userPersonaDocuments,+ users,+} from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import type { LayerBaseMemorySignals } from '../query';+import { UserMemoryQueryModel } from '../query';+import { buildUserMemoryWhere } from '../where';++const userId = 'memory-query-layers-user';+const otherUserId = 'memory-query-layers-other-user';++const serverDB: LobeChatDatabase = await getTestDB();++type Rows = Array<{ id: string } & Record<string, unknown>>;+type LexicalSearch = (query: string | undefined, limit: number, params: object) => Promise<Rows>;+type SemanticSearch = (embedding: number[], limit: number, params: object) => Promise<Rows>;++interface QueryContext {+ loadBaseSignals: (+ items: Array<{ id: string; userMemoryId?: string | null }>,+ ) => Promise<Map<string, LayerBaseMemorySignals>>;+ searchActivitiesLexical: LexicalSearch;+ searchContextsLexical: LexicalSearch;+ searchContextsSemantic: SemanticSearch;+ searchExperiencesLexical: LexicalSearch;+ searchExperiencesSemantic: SemanticSearch;+ searchHybridExperiences: (params: {+ embeddings: number[][];+ lexicalSearch: boolean;+ params: object;+ queries: string[];+ }) => Promise<Array<{ item: { id: string } }>>;+ searchIdentitiesLexical: LexicalSearch;+ searchIdentitiesSemantic: SemanticSearch;+ searchPreferencesLexical: LexicalSearch;+ searchPreferencesSemantic: SemanticSearch;+}++const contextOf = (model: UserMemoryQueryModel) => Reflect.get(model, 'context') as QueryContext;++const vec = (seed: number) => Array.from({ length: 1024 }, (_, index) => (index === 0 ? seed : 1));++const insertBaseMemory = async (+ layer: string,+ values: Partial<typeof userMemories.$inferInsert>,+) => {+ const [memory] = await serverDB+ .insert(userMemories)+ .values({+ details: `${layer} details`,+ lastAccessedAt: new Date(),+ memoryLayer: layer,+ memoryType: layer,+ summary: `${layer} summary`,+ title: `${layer} memory`,+ userId,+ ...values,+ })+ .returning();++ return memory;+};++const insertExperience = async (opts: {+ memoryCategory?: string;+ tags?: string[];+ type: string;+}) => {+ const memory = await insertBaseMemory('experience', { memoryCategory: opts.memoryCategory });+ const [experience] = await serverDB+ .insert(userMemoriesExperiences)+ .values({+ situation: `situation for ${opts.type}`,+ situationVector: vec(1),+ tags: opts.tags,+ type: opts.type,+ userId,+ userMemoryId: memory.id,+ })+ .returning();++ return experience;+};++const insertContext = async (opts: {+ currentStatus?: string;+ tags?: string[];+ type?: string | null;+}) => {+ const memory = await insertBaseMemory('context', {});+ const [context] = await serverDB+ .insert(userMemoriesContexts)+ .values({+ currentStatus: opts.currentStatus,+ description: 'context description',+ descriptionVector: vec(1),+ tags: opts.tags,+ title: 'context title',+ type: opts.type,+ userId,+ userMemoryIds: [memory.id],+ })+ .returning();++ return context;+};++beforeEach(async () => {+ await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+});++afterEach(async () => {+ vi.restoreAllMocks();+ await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));+});++describe('UserMemoryQueryModel layer retrieval', () => {+ describe('experiences', () => {+ it('filters lexical experiences by category and type without a query', async () => {+ const lesson = await insertExperience({ memoryCategory: 'work', type: 'lesson' });+ await insertExperience({ memoryCategory: 'work', type: 'mistake' });+ await insertExperience({ memoryCategory: 'life', type: 'lesson' });++ const rows = await contextOf(+ new UserMemoryQueryModel(serverDB, userId),+ ).searchExperiencesLexical(undefined, 10, { categories: ['work'], types: ['lesson'] });++ expect(rows.map(({ id }) => id)).toEqual([lesson.id]);+ });++ it('narrows lexical experiences to the external candidates for a query', async () => {+ const wanted = await insertExperience({ type: 'lesson' });+ await insertExperience({ type: 'lesson' });+ const ftsSearchCandidates = vi+ .fn()+ .mockResolvedValue({ candidates: [{ id: wanted.id, score: 1 }], total: 1 });+ const model = new UserMemoryQueryModel(serverDB, userId, {+ ftsSearchCandidateEnabled: true,+ ftsSearchCandidates,+ });++ const rows = await contextOf(model).searchExperiencesLexical(' migration ', 4, {});++ expect(rows.map(({ id }) => id)).toEqual([wanted.id]);+ expect(ftsSearchCandidates).toHaveBeenCalledWith(+ expect.objectContaining({+ entity: 'memoryExperiences',+ pagination: { limit: 4 },+ query: expect.objectContaining({ text: 'migration' }),+ }),+ );+ });++ it('filters semantic experiences by type and leaves other users out', async () => {+ const lesson = await insertExperience({ type: 'lesson' });+ await insertExperience({ type: 'mistake' });++ const rows = await contextOf(+ new UserMemoryQueryModel(serverDB, userId),+ ).searchExperiencesSemantic(vec(1), 10, { types: ['lesson'] });+ const otherRows = await contextOf(+ new UserMemoryQueryModel(serverDB, otherUserId),+ ).searchExperiencesSemantic(vec(1), 10, {});++ expect(rows.map(({ id }) => id)).toEqual([lesson.id]);+ expect(otherRows).toEqual([]);+ });++ it('ranks filtered experiences through the hybrid pipeline', async () => {+ const lesson = await insertExperience({ tags: ['db'], type: 'lesson' });+ await insertExperience({ type: 'mistake' });++ const ranked = await contextOf(+ new UserMemoryQueryModel(serverDB, userId),+ ).searchHybridExperiences({+ embeddings: [],+ lexicalSearch: true,+ params: { types: ['lesson'] },+ queries: [],+ });++ expect(ranked.map(({ item }) => item.id)).toEqual([lesson.id]);+ });+ });++ describe('contexts', () => {+ it('filters lexical and semantic contexts by current status and type', async () => {+ const active = await insertContext({ currentStatus: 'active', type: 'project' });+ await insertContext({ currentStatus: 'paused', type: 'project' });+ await insertContext({ currentStatus: 'active', type: 'goal' });+ const ctx = contextOf(new UserMemoryQueryModel(serverDB, userId));+ const params = { status: ['active'], types: ['project'] };++ const lexical = await ctx.searchContextsLexical(undefined, 10, params);+ const semantic = await ctx.searchContextsSemantic(vec(1), 10, params);++ expect(lexical.map(({ id }) => id)).toEqual([active.id]);+ expect(semantic.map(({ id }) => id)).toEqual([active.id]);+ });+ });++ describe('preferences and identities', () => {+ it('returns unfiltered semantic preferences of the user only', async () => {+ const memory = await insertBaseMemory('preference', {});+ const [preference] = await serverDB+ .insert(userMemoriesPreferences)+ .values({+ conclusionDirectives: 'prefer dark mode',+ conclusionDirectivesVector: vec(1),+ type: 'ui',+ userId,+ userMemoryId: memory.id,+ })+ .returning();++ const rows = await contextOf(+ new UserMemoryQueryModel(serverDB, userId),+ ).searchPreferencesSemantic(vec(1), 10, {});++ expect(rows.map(({ id }) => id)).toEqual([preference.id]);+ });++ it('filters semantic identities by type without category or relationship filters', async () => {+ const identities: Array<{ id: string }> = [];+ for (const type of ['personal', 'professional']) {+ const memory = await insertBaseMemory('identity', {});+ const [identity] = await serverDB+ .insert(userMemoriesIdentities)+ .values({+ description: `${type} identity`,+ descriptionVector: vec(1),+ type,+ userId,+ userMemoryId: memory.id,+ })+ .returning();+ identities.push(identity);+ }++ const rows = await contextOf(+ new UserMemoryQueryModel(serverDB, userId),+ ).searchIdentitiesSemantic(vec(1), 10, { types: ['professional'] });++ expect(rows.map(({ id }) => id)).toEqual([identities[1].id]);+ });+ });++ describe('lexical queries without a candidate source', () => {+ it('matches each layer with BM25 over the base memory and the layer row', async () => {+ const statements: string[] = [];+ const captureDB = drizzleProxy(+ async (query) => {+ statements.push(query);+ return { rows: [] };+ },+ { schema },+ ) as unknown as LobeChatDatabase;+ const ctx = contextOf(new UserMemoryQueryModel(captureDB, userId));++ const searches: Array<[LexicalSearch, string]> = [+ [ctx.searchActivitiesLexical, 'user_memories_activities'],+ [ctx.searchContextsLexical, 'user_memories_contexts'],+ [ctx.searchExperiencesLexical, 'user_memories_experiences'],+ [ctx.searchIdentitiesLexical, 'user_memories_identities'],+ [ctx.searchPreferencesLexical, 'user_memories_preferences'],+ ];++ for (const [search, table] of searches) {+ statements.length = 0;++ await expect(search('atlas', 5, {})).resolves.toEqual([]);+ expect(statements).toHaveLength(1);+ expect(statements[0]).toContain('"user_memories"."id" @@@ paradedb.boolean');+ expect(statements[0]).toContain(`"${table}"."id" @@@ paradedb.boolean`);+ }+ });+ });++ describe('base signals', () => {+ it('ignores candidate items whose linked memory is not visible', async () => {+ const visible = await insertBaseMemory('activity', { memoryCategory: 'work', tags: ['a'] });+ const ctx = contextOf(new UserMemoryQueryModel(serverDB, userId));++ const signals = await ctx.loadBaseSignals([+ { id: 'item-missing', userMemoryId: 'memory-that-does-not-exist' },+ { id: 'item-visible', userMemoryId: visible.id },+ ]);++ expect(signals.get('item-missing')).toEqual({+ categories: [],+ memoryIds: [],+ tags: [],+ times: [],+ });+ expect(signals.get('item-visible')).toMatchObject({+ categories: ['work'],+ memoryIds: [visible.id],+ tags: ['a'],+ });+ });+ });++ describe('searchMemory', () => {+ it('uses the default per-layer limits when topK is omitted', async () => {+ const memory = await insertBaseMemory('activity', { memoryCategory: 'work' });+ const [activity] = await serverDB+ .insert(userMemoriesActivities)+ .values({ narrative: 'shipped it', type: 'task', userId, userMemoryId: memory.id })+ .returning();+ await insertExperience({ memoryCategory: 'work', type: 'lesson' });++ const result = await new UserMemoryQueryModel(serverDB, userId).searchMemory({+ categories: ['work'],+ });++ expect(result.activities.map(({ id }) => id)).toEqual([activity.id]);+ expect(result.experiences).toEqual([]);+ expect(result.meta.layers.activities).toEqual({ hasMore: false, returned: 1, total: 1 });+ expect(result.meta.layers.experiences).toEqual({ hasMore: false, returned: 0, total: 0 });+ });+ });++ describe('queryTaxonomyOptions', () => {+ it('restricts tags and labels to the requested layers', async () => {+ const activityMemory = await insertBaseMemory('activity', { tags: ['base-activity'] });+ await serverDB.insert(userMemoriesActivities).values({+ narrative: 'labelled',+ tags: ['label-activity'],+ type: 'task',+ userId,+ userMemoryId: activityMemory.id,+ });+ await insertContext({ tags: ['label-context'] });+ await insertBaseMemory('context', { tags: ['base-context'] });++ const result = await new UserMemoryQueryModel(serverDB, userId).queryTaxonomyOptions({+ include: ['labels', 'tags'],+ layers: [LayersEnum.Activity],+ });++ expect(result.tags).toEqual([{ count: 1, layers: undefined, value: 'base-activity' }]);+ expect(result.labels).toEqual([+ { count: 1, layers: [LayersEnum.Activity], value: 'label-activity' },+ ]);+ });++ it('drops contexts without a type from the type options', async () => {+ await insertContext({ type: null });+ await insertContext({ type: 'project' });++ const result = await new UserMemoryQueryModel(serverDB, userId).queryTaxonomyOptions({+ include: ['types'],+ layers: [LayersEnum.Context],+ });++ expect(result.types).toEqual([{ count: 1, layers: [LayersEnum.Context], value: 'project' }]);+ });+ });++ describe('buildUserMemoryWhere', () => {+ it('scopes a table without memory links to the user alone', async () => {+ await serverDB.insert(userPersonaDocuments).values([+ { persona: 'mine', userId },+ { persona: 'theirs', userId: otherUserId },+ ]);++ const rows = await serverDB+ .select({ persona: userPersonaDocuments.persona })+ .from(userPersonaDocuments)+ .where(buildUserMemoryWhere(serverDB, userId, { userId: userPersonaDocuments.userId }));++ expect(rows).toEqual([{ persona: 'mine' }]);+ expect(+ await serverDB+ .select({ id: userPersonaDocuments.id })+ .from(userPersonaDocuments)+ .where(eq(userPersonaDocuments.userId, otherUserId)),+ ).toHaveLength(1);+ });+ });+});diff --git a/packages/database/src/models/userMemory/model/utils.ts b/packages/database/src/models/userMemory/model/utils.tsindex 0999bbd6815..db306d68eb7 100644--- a/packages/database/src/models/userMemory/model/utils.ts+++ b/packages/database/src/models/userMemory/model/utils.ts@@ -36,7 +36,14 @@ export const isPGliteDatabase = (db: LobeChatDatabase) => {}).$client;- return 'waitReady' in (client ?? {}) && 'dataDir' in (client ?? {});+ return (+ 'waitReady' in (client ?? {}) &&+ 'dataDir' in+ (client ??+ // v8 ignore start -- unreachable: a nullish client already failed the waitReady check+ {})+ // v8 ignore stop+ );};export const buildTextSearchCondition = (params: {@@ -69,4 +76,5 @@ export const buildTextSearchCondition = (params: {return conditions.length > 0 ? or(...conditions) : undefined;};+/* v8 ignore next -- unreachable: module-private helper with no callers */const _pickSingleSearchType = (types?: string[]) => (types?.length === 1 ? types[0] : undefined);diff --git a/packages/database/src/models/userMemory/query/scoring.ts b/packages/database/src/models/userMemory/query/scoring.tsindex 917a287600b..0c20c366f1f 100644--- a/packages/database/src/models/userMemory/query/scoring.ts+++ b/packages/database/src/models/userMemory/query/scoring.ts@@ -14,12 +14,26 @@ const SHORT_TERM_ASSOCIATION_WINDOW_MS = 1000 * 60 * 60 * 24 * 3;const normalizeSimilarityTerm = (value: string) => value.trim().toLowerCase();const normalizeSearchTerms = (values?: string[]) => [- ...new Set((values ?? []).map((value) => normalizeSimilarityTerm(value)).filter(Boolean)),+ ...new Set(+ (+ values ??+ // v8 ignore start -- unreachable: both callers pass an array+ []+ )+ // v8 ignore stop+ .map((value) => normalizeSimilarityTerm(value))+ .filter(Boolean),+ ),];const clampScore = (value: number) => Math.max(0, Math.min(1, value));-const reciprocalRankScore = (rank?: number) => (rank === undefined ? 0 : 1 / (rank + 1));+const reciprocalRankScore = (rank?: number) =>+ rank === undefined+ ? // v8 ignore start -- unreachable: callers always pass the list index; the pair is ignored because a skipped first arm shifts the second arm's count+ 0+ : 1 / (rank + 1);+// v8 ignore stopconst tokenizeSimilarityTerm = (value: string) =>normalizeSimilarityTerm(value)@@ -34,7 +48,11 @@ const computeTokenJaccard = (left: string[], right: string[]) => {const intersection = [...leftSet].filter((token) => rightSet.has(token)).length;const union = new Set([...leftSet, ...rightSet]).size;- return union === 0 ? 0 : intersection / union;+ return union === 0+ ? // v8 ignore start -- unreachable: both token lists are non-empty here; the pair is ignored because a skipped first arm shifts the second arm's count+ 0+ : intersection / union;+ // v8 ignore stop};const computeTermSimilarity = (left: string, right: string) => {diff --git a/packages/database/src/models/userMemory/query/searchMemory.ts b/packages/database/src/models/userMemory/query/searchMemory.tsindex 929510e1d96..8a279cf5c6e 100644--- a/packages/database/src/models/userMemory/query/searchMemory.ts+++ b/packages/database/src/models/userMemory/query/searchMemory.ts@@ -49,16 +49,36 @@ export const searchMemory = async (if (layer === LayersEnum.Experience) return false;switch (layer) {case LayersEnum.Activity: {- return (limits.activities ?? 0) > 0;+ return (+ (limits.activities ??+ // v8 ignore start -- unreachable: limits.activities always falls back to DEFAULT_HYBRID_SEARCH_LIMIT+ 0) > 0+ // v8 ignore stop+ );}case LayersEnum.Context: {- return (limits.contexts ?? 0) > 0;+ return (+ (limits.contexts ??+ // v8 ignore start -- unreachable: limits.contexts always falls back to DEFAULT_HYBRID_SEARCH_LIMIT+ 0) > 0+ // v8 ignore stop+ );}case LayersEnum.Identity: {- return (limits.identities ?? 0) > 0;+ return (+ (limits.identities ??+ // v8 ignore start -- unreachable: limits.identities always falls back to DEFAULT_HYBRID_SEARCH_LIMIT+ 0) > 0+ // v8 ignore stop+ );}case LayersEnum.Preference: {- return (limits.preferences ?? 0) > 0;+ return (+ (limits.preferences ??+ // v8 ignore start -- unreachable: limits.preferences always falls back to DEFAULT_HYBRID_SEARCH_LIMIT+ 0) > 0+ // v8 ignore stop+ );}}}),@@ -84,13 +104,15 @@ export const searchMemory = async (}): Promise.resolve([]),requestedLayers.has(LayersEnum.Experience)- ? ctx.searchHybridExperiences({+ ? // v8 ignore start -- unreachable: requestedLayers filters out LayersEnum.Experience; the pair is ignored because a skipped first arm shifts the second arm's count+ ctx.searchHybridExperiences({embeddings: queryEmbeddings,lexicalSearch,params,queries: appliedQueries,}): Promise.resolve([]),+ // v8 ignore stoprequestedLayers.has(LayersEnum.Identity)? ctx.searchHybridIdentities({embeddings: queryEmbeddings,@@ -115,7 +137,11 @@ export const searchMemory = async (key: SearchLayerKey,items: RankedSearchCandidate<T>[],) => {- const limit = limits[key] ?? DEFAULT_HYBRID_SEARCH_LIMIT;+ const limit =+ limits[key] ??+ // v8 ignore start -- unreachable: every limits entry is already defaulted+ DEFAULT_HYBRID_SEARCH_LIMIT;+ // v8 ignore stopconst sorted = items.sort((left, right) => right.score.final - left.score.final);const selected = sorted.slice(0, limit).map((entry) => entry.item);ranking[key] = Object.fromEntries(diff --git a/packages/database/src/models/userMemory/sources/benchmarkLoCoMo.ts b/packages/database/src/models/userMemory/sources/benchmarkLoCoMo.tsindex 31b3ea2609e..855b5df3246 100644--- a/packages/database/src/models/userMemory/sources/benchmarkLoCoMo.ts+++ b/packages/database/src/models/userMemory/sources/benchmarkLoCoMo.ts@@ -85,7 +85,16 @@ export class UserMemorySourceBenchmarkLoCoMoModel {.sort((a, b) => {if (a.partIndex !== b.partIndex) return a.partIndex - b.partIndex;- return (a.createdAt?.getTime() ?? 0) - (b.createdAt?.getTime() ?? 0);+ return (+ (a.createdAt?.getTime() ??+ // v8 ignore start -- unreachable: replaceParts always sets createdAt+ 0) -+ // v8 ignore stop+ (b.createdAt?.getTime() ??+ // v8 ignore start -- unreachable: replaceParts always sets createdAt+ 0)+ // v8 ignore stop+ );});}}