🤯 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
🔨 chore(database): added user memory db model (#10062)
Neko9caacde1c1e0
diff --git a/packages/database/src/models/__tests__/userMemories.test.ts b/packages/database/src/models/__tests__/userMemories.test.tsnew file mode 100644index 00000000000..46b8c7afbfe--- /dev/null+++ b/packages/database/src/models/__tests__/userMemories.test.ts@@ -0,0 +1,1382 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { nanoid } from 'nanoid';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { idGenerator } from '@/database/utils/idGenerator';+import { LayersEnum, MergeStrategyEnum, TypesEnum } from '@/types/userMemory';++import {+ userMemories,+ userMemoriesContexts,+ userMemoriesExperiences,+ userMemoriesIdentities,+ userMemoriesPreferences,+ users,+} from '../../schemas';+import { LobeChatDatabase } from '../../type';+import {+ BaseCreateUserMemoryParams,+ CreateUserMemoryContextParams,+ CreateUserMemoryExperienceParams,+ CreateUserMemoryIdentityParams,+ CreateUserMemoryPreferenceParams,+ UserMemoryModel,+} from '../userMemory';+import { getTestDB } from './_util';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = idGenerator('user');+const userId2 = idGenerator('user');+const userMemoryModel = new UserMemoryModel(serverDB, userId);++/**+ * Generate a random normalized embedding vector+ * @param dimensions - Vector dimensions (default: 1024)+ * @returns Normalized random vector+ */+function generateRandomEmbedding(dimensions: number = 1024): number[] {+ const vector = Array(dimensions)+ .fill(0)+ .map(() => Math.random() * 2 - 1); // Random values between -1 and 1++ // Normalize the vector+ const magnitude = Math.sqrt(vector.reduce((sum, val) => sum + val * val, 0));+ return vector.map((val) => val / magnitude);+}++const mockEmbedding = generateRandomEmbedding();+const mockEmbedding2 = generateRandomEmbedding();++function createAxisVector(dimensions: number = 1024, index: number = 0): number[] {+ return Array.from({ length: dimensions }, (_, i) => (i === index ? 1 : 0));+}++// Assert that two numeric vectors are equal within a precision tolerance+function expectVectorToBeClose(+ actual: number[] | null | undefined,+ expected: number[],+ precision: number = 5,+) {+ expect(actual).toBeDefined();+ expect(actual).not.toBeNull();++ const actualVector = actual as number[];++ expect(actualVector.length).toBe(expected.length);+ actualVector.forEach((value, index) => {+ expect(value).toBeCloseTo(expected[index]!, precision);+ });+}++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: userId2 }]);+});++afterEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+});++function generateRandomCreateUserMemoryParams(+ memoryLayer: BaseCreateUserMemoryParams['memoryLayer'],+): BaseCreateUserMemoryParams {+ return {+ title: 'title ' + nanoid(),+ summary: 'summary ' + nanoid(),+ summaryEmbedding: generateRandomEmbedding(),+ memoryType: TypesEnum.Activity,+ memoryCategory: 'category',+ memoryLayer,+ details: 'details ' + nanoid(),+ } satisfies BaseCreateUserMemoryParams;+}++function generateRandomCreateUserMemoryExperienceParams() {+ return {+ ...generateRandomCreateUserMemoryParams(LayersEnum.Experience),+ experience: {+ action: 'action ' + nanoid(),+ actionVector: generateRandomEmbedding(),+ keyLearning: 'keyLearning ' + nanoid(),+ keyLearningVector: generateRandomEmbedding(),+ metadata: {},+ possibleOutcome: 'possibleOutcome ' + nanoid(),+ reasoning: 'reasoning ' + nanoid(),+ scoreConfidence: 0.5,+ situation: 'situation ' + nanoid(),+ situationVector: generateRandomEmbedding(),+ tags: [],+ type: 'learning',+ },+ } as CreateUserMemoryExperienceParams;+}++function generateRandomCreateUserMemoryIdentityParams() {+ const relationshipOptions = ['self', 'friend', 'colleague', 'other'];++ return {+ ...generateRandomCreateUserMemoryParams(LayersEnum.Identity),+ identity: {+ description: 'identity description ' + nanoid(),+ descriptionVector: generateRandomEmbedding(),+ episodicDate: new Date(),+ metadata: {},+ relationship: relationshipOptions[Math.floor(Math.random() * relationshipOptions.length)],+ role: 'role ' + nanoid(),+ tags: [],+ type: 'personal',+ },+ } as CreateUserMemoryIdentityParams;+}++function generateRandomCreateUserMemoryContextParams() {+ return {+ ...generateRandomCreateUserMemoryParams(LayersEnum.Context),+ context: {+ associatedObjects: [],+ associatedSubjects: [],+ currentStatus: 'status ' + nanoid(),+ description: 'context description ' + nanoid(),+ descriptionVector: generateRandomEmbedding(),+ metadata: {},+ scoreImpact: 0.5,+ scoreUrgency: 0.4,+ tags: [],+ title: 'context title ' + nanoid(),+ titleVector: generateRandomEmbedding(),+ type: 'environment',+ userMemoryIds: [],+ },+ } as CreateUserMemoryContextParams;+}++function generateRandomCreateUserMemoryPreferenceParams() {+ return {+ ...generateRandomCreateUserMemoryParams(LayersEnum.Preference),+ preference: {+ conclusionDirectives: 'directive ' + nanoid(),+ conclusionDirectivesVector: generateRandomEmbedding(),+ metadata: {},+ scorePriority: 0.7,+ suggestions: 'suggestions ' + nanoid(),+ tags: [],+ type: 'choice',+ },+ } as CreateUserMemoryPreferenceParams;+}++describe('UserMemoryModel', () => {+ describe('create layered memories', () => {+ it('creates a context memory and links the base record', async () => {+ const params = generateRandomCreateUserMemoryContextParams();+ params.context.metadata = { contextMeta: true };+ params.context.tags = ['context-tag'];++ const { context, memory } = await userMemoryModel.createContextMemory(params);++ const persistedMemory = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, memory.id),+ });+ const persistedContext = await serverDB.query.userMemoriesContexts.findFirst({+ where: eq(userMemoriesContexts.id, context.id),+ });++ expect(persistedMemory?.metadata).toEqual({ contextMeta: true });+ expect(persistedMemory?.tags).toEqual(['context-tag']);+ expect(persistedContext?.userMemoryIds).toEqual([memory.id]);+ expect(persistedContext?.metadata).toEqual({ contextMeta: true });+ expect(persistedContext?.tags).toEqual(['context-tag']);+ });++ it('creates an experience memory and stores vectors and fallbacks', async () => {+ const params = generateRandomCreateUserMemoryExperienceParams();+ params.experience.metadata = { expMeta: 1 };+ params.experience.tags = ['exp-tag'];+ params.experience.type = null;++ const { experience, memory } = await userMemoryModel.createExperienceMemory(params);++ const persistedMemory = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, memory.id),+ });+ const persistedExperience = await serverDB.query.userMemoriesExperiences.findFirst({+ where: eq(userMemoriesExperiences.id, experience.id),+ });++ expect(persistedMemory?.metadata).toEqual({ expMeta: 1 });+ expect(persistedMemory?.tags).toEqual(['exp-tag']);+ expect(persistedExperience?.userMemoryId).toBe(memory.id);+ expect(persistedExperience?.type).toBe(params.memoryType);+ expectVectorToBeClose(persistedExperience?.actionVector, params.experience.actionVector!);+ expectVectorToBeClose(+ persistedExperience?.situationVector,+ params.experience.situationVector!,+ );+ });++ it('creates a preference memory and links to the base record', async () => {+ const params = generateRandomCreateUserMemoryPreferenceParams();+ params.preference.metadata = { prefMeta: 'yes' };+ params.preference.tags = ['pref-tag'];+ params.preference.type = null;++ const { preference, memory } = await userMemoryModel.createPreferenceMemory(params);++ const persistedMemory = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, memory.id),+ });+ const persistedPreference = await serverDB.query.userMemoriesPreferences.findFirst({+ where: eq(userMemoriesPreferences.id, preference.id),+ });++ expect(persistedMemory?.metadata).toEqual({ prefMeta: 'yes' });+ expect(persistedMemory?.tags).toEqual(['pref-tag']);+ expect(persistedPreference?.userMemoryId).toBe(memory.id);+ expect(persistedPreference?.type).toBe(params.memoryType);+ expectVectorToBeClose(+ persistedPreference?.conclusionDirectivesVector,+ params.preference.conclusionDirectivesVector!,+ );+ });+ });++ describe('delete', () => {+ it('should delete a memory by id', async () => {+ const created = await userMemoryModel.create(+ generateRandomCreateUserMemoryExperienceParams(),+ );++ await userMemoryModel.delete(created.id);++ const deleted = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, created.id),+ });++ expect(deleted).toBeUndefined();+ });++ it('should only delete own user memories', async () => {+ const anotherUserModel = new UserMemoryModel(serverDB, userId2);+ const created = await anotherUserModel.create(+ generateRandomCreateUserMemoryExperienceParams(),+ );++ await userMemoryModel.delete(created.id);++ const stillExists = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, created.id),+ });++ expect(stillExists).toBeDefined();+ });+ });++ describe('deleteAll', () => {+ it('should delete all memories for the user', async () => {+ await userMemoryModel.create(generateRandomCreateUserMemoryExperienceParams());+ await userMemoryModel.create(generateRandomCreateUserMemoryIdentityParams());+ await userMemoryModel.create(generateRandomCreateUserMemoryContextParams());+ await userMemoryModel.create(generateRandomCreateUserMemoryPreferenceParams());+ await userMemoryModel.deleteAll();++ const remaining = await serverDB.query.userMemories.findMany({+ where: eq(userMemories.userId, userId),+ });++ expect(remaining).toHaveLength(0);+ });++ it('should only delete memories for the user, not others', async () => {+ // user 2+ const user2Memory = await userMemoryModel.create(+ generateRandomCreateUserMemoryExperienceParams(),+ );+ await serverDB+ .update(userMemories)+ .set({ userId: userId2 })+ .where(eq(userMemories.id, user2Memory.id));++ await userMemoryModel.create(generateRandomCreateUserMemoryIdentityParams());+ await userMemoryModel.create(generateRandomCreateUserMemoryContextParams());+ await userMemoryModel.create(generateRandomCreateUserMemoryPreferenceParams());+ await userMemoryModel.deleteAll();++ const user1Remaining = await serverDB.query.userMemories.findMany({+ where: eq(userMemories.userId, userId),+ });+ const user2Remaining = await serverDB.query.userMemories.findMany({+ where: eq(userMemories.userId, userId2),+ });++ expect(user1Remaining).toHaveLength(0);+ expect(user2Remaining).toHaveLength(1);+ });+ });++ describe('search', () => {+ it('should return layered results with split limits', async () => {+ const experienceMemoryOne = await userMemoryModel.create(+ generateRandomCreateUserMemoryExperienceParams(),+ );+ await serverDB.insert(userMemoriesExperiences).values({+ ...generateRandomCreateUserMemoryExperienceParams().experience,+ userId,+ userMemoryId: experienceMemoryOne.id,+ });++ const experienceMemoryTwo = await userMemoryModel.create(+ generateRandomCreateUserMemoryExperienceParams(),+ );+ await serverDB.insert(userMemoriesExperiences).values({+ ...generateRandomCreateUserMemoryExperienceParams().experience,+ userId,+ userMemoryId: experienceMemoryTwo.id,+ });++ const preferenceMemoryOne = await userMemoryModel.create(+ generateRandomCreateUserMemoryPreferenceParams(),+ );+ await serverDB.insert(userMemoriesPreferences).values({+ ...generateRandomCreateUserMemoryPreferenceParams().preference,+ userId,+ userMemoryId: preferenceMemoryOne.id,+ });++ const preferenceMemoryTwo = await userMemoryModel.create(+ generateRandomCreateUserMemoryPreferenceParams(),+ );+ await serverDB.insert(userMemoriesPreferences).values({+ ...generateRandomCreateUserMemoryPreferenceParams().preference,+ userId,+ userMemoryId: preferenceMemoryTwo.id,+ });++ await serverDB.insert(userMemoriesContexts).values({+ ...generateRandomCreateUserMemoryContextParams().context,+ userId,+ userMemoryIds: [experienceMemoryOne.id, preferenceMemoryOne.id],+ });+ await serverDB.insert(userMemoriesContexts).values({+ ...generateRandomCreateUserMemoryContextParams().context,+ userId,+ userMemoryIds: [experienceMemoryTwo.id, preferenceMemoryTwo.id],+ });++ const result = await userMemoryModel.search({+ limit: 5,+ limits: {+ contexts: 1,+ experiences: 1,+ preferences: 1,+ },+ });++ expect(result.experiences).toHaveLength(1);+ expect(result.preferences).toHaveLength(1);+ expect(result.contexts).toHaveLength(1);+ });++ it('ranks contexts, experiences, and preferences by embedding similarity', async () => {+ const now = new Date('2024-01-01T00:00:00.000Z');+ const axis0 = createAxisVector();+ const axis1 = createAxisVector(1024, 1);++ const closeContextId = idGenerator('memory');+ const farContextId = idGenerator('memory');+ await serverDB.insert(userMemoriesContexts).values([+ {+ accessedAt: now,+ createdAt: now,+ description: 'close context',+ descriptionVector: axis0,+ id: closeContextId,+ updatedAt: now,+ userId,+ },+ {+ accessedAt: now,+ createdAt: now,+ description: 'far context',+ descriptionVector: axis1,+ id: farContextId,+ updatedAt: now,+ userId,+ },+ ]);++ const closeExperienceMemoryId = idGenerator('memory');+ const farExperienceMemoryId = idGenerator('memory');+ await serverDB.insert(userMemories).values([+ {+ accessedAt: now,+ createdAt: now,+ id: closeExperienceMemoryId,+ lastAccessedAt: now,+ memoryLayer: 'experience',+ summary: 'close experience base',+ updatedAt: now,+ userId,+ },+ {+ accessedAt: now,+ createdAt: now,+ id: farExperienceMemoryId,+ lastAccessedAt: now,+ memoryLayer: 'experience',+ summary: 'far experience base',+ updatedAt: now,+ userId,+ },+ ]);++ const closeExperienceId = idGenerator('memory');+ const farExperienceId = idGenerator('memory');+ await serverDB.insert(userMemoriesExperiences).values([+ {+ accessedAt: now,+ action: 'close action',+ actionVector: axis0,+ createdAt: now,+ id: closeExperienceId,+ situation: 'close situation',+ situationVector: axis0,+ updatedAt: now,+ userId,+ userMemoryId: closeExperienceMemoryId,+ },+ {+ accessedAt: now,+ action: 'far action',+ actionVector: axis1,+ createdAt: now,+ id: farExperienceId,+ situation: 'far situation',+ situationVector: axis1,+ updatedAt: now,+ userId,+ userMemoryId: farExperienceMemoryId,+ },+ ]);++ const closePreferenceMemoryId = idGenerator('memory');+ const farPreferenceMemoryId = idGenerator('memory');+ await serverDB.insert(userMemories).values([+ {+ accessedAt: now,+ createdAt: now,+ id: closePreferenceMemoryId,+ lastAccessedAt: now,+ memoryLayer: 'preference',+ summary: 'close preference base',+ updatedAt: now,+ userId,+ },+ {+ accessedAt: now,+ createdAt: now,+ id: farPreferenceMemoryId,+ lastAccessedAt: now,+ memoryLayer: 'preference',+ summary: 'far preference base',+ updatedAt: now,+ userId,+ },+ ]);++ const closePreferenceId = idGenerator('memory');+ const farPreferenceId = idGenerator('memory');+ await serverDB.insert(userMemoriesPreferences).values([+ {+ accessedAt: now,+ conclusionDirectives: 'close preference',+ conclusionDirectivesVector: axis0,+ createdAt: now,+ id: closePreferenceId,+ updatedAt: now,+ userId,+ userMemoryId: closePreferenceMemoryId,+ },+ {+ accessedAt: now,+ conclusionDirectives: 'far preference',+ conclusionDirectivesVector: axis1,+ createdAt: now,+ id: farPreferenceId,+ updatedAt: now,+ userId,+ userMemoryId: farPreferenceMemoryId,+ },+ ]);++ const result = await userMemoryModel.searchWithEmbedding({+ embedding: axis0,+ limits: {+ contexts: 2,+ experiences: 2,+ preferences: 2,+ },+ });++ expect(result.contexts[0]?.id).toBe(closeContextId);+ expect(result.experiences[0]?.id).toBe(closeExperienceId);+ expect(result.preferences[0]?.id).toBe(closePreferenceId);+ });+ });++ describe('findById', () => {+ it('returns own memories and updates access metrics', async () => {+ const created = await userMemoryModel.create(+ generateRandomCreateUserMemoryExperienceParams(),+ );++ const before = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, created.id),+ });++ expect(before).toBeDefined();+ expect(before?.accessedCount).toBe(0);++ const found = await userMemoryModel.findById(created.id);++ expect(found).toBeDefined();+ expect(found?.id).toBe(created.id);++ const after = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, created.id),+ });++ expect(after?.accessedCount).toBe((before?.accessedCount ?? 0) + 1);+ expect(after?.lastAccessedAt.getTime()).toBeGreaterThanOrEqual(+ before!.lastAccessedAt.getTime(),+ );+ });++ it('does not expose or mutate memories belonging to other users', async () => {+ const anotherUserModel = new UserMemoryModel(serverDB, userId2);+ const otherMemory = await anotherUserModel.create(+ generateRandomCreateUserMemoryExperienceParams(),+ );++ const found = await userMemoryModel.findById(otherMemory.id);++ expect(found).toBeUndefined();++ const persisted = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, otherMemory.id),+ });++ expect(persisted?.accessedCount).toBe(0);+ });+ });++ describe('update', () => {+ it('updates mutable fields for own memories only', async () => {+ const created = await userMemoryModel.create(+ generateRandomCreateUserMemoryExperienceParams(),+ );++ await userMemoryModel.update(created.id, {+ memoryCategory: 'updated-category',+ summary: 'Updated summary',+ title: 'Updated title',+ });++ const updated = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, created.id),+ });++ expect(updated?.memoryCategory).toBe('updated-category');+ expect(updated?.summary).toBe('Updated summary');+ expect(updated?.title).toBe('Updated title');+ expect(updated?.updatedAt.getTime()).toBeGreaterThan(created.createdAt.getTime());+ });++ it('ignores updates for memories owned by other users', async () => {+ const anotherUserModel = new UserMemoryModel(serverDB, userId2);+ const otherMemory = await anotherUserModel.create(+ generateRandomCreateUserMemoryExperienceParams(),+ );++ await userMemoryModel.update(otherMemory.id, {+ summary: 'Should not update',+ });++ const persisted = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, otherMemory.id),+ });++ expect(persisted?.summary).not.toBe('Should not update');+ });+ });++ describe('update vector methods', () => {+ it('updates base user memory vectors', async () => {+ const memoryId = idGenerator('memory');+ await serverDB.insert(userMemories).values({+ details: 'details',+ id: memoryId,+ lastAccessedAt: new Date(),+ summary: 'summary',+ title: 'title',+ userId,+ });++ const summaryVector = generateRandomEmbedding();+ const detailsVector = generateRandomEmbedding();++ await userMemoryModel.updateUserMemoryVectors(memoryId, {+ detailsVector1024: detailsVector,+ summaryVector1024: summaryVector,+ });++ const updated = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, memoryId),+ });++ expectVectorToBeClose(updated?.summaryVector1024, summaryVector);+ expectVectorToBeClose(updated?.detailsVector1024, detailsVector);+ });++ it('ignores user memory vector updates when payload is empty', async () => {+ const memoryId = idGenerator('memory');+ const timestamp = new Date('2024-01-01T00:00:00.000Z');+ const summaryVector = generateRandomEmbedding();++ await serverDB.insert(userMemories).values({+ accessedAt: timestamp,+ createdAt: timestamp,+ details: 'details',+ id: memoryId,+ lastAccessedAt: timestamp,+ summary: 'summary',+ summaryVector1024: summaryVector,+ updatedAt: timestamp,+ userId,+ });++ const before = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, memoryId),+ });++ await userMemoryModel.updateUserMemoryVectors(memoryId, {});++ const after = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, memoryId),+ });++ expect(after?.updatedAt.getTime()).toBe(before?.updatedAt.getTime());+ expectVectorToBeClose(after?.summaryVector1024, summaryVector);+ });++ it('updates context vectors', async () => {+ const contextId = idGenerator('memory');+ await serverDB.insert(userMemoriesContexts).values({+ description: 'desc',+ id: contextId,+ title: 'title',+ userId,+ });++ const descriptionVector = generateRandomEmbedding();+ await userMemoryModel.updateContextVectors(contextId, { descriptionVector });+ const updated = await serverDB.query.userMemoriesContexts.findFirst({+ where: eq(userMemoriesContexts.id, contextId),+ });++ expectVectorToBeClose(updated?.descriptionVector, descriptionVector);+ });++ it('updates preference vector values including null assignments', async () => {+ const preferenceId = idGenerator('memory');+ await serverDB.insert(userMemoriesPreferences).values({+ conclusionDirectives: 'directive',+ conclusionDirectivesVector: generateRandomEmbedding(),+ id: preferenceId,+ userId,+ });++ await userMemoryModel.updatePreferenceVectors(preferenceId, {+ conclusionDirectivesVector: null,+ });++ const updated = await serverDB.query.userMemoriesPreferences.findFirst({+ where: eq(userMemoriesPreferences.id, preferenceId),+ });++ expect(updated?.conclusionDirectivesVector).toBeNull();+ });++ it('updates identity vectors', async () => {+ const identityId = idGenerator('memory');+ await serverDB.insert(userMemoriesIdentities).values({+ description: 'identity',+ id: identityId,+ userId,+ });++ const descriptionVector = generateRandomEmbedding();++ await userMemoryModel.updateIdentityVectors(identityId, {+ descriptionVector,+ });++ const updated = await serverDB.query.userMemoriesIdentities.findFirst({+ where: eq(userMemoriesIdentities.id, identityId),+ });++ expectVectorToBeClose(updated?.descriptionVector, descriptionVector);+ });++ it('skips identity vector updates when no fields are provided', async () => {+ const identityId = idGenerator('memory');+ const timestamp = new Date('2024-03-01T00:00:00.000Z');+ const descriptionVector = generateRandomEmbedding();++ await serverDB.insert(userMemoriesIdentities).values({+ accessedAt: timestamp,+ createdAt: timestamp,+ description: 'identity',+ descriptionVector,+ id: identityId,+ updatedAt: timestamp,+ userId,+ });++ await userMemoryModel.updateIdentityVectors(identityId, {});++ const persisted = await serverDB.query.userMemoriesIdentities.findFirst({+ where: eq(userMemoriesIdentities.id, identityId),+ });++ expect(persisted?.updatedAt.getTime()).toBe(timestamp.getTime());+ expectVectorToBeClose(persisted?.descriptionVector, descriptionVector);+ });++ it('updates experience vectors without touching unspecified fields', async () => {+ const experienceId = idGenerator('memory');+ const originalSituationVector = generateRandomEmbedding();+ const originalKeyLearningVector = generateRandomEmbedding();+ const originalActionVector = generateRandomEmbedding();++ await serverDB.insert(userMemoriesExperiences).values({+ action: 'action',+ actionVector: originalActionVector,+ id: experienceId,+ keyLearning: 'key learning',+ keyLearningVector: originalKeyLearningVector,+ situation: 'situation',+ situationVector: originalSituationVector,+ userId,+ });++ const updatedActionVector = generateRandomEmbedding();++ await userMemoryModel.updateExperienceVectors(experienceId, {+ actionVector: updatedActionVector,+ });++ const updated = await serverDB.query.userMemoriesExperiences.findFirst({+ where: eq(userMemoriesExperiences.id, experienceId),+ });++ expectVectorToBeClose(updated?.actionVector, updatedActionVector);+ expectVectorToBeClose(updated?.situationVector, originalSituationVector);+ expectVectorToBeClose(updated?.keyLearningVector, originalKeyLearningVector);+ });++ it('updates multiple experience vector fields and supports null assignments', async () => {+ const experienceId = idGenerator('memory');+ const originalSituationVector = generateRandomEmbedding();+ const originalKeyLearningVector = generateRandomEmbedding();+ const originalActionVector = generateRandomEmbedding();++ await serverDB.insert(userMemoriesExperiences).values({+ action: 'action',+ actionVector: originalActionVector,+ id: experienceId,+ keyLearning: 'key learning',+ keyLearningVector: originalKeyLearningVector,+ situation: 'situation',+ situationVector: originalSituationVector,+ userId,+ });++ const newSituationVector = generateRandomEmbedding();++ await userMemoryModel.updateExperienceVectors(experienceId, {+ keyLearningVector: null,+ situationVector: newSituationVector,+ });++ const updated = await serverDB.query.userMemoriesExperiences.findFirst({+ where: eq(userMemoriesExperiences.id, experienceId),+ });++ expectVectorToBeClose(updated?.situationVector, newSituationVector);+ expect(updated?.keyLearningVector).toBeNull();+ expectVectorToBeClose(updated?.actionVector, originalActionVector);+ });+ });++ describe('identity entry operations', () => {+ it('adds a new identity entry with base memory', async () => {+ const summaryVector = generateRandomEmbedding();+ const descriptionVector = generateRandomEmbedding();++ const { identityId, userMemoryId } = await userMemoryModel.addIdentityEntry({+ base: {+ memoryCategory: 'profile',+ memoryLayer: 'identity',+ memoryType: 'personal-profile',+ metadata: { meta: 'value' },+ summary: 'Initial summary',+ summaryVector1024: summaryVector,+ title: 'Identity Summary',+ },+ identity: {+ description: 'A detailed description of the user identity',+ descriptionVector,+ episodicDate: new Date('2024-01-01T00:00:00.000Z'),+ metadata: { extracted: ['friend'] },+ relationship: 'friend',+ role: 'software engineer',+ tags: ['tag-a'],+ type: 'personal',+ },+ });++ const baseMemory = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, userMemoryId),+ });+ const identityMemory = await serverDB.query.userMemoriesIdentities.findFirst({+ where: eq(userMemoriesIdentities.id, identityId),+ });++ expect(baseMemory?.summary).toBe('Initial summary');+ expectVectorToBeClose(baseMemory?.summaryVector1024, summaryVector);+ expect(baseMemory?.memoryLayer).toBe('identity');+ expect(baseMemory?.metadata).toEqual({ meta: 'value' });++ expect(identityMemory?.description).toBe('A detailed description of the user identity');+ expectVectorToBeClose(identityMemory?.descriptionVector, descriptionVector);+ expect(identityMemory?.relationship).toBe('friend');+ expect(identityMemory?.role).toBe('software engineer');+ expect(identityMemory?.type).toBe('personal');+ expect(identityMemory?.userMemoryId).toBe(userMemoryId);+ });++ it('normalizes identity fields and coerces date inputs when adding entries', async () => {+ const baseDate = '2024-02-02T12:00:00.000Z';+ const episodicDate = '2024-03-03T00:00:00.000Z';++ const { identityId, userMemoryId } = await userMemoryModel.addIdentityEntry({+ base: {+ lastAccessedAt: baseDate,+ summary: 'Normalize base',+ },+ identity: {+ description: 'Normalize identity',+ episodicDate,+ relationship: ' FRIEND ',+ type: ' PERSONAL ',+ },+ });++ const baseMemory = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, userMemoryId),+ });+ const identityMemory = await serverDB.query.userMemoriesIdentities.findFirst({+ where: eq(userMemoriesIdentities.id, identityId),+ });++ expect(baseMemory?.lastAccessedAt.toISOString()).toBe(new Date(baseDate).toISOString());+ expect(identityMemory?.relationship).toBe('friend');+ expect(identityMemory?.type).toBe('personal');+ expect(identityMemory?.episodicDate?.toISOString()).toBe(+ new Date(episodicDate).toISOString(),+ );+ });++ it('falls back to defaults when invalid identity data is provided', async () => {+ const frozenNow = new Date('2024-05-05T00:00:00.000Z');+ vi.useFakeTimers();+ vi.setSystemTime(frozenNow);++ try {+ const { identityId, userMemoryId } = await userMemoryModel.addIdentityEntry({+ base: {+ lastAccessedAt: 'not-a-date',+ status: undefined,+ },+ identity: {+ description: 'Invalid identity',+ episodicDate: 'invalid',+ relationship: 'bestie',+ type: 'unknown',+ },+ });++ const baseMemory = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, userMemoryId),+ });+ const identityMemory = await serverDB.query.userMemoriesIdentities.findFirst({+ where: eq(userMemoriesIdentities.id, identityId),+ });++ expect(baseMemory?.status).toBe('active');+ expect(baseMemory?.lastAccessedAt.toISOString()).toBe(frozenNow.toISOString());+ expect(identityMemory?.relationship).toBeNull();+ expect(identityMemory?.type).toBeNull();+ expect(identityMemory?.episodicDate).toBeNull();+ } finally {+ vi.useRealTimers();+ }+ });++ it('updates identity entry fields with merge strategy', async () => {+ const { identityId, userMemoryId } = await userMemoryModel.addIdentityEntry({+ base: {+ memoryCategory: 'profile',+ summary: 'Original summary',+ title: 'Original title',+ },+ identity: {+ description: 'Original identity description',+ relationship: 'friend',+ role: 'developer',+ type: 'personal',+ },+ });++ const updated = await userMemoryModel.updateIdentityEntry({+ identityId,+ mergeStrategy: MergeStrategyEnum.Merge,+ base: {+ summary: 'Updated summary',+ },+ identity: {+ description: 'Updated identity description',+ relationship: 'mentor',+ },+ });++ expect(updated).toBe(true);++ const baseMemory = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, userMemoryId),+ });+ const identityMemory = await serverDB.query.userMemoriesIdentities.findFirst({+ where: eq(userMemoriesIdentities.id, identityId),+ });++ expect(baseMemory?.summary).toBe('Updated summary');+ expect(baseMemory?.title).toBe('Original title');+ expect(identityMemory?.description).toBe('Updated identity description');+ expect(identityMemory?.relationship).toBe('mentor');+ expect(identityMemory?.role).toBe('developer');+ });++ it('normalizes identity values and coerces dates when updating entries', async () => {+ const { identityId, userMemoryId } = await userMemoryModel.addIdentityEntry({+ base: {+ summary: 'base summary',+ },+ identity: {+ description: 'base identity',+ },+ });++ await userMemoryModel.updateIdentityEntry({+ identityId,+ base: {+ lastAccessedAt: '2024-06-06T00:00:00.000Z',+ },+ identity: {+ episodicDate: '2024-07-07T00:00:00.000Z',+ relationship: ' COLLEAGUE ',+ type: ' PROFESSIONAL ',+ },+ });++ const baseMemory = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, userMemoryId),+ });+ const identityMemory = await serverDB.query.userMemoriesIdentities.findFirst({+ where: eq(userMemoriesIdentities.id, identityId),+ });++ expect(baseMemory?.lastAccessedAt.toISOString()).toBe('2024-06-06T00:00:00.000Z');+ expect(identityMemory?.relationship).toBe('colleague');+ expect(identityMemory?.type).toBe('professional');+ expect(identityMemory?.episodicDate?.toISOString()).toBe('2024-07-07T00:00:00.000Z');+ });++ it('replaces identity entry fields and clears unspecified values when mergeStrategy is replace', async () => {+ const { identityId } = await userMemoryModel.addIdentityEntry({+ base: {+ summary: 'Summary to replace',+ title: 'Title to replace',+ },+ identity: {+ description: 'Description to replace',+ relationship: 'mentor',+ role: 'manager',+ type: 'professional',+ },+ });++ const replaced = await userMemoryModel.updateIdentityEntry({+ identityId,+ mergeStrategy: MergeStrategyEnum.Replace,+ identity: {+ description: 'Fresh description',+ type: 'personal',+ },+ });++ expect(replaced).toBe(true);++ const identityMemory = await serverDB.query.userMemoriesIdentities.findFirst({+ where: eq(userMemoriesIdentities.id, identityId),+ });++ expect(identityMemory?.description).toBe('Fresh description');+ expect(identityMemory?.type).toBe('personal');+ expect(identityMemory?.relationship).toBeNull();+ expect(identityMemory?.role).toBeNull();+ });++ it('keeps existing identity fields when merge payload is empty', async () => {+ const { identityId } = await userMemoryModel.addIdentityEntry({+ base: { summary: 'keep base' },+ identity: {+ description: 'Keep description',+ metadata: { keep: true },+ relationship: 'colleague',+ role: 'engineer',+ tags: ['keep'],+ type: 'professional',+ },+ });++ await userMemoryModel.updateIdentityEntry({+ identityId,+ identity: {},+ mergeStrategy: MergeStrategyEnum.Merge,+ });++ const identityMemory = await serverDB.query.userMemoriesIdentities.findFirst({+ where: eq(userMemoriesIdentities.id, identityId),+ });++ expect(identityMemory?.description).toBe('Keep description');+ expect(identityMemory?.metadata).toEqual({ keep: true });+ expect(identityMemory?.relationship).toBe('colleague');+ expect(identityMemory?.role).toBe('engineer');+ expect(identityMemory?.tags).toEqual(['keep']);+ expect(identityMemory?.type).toBe('professional');+ });++ it('clears all identity fields when replacing with an empty payload', async () => {+ const { identityId } = await userMemoryModel.addIdentityEntry({+ base: { summary: 'keep base' },+ identity: {+ description: 'Will be cleared',+ metadata: { existing: true },+ relationship: 'mentor',+ role: 'lead',+ tags: ['tagged'],+ type: 'personal',+ },+ });++ await userMemoryModel.updateIdentityEntry({+ identityId,+ identity: {},+ mergeStrategy: MergeStrategyEnum.Replace,+ });++ const identityMemory = await serverDB.query.userMemoriesIdentities.findFirst({+ where: eq(userMemoriesIdentities.id, identityId),+ });++ expect(identityMemory?.description).toBeNull();+ expect(identityMemory?.metadata).toBeNull();+ expect(identityMemory?.relationship).toBeNull();+ expect(identityMemory?.role).toBeNull();+ expect(identityMemory?.tags).toBeNull();+ expect(identityMemory?.type).toBeNull();+ });++ it('removes identity entry and associated base memory', async () => {+ const { identityId, userMemoryId } = await userMemoryModel.addIdentityEntry({+ base: {+ summary: 'Summary to delete',+ },+ identity: {+ description: 'Identity to delete',+ },+ });++ const removed = await userMemoryModel.removeIdentityEntry(identityId);++ const baseMemory = await serverDB.query.userMemories.findFirst({+ where: eq(userMemories.id, userMemoryId),+ });+ const identityMemory = await serverDB.query.userMemoriesIdentities.findFirst({+ where: eq(userMemoriesIdentities.id, identityId),+ });++ expect(removed).toBe(true);+ expect(baseMemory).toBeUndefined();+ expect(identityMemory).toBeUndefined();+ });+ });++ describe('getAllIdentities', () => {+ it('returns all identities for current user ordered by newest first', async () => {+ const first = await userMemoryModel.addIdentityEntry({+ base: { summary: 'first' },+ identity: { description: 'first identity', type: 'personal' },+ });++ const second = await userMemoryModel.addIdentityEntry({+ base: { summary: 'second' },+ identity: { description: 'second identity', type: 'professional' },+ });++ const third = await userMemoryModel.addIdentityEntry({+ base: { summary: 'third' },+ identity: { description: 'third identity', type: 'demographic' },+ });++ const anotherUserModel = new UserMemoryModel(serverDB, userId2);+ await anotherUserModel.addIdentityEntry({+ base: { summary: 'other-user' },+ identity: { description: 'other identity', type: 'personal' },+ });++ await serverDB+ .update(userMemoriesIdentities)+ .set({ createdAt: new Date('2024-01-01T00:00:00.000Z') })+ .where(eq(userMemoriesIdentities.id, first.identityId));+ await serverDB+ .update(userMemoriesIdentities)+ .set({ createdAt: new Date('2024-02-01T00:00:00.000Z') })+ .where(eq(userMemoriesIdentities.id, second.identityId));+ await serverDB+ .update(userMemoriesIdentities)+ .set({ createdAt: new Date('2024-03-01T00:00:00.000Z') })+ .where(eq(userMemoriesIdentities.id, third.identityId));++ const identities = await userMemoryModel.getAllIdentities();++ expect(identities).toHaveLength(3);+ expect(identities[0]?.id).toBe(third.identityId);+ expect(identities[1]?.id).toBe(second.identityId);+ expect(identities[2]?.id).toBe(first.identityId);+ identities.forEach((identity) => {+ expect(identity.userId).toBe(userId);+ });+ });+ });++ describe('getIdentitiesByType', () => {+ it('returns the newest identities of the requested type for the current user', async () => {+ const resultOne = await userMemoryModel.addIdentityEntry({+ base: {+ summary: 'personal-one',+ },+ identity: {+ description: 'first personal',+ type: 'personal',+ },+ });++ const resultTwo = await userMemoryModel.addIdentityEntry({+ base: {+ summary: 'personal-two',+ },+ identity: {+ description: 'second personal',+ type: 'personal',+ },+ });++ await userMemoryModel.addIdentityEntry({+ base: {+ summary: 'preference-not-personal',+ },+ identity: {+ description: 'professional identity',+ type: 'professional',+ },+ });++ const anotherUserModel = new UserMemoryModel(serverDB, userId2);+ await anotherUserModel.addIdentityEntry({+ base: {+ summary: 'other user personal',+ },+ identity: {+ description: 'should not show',+ type: 'personal',+ },+ });++ // Ensure deterministic ordering by forcing createdAt values+ await serverDB+ .update(userMemoriesIdentities)+ .set({ createdAt: new Date('2024-01-01T00:00:00.000Z') })+ .where(eq(userMemoriesIdentities.id, resultOne.identityId));+ await serverDB+ .update(userMemoriesIdentities)+ .set({ createdAt: new Date('2024-02-01T00:00:00.000Z') })+ .where(eq(userMemoriesIdentities.id, resultTwo.identityId));++ const identities = await userMemoryModel.getIdentitiesByType('personal');++ expect(identities).toHaveLength(2);+ expect(identities[0]?.id).toBe(resultTwo.identityId);+ expect(identities[1]?.id).toBe(resultOne.identityId);+ identities.forEach((identity) => {+ expect(identity.type).toBe('personal');+ expect(identity.userId).toBe(userId);+ });+ });+ });++ describe('access metrics', () => {+ it('should update accessedAt for each layer table', async () => {+ const experienceParams = generateRandomCreateUserMemoryExperienceParams();+ const experienceMemory = await userMemoryModel.create(experienceParams);+ await serverDB.insert(userMemoriesExperiences).values({+ ...experienceParams.experience,+ userId,+ userMemoryId: experienceMemory.id,+ });++ const preferenceParams = generateRandomCreateUserMemoryPreferenceParams();+ const preferenceMemory = await userMemoryModel.create(preferenceParams);+ await serverDB.insert(userMemoriesPreferences).values({+ ...preferenceParams.preference,+ userId,+ userMemoryId: preferenceMemory.id,+ });++ const contextParams = generateRandomCreateUserMemoryContextParams();+ await serverDB.insert(userMemoriesContexts).values({+ ...contextParams.context,+ userId,+ userMemoryIds: [experienceMemory.id, preferenceMemory.id],+ });++ const beforeContexts = await serverDB.query.userMemoriesContexts.findMany({+ where: eq(userMemoriesContexts.userId, userId),+ });++ const beforeExperience = await serverDB.query.userMemoriesExperiences.findFirst({+ where: eq(userMemoriesExperiences.userMemoryId, experienceMemory.id),+ });+ const beforePreference = await serverDB.query.userMemoriesPreferences.findFirst({+ where: eq(userMemoriesPreferences.userMemoryId, preferenceMemory.id),+ });++ const beforeBaseMemories = await serverDB.query.userMemories.findMany({+ where: eq(userMemories.userId, userId),+ });++ await userMemoryModel.search({ limit: 10 });++ const afterExperience = await serverDB.query.userMemoriesExperiences.findFirst({+ where: eq(userMemoriesExperiences.userMemoryId, experienceMemory.id),+ });+ const afterPreference = await serverDB.query.userMemoriesPreferences.findFirst({+ where: eq(userMemoriesPreferences.userMemoryId, preferenceMemory.id),+ });+ const afterContexts = await serverDB.query.userMemoriesContexts.findMany({+ where: eq(userMemoriesContexts.userId, userId),+ });+ const afterBaseMemoryMap = new Map(+ (+ await serverDB.query.userMemories.findMany({+ where: eq(userMemories.userId, userId),+ })+ ).map((memory) => [memory.id, memory]),+ );++ expect(beforeExperience?.accessedAt?.getTime()).toBeDefined();+ expect(afterExperience?.accessedAt?.getTime()).toBeDefined();+ expect(afterExperience!.accessedAt.getTime()).toBeGreaterThanOrEqual(+ beforeExperience!.accessedAt.getTime(),+ );++ expect(beforePreference?.accessedAt?.getTime()).toBeDefined();+ expect(afterPreference?.accessedAt?.getTime()).toBeDefined();+ expect(afterPreference!.accessedAt.getTime()).toBeGreaterThanOrEqual(+ beforePreference!.accessedAt.getTime(),+ );++ beforeContexts.forEach((beforeContext) => {+ const afterContext = afterContexts.find((ctx) => ctx.id === beforeContext.id);+ expect(afterContext).toBeDefined();+ expect(afterContext!.accessedAt.getTime()).toBeGreaterThanOrEqual(+ beforeContext.accessedAt.getTime(),+ );+ });++ const updatedIds = new Set([experienceMemory.id, preferenceMemory.id]);++ for (const before of beforeBaseMemories) {+ const after = afterBaseMemoryMap.get(before.id);+ expect(after).toBeDefined();+ if (updatedIds.has(before.id)) {+ expect(after!.accessedCount).toBeDefined();+ expect(after!.accessedCount).toBe((before.accessedCount ?? 0) + 1);+ expect(after!.accessedAt.getTime()).toBeGreaterThanOrEqual(before.accessedAt.getTime());+ expect(after!.lastAccessedAt.getTime()).toBeGreaterThanOrEqual(+ before.lastAccessedAt.getTime(),+ );+ } else {+ expect(after!.accessedCount).toBe(before.accessedCount);+ }+ }+ });++ it('updates accessedAt on identity layer records when base memory is identity', async () => {+ const { identityId, userMemoryId } = await userMemoryModel.addIdentityEntry({+ base: {+ memoryLayer: 'identity',+ summary: 'identity base',+ },+ identity: {+ description: 'identity description',+ type: 'personal',+ },+ });++ const past = new Date('2023-01-01T00:00:00.000Z');+ await serverDB+ .update(userMemoriesIdentities)+ .set({ accessedAt: past })+ .where(eq(userMemoriesIdentities.id, identityId));++ const before = await serverDB.query.userMemoriesIdentities.findFirst({+ where: eq(userMemoriesIdentities.id, identityId),+ });+ expect(before).toBeDefined();+ expect(before?.accessedAt.getTime()).toBe(past.getTime());++ await userMemoryModel.findById(userMemoryId);++ const after = await serverDB.query.userMemoriesIdentities.findFirst({+ where: eq(userMemoriesIdentities.id, identityId),+ });++ expect(after).toBeDefined();+ expect(after!.accessedAt.getTime()).toBeGreaterThan(past.getTime());+ });+ });+});diff --git a/packages/database/src/models/userMemory.ts b/packages/database/src/models/userMemory.tsnew file mode 100644index 00000000000..e704b9ed37e--- /dev/null+++ b/packages/database/src/models/userMemory.ts@@ -0,0 +1,993 @@+import {+ IdentityTypeEnum,+ LayersEnum,+ MergeStrategyEnum,+ RelationshipEnum,+ TypesEnum,+} from '@lobechat/types';+import { and, cosineDistance, desc, eq, inArray, sql } from 'drizzle-orm';++import { merge } from '@/utils/merge';++import {+ UserMemoryContext,+ UserMemoryContextsWithoutVectors,+ UserMemoryExperience,+ UserMemoryExperiencesWithoutVectors,+ UserMemoryIdentitiesWithoutVectors,+ UserMemoryIdentity,+ UserMemoryItem,+ UserMemoryPreference,+ UserMemoryPreferencesWithoutVectors,+ userMemories,+ userMemoriesContexts,+ userMemoriesExperiences,+ userMemoriesIdentities,+ userMemoriesPreferences,+} from '../schemas';+import { LobeChatDatabase } from '../type';++const normalizeRelationshipValue = (input: unknown): RelationshipEnum | null => {+ if (input === null) return null;+ if (typeof input !== 'string') return null;+ const normalized = input.trim().toLowerCase();+ return Object.values(RelationshipEnum).includes(normalized as RelationshipEnum)+ ? (normalized as RelationshipEnum)+ : null;+};++const normalizeIdentityTypeValue = (input: unknown): IdentityTypeEnum | null => {+ if (input === null) return null;+ if (typeof input !== 'string') return null;+ const normalized = input.trim().toLowerCase();+ return Object.values(IdentityTypeEnum).includes(normalized as IdentityTypeEnum)+ ? (normalized as IdentityTypeEnum)+ : null;+};++const coerceDate = (input: unknown): Date | null => {+ if (input === null || input === undefined) return null;+ if (input instanceof Date) {+ return Number.isNaN(input.getTime()) ? null : input;+ }+ if (typeof input === 'string' || typeof input === 'number') {+ const date = new Date(input);+ return Number.isNaN(date.getTime()) ? null : date;+ }++ return null;+};++export interface BaseCreateUserMemoryParams {+ details: string;+ detailsEmbedding?: number[];+ memoryCategory: string;+ memoryLayer: LayersEnum;+ memoryType: TypesEnum;+ summary: string;+ summaryEmbedding?: number[];+ title: string;+ titleEmbedding?: number[];+}++export interface CreateUserMemoryContextParams extends BaseCreateUserMemoryParams {+ context: Omit<+ UserMemoryContext,+ 'id' | 'userId' | 'createdAt' | 'updatedAt' | 'accessedAt' | 'userMemoryIds'+ >;+}++export interface CreateUserMemoryExperienceParams extends BaseCreateUserMemoryParams {+ experience: Omit<+ UserMemoryExperience,+ 'id' | 'userId' | 'createdAt' | 'updatedAt' | 'accessedAt' | 'userMemoryId'+ >;+}++export interface CreateUserMemoryIdentityParams extends BaseCreateUserMemoryParams {+ identity: Omit<+ UserMemoryIdentity,+ 'id' | 'userId' | 'createdAt' | 'updatedAt' | 'accessedAt' | 'userMemoryId'+ >;+}++export interface CreateUserMemoryPreferenceParams extends BaseCreateUserMemoryParams {+ preference: Omit<+ UserMemoryPreference,+ 'id' | 'userId' | 'createdAt' | 'updatedAt' | 'accessedAt' | 'userMemoryId'+ >;+}++export type CreateUserMemoryParams =+ | CreateUserMemoryContextParams+ | CreateUserMemoryExperienceParams+ | CreateUserMemoryIdentityParams+ | CreateUserMemoryPreferenceParams;++export interface SearchUserMemoryParams {+ embedding?: number[];+ limit?: number;+ limits?: Partial<Record<'contexts' | 'experiences' | 'preferences', number>>;+ memoryCategory?: string;+ memoryType?: string;+ query?: string;+}++export interface SearchUserMemoryWithEmbeddingParams {+ embedding: number[];+ limits?: Partial<Record<'contexts' | 'experiences' | 'preferences', number>>;+ memoryCategory?: string;+ memoryType?: string;+}++export interface UserMemorySearchAggregatedResult {+ contexts: UserMemoryContextsWithoutVectors[];+ experiences: UserMemoryExperiencesWithoutVectors[];+ preferences: UserMemoryPreferencesWithoutVectors[];+}++export interface UpdateUserMemoryVectorsParams {+ detailsVector1024?: number[] | null;+ summaryVector1024?: number[] | null;+}++export interface UpdateContextVectorsParams {+ descriptionVector?: number[] | null;+ titleVector?: number[] | null;+}++export interface UpdatePreferenceVectorsParams {+ conclusionDirectivesVector?: number[] | null;+}++export interface UpdateIdentityVectorsParams {+ descriptionVector?: number[] | null;+}++export interface UpdateExperienceVectorsParams {+ actionVector?: number[] | null;+ keyLearningVector?: number[] | null;+ situationVector?: number[] | null;+}++export interface IdentityEntryPayload {+ description?: string | null;+ descriptionVector?: number[] | null;+ episodicDate?: string | Date | null;+ metadata?: Record<string, unknown> | null;+ relationship?: RelationshipEnum | string | null;+ role?: string | null;+ tags?: string[] | null;+ type?: IdentityTypeEnum | string | null;+}++export interface IdentityEntryBasePayload {+ details?: string | null;+ detailsVector1024?: number[] | null;+ lastAccessedAt?: string | Date | null;+ memoryCategory?: string | null;+ memoryLayer?: string | null;+ memoryType?: string | null;+ metadata?: Record<string, unknown> | null;+ status?: string | null;+ summary?: string | null;+ summaryVector1024?: number[] | null;+ tags?: string[] | null;+ title?: string | null;+}++export interface AddIdentityEntryParams {+ base: IdentityEntryBasePayload;+ identity: IdentityEntryPayload;+}++export interface AddIdentityEntryResult {+ identityId: string;+ userMemoryId: string;+}++export interface UpdateIdentityEntryParams {+ base?: IdentityEntryBasePayload;+ identity?: IdentityEntryPayload;+ identityId: string;+ mergeStrategy?: MergeStrategyEnum;+}++export class UserMemoryModel {+ private userId: string;+ private db: LobeChatDatabase;++ constructor(db: LobeChatDatabase, userId: string) {+ this.userId = userId;+ this.db = db;+ }++ private buildBaseMemoryInsertValues(+ params: BaseCreateUserMemoryParams,+ options?: {+ metadata?: Record<string, unknown> | null;+ status?: string | null;+ tags?: string[] | null;+ },+ ): typeof userMemories.$inferInsert {+ const now = new Date();++ return {+ accessedCount: 0,+ details: params.details ?? null,+ detailsVector1024: params.detailsEmbedding ?? null,+ lastAccessedAt: now,+ memoryCategory: params.memoryCategory ?? null,+ memoryLayer: params.memoryLayer,+ memoryType: params.memoryType ?? null,+ metadata: options?.metadata ?? null,+ status: options?.status ?? null,+ summary: params.summary ?? null,+ summaryVector1024: params.summaryEmbedding ?? null,+ tags: options?.tags ?? null,+ title: params.title ?? null,+ userId: this.userId,+ } satisfies typeof userMemories.$inferInsert;+ }++ create = async (params: CreateUserMemoryParams): Promise<UserMemoryItem> => {+ const [result] = await this.db+ .insert(userMemories)+ .values(this.buildBaseMemoryInsertValues(params))+ .returning();++ return result;+ };++ createContextMemory = async (+ params: CreateUserMemoryContextParams,+ ): Promise<{ context: UserMemoryContext; memory: UserMemoryItem }> => {+ return this.db.transaction(async (tx) => {+ const baseValues = this.buildBaseMemoryInsertValues(params, {+ metadata: params.context.metadata ?? null,+ tags: params.context.tags ?? null,+ });++ const [memory] = await tx.insert(userMemories).values(baseValues).returning();+ if (!memory) throw new Error('Failed to create user memory context');++ const contextValues = {+ associatedObjects: params.context.associatedObjects ?? [],+ associatedSubjects: params.context.associatedSubjects ?? [],+ currentStatus: params.context.currentStatus ?? null,+ description: params.context.description ?? null,+ descriptionVector: params.context.descriptionVector ?? null,+ metadata: params.context.metadata ?? null,+ scoreImpact: params.context.scoreImpact ?? null,+ scoreUrgency: params.context.scoreUrgency ?? null,+ tags: params.context.tags ?? [],+ title: params.context.title ?? null,+ type: params.context.type ?? null,+ userId: this.userId,+ userMemoryIds: [memory.id],+ } satisfies typeof userMemoriesContexts.$inferInsert;++ const [context] = await tx.insert(userMemoriesContexts).values(contextValues).returning();++ return { context, memory };+ });+ };++ createExperienceMemory = async (+ params: CreateUserMemoryExperienceParams,+ ): Promise<{ experience: UserMemoryExperience; memory: UserMemoryItem }> => {+ return this.db.transaction(async (tx) => {+ const baseValues = this.buildBaseMemoryInsertValues(params, {+ metadata: params.experience.metadata ?? null,+ tags: params.experience.tags ?? null,+ });++ const [memory] = await tx.insert(userMemories).values(baseValues).returning();+ if (!memory) throw new Error('Failed to create user memory experience');++ const experienceValues = {+ action: params.experience.action ?? null,+ actionVector: params.experience.actionVector ?? null,+ keyLearning: params.experience.keyLearning ?? null,+ keyLearningVector: params.experience.keyLearningVector ?? null,+ metadata: params.experience.metadata ?? null,+ possibleOutcome: params.experience.possibleOutcome ?? null,+ reasoning: params.experience.reasoning ?? null,+ scoreConfidence: params.experience.scoreConfidence ?? null,+ situation: params.experience.situation ?? null,+ situationVector: params.experience.situationVector ?? null,+ tags: params.experience.tags ?? [],+ type: params.experience.type ?? params.memoryType ?? null,+ userId: this.userId,+ userMemoryId: memory.id,+ } satisfies typeof userMemoriesExperiences.$inferInsert;++ const [experience] = await tx+ .insert(userMemoriesExperiences)+ .values(experienceValues)+ .returning();++ return { experience, memory };+ });+ };++ createPreferenceMemory = async (+ params: CreateUserMemoryPreferenceParams,+ ): Promise<{ memory: UserMemoryItem; preference: UserMemoryPreference }> => {+ return this.db.transaction(async (tx) => {+ const baseValues = this.buildBaseMemoryInsertValues(params, {+ metadata: params.preference.metadata ?? null,+ tags: params.preference.tags ?? null,+ });++ const [memory] = await tx.insert(userMemories).values(baseValues).returning();+ if (!memory) throw new Error('Failed to create user memory preference');++ const preferenceValues = {+ conclusionDirectives: params.preference.conclusionDirectives ?? null,+ conclusionDirectivesVector: params.preference.conclusionDirectivesVector ?? null,+ metadata: params.preference.metadata ?? null,+ scorePriority: params.preference.scorePriority ?? null,+ suggestions: params.preference.suggestions ?? null,+ tags: params.preference.tags ?? [],+ type: params.preference.type ?? params.memoryType ?? null,+ userId: this.userId,+ userMemoryId: memory.id,+ } satisfies typeof userMemoriesPreferences.$inferInsert;++ const [preference] = await tx+ .insert(userMemoriesPreferences)+ .values(preferenceValues)+ .returning();++ return { memory, preference };+ });+ };++ search = async (params: SearchUserMemoryParams): Promise<UserMemorySearchAggregatedResult> => {+ const { embedding, limits } = params;++ const resolvedLimits = {+ contexts: limits?.contexts,+ experiences: limits?.experiences,+ preferences: limits?.preferences,+ };++ const [experiences, contexts, preferences] = await Promise.all([+ this.searchExperiences({+ embedding,+ limit: resolvedLimits.experiences,+ }),+ this.searchContexts({+ embedding,+ limit: resolvedLimits.contexts,+ }),+ this.searchPreferences({+ embedding,+ limit: resolvedLimits.preferences,+ }),+ ]);++ const accessedMemoryIds = new Set<string>();+ experiences.forEach((experience) => {+ if (experience.userMemoryId) accessedMemoryIds.add(experience.userMemoryId);+ });+ preferences.forEach((preference) => {+ if (preference.userMemoryId) accessedMemoryIds.add(preference.userMemoryId);+ });+ const contextLinkIds: string[] = [];+ contexts.forEach((context) => {+ const ids = Array.isArray(context.userMemoryIds) ? (context.userMemoryIds as string[]) : [];+ ids.forEach((id) => accessedMemoryIds.add(id));+ contextLinkIds.push(context.id);+ });++ if (accessedMemoryIds.size > 0 || contextLinkIds.length > 0) {+ await this.updateAccessMetrics([...accessedMemoryIds], {+ contextIds: contextLinkIds,+ timestamp: new Date(),+ });+ }++ return {+ contexts,+ experiences,+ preferences,+ };+ };++ searchWithEmbedding = async (+ params: SearchUserMemoryWithEmbeddingParams,+ ): Promise<UserMemorySearchAggregatedResult> => {+ return this.search(params);+ };++ findById = async (id: string): Promise<UserMemoryItem | undefined> => {+ const result = await this.db.query.userMemories.findFirst({+ where: and(eq(userMemories.id, id), eq(userMemories.userId, this.userId)),+ });++ if (result) {+ await this.updateAccessMetrics([id]);+ }++ return result;+ };++ update = async (id: string, params: Partial<CreateUserMemoryParams>): Promise<void> => {+ await this.db+ .update(userMemories)+ .set({ ...params, updatedAt: new Date() })+ .where(and(eq(userMemories.id, id), eq(userMemories.userId, this.userId)));+ };++ updateUserMemoryVectors = async (+ id: string,+ vectors: UpdateUserMemoryVectorsParams,+ ): Promise<void> => {+ const vectorUpdates: Partial<typeof userMemories.$inferInsert> = {};+ if (vectors.detailsVector1024 !== undefined) {+ vectorUpdates.detailsVector1024 = vectors.detailsVector1024;+ }+ if (vectors.summaryVector1024 !== undefined) {+ vectorUpdates.summaryVector1024 = vectors.summaryVector1024;+ }++ if (Object.keys(vectorUpdates).length === 0) {+ return;+ }++ await this.db+ .update(userMemories)+ .set({+ ...vectorUpdates,+ updatedAt: new Date(),+ })+ .where(and(eq(userMemories.id, id), eq(userMemories.userId, this.userId)));+ };++ updateContextVectors = async (id: string, vectors: UpdateContextVectorsParams): Promise<void> => {+ const vectorUpdates: Partial<typeof userMemoriesContexts.$inferInsert> = {};+ if (vectors.descriptionVector !== undefined) {+ vectorUpdates.descriptionVector = vectors.descriptionVector;+ }+ if (Object.keys(vectorUpdates).length === 0) {+ return;+ }++ await this.db+ .update(userMemoriesContexts)+ .set({+ ...vectorUpdates,+ updatedAt: new Date(),+ })+ .where(and(eq(userMemoriesContexts.id, id), eq(userMemoriesContexts.userId, this.userId)));+ };++ updatePreferenceVectors = async (+ id: string,+ vectors: UpdatePreferenceVectorsParams,+ ): Promise<void> => {+ const vectorUpdates: Partial<typeof userMemoriesPreferences.$inferInsert> = {};+ if (vectors.conclusionDirectivesVector !== undefined) {+ vectorUpdates.conclusionDirectivesVector = vectors.conclusionDirectivesVector;+ }++ if (Object.keys(vectorUpdates).length === 0) {+ return;+ }++ await this.db+ .update(userMemoriesPreferences)+ .set({+ ...vectorUpdates,+ updatedAt: new Date(),+ })+ .where(+ and(eq(userMemoriesPreferences.id, id), eq(userMemoriesPreferences.userId, this.userId)),+ );+ };++ updateIdentityVectors = async (+ id: string,+ vectors: UpdateIdentityVectorsParams,+ ): Promise<void> => {+ const vectorUpdates: Partial<typeof userMemoriesIdentities.$inferInsert> = {};+ if (vectors.descriptionVector !== undefined) {+ vectorUpdates.descriptionVector = vectors.descriptionVector;+ }++ if (Object.keys(vectorUpdates).length === 0) {+ return;+ }++ await this.db+ .update(userMemoriesIdentities)+ .set({+ ...vectorUpdates,+ updatedAt: new Date(),+ })+ .where(+ and(eq(userMemoriesIdentities.id, id), eq(userMemoriesIdentities.userId, this.userId)),+ );+ };++ updateExperienceVectors = async (+ id: string,+ vectors: UpdateExperienceVectorsParams,+ ): Promise<void> => {+ const vectorUpdates: Partial<typeof userMemoriesExperiences.$inferInsert> = {};+ if (vectors.actionVector !== undefined) {+ vectorUpdates.actionVector = vectors.actionVector;+ }+ if (vectors.keyLearningVector !== undefined) {+ vectorUpdates.keyLearningVector = vectors.keyLearningVector;+ }+ if (vectors.situationVector !== undefined) {+ vectorUpdates.situationVector = vectors.situationVector;+ }++ if (Object.keys(vectorUpdates).length === 0) {+ return;+ }++ await this.db+ .update(userMemoriesExperiences)+ .set({+ ...vectorUpdates,+ updatedAt: new Date(),+ })+ .where(+ and(eq(userMemoriesExperiences.id, id), eq(userMemoriesExperiences.userId, this.userId)),+ );+ };++ addIdentityEntry = async (params: AddIdentityEntryParams): Promise<AddIdentityEntryResult> => {+ const now = new Date();++ return this.db.transaction(async (tx) => {+ const base = params.base ?? {};+ const baseValues: typeof userMemories.$inferInsert = {+ accessedCount: 0,+ details: base.details ?? null,+ detailsVector1024: base.detailsVector1024 ?? null,+ lastAccessedAt: coerceDate(base.lastAccessedAt) ?? now,+ memoryCategory: base.memoryCategory ?? null,+ memoryLayer: base.memoryLayer ?? 'identity',+ memoryType: base.memoryType ?? null,+ metadata: base.metadata ?? null,+ status: base.status === undefined ? 'active' : base.status,+ summary: base.summary ?? null,+ summaryVector1024: base.summaryVector1024 ?? null,+ tags: base.tags ?? null,+ title: base.title ?? null,+ userId: this.userId,+ };++ const [userMemoryRecord] = await tx+ .insert(userMemories)+ .values(baseValues)+ .returning({ id: userMemories.id });++ const identity = params.identity ?? {};+ const identityValues: typeof userMemoriesIdentities.$inferInsert = {+ description: identity.description ?? null,+ descriptionVector: identity.descriptionVector ?? null,+ episodicDate:+ identity.episodicDate === undefined ? null : coerceDate(identity.episodicDate),+ metadata: identity.metadata ?? null,+ relationship:+ identity.relationship === undefined+ ? null+ : identity.relationship === null+ ? null+ : (normalizeRelationshipValue(identity.relationship) ?? null),+ role: identity.role ?? null,+ tags: identity.tags ?? null,+ type:+ identity.type === undefined+ ? null+ : identity.type === null+ ? null+ : (normalizeIdentityTypeValue(identity.type) ?? null),+ userId: this.userId,+ userMemoryId: userMemoryRecord.id,+ };++ const [identityRecord] = await tx+ .insert(userMemoriesIdentities)+ .values(identityValues)+ .returning({ id: userMemoriesIdentities.id });++ return {+ identityId: identityRecord.id,+ userMemoryId: userMemoryRecord.id,+ };+ });+ };++ updateIdentityEntry = async (params: UpdateIdentityEntryParams): Promise<boolean> => {+ const mergeStrategy = params.mergeStrategy ?? 'merge';++ return this.db.transaction(async (tx) => {+ const identity = await tx.query.userMemoriesIdentities.findFirst({+ where: and(+ eq(userMemoriesIdentities.id, params.identityId),+ eq(userMemoriesIdentities.userId, this.userId),+ ),+ });+ if (!identity || !identity.userMemoryId) {+ return false;+ }++ let baseUpdate: Partial<typeof userMemories.$inferInsert> = {};+ let identityUpdate: Partial<typeof userMemoriesIdentities.$inferInsert> = {};++ if (params.base) {+ baseUpdate = merge(baseUpdate, params.base);+ if (baseUpdate.lastAccessedAt !== undefined) {+ baseUpdate.lastAccessedAt = coerceDate(baseUpdate.lastAccessedAt) ?? new Date();+ }++ if (Object.keys(baseUpdate).length > 0) {+ baseUpdate.updatedAt = new Date();+ await tx+ .update(userMemories)+ .set(baseUpdate)+ .where(+ and(eq(userMemories.id, identity.userMemoryId), eq(userMemories.userId, this.userId)),+ );+ }+ }++ if (params.identity) {+ if (mergeStrategy === 'replace') {+ const identity = params.identity;++ identityUpdate = {+ description: identity.description ?? null,+ descriptionVector: identity.descriptionVector ?? null,+ episodicDate:+ identity.episodicDate === undefined ? null : coerceDate(identity.episodicDate),+ metadata: identity.metadata ?? null,+ relationship:+ identity.relationship === undefined+ ? null+ : identity.relationship === null+ ? null+ : (normalizeRelationshipValue(identity.relationship) ?? null),+ role: identity.role ?? null,+ tags: identity.tags ?? null,+ type:+ identity.type === undefined+ ? null+ : identity.type === null+ ? null+ : (normalizeIdentityTypeValue(identity.type) ?? null),+ };+ } else {+ identityUpdate = merge(identityUpdate, params.identity);++ if (params.identity.type !== undefined) {+ identityUpdate.type =+ params.identity.type === null+ ? null+ : (normalizeIdentityTypeValue(params.identity.type) ?? null);+ }++ if (params.identity.relationship !== undefined) {+ identityUpdate.relationship =+ params.identity.relationship === null+ ? null+ : (normalizeRelationshipValue(params.identity.relationship) ?? null);+ }++ if (params.identity.episodicDate !== undefined) {+ identityUpdate.episodicDate = coerceDate(params.identity.episodicDate);+ }+ }++ if (Object.keys(identityUpdate).length > 0) {+ identityUpdate.updatedAt = new Date();+ await tx+ .update(userMemoriesIdentities)+ .set(identityUpdate)+ .where(+ and(+ eq(userMemoriesIdentities.id, params.identityId),+ eq(userMemoriesIdentities.userId, this.userId),+ ),+ );+ }+ }++ return true;+ });+ };++ removeIdentityEntry = async (identityId: string): Promise<boolean> => {+ return this.db.transaction(async (tx) => {+ const identity = await tx.query.userMemoriesIdentities.findFirst({+ where: and(+ eq(userMemoriesIdentities.id, identityId),+ eq(userMemoriesIdentities.userId, this.userId),+ ),+ });++ if (!identity || !identity.userMemoryId) {+ return false;+ }++ await tx+ .delete(userMemories)+ .where(+ and(eq(userMemories.id, identity.userMemoryId), eq(userMemories.userId, this.userId)),+ );++ return true;+ });+ };++ delete = async (id: string): Promise<void> => {+ await this.db+ .delete(userMemories)+ .where(and(eq(userMemories.id, id), eq(userMemories.userId, this.userId)));+ };++ deleteAll = async (): Promise<void> => {+ await this.db.delete(userMemories).where(eq(userMemories.userId, this.userId));+ };++ searchContexts = async (params: {+ embedding?: number[];+ limit?: number;+ type?: string;+ }): Promise<UserMemoryContextsWithoutVectors[]> => {+ const { embedding, limit = 5, type } = params;+ if (limit <= 0) {+ return [];+ }++ let query = this.db+ .select({+ accessedAt: userMemoriesContexts.accessedAt,+ associatedObjects: userMemoriesContexts.associatedObjects,+ associatedSubjects: userMemoriesContexts.associatedSubjects,+ createdAt: userMemoriesContexts.createdAt,+ currentStatus: userMemoriesContexts.currentStatus,+ description: userMemoriesContexts.description,+ id: userMemoriesContexts.id,+ metadata: userMemoriesContexts.metadata,+ scoreImpact: userMemoriesContexts.scoreImpact,+ scoreUrgency: userMemoriesContexts.scoreUrgency,+ tags: userMemoriesContexts.tags,+ title: userMemoriesContexts.title,+ type: userMemoriesContexts.type,+ updatedAt: userMemoriesContexts.updatedAt,+ userId: userMemoriesContexts.userId,+ userMemoryIds: userMemoriesContexts.userMemoryIds,+ ...(embedding && {+ similarity: sql<number>`1 - (${cosineDistance(userMemoriesContexts.descriptionVector, embedding)}) AS similarity`,+ }),+ })+ .from(userMemoriesContexts)+ .$dynamic();++ const conditions = [eq(userMemoriesContexts.userId, this.userId)];+ if (type) {+ conditions.push(eq(userMemoriesContexts.type, type));+ }++ query = query.where(and(...conditions));++ if (embedding) {+ query = query.orderBy(desc(sql`similarity`));+ } else {+ query = query.orderBy(desc(userMemoriesContexts.createdAt));+ }++ return query.limit(limit);+ };++ searchExperiences = async (params: {+ embedding?: number[];+ limit?: number;+ type?: string;+ }): Promise<UserMemoryExperiencesWithoutVectors[]> => {+ const { embedding, limit = 5, type } = params;+ if (limit <= 0) {+ return [];+ }++ let query = this.db+ .select({+ accessedAt: userMemoriesExperiences.accessedAt,+ action: userMemoriesExperiences.action,+ createdAt: userMemoriesExperiences.createdAt,+ id: userMemoriesExperiences.id,+ keyLearning: userMemoriesExperiences.keyLearning,+ metadata: userMemoriesExperiences.metadata,+ possibleOutcome: userMemoriesExperiences.possibleOutcome,+ reasoning: userMemoriesExperiences.reasoning,+ scoreConfidence: userMemoriesExperiences.scoreConfidence,+ situation: userMemoriesExperiences.situation,+ tags: userMemoriesExperiences.tags,+ type: userMemoriesExperiences.type,+ updatedAt: userMemoriesExperiences.updatedAt,+ userId: userMemoriesExperiences.userId,+ userMemoryId: userMemoriesExperiences.userMemoryId,+ ...(embedding && {+ similarity: sql<number>`1 - (${cosineDistance(userMemoriesExperiences.situationVector, embedding)}) AS similarity`,+ }),+ })+ .from(userMemoriesExperiences)+ .$dynamic();++ const conditions = [eq(userMemoriesExperiences.userId, this.userId)];+ if (type) {+ conditions.push(eq(userMemoriesExperiences.type, type));+ }++ query = query.where(and(...conditions));++ if (embedding) {+ query = query.orderBy(desc(sql`similarity`));+ } else {+ query = query.orderBy(desc(userMemoriesExperiences.createdAt));+ }++ return query.limit(limit);+ };++ searchPreferences = async (params: {+ embedding?: number[];+ limit?: number;+ type?: string;+ }): Promise<UserMemoryPreferencesWithoutVectors[]> => {+ const { embedding, limit = 5, type } = params;+ if (limit <= 0) {+ return [];+ }++ let query = this.db+ .select({+ accessedAt: userMemoriesPreferences.accessedAt,+ conclusionDirectives: userMemoriesPreferences.conclusionDirectives,+ createdAt: userMemoriesPreferences.createdAt,+ id: userMemoriesPreferences.id,+ metadata: userMemoriesPreferences.metadata,+ scorePriority: userMemoriesPreferences.scorePriority,+ suggestions: userMemoriesPreferences.suggestions,+ tags: userMemoriesPreferences.tags,+ type: userMemoriesPreferences.type,+ updatedAt: userMemoriesPreferences.updatedAt,+ userId: userMemoriesPreferences.userId,+ userMemoryId: userMemoriesPreferences.userMemoryId,+ ...(embedding && {+ similarity: sql<number>`1 - (${cosineDistance(userMemoriesPreferences.conclusionDirectivesVector, embedding)}) AS similarity`,+ }),+ })+ .from(userMemoriesPreferences)+ .$dynamic();++ const conditions = [eq(userMemoriesPreferences.userId, this.userId)];+ if (type) {+ conditions.push(eq(userMemoriesPreferences.type, type));+ }++ query = query.where(and(...conditions));++ if (embedding) {+ query = query.orderBy(desc(sql`similarity`));+ } else {+ query = query.orderBy(desc(userMemoriesPreferences.createdAt));+ }++ return query.limit(limit);+ };++ getAllIdentities = async (): Promise<UserMemoryIdentitiesWithoutVectors[]> => {+ return this.db.query.userMemoriesIdentities.findMany({+ orderBy: [desc(userMemoriesIdentities.createdAt)],+ where: eq(userMemoriesIdentities.userId, this.userId),+ });+ };++ getIdentitiesByType = async (type: string): Promise<UserMemoryIdentitiesWithoutVectors[]> => {+ return this.db.query.userMemoriesIdentities.findMany({+ orderBy: [desc(userMemoriesIdentities.createdAt)],+ where: and(+ eq(userMemoriesIdentities.userId, this.userId),+ eq(userMemoriesIdentities.type, type),+ ),+ });+ };++ private updateAccessMetrics = async (+ memoryIds: string[],+ options?: { contextIds?: string[]; timestamp?: Date },+ ): Promise<void> => {+ const contextIds = options?.contextIds ?? [];+ if (memoryIds.length === 0 && contextIds.length === 0) return;++ const now = options?.timestamp ?? new Date();++ await this.db.transaction(async (tx) => {+ if (memoryIds.length > 0) {+ await tx+ .update(userMemories)+ .set({+ accessedAt: now,+ accessedCount: sql`${userMemories.accessedCount} + 1`,+ lastAccessedAt: now,+ })+ .where(and(eq(userMemories.userId, this.userId), inArray(userMemories.id, memoryIds)));++ const memories = await tx+ .select({+ id: userMemories.id,+ layer: userMemories.memoryLayer,+ })+ .from(userMemories)+ .where(and(eq(userMemories.userId, this.userId), inArray(userMemories.id, memoryIds)));++ const experienceIds = memories+ .filter((memory) => memory.layer === 'experience')+ .map((memory) => memory.id);+ if (experienceIds.length > 0) {+ await tx+ .update(userMemoriesExperiences)+ .set({ accessedAt: now })+ .where(+ and(+ eq(userMemoriesExperiences.userId, this.userId),+ inArray(userMemoriesExperiences.userMemoryId, experienceIds),+ ),+ );+ }++ const identityIds = memories+ .filter((memory) => memory.layer === 'identity')+ .map((memory) => memory.id);+ if (identityIds.length > 0) {+ await tx+ .update(userMemoriesIdentities)+ .set({ accessedAt: now })+ .where(+ and(+ eq(userMemoriesIdentities.userId, this.userId),+ inArray(userMemoriesIdentities.userMemoryId, identityIds),+ ),+ );+ }++ const preferenceIds = memories+ .filter((memory) => memory.layer === 'preference')+ .map((memory) => memory.id);+ if (preferenceIds.length > 0) {+ await tx+ .update(userMemoriesPreferences)+ .set({ accessedAt: now })+ .where(+ and(+ eq(userMemoriesPreferences.userId, this.userId),+ inArray(userMemoriesPreferences.userMemoryId, preferenceIds),+ ),+ );+ }+ }++ if (contextIds.length > 0) {+ await tx+ .update(userMemoriesContexts)+ .set({ accessedAt: now })+ .where(+ and(+ eq(userMemoriesContexts.userId, this.userId),+ inArray(userMemoriesContexts.id, contextIds),+ ),+ );+ }+ });+ };+}diff --git a/packages/database/src/schemas/userMemories.ts b/packages/database/src/schemas/userMemories.tsindex b14450ef0da..a957373fc54 100644--- a/packages/database/src/schemas/userMemories.ts+++ b/packages/database/src/schemas/userMemories.ts@@ -17,7 +17,7 @@ export const userMemories = pgTable(memoryCategory: varchar255('memory_category'),memoryLayer: varchar255('memory_layer'),memoryType: varchar255('memory_type'),- metadata: jsonb('metadata'),+ metadata: jsonb('metadata').$type<Record<string, unknown>>(),tags: text('tags').array(),title: varchar255('title'),@@ -55,7 +55,7 @@ export const userMemoriesContexts = pgTable(userId: text('user_id').references(() => users.id, { onDelete: 'cascade' }),userMemoryIds: jsonb('user_memory_ids'),- metadata: jsonb('metadata'),+ metadata: jsonb('metadata').$type<Record<string, unknown>>(),tags: text('tags').array(),associatedObjects: jsonb('associated_objects'),@@ -99,7 +99,7 @@ export const userMemoriesPreferences = pgTable(onDelete: 'cascade',}),- metadata: jsonb('metadata'),+ metadata: jsonb('metadata').$type<Record<string, unknown>>(),tags: text('tags').array(),conclusionDirectives: text('conclusion_directives'),@@ -132,7 +132,7 @@ export const userMemoriesIdentities = pgTable(onDelete: 'cascade',}),- metadata: jsonb('metadata'),+ metadata: jsonb('metadata').$type<Record<string, unknown>>(),tags: text('tags').array(),type: varchar255('type'),@@ -165,7 +165,7 @@ export const userMemoriesExperiences = pgTable(onDelete: 'cascade',}),- metadata: jsonb('metadata'),+ metadata: jsonb('metadata').$type<Record<string, unknown>>(),tags: text('tags').array(),type: varchar255('type'),@@ -200,16 +200,33 @@ export const userMemoriesExperiences = pgTable();export type UserMemoryItem = typeof userMemories.$inferSelect;+export type UserMemoryItemWithoutVectors = Omit<+ UserMemoryItem,+ 'summaryVector1024' | 'detailsVector1024'+>;export type NewUserMemory = typeof userMemories.$inferInsert;export type UserMemoryPreference = typeof userMemoriesPreferences.$inferSelect;+export type UserMemoryPreferencesWithoutVectors = Omit<+ UserMemoryPreference,+ 'conclusionDirectivesVector'+>;export type NewUserMemoryPreference = typeof userMemoriesPreferences.$inferInsert;export type UserMemoryContext = typeof userMemoriesContexts.$inferSelect;+export type UserMemoryContextsWithoutVectors = Omit<+ UserMemoryContext,+ 'titleVector' | 'descriptionVector'+>;export type NewUserMemoryContext = typeof userMemoriesContexts.$inferInsert;export type UserMemoryIdentity = typeof userMemoriesIdentities.$inferSelect;+export type UserMemoryIdentitiesWithoutVectors = Omit<UserMemoryIdentity, 'descriptionVector'>;export type NewUserMemoryIdentity = typeof userMemoriesIdentities.$inferInsert;export type UserMemoryExperience = typeof userMemoriesExperiences.$inferSelect;+export type UserMemoryExperiencesWithoutVectors = Omit<+ UserMemoryExperience,+ 'situationVector' | 'actionVector' | 'keyLearningVector'+>;export type NewUserMemoryExperience = typeof userMemoriesExperiences.$inferInsert;diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex cb706a3f78f..0c7a2e3f02d 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -36,4 +36,5 @@ export * from './openai/chat';export * from './openai/plugin';export * from './subscription';export * from './trace';+export * from './userMemory';export * from './zustand';diff --git a/packages/types/src/userMemory/index.ts b/packages/types/src/userMemory/index.tsnew file mode 100644index 00000000000..f4835c2b72b--- /dev/null+++ b/packages/types/src/userMemory/index.ts@@ -0,0 +1,3 @@+export * from './layers';+export * from './shared';+export * from './tools';diff --git a/packages/types/src/userMemory/layers.ts b/packages/types/src/userMemory/layers.tsnew file mode 100644index 00000000000..6bae759e263--- /dev/null+++ b/packages/types/src/userMemory/layers.ts@@ -0,0 +1,54 @@+export interface UserMemoryTimestamps {+ accessedAt: Date;+ createdAt: Date;+ updatedAt: Date;+}++export interface UserMemoryContext extends UserMemoryTimestamps {+ associatedObjects: Record<string, unknown>[] | null;+ associatedSubjects: Record<string, unknown>[] | null;+ currentStatus: string | null;+ description: string | null;+ descriptionVector: number[] | null;+ id: string;+ metadata: Record<string, unknown> | null;+ scoreImpact: number | null;+ scoreUrgency: number | null;+ tags: string[] | null;+ title: string | null;+ titleVector: number[] | null;+ type: string | null;+ userId: string | null;+ userMemoryIds: string[] | null;+}++export interface UserMemoryExperience extends UserMemoryTimestamps {+ action: string | null;+ actionVector: number[] | null;+ id: string;+ keyLearning: string | null;+ keyLearningVector: number[] | null;+ metadata: Record<string, unknown> | null;+ possibleOutcome: string | null;+ reasoning: string | null;+ scoreConfidence: number | null;+ situation: string | null;+ situationVector: number[] | null;+ tags: string[] | null;+ type: string | null;+ userId: string | null;+ userMemoryId: string | null;+}++export interface UserMemoryPreference extends UserMemoryTimestamps {+ conclusionDirectives: string | null;+ conclusionDirectivesVector: number[] | null;+ id: string;+ metadata: Record<string, unknown> | null;+ scorePriority: number | null;+ suggestions: string | null;+ tags: string[] | null;+ type: string | null;+ userId: string | null;+ userMemoryId: string | null;+}diff --git a/packages/types/src/userMemory/shared.ts b/packages/types/src/userMemory/shared.tsnew file mode 100644index 00000000000..cf3d5b18cb1--- /dev/null+++ b/packages/types/src/userMemory/shared.ts@@ -0,0 +1,64 @@+export enum RelationshipEnum {+ Aunt = 'aunt',+ Brother = 'brother',+ Classmate = 'classmate',+ Colleague = 'colleague',+ Couple = 'couple',+ Coworker = 'coworker',+ Daughter = 'daughter',+ Father = 'father',+ Friend = 'friend',+ Granddaughter = 'granddaughter',+ Grandfather = 'grandfather',+ Grandmother = 'grandmother',+ Grandson = 'grandson',+ Husband = 'husband',+ Manager = 'manager',+ Mentee = 'mentee',+ Mentor = 'mentor',+ Mother = 'mother',+ Nephew = 'nephew',+ Niece = 'niece',+ Other = 'other',+ Partner = 'partner',+ Self = 'self',+ Sibling = 'sibling',+ Sister = 'sister',+ Son = 'son',+ Spouse = 'spouse',+ Teammate = 'teammate',+ Uncle = 'uncle',+ Wife = 'wife',+}++export enum MergeStrategyEnum {+ Merge = 'merge',+ Replace = 'replace',+}++export enum IdentityTypeEnum {+ Demographic = 'demographic',+ Personal = 'personal',+ Professional = 'professional',+}++export enum LayersEnum {+ Activity = 'activity',+ Context = 'context',+ Experience = 'experience',+ Identity = 'identity',+ Preference = 'preference',+}++export enum TypesEnum {+ Activity = 'activity',+ Context = 'context',+ Event = 'event',+ Fact = 'fact',+ Location = 'location',+ Other = 'other',+ People = 'people',+ Preference = 'preference',+ Technology = 'technology',+ Topic = 'topic',+}diff --git a/packages/types/src/userMemory/tools.ts b/packages/types/src/userMemory/tools.tsnew file mode 100644index 00000000000..7814aad5f7b--- /dev/null+++ b/packages/types/src/userMemory/tools.ts@@ -0,0 +1,240 @@+import { z } from 'zod';++import { UserMemoryContext, UserMemoryExperience, UserMemoryPreference } from './layers';+import {+ IdentityTypeEnum,+ LayersEnum,+ MergeStrategyEnum,+ RelationshipEnum,+ TypesEnum,+} from './shared';++export const addMemoryBaseSchema = z.object({+ details: z.string().describe('Optional detailed information'),+ memoryCategory: z+ .string()+ .describe(+ 'Category of memory, describes the domain or context the memory belongs to, e.g. talking travel plan counts as `travel` category, all work related memories could be `work` category, except side projects, where we belongs to `project` category',+ ),+ // TODO: migrate to .enum() if we could move to+ // zod v4+ // Read more: https://zod.dev/api#enum+ memoryLayer: z+ .nativeEnum(LayersEnum)+ .describe(+ 'Memory layer, must be one of `context`, `identity`, `preference`, `experience`, `activity`',+ ),+ memoryType: z+ .nativeEnum(TypesEnum)+ .describe(+ 'Type of memory, used to describe the specific nature or classification of the memory related to',+ ),+ summary: z.string().describe('Concise overview of this specific memory'),+ title: z.string().describe('Brief descriptive title'),+});++export type AddMemoryBaseParams = z.infer<typeof addMemoryBaseSchema>;++export const addExperienceMemorySchema = addMemoryBaseSchema.extend({+ withExperience: z.object({+ action: z+ .string()+ .nullable()+ .describe('Narrative describing actions taken or behaviors exhibited'),+ keyLearning: z+ .string()+ .nullable()+ .describe('Narrative describing key insights or lessons learned'),+ possibleOutcome: z+ .string()+ .nullable()+ .describe('Narrative describing potential outcomes or learnings'),+ reasoning: z+ .string()+ .nullable()+ .describe('Narrative describing the thought process or motivations'),+ scoreConfidence: z+ .number()+ .nullable()+ .describe(+ 'Numeric score (0-1 or domain-specific) describing confidence in the experience details',+ ),+ situation: z.string().nullable().describe('Narrative describing the situation or event'),+ tags: z.array(z.string()).describe('Model generated tags that summarize the experience facets'),+ }),+});++export type AddExperienceMemoryParams = z.infer<typeof addExperienceMemorySchema>;++export const addContextMemorySchema = addMemoryBaseSchema.extend({+ withContext: z.object({+ associatedObjects: z+ .array(z.object({}))+ .describe('describing involved roles, entities, or resources'),+ associatedSubjects: z+ .array(z.object({}))+ .describe('describing involved roles, entities, or resources'),+ currentStatus: z+ .string()+ .nullable()+ .describe("High level status markers (e.g., 'active', 'pending')"),+ description: z+ .string()+ .describe('Rich narrative describing the situation, timeline, or environment'),+ scoreImpact: z+ .number()+ .nullable()+ .describe('Numeric score (0-1 or domain-specific) describing importance'),+ scoreUrgency: z+ .number()+ .nullable()+ .describe('Numeric score (0-1 or domain-specific) describing urgency'),+ tags: z.array(z.string()).describe('Model generated tags that summarize the context themes'),+ title: z.string().nullable().describe('Optional synthesized context headline'),+ type: z+ .string()+ .nullable()+ .describe(+ "High level context archetype (e.g., 'temporarily', 'private', 'questioning', 'formal', 'assistant', 'mentorship')",+ ),+ }),+});++export type AddContextMemoryParams = z.infer<typeof addContextMemorySchema>;++export const addPreferenceMemorySchema = addMemoryBaseSchema.extend({+ withPreference: z.object({+ appContext: z+ .object({+ app: z.string().nullable().describe('App or product name this applies to'),+ feature: z.string().nullable(),+ route: z.string().nullable(),+ surface: z.string().nullable().describe('e.g., chat, emails, code review, notes'),+ })+ .strict()+ .describe('Application/surface specific preference, if any'),+ conclusionDirectives: z+ .string()+ .describe(+ "Direct, self-contained instruction to the assistant from the user's perspective (what to do, not how to implement)",+ ),+ extractedScopes: z+ .array(z.string())+ .describe('describing preference facets and applicable scopes'),+ originContext: z+ .object({+ actor: z.string().nullable().describe("Who stated the preference; use 'User' for the user"),+ applicableWhen: z.string().nullable().describe('Conditions where this preference applies'),+ notApplicableWhen: z.string().nullable().describe('Conditions where it does not apply'),+ scenario: z.string().nullable().describe('Applicable scenario or use case'),+ trigger: z.string().nullable().describe('What prompted this preference'),+ })+ .strict()+ .describe('Context of how/why this preference was expressed'),+ scorePriority: z+ .number()+ .nullable()+ .describe('Numeric prioritization weight where higher means more critical to respect'),+ suggestions: z+ .array(z.string())+ .describe('Follow-up actions or assistant guidance derived from the preference'),+ tags: z.array(z.string()).describe('Model generated tags that summarize the preference facets'),+ type: z+ .string()+ .nullable()+ .describe("High level preference classification (e.g., 'lifestyle', 'communication')"),+ }),+});++export type AddPreferenceMemoryParams = z.infer<typeof addPreferenceMemorySchema>;++export const addIdentityMemorySchema = addMemoryBaseSchema.extend({+ withIdentity: z.object({+ description: z+ .string()+ .describe(+ "Rich narrative describing the person's background, roles, and attributes (required)",+ ),+ episodicDate: z+ .string()+ .nullable()+ .describe(+ 'Optional ISO 8601 timestamp describing when this identity aspect is most relevant',+ ),+ relationship: z+ .nativeEnum(RelationshipEnum)+ .describe(+ "Relationship of this identity to the user. Use 'self' when the identity is the user themselves",+ ),+ role: z+ .string()+ .nullable()+ .describe("Short role label (e.g., 'software engineer', 'student', 'manager', 'mentor')"),+ scoreConfidence: z+ .number()+ .nullable()+ .describe('Model confidence (0-1) that this identity aspect is correct'),+ sourceEvidence: z+ .string()+ .nullable()+ .describe('Optional short quote or pointer to evidence in the current conversation'),+ tags: z.array(z.string()).describe('Model generated tags that summarize the identity facets'),+ type: z.nativeEnum(IdentityTypeEnum).describe('High level identity archetype'),+ }),+});++export type AddIdentityMemoryParams = z.infer<typeof addIdentityMemorySchema>;++export const updateIdentityMemorySchema = z.object({+ id: z.string().describe('The ID of the identity entry to update'),+ mergeStrategy: z+ .nativeEnum(MergeStrategyEnum)+ .describe('replace: overwrite all fields; merge: update only provided fields'),+ set: z+ .object({+ description: z.string().optional(),+ episodicDate: z.string().nullable().optional(),+ relationship: z.nativeEnum(RelationshipEnum).optional(),+ role: z.string().nullable().optional(),+ scoreConfidence: z.number().nullable().optional(),+ sourceEvidence: z.string().nullable().optional(),+ tags: z.array(z.string()).optional(),+ type: z.string().nullable().optional(),+ })+ .strict()+ .describe('Fields to update'),+});++export type UpdateIdentityMemoryParams = z.infer<typeof updateIdentityMemorySchema>;++export const removeIdentityMemorySchema = z.object({+ id: z.string().describe('The ID of the identity entry to remove'),+ reason: z.string().describe('Brief reasoning: incorrect, obsolete, or duplicate'),+});++export type RemoveIdentityMemoryParams = z.infer<typeof removeIdentityMemorySchema>;++export const searchMemorySchema = z.object({+ // TODO: we need to dynamically fetch the available categories/types from the backend+ // memoryCategory: z.string().optional(),+ // memoryType: z.string().optional(),+ query: z.string(),+ topK: z.object({+ contexts: z.coerce.number().int().min(0),+ experiences: z.coerce.number().int().min(0),+ preferences: z.coerce.number().int().min(0),+ }),+});++export type SearchMemoryParams = z.infer<typeof searchMemorySchema>;++export interface SearchMemoryResult {+ contexts: Array<Omit<UserMemoryContext, 'userId' | 'descriptionVector'>>;+ experiences: Array<+ Omit<UserMemoryExperience, 'userId' | 'actionVector' | 'situationVector' | 'keyLearningVector'>+ >;+ preferences: Array<Omit<UserMemoryPreference, 'userId' | 'conclusionDirectivesVector'>>;+}++export type RetrieveMemoryParams = SearchMemoryParams;+export type RetrieveMemoryResult = SearchMemoryResult;