Skip to content

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

✨ feat: add user memory

arvinxxc305889ac4d8
diff --git a/packages/database/src/models/__tests__/userMemories.test.ts b/packages/database/src/models/__tests__/userMemories.test.ts
index 6c4d17b7dfe..f646f055ea3 100644
--- a/packages/database/src/models/__tests__/userMemories.test.ts
+++ b/packages/database/src/models/__tests__/userMemories.test.ts
@@ -1,12 +1,13 @@
// @vitest-environment node
+import { LayersEnum, MemorySourceType, MergeStrategyEnum, TypesEnum } from '@lobechat/types';
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 {
+ topics,
userMemories,
userMemoriesContexts,
userMemoriesExperiences,
@@ -172,6 +173,51 @@ function generateRandomCreateUserMemoryPreferenceParams() {
}
describe('UserMemoryModel', () => {
+ describe('parseAssociatedObjects', () => {
+ it('returns null when input is not an array or contains no valid items', () => {
+ expect(UserMemoryModel.parseAssociatedObjects(undefined)).toHaveLength(0);
+ expect(UserMemoryModel.parseAssociatedObjects('not-array')).toHaveLength(0);
+ expect(UserMemoryModel.parseAssociatedObjects([null, undefined, '', ' ', 0])).toHaveLength(
+ 0,
+ );
+ });
+
+ it('normalizes objects', () => {
+ const result = UserMemoryModel.parseAssociatedObjects([
+ { name: 'object' },
+ ' { "name": "json" } ',
+ 'raw',
+ { another: true },
+ ]);
+
+ expect(result).toEqual([{ name: 'object' }]);
+ });
+ });
+
+ describe('parseDateFromString', () => {
+ it('returns null for empty, nullish, non-string, or invalid Date inputs', () => {
+ expect(UserMemoryModel.parseDateFromString()).toBeNull();
+ expect(UserMemoryModel.parseDateFromString(null)).toBeNull();
+ expect(UserMemoryModel.parseDateFromString(' ')).toBeNull();
+ expect(UserMemoryModel.parseDateFromString(123 as unknown as string)).toBeNull();
+ expect(UserMemoryModel.parseDateFromString(new Date('invalid'))).toBeNull();
+ });
+
+ it('parses valid dates from strings and returns the same valid Date instance', () => {
+ const date = new Date('2024-01-01T00:00:00.000Z');
+
+ expect(UserMemoryModel.parseDateFromString(' 2024-01-01T00:00:00.000Z ')).toEqual(date);
+ expect(UserMemoryModel.parseDateFromString(date)).toBe(date);
+ });
+
+ it('returns an invalid Date object when the input string cannot be parsed', () => {
+ const invalid = UserMemoryModel.parseDateFromString('not-a-date');
+
+ expect(invalid).toBeInstanceOf(Date);
+ expect(Number.isNaN(invalid!.getTime())).toBe(true);
+ });
+ });
+
describe('create layered memories', () => {
it('creates a context memory and links the base record', async () => {
const params = generateRandomCreateUserMemoryContextParams();
@@ -319,6 +365,127 @@ describe('UserMemoryModel', () => {
});
});
+ describe('remove layered entries', () => {
+ it('removes context entry and linked base memories only for current user', async () => {
+ const experienceMemory = await userMemoryModel.create(
+ generateRandomCreateUserMemoryExperienceParams(),
+ );
+ const preferenceMemory = await userMemoryModel.create(
+ generateRandomCreateUserMemoryPreferenceParams(),
+ );
+
+ const anotherUserModel = new UserMemoryModel(serverDB, userId2);
+ const otherMemory = await anotherUserModel.create(
+ generateRandomCreateUserMemoryExperienceParams(),
+ );
+
+ const contextId = idGenerator('memory');
+ await serverDB.insert(userMemoriesContexts).values({
+ description: 'context to remove',
+ id: contextId,
+ userId,
+ userMemoryIds: [experienceMemory.id, preferenceMemory.id, otherMemory.id],
+ });
+
+ const removed = await userMemoryModel.removeContextEntry(contextId);
+
+ expect(removed).toBe(true);
+ const deletedContext = await serverDB.query.userMemoriesContexts.findFirst({
+ where: eq(userMemoriesContexts.id, contextId),
+ });
+ const deletedExperience = await serverDB.query.userMemories.findFirst({
+ where: eq(userMemories.id, experienceMemory.id),
+ });
+ const deletedPreference = await serverDB.query.userMemories.findFirst({
+ where: eq(userMemories.id, preferenceMemory.id),
+ });
+ const otherUserMemory = await serverDB.query.userMemories.findFirst({
+ where: eq(userMemories.id, otherMemory.id),
+ });
+
+ expect(deletedContext).toBeUndefined();
+ expect(deletedExperience).toBeUndefined();
+ expect(deletedPreference).toBeUndefined();
+ expect(otherUserMemory).toBeDefined();
+ });
+
+ it('returns false when removing a context owned by another user', async () => {
+ const anotherUserModel = new UserMemoryModel(serverDB, userId2);
+ const { context } = await anotherUserModel.createContextMemory(
+ generateRandomCreateUserMemoryContextParams(),
+ );
+
+ const removed = await userMemoryModel.removeContextEntry(context.id);
+
+ expect(removed).toBe(false);
+ const persisted = await serverDB.query.userMemoriesContexts.findFirst({
+ where: eq(userMemoriesContexts.id, context.id),
+ });
+ expect(persisted).toBeDefined();
+ });
+
+ it('removes experience entry together with its base memory', async () => {
+ const baseMemory = await userMemoryModel.create(
+ generateRandomCreateUserMemoryExperienceParams(),
+ );
+ const experienceId = idGenerator('memory');
+ await serverDB.insert(userMemoriesExperiences).values({
+ ...generateRandomCreateUserMemoryExperienceParams().experience,
+ id: experienceId,
+ userId,
+ userMemoryId: baseMemory.id,
+ });
+
+ const removed = await userMemoryModel.removeExperienceEntry(experienceId);
+
+ expect(removed).toBe(true);
+ const persistedExperience = await serverDB.query.userMemoriesExperiences.findFirst({
+ where: eq(userMemoriesExperiences.id, experienceId),
+ });
+ const persistedBase = await serverDB.query.userMemories.findFirst({
+ where: eq(userMemories.id, baseMemory.id),
+ });
+
+ expect(persistedExperience).toBeUndefined();
+ expect(persistedBase).toBeUndefined();
+ });
+
+ it('removes preference entry and keeps other users data intact', async () => {
+ const baseMemory = await userMemoryModel.create(
+ generateRandomCreateUserMemoryPreferenceParams(),
+ );
+ const preferenceId = idGenerator('memory');
+ await serverDB.insert(userMemoriesPreferences).values({
+ ...generateRandomCreateUserMemoryPreferenceParams().preference,
+ id: preferenceId,
+ userId,
+ userMemoryId: baseMemory.id,
+ });
+
+ const anotherUserModel = new UserMemoryModel(serverDB, userId2);
+ const otherPreference = await anotherUserModel.createPreferenceMemory(
+ generateRandomCreateUserMemoryPreferenceParams(),
+ );
+
+ const removed = await userMemoryModel.removePreferenceEntry(preferenceId);
+
+ expect(removed).toBe(true);
+ const persistedPreference = await serverDB.query.userMemoriesPreferences.findFirst({
+ where: eq(userMemoriesPreferences.id, preferenceId),
+ });
+ const persistedBase = await serverDB.query.userMemories.findFirst({
+ where: eq(userMemories.id, baseMemory.id),
+ });
+ const otherUserPreference = await serverDB.query.userMemoriesPreferences.findFirst({
+ where: eq(userMemoriesPreferences.id, otherPreference.preference.id),
+ });
+
+ expect(persistedPreference).toBeUndefined();
+ expect(persistedBase).toBeUndefined();
+ expect(otherUserPreference).toBeDefined();
+ });
+ });
+
describe('search', () => {
it('should return layered results with split limits', async () => {
const experienceMemoryOne = await userMemoryModel.create(
@@ -529,6 +696,374 @@ describe('UserMemoryModel', () => {
});
});
+ describe('search helpers', () => {
+ it('returns empty arrays when limit is zero or negative', async () => {
+ const contexts = await userMemoryModel.searchContexts({ limit: 0 });
+ const experiences = await userMemoryModel.searchExperiences({ limit: -1 });
+ const preferences = await userMemoryModel.searchPreferences({ limit: 0 });
+
+ expect(contexts).toEqual([]);
+ expect(experiences).toEqual([]);
+ expect(preferences).toEqual([]);
+ });
+
+ it('filters contexts by type and orders by newest when no embedding', async () => {
+ const oldContextId = idGenerator('memory');
+ const recentContextId = idGenerator('memory');
+ await serverDB.insert(userMemoriesContexts).values([
+ {
+ createdAt: new Date('2024-01-01T00:00:00.000Z'),
+ description: 'old match',
+ id: oldContextId,
+ type: 'target',
+ updatedAt: new Date('2024-01-01T00:00:00.000Z'),
+ userId,
+ },
+ {
+ createdAt: new Date('2024-02-01T00:00:00.000Z'),
+ description: 'recent match',
+ id: recentContextId,
+ type: 'target',
+ updatedAt: new Date('2024-02-01T00:00:00.000Z'),
+ userId,
+ },
+ {
+ description: 'different type',
+ id: idGenerator('memory'),
+ type: 'other',
+ userId,
+ },
+ ]);
+
+ const contexts = await userMemoryModel.searchContexts({ limit: 5, type: 'target' });
+
+ expect(contexts).toHaveLength(2);
+ expect(contexts[0]?.id).toBe(recentContextId);
+ expect(contexts[1]?.id).toBe(oldContextId);
+ contexts.forEach((context) => {
+ expect(context.type).toBe('target');
+ });
+ });
+ });
+
+ describe('queryIdentityRoles', () => {
+ it('aggregates identity tags and roles for the current user only', async () => {
+ const now = new Date('2024-04-02T00:00:00.000Z');
+ const anotherUserModel = new UserMemoryModel(serverDB, userId2);
+
+ await userMemoryModel.addIdentityEntry({
+ base: { lastAccessedAt: now, tags: [] },
+ identity: { role: 'engineer', tags: ['alpha', 'beta'] },
+ });
+ await userMemoryModel.addIdentityEntry({
+ base: { lastAccessedAt: now, tags: [] },
+ identity: { role: 'engineer', tags: ['alpha'] },
+ });
+ await userMemoryModel.addIdentityEntry({
+ base: { lastAccessedAt: now, tags: [] },
+ identity: { role: 'manager', tags: [] },
+ });
+
+ await anotherUserModel.addIdentityEntry({
+ base: { lastAccessedAt: now, tags: [] },
+ identity: { role: 'engineer', tags: ['alpha'] },
+ });
+
+ const result = await userMemoryModel.queryIdentityRoles({ size: 5 });
+
+ expect(result).toEqual({
+ roles: [
+ { count: 2, role: 'engineer' },
+ { count: 1, role: 'manager' },
+ ],
+ tags: [
+ { count: 2, tag: 'alpha' },
+ { count: 1, tag: 'beta' },
+ ],
+ });
+ });
+ });
+
+ describe('queryTags', () => {
+ it('aggregates tag counts by layer and ignores empty values', async () => {
+ const now = new Date('2024-04-01T00:00:00.000Z');
+ await serverDB.insert(userMemories).values([
+ {
+ id: idGenerator('memory'),
+ lastAccessedAt: now,
+ memoryLayer: 'identity',
+ tags: ['alpha', 'beta'],
+ userId,
+ },
+ {
+ id: idGenerator('memory'),
+ lastAccessedAt: now,
+ memoryLayer: 'identity',
+ tags: ['alpha', ''],
+ userId,
+ },
+ {
+ id: idGenerator('memory'),
+ lastAccessedAt: now,
+ memoryLayer: 'experience',
+ tags: ['beta'],
+ userId,
+ },
+ ]);
+
+ await serverDB.insert(userMemories).values({
+ id: idGenerator('memory'),
+ lastAccessedAt: now,
+ memoryLayer: 'identity',
+ tags: ['alpha'],
+ userId: userId2,
+ });
+
+ const tags = await userMemoryModel.queryTags({ layers: [LayersEnum.Identity], size: 2 });
+
+ expect(tags).toEqual([
+ { count: 2, tag: 'alpha' },
+ { count: 1, tag: 'beta' },
+ ]);
+ });
+ });
+
+ describe('queryMemories', () => {
+ it('supports filtering, sorting, and pagination for memories', async () => {
+ const baseTime = new Date('2024-04-05T00:00:00.000Z');
+ const newerId = idGenerator('memory');
+ const olderId = idGenerator('memory');
+
+ await serverDB.insert(userMemories).values([
+ {
+ createdAt: baseTime,
+ id: newerId,
+ lastAccessedAt: baseTime,
+ memoryCategory: 'work',
+ memoryLayer: LayersEnum.Context,
+ memoryType: TypesEnum.Topic,
+ summary: 'Atlas launch retrospective',
+ tags: ['atlas', 'project'],
+ title: 'Project Atlas retrospective',
+ updatedAt: new Date('2024-04-06T00:00:00.000Z'),
+ userId,
+ },
+ {
+ createdAt: baseTime,
+ id: olderId,
+ lastAccessedAt: baseTime,
+ memoryCategory: 'work',
+ memoryLayer: LayersEnum.Context,
+ memoryType: TypesEnum.Topic,
+ summary: 'Atlas kickoff planning',
+ tags: ['atlas'],
+ title: 'Atlas kickoff',
+ updatedAt: new Date('2024-04-05T12:00:00.000Z'),
+ userId,
+ },
+ {
+ createdAt: baseTime,
+ id: idGenerator('memory'),
+ lastAccessedAt: baseTime,
+ memoryCategory: 'personal',
+ memoryLayer: LayersEnum.Preference,
+ memoryType: TypesEnum.Preference,
+ summary: 'Atlas weekend plan',
+ tags: ['weekend'],
+ title: 'Weekend notes',
+ updatedAt: new Date('2024-04-07T00:00:00.000Z'),
+ userId,
+ },
+ {
+ createdAt: baseTime,
+ id: idGenerator('memory'),
+ lastAccessedAt: baseTime,
+ memoryCategory: 'work',
+ memoryLayer: LayersEnum.Context,
+ memoryType: TypesEnum.Topic,
+ summary: 'Atlas private note',
+ tags: ['atlas'],
+ title: 'Should not be visible',
+ updatedAt: new Date('2024-04-08T00:00:00.000Z'),
+ userId: userId2,
+ },
+ ]);
+
+ await serverDB.insert(userMemoriesContexts).values([
+ {
+ createdAt: baseTime,
+ description: 'Context newer',
+ id: idGenerator('memory'),
+ scoreImpact: 0.3,
+ title: 'Newer Context',
+ updatedAt: new Date('2024-04-06T00:00:00.000Z'),
+ userId,
+ userMemoryIds: [newerId],
+ },
+ {
+ createdAt: baseTime,
+ description: 'Context older',
+ id: idGenerator('memory'),
+ scoreImpact: 0.9,
+ title: 'Older Context',
+ updatedAt: new Date('2024-04-05T12:00:00.000Z'),
+ userId,
+ userMemoryIds: [olderId],
+ },
+ ]);
+
+ const firstPage = await userMemoryModel.queryMemories({
+ categories: ['work'],
+ layer: LayersEnum.Context,
+ order: 'desc',
+ page: 1,
+ pageSize: 1,
+ q: 'Atlas',
+ sort: 'scoreImpact',
+ tags: ['atlas'],
+ types: [TypesEnum.Topic],
+ });
+
+ expect(firstPage.total).toBe(2);
+ expect(firstPage.page).toBe(1);
+ expect(firstPage.pageSize).toBe(1);
+ expect(firstPage.items).toHaveLength(1);
+ expect(firstPage.items[0]?.memory.id).toBe(olderId);
+ expect(firstPage.items[0]?.layer).toBe(LayersEnum.Context);
+ expect((firstPage.items[0] as any).context.title).toBe('Older Context');
+
+ const secondPage = await userMemoryModel.queryMemories({
+ categories: ['work'],
+ layer: LayersEnum.Context,
+ order: 'desc',
+ page: 2,
+ pageSize: 1,
+ q: 'Atlas',
+ sort: 'scoreImpact',
+ tags: ['atlas'],
+ types: [TypesEnum.Topic],
+ });
+
+ expect(secondPage.items).toHaveLength(1);
+ expect(secondPage.items[0]?.memory.id).toBe(newerId);
+ expect((secondPage.items[0] as any).context.title).toBe('Newer Context');
+ });
+
+ it('returns defaults when no filters are provided', async () => {
+ const timestamp = new Date('2024-04-05T00:00:00.000Z');
+ const id = idGenerator('memory');
+
+ await serverDB.insert(userMemories).values({
+ createdAt: timestamp,
+ id,
+ lastAccessedAt: timestamp,
+ memoryCategory: 'misc',
+ memoryLayer: LayersEnum.Context,
+ memoryType: TypesEnum.Other,
+ summary: 'General note',
+ tags: ['general'],
+ title: 'Default',
+ updatedAt: timestamp,
+ userId,
+ });
+
+ await serverDB.insert(userMemoriesContexts).values({
+ createdAt: timestamp,
+ description: 'General context',
+ id: idGenerator('memory'),
+ title: 'Context title',
+ updatedAt: timestamp,
+ userId,
+ userMemoryIds: [id],
+ });
+
+ const result = await userMemoryModel.queryMemories();
+
+ expect(result.page).toBe(1);
+ expect(result.pageSize).toBe(20);
+ expect(result.total).toBe(1);
+ expect(result.items[0]?.memory.id).toBe(id);
+ expect(result.items[0]?.layer).toBe(LayersEnum.Context);
+ });
+
+ it('returns newly inserted layered memories when querying without filters', async () => {
+ const contextInput = generateRandomCreateUserMemoryContextParams();
+ const experienceInput = generateRandomCreateUserMemoryExperienceParams();
+ const preferenceInput = generateRandomCreateUserMemoryPreferenceParams();
+ const identityDescription = 'identity ' + nanoid();
+
+ const { context, memory: contextMemory } =
+ await userMemoryModel.createContextMemory(contextInput);
+ const { experience, memory: experienceMemory } =
+ await userMemoryModel.createExperienceMemory(experienceInput);
+ const { preference, memory: preferenceMemory } =
+ await userMemoryModel.createPreferenceMemory(preferenceInput);
+ const { identityId, userMemoryId: identityMemoryId } = await userMemoryModel.addIdentityEntry(
+ {
+ base: { summary: 'identity summary ' + nanoid(), tags: ['identity'] },
+ identity: {
+ description: identityDescription,
+ relationship: 'friend',
+ tags: ['identity'],
+ type: 'personal',
+ },
+ },
+ );
+
+ const identity = await serverDB.query.userMemoriesIdentities.findFirst({
+ where: eq(userMemoriesIdentities.id, identityId),
+ });
+
+ const contextResult = await userMemoryModel.queryMemories({
+ layer: LayersEnum.Context,
+ sort: 'scoreImpact',
+ });
+
+ expect(contextResult.total).toBe(1);
+ expect(contextResult.items).toHaveLength(1);
+ const contextItem = contextResult.items[0] as any;
+ expect(contextItem.layer).toBe(LayersEnum.Context);
+ expect(contextItem.context.description).toBe(context.description);
+ expect(contextItem.context.userMemoryIds).toEqual([contextMemory.id]);
+
+ const experienceResult = await userMemoryModel.queryMemories({
+ layer: LayersEnum.Experience,
+ sort: 'scoreConfidence',
+ });
+
+ expect(experienceResult.total).toBe(1);
+ expect(experienceResult.items).toHaveLength(1);
+ const experienceItem = experienceResult.items[0] as any;
+ expect(experienceItem.layer).toBe(LayersEnum.Experience);
+ expect(experienceItem.experience.situation).toBe(experience.situation);
+ expect(experienceItem.experience.userMemoryId).toBe(experienceMemory.id);
+
+ const preferenceResult = await userMemoryModel.queryMemories({
+ layer: LayersEnum.Preference,
+ sort: 'scorePriority',
+ });
+
+ expect(preferenceResult.total).toBe(1);
+ expect(preferenceResult.items).toHaveLength(1);
+ const preferenceItem = preferenceResult.items[0] as any;
+ expect(preferenceItem.layer).toBe(LayersEnum.Preference);
+ expect(preferenceItem.preference.conclusionDirectives).toBe(preference.conclusionDirectives);
+ expect(preferenceItem.preference.userMemoryId).toBe(preferenceMemory.id);
+
+ const identityResult = await userMemoryModel.queryMemories({
+ layer: LayersEnum.Identity,
+ });
+
+ expect(identityResult.total).toBe(1);
+ expect(identityResult.items).toHaveLength(1);
+ const identityItem = identityResult.items[0] as any;
+ expect(identityItem.layer).toBe(LayersEnum.Identity);
+ expect(identityItem.identity.description).toBe(identityDescription);
+ expect(identityItem.identity.userMemoryId).toBe(identityMemoryId);
+ expect(identityItem.identity.type).toBe(identity?.type);
+ });
+ });
+
describe('findById', () => {
it('returns own memories and updates access metrics', async () => {
const created = await userMemoryModel.create(
@@ -575,6 +1110,86 @@ describe('UserMemoryModel', () => {
});
});
+ describe('getMemoryDetail', () => {
+ it('returns full context memory detail and bumps access metrics', async () => {
+ const params = generateRandomCreateUserMemoryContextParams();
+ params.context.metadata = { contextDetail: true };
+ params.context.associatedObjects = [{ name: 'Doc', extra: { url: 'https://example.com' } }];
+
+ const { context, memory } = await userMemoryModel.createContextMemory(params);
+
+ const detail = await userMemoryModel.getMemoryDetail({
+ id: context.id,
+ layer: LayersEnum.Context,
+ });
+
+ expect(detail?.layer).toBe(LayersEnum.Context);
+ expect(detail?.memory.id).toBe(memory.id);
+ expect(detail && 'context' in detail ? detail.context.id : undefined).toBe(context.id);
+ expect((detail as any).context.userMemoryIds).toEqual([memory.id]);
+ expect((detail as any).context.metadata).toEqual(params.context.metadata);
+ expect(detail?.memory.memoryLayer).toBe(LayersEnum.Context);
+ expect(detail?.source).toBeUndefined();
+ expect(detail?.sourceType).toBe(MemorySourceType.ChatTopic);
+
+ const persisted = await serverDB.query.userMemories.findFirst({
+ where: eq(userMemories.id, memory.id),
+ });
+
+ expect(persisted?.accessedCount).toBe(0);
+ });
+
+ it('resolves topic source data for memory detail', async () => {
+ const topic = {
+ agentId: 'agent-1',
+ id: idGenerator('topics'),
+ sessionId: 'session-1',
+ title: 'Topic title',
+ userId,
+ };
+
+ const topicSpy = vi
+ .spyOn((userMemoryModel as any).topicModel, 'findById')
+ .mockResolvedValue(topic as any);
+
+ const params = generateRandomCreateUserMemoryContextParams();
+ params.context.metadata = { sourceId: topic.id };
+
+ const { context } = await userMemoryModel.createContextMemory(params);
+
+ const detail = await userMemoryModel.getMemoryDetail({
+ id: context.id,
+ layer: LayersEnum.Context,
+ });
+
+ expect(detail?.sourceType).toBe(MemorySourceType.ChatTopic);
+ expect(detail?.source?.id).toBe(topic.id);
+ expect(detail?.source?.title).toBe(topic.title);
+
+ topicSpy.mockRestore();
+ });
+
+ it('returns undefined for memories owned by another user', async () => {
+ const otherModel = new UserMemoryModel(serverDB, userId2);
+ const { experience, memory } = await otherModel.createExperienceMemory(
+ generateRandomCreateUserMemoryExperienceParams(),
+ );
+
+ const detail = await userMemoryModel.getMemoryDetail({
+ id: experience.id,
+ layer: LayersEnum.Experience,
+ });
+
+ expect(detail).toBeUndefined();
+
+ const persisted = await serverDB.query.userMemories.findFirst({
+ where: eq(userMemories.id, memory.id),
+ });
+
+ expect(persisted?.accessedCount).toBe(0);
+ });
+ });
+
describe('update', () => {
it('updates mutable fields for own memories only', async () => {
const created = await userMemoryModel.create(
@@ -1348,39 +1963,5 @@ describe('UserMemoryModel', () => {
}
}
});
-
- 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.ts
deleted file mode 100644
index 750f49fdab2..00000000000
--- a/packages/database/src/models/userMemory.ts
+++ /dev/null
@@ -1,996 +0,0 @@
-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,
- capturedAt: userMemoriesContexts.capturedAt,
- 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,
- capturedAt: userMemoriesExperiences.capturedAt,
- 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,
- capturedAt: userMemoriesPreferences.capturedAt,
- 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/models/userMemory/context.ts b/packages/database/src/models/userMemory/context.ts
new file mode 100644
index 00000000000..6ddc34cea9a
--- /dev/null
+++ b/packages/database/src/models/userMemory/context.ts
@@ -0,0 +1,85 @@
+import { and, desc, eq } from 'drizzle-orm';
+
+import {
+ NewUserMemoryContext,
+ UserMemoryContext,
+ userMemories,
+ userMemoriesContexts,
+} from '../../schemas';
+import { LobeChatDatabase } from '../../type';
+
+export class UserMemoryContextModel {
+ private userId: string;
+ private db: LobeChatDatabase;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.userId = userId;
+ this.db = db;
+ }
+
+ create = async (params: Omit<NewUserMemoryContext, 'userId'>) => {
+ const [result] = await this.db
+ .insert(userMemoriesContexts)
+ .values({ ...params, userId: this.userId })
+ .returning();
+
+ return result;
+ };
+
+ delete = async (id: string) => {
+ return this.db.transaction(async (tx) => {
+ const context = await tx.query.userMemoriesContexts.findFirst({
+ where: and(eq(userMemoriesContexts.id, id), eq(userMemoriesContexts.userId, this.userId)),
+ });
+
+ if (!context) {
+ return { success: false };
+ }
+
+ // Delete associated user memories if any
+ const memoryIds = Array.isArray(context.userMemoryIds)
+ ? (context.userMemoryIds as string[])
+ : [];
+
+ if (memoryIds.length > 0) {
+ for (const memoryId of memoryIds) {
+ await tx
+ .delete(userMemories)
+ .where(and(eq(userMemories.id, memoryId), eq(userMemories.userId, this.userId)));
+ }
+ }
+
+ // Delete the context entry
+ await tx
+ .delete(userMemoriesContexts)
+ .where(and(eq(userMemoriesContexts.id, id), eq(userMemoriesContexts.userId, this.userId)));
+
+ return { success: true };
+ });
+ };
+
+ deleteAll = async () => {
+ return this.db.delete(userMemoriesContexts).where(eq(userMemoriesContexts.userId, this.userId));
+ };
+
+ query = async (limit = 50) => {
+ return this.db.query.userMemoriesContexts.findMany({
+ limit,
+ orderBy: [desc(userMemoriesContexts.createdAt)],
+ where: eq(userMemoriesContexts.userId, this.userId),
+ });
+ };
+
+ findById = async (id: string) => {
+ return this.db.query.userMemoriesContexts.findFirst({
+ where: and(eq(userMemoriesContexts.id, id), eq(userMemoriesContexts.userId, this.userId)),
+ });
+ };
+
+ update = async (id: string, value: Partial<UserMemoryContext>) => {
+ return this.db
+ .update(userMemoriesContexts)
+ .set({ ...value, updatedAt: new Date() })
+ .where(and(eq(userMemoriesContexts.id, id), eq(userMemoriesContexts.userId, this.userId)));
+ };
+}
diff --git a/packages/database/src/models/userMemory/experience.ts b/packages/database/src/models/userMemory/experience.ts
new file mode 100644
index 00000000000..621a47c6d75
--- /dev/null
+++ b/packages/database/src/models/userMemory/experience.ts
@@ -0,0 +1,84 @@
+import { and, desc, eq } from 'drizzle-orm';
+
+import {
+ NewUserMemoryExperience,
+ UserMemoryExperience,
+ userMemories,
+ userMemoriesExperiences,
+} from '../../schemas';
+import { LobeChatDatabase } from '../../type';
+
+export class UserMemoryExperienceModel {
+ private userId: string;
+ private db: LobeChatDatabase;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.userId = userId;
+ this.db = db;
+ }
+
+ create = async (params: Omit<NewUserMemoryExperience, 'userId'>) => {
+ const [result] = await this.db
+ .insert(userMemoriesExperiences)
+ .values({ ...params, userId: this.userId })
+ .returning();
+
+ return result;
+ };
+
+ delete = async (id: string) => {
+ return this.db.transaction(async (tx) => {
+ const experience = await tx.query.userMemoriesExperiences.findFirst({
+ where: and(
+ eq(userMemoriesExperiences.id, id),
+ eq(userMemoriesExperiences.userId, this.userId),
+ ),
+ });
+
+ if (!experience || !experience.userMemoryId) {
+ return { success: false };
+ }
+
+ // Delete the base user memory (cascade will handle the experience)
+ await tx
+ .delete(userMemories)
+ .where(
+ and(eq(userMemories.id, experience.userMemoryId), eq(userMemories.userId, this.userId)),
+ );
+
+ return { success: true };
+ });
+ };
+
+ deleteAll = async () => {
+ return this.db
+ .delete(userMemoriesExperiences)
+ .where(eq(userMemoriesExperiences.userId, this.userId));
+ };
+
+ query = async (limit = 50) => {
+ return this.db.query.userMemoriesExperiences.findMany({
+ limit,
+ orderBy: [desc(userMemoriesExperiences.createdAt)],
+ where: eq(userMemoriesExperiences.userId, this.userId),
+ });
+ };
+
+ findById = async (id: string) => {
+ return this.db.query.userMemoriesExperiences.findFirst({
+ where: and(
+ eq(userMemoriesExperiences.id, id),
+ eq(userMemoriesExperiences.userId, this.userId),
+ ),
+ });
+ };
+
+ update = async (id: string, value: Partial<UserMemoryExperience>) => {
+ return this.db
+ .update(userMemoriesExperiences)
+ .set({ ...value, updatedAt: new Date() })
+ .where(
+ and(eq(userMemoriesExperiences.id, id), eq(userMemoriesExperiences.userId, this.userId)),
+ );
+ };
+}
diff --git a/packages/database/src/models/userMemory/identity.ts b/packages/database/src/models/userMemory/identity.ts
new file mode 100644
index 00000000000..0a75b267f02
--- /dev/null
+++ b/packages/database/src/models/userMemory/identity.ts
@@ -0,0 +1,81 @@
+import { and, desc, eq } from 'drizzle-orm';
+
+import {
+ NewUserMemoryIdentity,
+ UserMemoryIdentity,
+ userMemories,
+ userMemoriesIdentities,
+} from '../../schemas';
+import { LobeChatDatabase } from '../../type';
+
+export class UserMemoryIdentityModel {
+ private userId: string;
+ private db: LobeChatDatabase;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.userId = userId;
+ this.db = db;
+ }
+
+ create = async (params: Omit<NewUserMemoryIdentity, 'userId'>) => {
+ const [result] = await this.db
+ .insert(userMemoriesIdentities)
+ .values({ ...params, userId: this.userId })
+ .returning();
+
+ return result;
+ };
+
+ delete = async (id: string) => {
+ return this.db.transaction(async (tx) => {
+ const identity = await tx.query.userMemoriesIdentities.findFirst({
+ where: and(
+ eq(userMemoriesIdentities.id, id),
+ eq(userMemoriesIdentities.userId, this.userId),
+ ),
+ });
+
+ if (!identity || !identity.userMemoryId) {
+ return { success: false };
+ }
+
+ // Delete the base user memory (cascade will handle the identity)
+ await tx
+ .delete(userMemories)
+ .where(
+ and(eq(userMemories.id, identity.userMemoryId), eq(userMemories.userId, this.userId)),
+ );
+
+ return { success: true };
+ });
+ };
+
+ deleteAll = async () => {
+ return this.db
+ .delete(userMemoriesIdentities)
+ .where(eq(userMemoriesIdentities.userId, this.userId));
+ };
+
+ query = async (limit = 50) => {
+ return this.db.query.userMemoriesIdentities.findMany({
+ limit,
+ orderBy: [desc(userMemoriesIdentities.createdAt)],
+ where: eq(userMemoriesIdentities.userId, this.userId),
+ });
+ };
+
+ findById = async (id: string) => {
+ return this.db.query.userMemoriesIdentities.findFirst({
+ where: and(eq(userMemoriesIdentities.id, id), eq(userMemoriesIdentities.userId, this.userId)),
+ });
+ };
+
+ update = async (id: string, value: Partial<UserMemoryIdentity>) => {
+ return this.db
+ .update(userMemoriesIdentities)
+ .set({ ...value, updatedAt: new Date() })
+ .where(
+ and(eq(userMemoriesIdentities.id, id), eq(userMemoriesIdentities.userId, this.userId)),
+ );
+ };
+}
diff --git a/packages/database/src/models/userMemory/index.ts b/packages/database/src/models/userMemory/index.ts
new file mode 100644
index 00000000000..d168e664d67
--- /dev/null
+++ b/packages/database/src/models/userMemory/index.ts
@@ -0,0 +1,5 @@
+export * from './context';
+export * from './experience';
+export * from './identity';
+export * from './model';
+export * from './preference';
diff --git a/packages/database/src/models/userMemory/model.ts b/packages/database/src/models/userMemory/model.ts
new file mode 100644
index 00000000000..96767bcb17b
--- /dev/null
+++ b/packages/database/src/models/userMemory/model.ts
@@ -0,0 +1,2044 @@
+import { AssociatedObjectSchema } from '@lobechat/memory-user-memory';
+import {
+ IdentityTypeEnum,
+ LayersEnum,
+ MemorySourceType,
+ MergeStrategyEnum,
+ Optional,
+ RelationshipEnum,
+ TypesEnum,
+ UserMemoryContextObjectType,
+ UserMemoryContextSubjectType,
+ UserMemoryContextWithoutVectors,
+ UserMemoryDetail,
+ UserMemoryExperienceWithoutVectors,
+ UserMemoryIdentityWithoutVectors,
+ UserMemoryItemSimple,
+ UserMemoryPreferenceWithoutVectors,
+ UserMemoryWithoutVectors,
+} from '@lobechat/types';
+import type { AnyColumn, SQL } from 'drizzle-orm';
+import {
+ and,
+ asc,
+ cosineDistance,
+ desc,
+ eq,
+ ilike,
+ inArray,
+ isNotNull,
+ ne,
+ or,
+ sql,
+} from 'drizzle-orm';
+
+import { merge } from '@/utils/merge';
+
+import {
+ UserMemoryContext,
+ UserMemoryExperience,
+ UserMemoryIdentity,
+ UserMemoryItem,
+ UserMemoryPreference,
+ userMemories,
+ userMemoriesContexts,
+ userMemoriesExperiences,
+ userMemoriesIdentities,
+ userMemoriesPreferences,
+} from '../../schemas';
+import { LobeChatDatabase } from '../../type';
+import { selectNonVectorColumns } from '../../utils/columns';
+import { TopicModel } from '../topic';
+
+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 {
+ capturedAt?: Date;
+ details: string;
+ detailsEmbedding?: number[];
+ memoryCategory: string;
+ memoryLayer: LayersEnum;
+ memoryType: TypesEnum;
+ summary: string;
+ summaryEmbedding?: number[];
+ title: string;
+ titleEmbedding?: number[];
+}
+
+export interface CreateUserMemoryContextParams extends BaseCreateUserMemoryParams {
+ context: Optional<
+ Omit<
+ UserMemoryContext,
+ 'id' | 'userId' | 'createdAt' | 'updatedAt' | 'accessedAt' | 'userMemoryIds'
+ >,
+ 'capturedAt'
+ >;
+}
+
+export interface CreateUserMemoryExperienceParams extends BaseCreateUserMemoryParams {
+ experience: Optional<
+ Omit<
+ UserMemoryExperience,
+ 'id' | 'userId' | 'createdAt' | 'updatedAt' | 'accessedAt' | 'userMemoryId'
+ >,
+ 'capturedAt'
+ >;
+}
+
+export interface CreateUserMemoryIdentityParams extends BaseCreateUserMemoryParams {
+ identity: Optional<
+ Omit<
+ UserMemoryIdentity,
+ 'id' | 'userId' | 'createdAt' | 'updatedAt' | 'accessedAt' | 'userMemoryId'
+ >,
+ 'capturedAt'
+ >;
+}
+
+export interface CreateUserMemoryPreferenceParams extends BaseCreateUserMemoryParams {
+ preference: Optional<
+ Omit<
+ UserMemoryPreference,
+ 'id' | 'userId' | 'createdAt' | 'updatedAt' | 'accessedAt' | 'userMemoryId'
+ >,
+ 'capturedAt'
+ >;
+}
+
+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: UserMemoryContextWithoutVectors[];
+ experiences: UserMemoryExperienceWithoutVectors[];
+ preferences: UserMemoryPreferenceWithoutVectors[];
+}
+
+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 {
+ capturedAt?: Date;
+ 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 {
+ capturedAt?: Date;
+ 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 interface ContextEntryPayload {
+ associatedObjects?:
+ | { extra?: Record<string, unknown>; name?: string; type?: UserMemoryContextObjectType }[]
+ | null;
+ associatedSubjects?:
+ | { extra?: Record<string, unknown>; name?: string; type?: UserMemoryContextSubjectType }[]
+ | null;
+ currentStatus?: string | null;
+ description?: string | null;
+ descriptionVector?: number[] | null;
+ metadata?: Record<string, unknown> | null;
+ scoreImpact?: number | null;
+ scoreUrgency?: number | null;
+ tags?: string[] | null;
+ title?: string | null;
+ type?: string | null;
+}
+
+export interface UpdateContextEntryParams {
+ context?: ContextEntryPayload;
+ contextId: string;
+}
+
+export interface ExperienceEntryPayload {
+ action?: string | null;
+ actionVector?: number[] | null;
+ 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;
+}
+
+export interface UpdateExperienceEntryParams {
+ experience?: ExperienceEntryPayload;
+ experienceId: string;
+}
+
+export interface PreferenceEntryPayload {
+ conclusionDirectives?: string | null;
+ conclusionDirectivesVector?: number[] | null;
+ metadata?: Record<string, unknown> | null;
+ scorePriority?: number | null;
+ suggestions?: string | null;
+ tags?: string[] | null;
+ type?: string | null;
+}
+
+export interface UpdatePreferenceEntryParams {
+ preference?: PreferenceEntryPayload;
+ preferenceId: string;
+}
+
+export interface QueryTagsParams {
+ layers?: LayersEnum[];
+ page?: number;
+ size?: number;
+}
+
+export interface QueryTagsResult {
+ count: number;
+ tag: string;
+}
+
+export interface QueryIdentityRolesParams {
+ page?: number;
+ size?: number;
+}
+
+export interface QueryIdentityRolesResult {
+ roles: Array<{ count: number; role: string }>;
+ tags: Array<{ count: number; tag: string }>;
+}
+
+export type QueryUserMemoriesSort =
+ | 'scoreConfidence' // user_memories_experiences
+ | 'scoreImpact' // user_memories_contexts
+ | 'scorePriority' // user_memories_preferences
+ | 'scoreUrgency'; // user_memories_contexts
+
+export interface QueryUserMemoriesParams {
+ categories?: string[];
+ layer?: LayersEnum;
+ order?: 'asc' | 'desc';
+ page?: number;
+ pageSize?: number;
+ q?: string;
+ sort?: QueryUserMemoriesSort;
+ tags?: string[];
+ types?: string[];
+}
+
+export interface GetMemoriesResult {
+ items: UserMemoryItemSimple[];
+ page: number;
+ pageSize: number;
+ total: number;
+}
+
+export interface GetMemoryDetailParams {
+ id: string;
+ layer: LayersEnum;
+}
+
+export class UserMemoryModel {
+ static parseAssociatedObjects(value?: unknown): Record<string, unknown>[] {
+ if (!Array.isArray(value)) return [];
+
+ const associations: Record<string, unknown>[] = [];
+
+ value.forEach((item) => {
+ const parsed = AssociatedObjectSchema.safeParse(item);
+ if (parsed.success) {
+ const extra = JSON.parse(parsed.data.extra || '{}');
+ parsed.data.extra = extra;
+ associations.push(parsed.data);
+ return;
+ }
+
+ if (
+ item &&
+ typeof item === 'object' &&
+ 'name' in item &&
+ typeof (item as any).name === 'string'
+ ) {
+ associations.push({ name: (item as any).name });
+ }
+ });
+
+ return associations.length > 0 ? associations : [];
+ }
+
+ static parseAssociatedSubjects(value?: unknown): Record<string, unknown>[] {
+ if (!Array.isArray(value)) return [];
+
+ const associations: Record<string, unknown>[] = [];
+
+ value.forEach((item) => {
+ const parsed = AssociatedObjectSchema.safeParse(item);
+ if (parsed.success) {
+ const extra = JSON.parse(parsed.data.extra || '{}');
+ parsed.data.extra = extra;
+ associations.push(parsed.data);
+ }
+ });
+
+ return associations.length > 0 ? associations : [];
+ }
+
+ static parseDateFromString(value?: string | Date | null): Date | null {
+ if (!value) return null;
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
+ if (typeof value !== 'string') return null;
+
+ const normalized = value.trim();
+ if (!normalized) return null;
+
+ return new Date(normalized);
+ }
+
+ private userId: string;
+ private db: LobeChatDatabase;
+ private topicModel: TopicModel;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.userId = userId;
+ this.db = db;
+ this.topicModel = new TopicModel(db, userId);
+ }
+
+ private extractSourceMetadata(metadata?: Record<string, unknown> | null): {
+ sourceId?: string;
+ sourceType?: MemorySourceType;
+ } {
+ if (!metadata || typeof metadata !== 'object') {
+ return {};
+ }
+
+ const sourceId = typeof metadata.sourceId === 'string' ? metadata.sourceId : undefined;
+ const rawSourceType =
+ typeof metadata.sourceType === 'string'
+ ? (metadata.sourceType as MemorySourceType)
+ : undefined;
+ const sourceType: MemorySourceType = rawSourceType ?? MemorySourceType.ChatTopic;
+
+ return { sourceId, sourceType };
+ }
+
+ 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,
+ capturedAt: params.capturedAt,
+ 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 ?? [],
+ capturedAt: params.context.capturedAt,
+ 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,
+ capturedAt: params.experience.capturedAt,
+ 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 = {
+ capturedAt: params.preference.capturedAt,
+ 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);
+ };
+
+ queryTags = async (params: QueryTagsParams = {}): Promise<QueryTagsResult[]> => {
+ const { layers, page = 1, size = 10 } = params;
+ const offset = (page - 1) * size;
+
+ const conditions = [eq(userMemories.userId, this.userId)];
+ if (layers && layers.length > 0) {
+ conditions.push(inArray(userMemories.memoryLayer, layers));
+ }
+
+ const unnestedTags = this.db.$with('unnested_tags').as(
+ this.db
+ .select({
+ tag: sql<string>`UNNEST(${userMemories.tags})`.as('tag'),
+ })
+ .from(userMemories)
+ .where(and(...conditions)),
+ );
+
+ const result = await this.db
+ .with(unnestedTags)
+ .select({
+ count: sql<number>`COUNT(${unnestedTags.tag})::int`.as('count'),
+ tag: unnestedTags.tag,
+ })
+ .from(unnestedTags)
+ .where(and(isNotNull(unnestedTags.tag), ne(unnestedTags.tag, '')))
+ .groupBy(unnestedTags.tag)
+ .orderBy(desc(sql<number>`count`))
+ .limit(size)
+ .offset(offset);
+
+ return result as QueryTagsResult[];
+ };
+
+ queryIdentityRoles = async (
+ params: QueryIdentityRolesParams = {},
+ ): Promise<QueryIdentityRolesResult> => {
+ const { page = 1, size = 10 } = params;
+ const offset = (page - 1) * size;
+
+ const identityConditions = [eq(userMemoriesIdentities.userId, this.userId)];
+
+ const identityTags = this.db.$with('identity_tags').as(
+ this.db
+ .select({
+ tag: sql<string>`UNNEST(${userMemoriesIdentities.tags})`.as('tag'),
+ })
+ .from(userMemoriesIdentities)
+ .where(and(...identityConditions)),
+ );
+
+ const [tags, roles] = await Promise.all([
+ this.db
+ .with(identityTags)
+ .select({
+ count: sql<number>`COUNT(${identityTags.tag})::int`.as('count'),
+ tag: identityTags.tag,
+ })
+ .from(identityTags)
+ .where(and(isNotNull(identityTags.tag), ne(identityTags.tag, '')))
+ .groupBy(identityTags.tag)
+ .orderBy(desc(sql<number>`count`))
+ .limit(size)
+ .offset(offset),
+ this.db
+ .select({
+ count: sql<number>`COUNT(${userMemoriesIdentities.role})::int`.as('count'),
+ role: userMemoriesIdentities.role,
+ })
+ .from(userMemoriesIdentities)
+ .where(
+ and(
+ ...identityConditions,
+ isNotNull(userMemoriesIdentities.role),
+ ne(userMemoriesIdentities.role, ''),
+ ),
+ )
+ .groupBy(userMemoriesIdentities.role)
+ .orderBy(desc(sql<number>`count`))
+ .limit(size)
+ .offset(offset),
+ ]);
+
+ return {
+ roles: roles as QueryIdentityRolesResult['roles'],
+ tags: tags as QueryIdentityRolesResult['tags'],
+ };
+ };
+
+ queryMemories = async (params: QueryUserMemoriesParams = {}): Promise<GetMemoriesResult> => {
+ const {
+ categories,
+ layer,
+ order = 'desc',
+ page = 1,
+ pageSize = 20,
+ q,
+ sort,
+ tags,
+ types,
+ } = params;
+
+ const resolvedPage = page ?? 1;
+ const resolvedPageSize = pageSize ?? 20;
+ const normalizedPage = Math.max(1, resolvedPage);
+ const normalizedPageSize = Math.min(Math.max(resolvedPageSize, 1), 100);
+ const offset = (normalizedPage - 1) * normalizedPageSize;
+
+ const normalizedQuery = typeof q === 'string' ? q.trim() : '';
+ const resolvedLayer = layer ?? LayersEnum.Context;
+
+ const conditions: Array<SQL | undefined> = [
+ eq(userMemories.userId, this.userId),
+ categories && categories.length > 0
+ ? inArray(userMemories.memoryCategory, categories)
+ : undefined,
+ eq(userMemories.memoryLayer, resolvedLayer),
+ normalizedQuery
+ ? or(
+ ilike(userMemories.title, `%${normalizedQuery}%`),
+ ilike(userMemories.summary, `%${normalizedQuery}%`),
+ ilike(userMemories.details, `%${normalizedQuery}%`),
+ )
+ : undefined,
+ ];
+
+ const filters = conditions.filter((condition): condition is SQL => condition !== undefined);
+ const whereClause = filters.length > 0 ? and(...filters) : undefined;
+
+ const applyOrder = order === 'asc' ? asc : desc;
+
+ const baseSelection = {
+ accessedAt: userMemories.accessedAt,
+ accessedCount: userMemories.accessedCount,
+ createdAt: userMemories.createdAt,
+ id: userMemories.id,
+ lastAccessedAt: userMemories.lastAccessedAt,
+ memoryCategory: userMemories.memoryCategory,
+ memoryLayer: userMemories.memoryLayer,
+ memoryType: userMemories.memoryType,
+ metadata: userMemories.metadata,
+ status: userMemories.status,
+ tags: userMemories.tags,
+ title: userMemories.title,
+ updatedAt: userMemories.updatedAt,
+ userId: userMemories.userId,
+ };
+
+ const buildOrderBy = (
+ scoreColumn: SQL | AnyColumn | undefined,
+ updatedAtColumn: AnyColumn | SQL,
+ createdAtColumn: AnyColumn | SQL,
+ ) =>
+ [
+ scoreColumn ? applyOrder(scoreColumn) : undefined,
+ applyOrder(updatedAtColumn),
+ applyOrder(createdAtColumn),
+ ].filter((item): item is SQL => item !== undefined);
+
+ switch (resolvedLayer) {
+ case LayersEnum.Context: {
+ const scoreColumn =
+ sort === 'scoreUrgency'
+ ? userMemoriesContexts.scoreUrgency
+ : userMemoriesContexts.scoreImpact;
+
+ const orderByClauses = buildOrderBy(
+ scoreColumn,
+ userMemoriesContexts.updatedAt,
+ userMemoriesContexts.createdAt,
+ );
+ const joinCondition = and(
+ eq(userMemories.userId, userMemoriesContexts.userId),
+ // Use jsonb key-existence (jsonb_exists) to check membership without expanding the array
+ sql<boolean>`
+ COALESCE(${userMemoriesContexts.userMemoryIds}, '[]'::jsonb) ? (${userMemories.id})::text
+ `,
+ );
+
+ const contextFilters: Array<SQL | undefined> = [
+ whereClause,
+ types && types.length > 0 ? inArray(userMemoriesContexts.type, types) : undefined,
+ tags && tags.length > 0
+ ? or(
+ ...tags.map(
+ (tag) =>
+ sql<boolean>`
+ COALESCE(${tag} = ANY(${userMemoriesContexts.tags}), false)
+ OR COALESCE(${tag} = ANY(${userMemories.tags}), false)
+ `,
+ ),
+ )
+ : undefined,
+ ];
+ const contextWhereClause = contextFilters.some(
+ (condition): condition is SQL => condition !== undefined,
+ )
+ ? and(
+ ...(contextFilters.filter(
+ (condition): condition is SQL => condition !== undefined,
+ ) as SQL[]),
+ )
+ : undefined;
+
+ const [rows, totalResult] = await Promise.all([
+ this.db
+ .select({
+ context: {
+ accessedAt: userMemoriesContexts.accessedAt,
+ 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,
+ },
+ memory: baseSelection,
+ })
+ .from(userMemories)
+ .innerJoin(userMemoriesContexts, joinCondition)
+ .where(contextWhereClause)
+ .orderBy(...orderByClauses)
+ .limit(normalizedPageSize)
+ .offset(offset),
+ this.db
+ .select({ count: sql<number>`COUNT(DISTINCT ${userMemories.id})::int` })
+ .from(userMemories)
+ .innerJoin(userMemoriesContexts, joinCondition)
+ .where(contextWhereClause),
+ ]);
+
+ return {
+ items: rows.map((row) => {
+ return {
+ context: row.context,
+ layer: LayersEnum.Context,
+ memory: row.memory,
+ };
+ }),
+ page: normalizedPage,
+ pageSize: normalizedPageSize,
+ total: Number(totalResult[0]?.count ?? 0),
+ };
+ }
+ case LayersEnum.Experience: {
+ const orderByClauses = buildOrderBy(
+ userMemoriesExperiences.scoreConfidence,
+ userMemoriesExperiences.updatedAt,
+ userMemoriesExperiences.createdAt,
+ );
+ const joinCondition = and(
+ eq(userMemories.id, userMemoriesExperiences.userMemoryId),
+ eq(userMemoriesExperiences.userId, this.userId),
+ );
+
+ const experienceFilters: Array<SQL | undefined> = [
+ whereClause,
+ types && types.length > 0 ? inArray(userMemoriesExperiences.type, types) : undefined,
+ tags && tags.length > 0
+ ? or(...tags.map((tag) => sql<boolean>`${tag} = ANY(${userMemoriesExperiences.tags})`))
+ : undefined,
+ ];
+ const experienceWhereClause = experienceFilters.some(
+ (condition): condition is SQL => condition !== undefined,
+ )
+ ? and(
+ ...(experienceFilters.filter(
+ (condition): condition is SQL => condition !== undefined,
+ ) as SQL[]),
+ )
+ : undefined;
+
+ const [rows, totalResult] = await Promise.all([
+ this.db
+ .select({
+ experience: {
+ accessedAt: userMemoriesExperiences.accessedAt,
+ action: userMemoriesExperiences.action,
+ createdAt: userMemoriesExperiences.createdAt,
+ id: userMemoriesExperiences.id,
+ keyLearning: userMemoriesExperiences.keyLearning,
+ metadata: userMemoriesExperiences.metadata,
+ scoreConfidence: userMemoriesExperiences.scoreConfidence,
+ situation: userMemoriesExperiences.situation,
+ tags: userMemoriesExperiences.tags,
+ type: userMemoriesExperiences.type,
+ updatedAt: userMemoriesExperiences.updatedAt,
+ userId: userMemoriesExperiences.userId,
+ userMemoryId: userMemoriesExperiences.userMemoryId,
+ },
+ memory: baseSelection,
+ })
+ .from(userMemories)
+ .innerJoin(userMemoriesExperiences, joinCondition)
+ .where(experienceWhereClause)
+ .orderBy(...orderByClauses)
+ .limit(normalizedPageSize)
+ .offset(offset),
+ this.db
+ .select({ count: sql<number>`COUNT(*)::int` })
+ .from(userMemories)
+ .innerJoin(userMemoriesExperiences, joinCondition)
+ .where(experienceWhereClause),
+ ]);
+
+ return {
+ items: rows.map((row) => {
+ return {
+ experience: row.experience,
+ layer: LayersEnum.Experience,
+ memory: row.memory,
+ };
+ }),
+ page: normalizedPage,
+ pageSize: normalizedPageSize,
+ total: Number(totalResult[0]?.count ?? 0),
+ };
+ }
+ case LayersEnum.Identity: {
+ const orderByClauses = buildOrderBy(
+ undefined,
+ userMemoriesIdentities.updatedAt,
+ userMemoriesIdentities.createdAt,
+ );
+ const joinCondition = and(
+ eq(userMemories.id, userMemoriesIdentities.userMemoryId),
+ eq(userMemoriesIdentities.userId, this.userId),
+ );
+
+ const identityFilters: Array<SQL | undefined> = [
+ whereClause,
+ types && types.length > 0 ? inArray(userMemoriesIdentities.type, types) : undefined,
+ tags && tags.length > 0
+ ? or(...tags.map((tag) => sql<boolean>`${tag} = ANY(${userMemoriesIdentities.tags})`))
+ : undefined,
+ ];
+ const identityWhereClause = identityFilters.some(
+ (condition): condition is SQL => condition !== undefined,
+ )
+ ? and(
+ ...(identityFilters.filter(
+ (condition): condition is SQL => condition !== undefined,
+ ) as SQL[]),
+ )
+ : undefined;
+
+ const [rows, totalResult] = await Promise.all([
+ this.db
+ .select({
+ identity: {
+ accessedAt: userMemoriesIdentities.accessedAt,
+ createdAt: userMemoriesIdentities.createdAt,
+ description: userMemoriesIdentities.description,
+ episodicDate: userMemoriesIdentities.episodicDate,
+ id: userMemoriesIdentities.id,
+ metadata: userMemoriesIdentities.metadata,
+ relationship: userMemoriesIdentities.relationship,
+ role: userMemoriesIdentities.role,
+ tags: userMemoriesIdentities.tags,
+ type: userMemoriesIdentities.type,
+ updatedAt: userMemoriesIdentities.updatedAt,
+ userId: userMemoriesIdentities.userId,
+ userMemoryId: userMemoriesIdentities.userMemoryId,
+ },
+ memory: baseSelection,
+ })
+ .from(userMemories)
+ .innerJoin(userMemoriesIdentities, joinCondition)
+ .where(identityWhereClause)
+ .orderBy(...orderByClauses)
+ .limit(normalizedPageSize)
+ .offset(offset),
+ this.db
+ .select({ count: sql<number>`COUNT(*)::int` })
+ .from(userMemories)
+ .innerJoin(userMemoriesIdentities, joinCondition)
+ .where(identityWhereClause),
+ ]);
+
+ return {
+ items: rows.map((row) => {
+ return {
+ identity: row.identity,
+ layer: LayersEnum.Identity,
+ memory: row.memory,
+ };
+ }),
+ page: normalizedPage,
+ pageSize: normalizedPageSize,
+ total: Number(totalResult[0]?.count ?? 0),
+ };
+ }
+ case LayersEnum.Preference: {
+ const orderByClauses = buildOrderBy(
+ userMemoriesPreferences.scorePriority,
+ userMemoriesPreferences.updatedAt,
+ userMemoriesPreferences.createdAt,
+ );
+ const joinCondition = and(
+ eq(userMemories.id, userMemoriesPreferences.userMemoryId),
+ eq(userMemoriesPreferences.userId, this.userId),
+ );
+
+ const preferenceFilters: Array<SQL | undefined> = [
+ whereClause,
+ types && types.length > 0 ? inArray(userMemoriesPreferences.type, types) : undefined,
+ tags && tags.length > 0
+ ? or(...tags.map((tag) => sql<boolean>`${tag} = ANY(${userMemoriesPreferences.tags})`))
+ : undefined,
+ ];
+ const preferenceWhereClause = preferenceFilters.some(
+ (condition): condition is SQL => condition !== undefined,
+ )
+ ? and(
+ ...(preferenceFilters.filter(
+ (condition): condition is SQL => condition !== undefined,
+ ) as SQL[]),
+ )
+ : undefined;
+
+ const [rows, totalResult] = await Promise.all([
+ this.db
+ .select({
+ memory: baseSelection,
+ preference: {
+ accessedAt: userMemoriesPreferences.accessedAt,
+ conclusionDirectives: userMemoriesPreferences.conclusionDirectives,
+ createdAt: userMemoriesPreferences.createdAt,
+ id: userMemoriesPreferences.id,
+ metadata: userMemoriesPreferences.metadata,
+ scorePriority: userMemoriesPreferences.scorePriority,
+ tags: userMemoriesPreferences.tags,
+ type: userMemoriesPreferences.type,
+ updatedAt: userMemoriesPreferences.updatedAt,
+ userId: userMemoriesPreferences.userId,
+ userMemoryId: userMemoriesPreferences.userMemoryId,
+ },
+ })
+ .from(userMemories)
+ .innerJoin(userMemoriesPreferences, joinCondition)
+ .where(preferenceWhereClause)
+ .orderBy(...orderByClauses)
+ .limit(normalizedPageSize)
+ .offset(offset),
+ this.db
+ .select({ count: sql<number>`COUNT(*)::int` })
+ .from(userMemories)
+ .innerJoin(userMemoriesPreferences, joinCondition)
+ .where(preferenceWhereClause),
+ ]);
+
+ return {
+ items: rows.map((row) => {
+ return {
+ layer: LayersEnum.Preference,
+ memory: row.memory,
+ preference: row.preference,
+ };
+ }),
+ page: normalizedPage,
+ pageSize: normalizedPageSize,
+ total: Number(totalResult[0]?.count ?? 0),
+ };
+ }
+ default: {
+ return {
+ items: [],
+ page: normalizedPage,
+ pageSize: normalizedPageSize,
+ total: 0,
+ };
+ }
+ }
+ };
+
+ getMemoryDetail = async (
+ params: GetMemoryDetailParams,
+ ): Promise<UserMemoryDetail | undefined> => {
+ const { id, layer } = params;
+
+ switch (layer) {
+ case LayersEnum.Context: {
+ const [context] = await this.db
+ .select({
+ accessedAt: userMemoriesContexts.accessedAt,
+ associatedObjects: userMemoriesContexts.associatedObjects,
+ associatedSubjects: userMemoriesContexts.associatedSubjects,
+ capturedAt: userMemoriesContexts.capturedAt,
+ 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,
+ })
+ .from(userMemoriesContexts)
+ .where(and(eq(userMemoriesContexts.id, id), eq(userMemoriesContexts.userId, this.userId)))
+ .limit(1);
+ if (!context) {
+ return undefined;
+ }
+
+ const memoryIds = Array.isArray(context.userMemoryIds)
+ ? (context.userMemoryIds as string[])
+ : [];
+
+ const memoryId = memoryIds[0];
+ if (!memoryId) {
+ return undefined;
+ }
+
+ const memory = await this.findUserMemoryRawById(memoryId);
+ if (!memory) {
+ return undefined;
+ }
+ if (memory.memoryLayer !== LayersEnum.Context) {
+ return undefined;
+ }
+
+ const { sourceId, sourceType } = await this.extractSourceMetadata(context.metadata);
+ const source = sourceId ? await this.topicModel.findById(sourceId) : undefined;
+
+ return {
+ context: context as UserMemoryContextWithoutVectors,
+ layer,
+ memory,
+ source,
+ sourceType,
+ };
+ }
+ case LayersEnum.Experience: {
+ const [experience] = await 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,
+ })
+ .from(userMemoriesExperiences)
+ .where(
+ and(
+ eq(userMemoriesExperiences.id, id),
+ eq(userMemoriesExperiences.userId, this.userId),
+ ),
+ )
+ .limit(1);
+ if (!experience?.userMemoryId) {
+ return undefined;
+ }
+
+ const memory = await this.findUserMemoryRawById(experience.userMemoryId);
+ if (!memory) {
+ return undefined;
+ }
+ if (memory.memoryLayer !== LayersEnum.Experience) {
+ return undefined;
+ }
+
+ const { sourceId, sourceType } = await this.extractSourceMetadata(experience.metadata);
+ const source = sourceId ? await this.topicModel.findById(sourceId) : undefined;
+
+ return {
+ experience,
+ layer,
+ memory,
+ source,
+ sourceType,
+ };
+ }
+ case LayersEnum.Identity: {
+ const [identity] = await this.db
+ .select({
+ accessedAt: userMemoriesIdentities.accessedAt,
+ createdAt: userMemoriesIdentities.createdAt,
+ description: userMemoriesIdentities.description,
+ episodicDate: userMemoriesIdentities.episodicDate,
+ id: userMemoriesIdentities.id,
+ metadata: userMemoriesIdentities.metadata,
+ relationship: userMemoriesIdentities.relationship,
+ role: userMemoriesIdentities.role,
+ tags: userMemoriesIdentities.tags,
+ type: userMemoriesIdentities.type,
+ updatedAt: userMemoriesIdentities.updatedAt,
+ userId: userMemoriesIdentities.userId,
+ userMemoryId: userMemoriesIdentities.userMemoryId,
+ })
+ .from(userMemoriesIdentities)
+ .where(
+ and(eq(userMemoriesIdentities.id, id), eq(userMemoriesIdentities.userId, this.userId)),
+ )
+ .limit(1);
+ if (!identity?.userMemoryId) {
+ return undefined;
+ }
+
+ const memory = await this.findUserMemoryRawById(identity.userMemoryId);
+ if (!memory) {
+ return undefined;
+ }
+ if (memory.memoryLayer !== LayersEnum.Identity) {
+ return undefined;
+ }
+
+ const { sourceId, sourceType } = await this.extractSourceMetadata(identity.metadata);
+ const source = sourceId ? await this.topicModel.findById(sourceId) : undefined;
+
+ return {
+ identity,
+ layer,
+ memory,
+ source,
+ sourceType,
+ };
+ }
+ case LayersEnum.Preference: {
+ const [preference] = await this.db
+ .select({
+ accessedAt: userMemoriesPreferences.accessedAt,
+ capturedAt: userMemoriesPreferences.capturedAt,
+ 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,
+ })
+ .from(userMemoriesPreferences)
+ .where(
+ and(
+ eq(userMemoriesPreferences.id, id),
+ eq(userMemoriesPreferences.userId, this.userId),
+ ),
+ )
+ .limit(1);
+ if (!preference?.userMemoryId) {
+ return undefined;
+ }
+
+ const memory = await this.findUserMemoryRawById(preference.userMemoryId);
+ if (!memory) {
+ return undefined;
+ }
+ if (memory.memoryLayer !== LayersEnum.Preference) {
+ return undefined;
+ }
+
+ const { sourceId, sourceType } = await this.extractSourceMetadata(preference.metadata);
+ const source = sourceId ? await this.topicModel.findById(sourceId) : undefined;
+
+ return {
+ layer,
+ memory,
+ preference,
+ source,
+ sourceType,
+ };
+ }
+ }
+ };
+
+ private findUserMemoryRawById = async (
+ memoryId: string,
+ ): Promise<UserMemoryWithoutVectors | undefined> => {
+ const [memory] = await this.db
+ .select({
+ accessedAt: userMemories.accessedAt,
+ accessedCount: userMemories.accessedCount,
+ capturedAt: userMemories.capturedAt,
+ createdAt: userMemories.createdAt,
+ details: userMemories.details,
+ id: userMemories.id,
+ lastAccessedAt: userMemories.lastAccessedAt,
+ memoryCategory: userMemories.memoryCategory,
+ memoryLayer: userMemories.memoryLayer,
+ memoryType: userMemories.memoryType,
+ metadata: userMemories.metadata,
+ status: userMemories.status,
+ summary: userMemories.summary,
+ tags: userMemories.tags,
+ title: userMemories.title,
+ updatedAt: userMemories.updatedAt,
+ userId: userMemories.userId,
+ })
+ .from(userMemories)
+ .where(and(eq(userMemories.id, memoryId), eq(userMemories.userId, this.userId)))
+ .limit(1);
+ if (!memory) {
+ return undefined;
+ }
+
+ return memory;
+ };
+
+ 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)),
+ });
+
+ 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,
+ capturedAt: base.capturedAt,
+ 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 = {
+ capturedAt: identity.capturedAt,
+ 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 = {
+ capturedAt: identity.capturedAt,
+ 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 (params.identity.capturedAt !== undefined) {
+ identityUpdate.capturedAt = params.identity.capturedAt;
+ }
+ }
+
+ 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;
+ });
+ };
+
+ removeContextEntry = async (contextId: string): Promise<boolean> => {
+ return this.db.transaction(async (tx) => {
+ const context = await tx.query.userMemoriesContexts.findFirst({
+ where: and(
+ eq(userMemoriesContexts.id, contextId),
+ eq(userMemoriesContexts.userId, this.userId),
+ ),
+ });
+
+ if (!context) {
+ return false;
+ }
+
+ // Delete associated user memories if any
+ const memoryIds = Array.isArray(context.userMemoryIds)
+ ? (context.userMemoryIds as string[])
+ : [];
+ if (memoryIds.length > 0) {
+ await tx
+ .delete(userMemories)
+ .where(and(inArray(userMemories.id, memoryIds), eq(userMemories.userId, this.userId)));
+ }
+
+ // Delete the context entry
+ await tx
+ .delete(userMemoriesContexts)
+ .where(
+ and(eq(userMemoriesContexts.id, contextId), eq(userMemoriesContexts.userId, this.userId)),
+ );
+
+ return true;
+ });
+ };
+
+ removeExperienceEntry = async (experienceId: string): Promise<boolean> => {
+ return this.db.transaction(async (tx) => {
+ const experience = await tx.query.userMemoriesExperiences.findFirst({
+ where: and(
+ eq(userMemoriesExperiences.id, experienceId),
+ eq(userMemoriesExperiences.userId, this.userId),
+ ),
+ });
+
+ if (!experience || !experience.userMemoryId) {
+ return false;
+ }
+
+ // Delete the base user memory (cascade will handle the experience)
+ await tx
+ .delete(userMemories)
+ .where(
+ and(eq(userMemories.id, experience.userMemoryId), eq(userMemories.userId, this.userId)),
+ );
+
+ return true;
+ });
+ };
+
+ removePreferenceEntry = async (preferenceId: string): Promise<boolean> => {
+ return this.db.transaction(async (tx) => {
+ const preference = await tx.query.userMemoriesPreferences.findFirst({
+ where: and(
+ eq(userMemoriesPreferences.id, preferenceId),
+ eq(userMemoriesPreferences.userId, this.userId),
+ ),
+ });
+
+ if (!preference || !preference.userMemoryId) {
+ return false;
+ }
+
+ // Delete the base user memory (cascade will handle the preference)
+ await tx
+ .delete(userMemories)
+ .where(
+ and(eq(userMemories.id, preference.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<UserMemoryContextWithoutVectors[]> => {
+ const { embedding, limit = 5, type } = params;
+ if (limit <= 0) {
+ return [];
+ }
+
+ let query = this.db
+ .select({
+ accessedAt: userMemoriesContexts.accessedAt,
+ associatedObjects: userMemoriesContexts.associatedObjects,
+ associatedSubjects: userMemoriesContexts.associatedSubjects,
+ capturedAt: userMemoriesContexts.capturedAt,
+ 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));
+ }
+
+ const res = (await query.limit(limit)) as UserMemoryContextWithoutVectors[];
+ return res;
+ };
+
+ searchExperiences = async (params: {
+ embedding?: number[];
+ limit?: number;
+ type?: string;
+ }): Promise<UserMemoryExperienceWithoutVectors[]> => {
+ const { embedding, limit = 5, type } = params;
+ if (limit <= 0) {
+ return [];
+ }
+
+ let query = this.db
+ .select({
+ accessedAt: userMemoriesExperiences.accessedAt,
+ action: userMemoriesExperiences.action,
+ capturedAt: userMemoriesExperiences.capturedAt,
+ 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<UserMemoryPreferenceWithoutVectors[]> => {
+ const { embedding, limit = 5, type } = params;
+ if (limit <= 0) {
+ return [];
+ }
+
+ let query = this.db
+ .select({
+ accessedAt: userMemoriesPreferences.accessedAt,
+ capturedAt: userMemoriesPreferences.capturedAt,
+ 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<UserMemoryIdentityWithoutVectors[]> => {
+ const res = await this.db
+ .select(selectNonVectorColumns(userMemoriesIdentities))
+ .from(userMemoriesIdentities)
+ .where(eq(userMemoriesIdentities.userId, this.userId))
+ .orderBy(desc(userMemoriesIdentities.createdAt));
+
+ return res;
+ };
+
+ getIdentitiesByType = async (type: string): Promise<UserMemoryIdentityWithoutVectors[]> => {
+ const res = await this.db
+ .select(selectNonVectorColumns(userMemoriesIdentities))
+ .from(userMemoriesIdentities)
+ .where(
+ and(eq(userMemoriesIdentities.userId, this.userId), eq(userMemoriesIdentities.type, type)),
+ )
+ .orderBy(desc(userMemoriesIdentities.createdAt));
+
+ return res;
+ };
+
+ private updateAccessMetrics = async (
+ memoryIds: string[],
+ options?: { contextIds?: string[]; timestamp?: Date },
+ ): Promise<void> => {
+ const contextIds = options?.contextIds ?? [];
+ const orderedMemoryIds = memoryIds.length > 1 ? [...memoryIds].sort() : memoryIds;
+ const orderedContextIds = contextIds.length > 1 ? [...contextIds].sort() : contextIds;
+
+ // Keep lock acquisition order deterministic to avoid deadlocks under concurrent updates
+ if (orderedMemoryIds.length === 0 && orderedContextIds.length === 0) return;
+
+ const now = options?.timestamp ?? new Date();
+
+ await this.db.transaction(async (tx) => {
+ if (orderedMemoryIds.length > 0) {
+ for (const memoryId of orderedMemoryIds) {
+ await tx
+ .update(userMemories)
+ .set({
+ accessedAt: now,
+ accessedCount: sql`${userMemories.accessedCount} + 1`,
+ lastAccessedAt: now,
+ })
+ .where(and(eq(userMemories.userId, this.userId), eq(userMemories.id, memoryId)));
+ }
+
+ const memories = await tx
+ .select({
+ id: userMemories.id,
+ layer: userMemories.memoryLayer,
+ })
+ .from(userMemories)
+ .where(
+ and(eq(userMemories.userId, this.userId), inArray(userMemories.id, orderedMemoryIds)),
+ );
+
+ 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 (orderedContextIds.length > 0) {
+ await tx
+ .update(userMemoriesContexts)
+ .set({ accessedAt: now })
+ .where(
+ and(
+ eq(userMemoriesContexts.userId, this.userId),
+ inArray(userMemoriesContexts.id, orderedContextIds),
+ ),
+ );
+ }
+ });
+ };
+}
diff --git a/packages/database/src/models/userMemory/preference.ts b/packages/database/src/models/userMemory/preference.ts
new file mode 100644
index 00000000000..244f3423a07
--- /dev/null
+++ b/packages/database/src/models/userMemory/preference.ts
@@ -0,0 +1,84 @@
+import { and, desc, eq } from 'drizzle-orm';
+
+import {
+ NewUserMemoryPreference,
+ UserMemoryPreference,
+ userMemories,
+ userMemoriesPreferences,
+} from '../../schemas';
+import { LobeChatDatabase } from '../../type';
+
+export class UserMemoryPreferenceModel {
+ private userId: string;
+ private db: LobeChatDatabase;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.userId = userId;
+ this.db = db;
+ }
+
+ create = async (params: Omit<NewUserMemoryPreference, 'userId'>) => {
+ const [result] = await this.db
+ .insert(userMemoriesPreferences)
+ .values({ ...params, userId: this.userId })
+ .returning();
+
+ return result;
+ };
+
+ delete = async (id: string) => {
+ return this.db.transaction(async (tx) => {
+ const preference = await tx.query.userMemoriesPreferences.findFirst({
+ where: and(
+ eq(userMemoriesPreferences.id, id),
+ eq(userMemoriesPreferences.userId, this.userId),
+ ),
+ });
+
+ if (!preference || !preference.userMemoryId) {
+ return { success: false };
+ }
+
+ // Delete the base user memory (cascade will handle the preference)
+ await tx
+ .delete(userMemories)
+ .where(
+ and(eq(userMemories.id, preference.userMemoryId), eq(userMemories.userId, this.userId)),
+ );
+
+ return { success: true };
+ });
+ };
+
+ deleteAll = async () => {
+ return this.db
+ .delete(userMemoriesPreferences)
+ .where(eq(userMemoriesPreferences.userId, this.userId));
+ };
+
+ query = async (limit = 50) => {
+ return this.db.query.userMemoriesPreferences.findMany({
+ limit,
+ orderBy: [desc(userMemoriesPreferences.createdAt)],
+ where: eq(userMemoriesPreferences.userId, this.userId),
+ });
+ };
+
+ findById = async (id: string) => {
+ return this.db.query.userMemoriesPreferences.findFirst({
+ where: and(
+ eq(userMemoriesPreferences.id, id),
+ eq(userMemoriesPreferences.userId, this.userId),
+ ),
+ });
+ };
+
+ update = async (id: string, value: Partial<UserMemoryPreference>) => {
+ return this.db
+ .update(userMemoriesPreferences)
+ .set({ ...value, updatedAt: new Date() })
+ .where(
+ and(eq(userMemoriesPreferences.id, id), eq(userMemoriesPreferences.userId, this.userId)),
+ );
+ };
+}
diff --git a/packages/database/src/repositories/userMemory/index.ts b/packages/database/src/repositories/userMemory/index.ts
new file mode 100644
index 00000000000..2cd16e135b4
--- /dev/null
+++ b/packages/database/src/repositories/userMemory/index.ts
@@ -0,0 +1,25 @@
+import {
+ UserMemoryContextsWithoutVectors,
+ UserMemoryExperiencesWithoutVectors,
+ UserMemoryIdentitiesWithoutVectors,
+ UserMemoryPreferencesWithoutVectors,
+} from '../../schemas';
+
+export interface MemorySource {
+ agentId: string | null;
+ id: string;
+ sessionId: string | null;
+ title: string | null;
+}
+
+export interface DisplayExperienceMemory extends UserMemoryExperiencesWithoutVectors {
+ title: string | null;
+}
+
+export interface DisplayPreferenceMemory extends UserMemoryPreferencesWithoutVectors {
+ title: string | null;
+}
+
+export type DisplayContextMemory = UserMemoryContextsWithoutVectors;
+
+export type DisplayIdentityMemory = UserMemoryIdentitiesWithoutVectors;
diff --git a/packages/types/src/userMemory/base.ts b/packages/types/src/userMemory/base.ts
new file mode 100644
index 00000000000..0efeb4fc318
--- /dev/null
+++ b/packages/types/src/userMemory/base.ts
@@ -0,0 +1,31 @@
+export interface UserMemory {
+ accessedAt: Date;
+ accessedCount: number | null;
+ capturedAt: Date;
+ createdAt: Date;
+ details: string | null;
+ detailsVector1024: number[] | null;
+ id: string;
+ lastAccessedAt: Date;
+ 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;
+ updatedAt: Date;
+ userId: string | null;
+}
+
+export type UserMemoryWithoutVectors = Omit<
+ UserMemory,
+ 'summaryVector1024' | 'detailsVector1024'
+>;
+
+export type UserMemoryListItem = Omit<
+ UserMemoryWithoutVectors,
+ 'details' | 'summary' | 'capturedAt'
+>;
diff --git a/packages/types/src/userMemory/identity.ts b/packages/types/src/userMemory/identity.ts
new file mode 100644
index 00000000000..22e6f3b9531
--- /dev/null
+++ b/packages/types/src/userMemory/identity.ts
@@ -0,0 +1,68 @@
+import { z } from 'zod';
+
+export type IdentityType = 'personal' | 'professional' | 'demographic';
+
+export interface UserMemoryIdentity {
+ accessedAt: Date;
+ createdAt: Date;
+ description?: string | null;
+ descriptionVector?: number[] | null;
+ episodicDate?: Date | null;
+ id: string;
+ metadata?: Record<string, unknown> | null;
+ relationship?: string | null;
+ role?: string | null;
+ tags?: string[] | null;
+ type?: string | null;
+ updatedAt: Date;
+ userId?: string | null;
+ userMemoryId?: string | null;
+}
+
+export type UserMemoryIdentityWithoutVectors = Omit<UserMemoryIdentity, 'descriptionVector'>;
+
+export type UserMemoryIdentitiesListItem = UserMemoryIdentityWithoutVectors;
+
+export interface NewUserMemoryIdentity {
+ description?: string;
+ episodicDate?: string;
+ extractedLabels?: string[];
+ labels?: Record<string, any>;
+ relationship?: string;
+ role?: string;
+ type?: IdentityType;
+ userMemoryId?: string;
+}
+
+export interface UpdateUserMemoryIdentity {
+ description?: string;
+ episodicDate?: string;
+ extractedLabels?: string[];
+ labels?: Record<string, any>;
+ relationship?: string;
+ role?: string;
+ type?: IdentityType;
+}
+
+export const IdentityTypeSchema = z.enum(['personal', 'professional', 'demographic']);
+
+export const CreateUserMemoryIdentitySchema = z.object({
+ description: z.string().optional(),
+ episodicDate: z.string().optional(),
+ extractedLabels: z.array(z.string()).optional(),
+ labels: z.record(z.any()).optional(),
+ relationship: z.string().optional(),
+ role: z.string().optional(),
+ type: IdentityTypeSchema.optional(),
+ userMemoryId: z.string().optional(),
+});
+
+export const UpdateUserMemoryIdentitySchema = z.object({
+ description: z.string().optional(),
+ episodicDate: z.string().optional(),
+ extractedLabels: z.array(z.string()).optional(),
+ labels: z.record(z.any()).optional(),
+ relationship: z.string().optional(),
+ role: z.string().optional(),
+ type: IdentityTypeSchema.optional(),
+});
diff --git a/packages/types/src/userMemory/index.ts b/packages/types/src/userMemory/index.ts
index f4835c2b72b..d4fa0f50a75 100644
--- a/packages/types/src/userMemory/index.ts
+++ b/packages/types/src/userMemory/index.ts
@@ -1,3 +1,7 @@
+export * from './base';
+export * from './identity';
export * from './layers';
+export * from './list';
export * from './shared';
export * from './tools';
+export * from './trace';
diff --git a/packages/types/src/userMemory/layers.ts b/packages/types/src/userMemory/layers.ts
index 6bae759e263..7955c9e350c 100644
--- a/packages/types/src/userMemory/layers.ts
+++ b/packages/types/src/userMemory/layers.ts
@@ -4,9 +4,25 @@ export interface UserMemoryTimestamps {
updatedAt: Date;
}
+export enum UserMemoryContextObjectType {
+ Application = 'application',
+ Item = 'item',
+ Knowledge = 'knowledge',
+ Other = 'other',
+ Person = 'person',
+ Place = 'place'
+}
+
+export enum UserMemoryContextSubjectType {
+ Item = 'item',
+ Other = 'other',
+ Person = 'person',
+ Pet = 'pet'
+}
+
export interface UserMemoryContext extends UserMemoryTimestamps {
- associatedObjects: Record<string, unknown>[] | null;
- associatedSubjects: Record<string, unknown>[] | null;
+ associatedObjects: { extra?: Record<string, unknown> | null, name?: string, type?: UserMemoryContextObjectType }[] | null;
+ associatedSubjects: { extra?: Record<string, unknown> | null, name?: string, type?: UserMemoryContextSubjectType }[] | null;
currentStatus: string | null;
description: string | null;
descriptionVector: number[] | null;
@@ -22,6 +38,17 @@ export interface UserMemoryContext extends UserMemoryTimestamps {
userMemoryIds: string[] | null;
}
+// eslint-disable-next-line @typescript-eslint/no-empty-interface
+export type UserMemoryContextWithoutVectors = Omit<
+ UserMemoryContext,
+ 'descriptionVector' | 'titleVector'
+>;
+
+export type UserMemoryContextsListItem = Omit<
+ UserMemoryContextWithoutVectors,
+ 'associatedObjects' | 'associatedSubjects'
+>;
+
export interface UserMemoryExperience extends UserMemoryTimestamps {
action: string | null;
actionVector: number[] | null;
@@ -40,6 +67,17 @@ export interface UserMemoryExperience extends UserMemoryTimestamps {
userMemoryId: string | null;
}
+// eslint-disable-next-line @typescript-eslint/no-empty-interface
+export type UserMemoryExperienceWithoutVectors = Omit<
+ UserMemoryExperience,
+ 'actionVector' | 'keyLearningVector' | 'situationVector'
+>;
+
+export type UserMemoryExperiencesListItem = Omit<
+ UserMemoryExperienceWithoutVectors,
+ 'possibleOutcome' | 'reasoning'
+>;
+
export interface UserMemoryPreference extends UserMemoryTimestamps {
conclusionDirectives: string | null;
conclusionDirectivesVector: number[] | null;
@@ -52,3 +90,14 @@ export interface UserMemoryPreference extends UserMemoryTimestamps {
userId: string | null;
userMemoryId: string | null;
}
+
+// eslint-disable-next-line @typescript-eslint/no-empty-interface
+export type UserMemoryPreferenceWithoutVectors = Omit<
+ UserMemoryPreference,
+ 'conclusionDirectivesVector'
+>;
+
+export type UserMemoryPreferencesListItem = Omit<
+ UserMemoryPreferenceWithoutVectors,
+ 'suggestions'
+>;
diff --git a/packages/types/src/userMemory/list.ts b/packages/types/src/userMemory/list.ts
new file mode 100644
index 00000000000..5b77b2da8c8
--- /dev/null
+++ b/packages/types/src/userMemory/list.ts
@@ -0,0 +1,99 @@
+import {
+ UserMemoryContextWithoutVectors,
+ UserMemoryExperienceWithoutVectors,
+ UserMemoryPreferenceWithoutVectors,
+ UserMemoryContextsListItem,
+ UserMemoryExperiencesListItem,
+ UserMemoryPreferencesListItem,
+} from './layers'
+import {
+ UserMemoryIdentityWithoutVectors,
+ UserMemoryIdentitiesListItem,
+} from './identity'
+import {
+ UserMemoryListItem,
+ UserMemoryWithoutVectors,
+} from './base'
+import { LayersEnum } from './shared';
+
+export interface TopicSource {
+ agentId: string | null;
+ id: string;
+ sessionId: string | null;
+ title: string | null;
+}
+
+// TODO: Extend to other source types later, e.g. Notion, Obsidian, YuQue
+export type MemorySource = TopicSource;
+
+export enum MemorySourceType {
+ ChatTopic = 'chat_topic',
+}
+
+export interface ContextMemorySimple {
+ context: UserMemoryContextsListItem;
+ layer: LayersEnum.Context;
+ memory: UserMemoryListItem
+}
+
+export interface ContextMemoryDetail {
+ context: UserMemoryContextWithoutVectors;
+ layer: LayersEnum.Context;
+ memory: UserMemoryWithoutVectors
+ source?: MemorySource;
+ sourceType?: MemorySourceType;
+}
+
+export interface ExperienceMemorySimple {
+ experience: UserMemoryExperiencesListItem;
+ layer: LayersEnum.Experience;
+ memory: UserMemoryListItem;
+}
+
+export interface ExperienceMemoryDetail {
+ experience: UserMemoryExperienceWithoutVectors;
+ layer: LayersEnum.Experience;
+ memory: UserMemoryWithoutVectors;
+ source?: MemorySource;
+ sourceType?: MemorySourceType;
+}
+
+export interface PreferenceMemorySimple {
+ layer: LayersEnum.Preference;
+ memory: UserMemoryListItem;
+ preference: UserMemoryPreferencesListItem;
+}
+
+export interface PreferenceMemoryDetail {
+ layer: LayersEnum.Preference;
+ memory: UserMemoryWithoutVectors;
+ preference: UserMemoryPreferenceWithoutVectors;
+ source?: MemorySource;
+ sourceType?: MemorySourceType;
+}
+
+export interface IdentityMemorySimple {
+ identity: UserMemoryIdentitiesListItem;
+ layer: LayersEnum.Identity;
+ memory: UserMemoryListItem;
+}
+
+export interface IdentityMemoryDetail {
+ identity: UserMemoryIdentityWithoutVectors;
+ layer: LayersEnum.Identity;
+ memory: UserMemoryWithoutVectors;
+ source?: MemorySource;
+ sourceType?: MemorySourceType;
+}
+
+export type UserMemoryItemSimple =
+ | ContextMemorySimple
+ | ExperienceMemorySimple
+ | IdentityMemorySimple
+ | PreferenceMemorySimple;
+
+export type UserMemoryDetail =
+ | ContextMemoryDetail
+ | ExperienceMemoryDetail
+ | IdentityMemoryDetail
+ | PreferenceMemoryDetail;
diff --git a/packages/types/src/userMemory/server.ts b/packages/types/src/userMemory/server.ts
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/packages/types/src/userMemory/shared.ts b/packages/types/src/userMemory/shared.ts
index cf3d5b18cb1..70a5c64954f 100644
--- a/packages/types/src/userMemory/shared.ts
+++ b/packages/types/src/userMemory/shared.ts
@@ -43,7 +43,6 @@ export enum IdentityTypeEnum {
}
export enum LayersEnum {
- Activity = 'activity',
Context = 'context',
Experience = 'experience',
Identity = 'identity',
@@ -62,3 +61,12 @@ export enum TypesEnum {
Technology = 'technology',
Topic = 'topic',
}
+
+export enum ContextStatusEnum {
+ Aborted = 'aborted',
+ Cancelled = 'cancelled',
+ Completed = 'completed',
+ OnHold = 'on_hold',
+ Ongoing = 'ongoing',
+ Planned = 'planned'
+}
diff --git a/packages/types/src/userMemory/tools.ts b/packages/types/src/userMemory/tools.ts
index 7814aad5f7b..d15a6f9482d 100644
--- a/packages/types/src/userMemory/tools.ts
+++ b/packages/types/src/userMemory/tools.ts
@@ -1,218 +1,6 @@
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
@@ -229,12 +17,47 @@ export const searchMemorySchema = z.object({
export type SearchMemoryParams = z.infer<typeof searchMemorySchema>;
export interface SearchMemoryResult {
- contexts: Array<Omit<UserMemoryContext, 'userId' | 'descriptionVector'>>;
+ contexts: Array<Omit<UserMemoryContext, 'userId' | 'titleVector' | 'descriptionVector'>>;
experiences: Array<
Omit<UserMemoryExperience, 'userId' | 'actionVector' | 'situationVector' | 'keyLearningVector'>
>;
preferences: Array<Omit<UserMemoryPreference, 'userId' | 'conclusionDirectivesVector'>>;
}
+interface MemoryToolBaseResult {
+ message: string;
+ success: boolean;
+}
+
+export interface AddContextMemoryResult extends MemoryToolBaseResult {
+ contextId?: string;
+ memoryId?: string;
+}
+
+export interface AddExperienceMemoryResult extends MemoryToolBaseResult {
+ experienceId?: string;
+ memoryId?: string;
+}
+
+export interface AddIdentityMemoryResult extends MemoryToolBaseResult {
+ identityId?: string;
+ memoryId?: string;
+}
+
+export interface AddPreferenceMemoryResult extends MemoryToolBaseResult {
+ memoryId?: string;
+ preferenceId?: string;
+}
+
+export interface RemoveIdentityMemoryResult extends MemoryToolBaseResult {
+ identityId?: string;
+ reason?: string;
+}
+
+export interface UpdateIdentityMemoryResult extends MemoryToolBaseResult {
+ identityId?: string;
+}
+
+// Aliases for retrieval (search) usage
export type RetrieveMemoryParams = SearchMemoryParams;
export type RetrieveMemoryResult = SearchMemoryResult;
diff --git a/packages/types/src/userMemory/trace.ts b/packages/types/src/userMemory/trace.ts
new file mode 100644
index 00000000000..1b4fc81027c
--- /dev/null
+++ b/packages/types/src/userMemory/trace.ts
@@ -0,0 +1,90 @@
+import type { LayersEnum } from './shared';
+
+export type MemoryExtractionAgent =
+ | 'gatekeeper'
+ | 'layer-context'
+ | 'layer-experience'
+ | 'layer-identity'
+ | 'layer-preference';
+
+export type MemoryExtractionSourceType = 'chat_topic' | 'lark' | 'notion' | 'obsidian';
+
+export interface MemoryExtractionTraceError {
+ message: string;
+ name?: string;
+ stack?: string;
+}
+
+export interface MemoryExtractionAgentCallTrace<TRequest = unknown, TResponse = unknown> {
+ durationMs?: number;
+ error?: MemoryExtractionTraceError;
+ request?: TRequest;
+ response?: TResponse;
+}
+
+export interface MemoryExtractionTraceBuiltContexts {
+ retrievalMemoryContext?: unknown;
+ retrievedIdentityContext?: unknown;
+ topicContext?: unknown;
+}
+
+export interface MemoryExtractionTraceTrimmedContexts {
+ retrievedContexts?: string[];
+ retrievedIdentitiesContext?: string;
+}
+
+export interface MemoryExtractionTraceContexts {
+ built?: MemoryExtractionTraceBuiltContexts;
+ trimmed?: MemoryExtractionTraceTrimmedContexts;
+}
+
+export interface MemoryExtractionTraceJob {
+ force?: boolean;
+ layers?: LayersEnum[];
+ source: MemoryExtractionSourceType;
+ sourceId: string;
+ sourceUpdatedAt?: string | Date;
+ userId: string;
+}
+
+export interface MemoryExtractionTracePersistedResult {
+ createdIds: string[];
+ layers: Partial<Record<LayersEnum, number>>;
+}
+
+export interface MemoryExtractionTraceMemories {
+ identities?: unknown;
+ layers?: unknown;
+}
+
+export interface MemoryExtractionTraceSource {
+ chatTopic?: {
+ conversations?: unknown;
+ topic?: unknown;
+ };
+}
+
+export interface MemoryExtractionTraceResult<TExtraction = unknown> {
+ extraction?: TExtraction | null;
+ persisted?: MemoryExtractionTracePersistedResult | null;
+}
+
+export interface MemoryExtractionTracePayload<
+ TExtraction = unknown,
+ TJob extends MemoryExtractionTraceJob | null = MemoryExtractionTraceJob | null,
+ TRequest = unknown,
+ TResponse = unknown,
+> {
+ agentCalls: Partial<
+ Record<MemoryExtractionAgent, MemoryExtractionAgentCallTrace<TRequest, TResponse>>
+ >;
+ contexts?: MemoryExtractionTraceContexts;
+ error?: MemoryExtractionTraceError;
+ extractionJob?: TJob;
+ memories?: MemoryExtractionTraceMemories;
+ result?: MemoryExtractionTraceResult<TExtraction>;
+ source?: MemoryExtractionTraceSource;
+ sourceType?: MemoryExtractionSourceType;
+ userId?: string;
+ userState?: unknown;
+}
diff --git a/src/server/services/memory/userMemory/extract.ts b/src/server/services/memory/userMemory/extract.ts
new file mode 100644
index 00000000000..d45a43aaa45
--- /dev/null
+++ b/src/server/services/memory/userMemory/extract.ts
@@ -0,0 +1,1613 @@
+import {
+ DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,
+ DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM,
+} from '@lobechat/const';
+import { messages, topics } from '@lobechat/database/schemas';
+import {
+ LobeChatTopicContextProvider,
+ LobeChatTopicResultRecorder,
+ MemoryExtractionService,
+ RetrievalUserMemoryContextProvider,
+ RetrievalUserMemoryIdentitiesProvider,
+} from '@lobechat/memory-user-memory';
+import type {
+ MemoryExtractionAgent,
+ MemoryExtractionJob,
+ MemoryExtractionResult,
+ MemoryExtractionSourceType,
+ PersistedMemoryResult,
+} from '@lobechat/memory-user-memory';
+import { ModelRuntime } from '@lobechat/model-runtime';
+import type {
+ Embeddings,
+ GenerateObjectPayload,
+ LLMRoleType,
+ OpenAIChatMessage,
+} from '@lobechat/model-runtime';
+import { SpanStatusCode } from '@lobechat/observability-otel/api';
+import {
+ ATTR_GEN_AI_OPERATION_NAME,
+ ATTR_GEN_AI_REQUEST_MODEL,
+} from '@lobechat/observability-otel/gen-ai';
+import {
+ layerEntriesHistogram,
+ processedDurationHistogram,
+ processedSourceCounter,
+ tracer,
+} from '@lobechat/observability-otel/modules/memory-user-memory';
+import { attributesCommon } from '@lobechat/observability-otel/node';
+import type {
+ MemoryExtractionAgentCallTrace,
+ MemoryExtractionTraceError,
+ MemoryExtractionTracePayload,
+} from '@lobechat/types';
+import { Client } from '@upstash/workflow';
+import { and, asc, eq, inArray } from 'drizzle-orm';
+import { join } from 'pathe';
+import { z } from 'zod';
+
+import type { ListTopicsForMemoryExtractorCursor } from '@/database/models/topic';
+import { TopicModel } from '@/database/models/topic';
+import type { ListUsersForMemoryExtractorCursor } from '@/database/models/user';
+import { UserModel } from '@/database/models/user';
+import { UserMemoryModel } from '@/database/models/userMemory';
+import { getServerDB } from '@/database/server';
+import { getServerGlobalConfig } from '@/server/globalConfig';
+import {
+ MemoryAgentConfig,
+ parseMemoryExtractionConfig,
+} from '@/server/globalConfig/parseMemoryExtractionConfig';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { S3 } from '@/server/modules/S3';
+import type { GlobalMemoryLayer } from '@/types/serverConfig';
+import type { UserKeyVaults } from '@/types/user/settings';
+import { LayersEnum, MergeStrategyEnum, TypesEnum } from '@/types/userMemory';
+import { encodeAsync } from '@/utils/tokenizer';
+
+const SOURCE_ALIAS_MAP: Record<string, MemoryExtractionSourceType> = {
+ chatTopic: 'chat_topic',
+ chatTopics: 'chat_topic',
+ chat_topic: 'chat_topic',
+ lark: 'lark',
+ notion: 'notion',
+ obsidian: 'obsidian',
+};
+
+const LAYER_ALIAS = new Set<LayersEnum>([
+ LayersEnum.Context,
+ LayersEnum.Experience,
+ LayersEnum.Identity,
+ LayersEnum.Preference,
+]);
+
+const LAYER_LABEL_MAP: Record<LayersEnum, string> = {
+ [LayersEnum.Context]: 'contexts',
+ [LayersEnum.Experience]: 'experiences',
+ [LayersEnum.Identity]: 'identities',
+ [LayersEnum.Preference]: 'preferences',
+};
+
+export interface MemoryExtractionWorkflowCursor {
+ createdAt: string;
+ id: string;
+}
+
+export interface TopicWorkflowCursor extends MemoryExtractionWorkflowCursor {
+ userId: string;
+}
+
+export interface MemoryExtractionNormalizedPayload {
+ baseUrl: string;
+ forceAll: boolean;
+ forceTopics: boolean;
+ from?: Date;
+ layers: LayersEnum[];
+ /**
+ * - `workflow` depends on Upstash Workflows to process the extraction asynchronously.
+ * - `direct` processes the extraction within the webhook request itself.
+ */
+ mode: 'workflow' | 'direct';
+ sources: MemoryExtractionSourceType[];
+ to?: Date;
+ topicCursor?: TopicWorkflowCursor;
+ topicIds: string[];
+ userCursor?: MemoryExtractionWorkflowCursor;
+ userId?: string;
+ userIds: string[];
+}
+
+export const memoryExtractionPayloadSchema = z.object({
+ baseUrl: z.string().url().optional(),
+ forceAll: z.boolean().optional(),
+ forceTopics: z.boolean().optional(),
+ fromDate: z.coerce.date().optional(),
+ layers: z.array(z.string()).optional(),
+ mode: z.enum(['workflow', 'direct']).optional(),
+ sources: z.array(z.string()).optional(),
+ toDate: z.coerce.date().optional(),
+ topicCursor: z
+ .object({
+ createdAt: z.string(),
+ id: z.string(),
+ userId: z.string(),
+ })
+ .optional(),
+ topicIds: z.array(z.string()).optional(),
+ userCursor: z
+ .object({
+ createdAt: z.string(),
+ id: z.string(),
+ })
+ .optional(),
+ userId: z.string().optional(),
+ userIds: z.array(z.string()).optional(),
+});
+
+export type MemoryExtractionPayloadInput = z.infer<typeof memoryExtractionPayloadSchema>;
+
+const normalizeSources = (sources?: string[]): MemoryExtractionSourceType[] => {
+ if (!sources) return [];
+
+ const normalized = sources
+ .map((source) => SOURCE_ALIAS_MAP[source as keyof typeof SOURCE_ALIAS_MAP])
+ .filter(Boolean) as MemoryExtractionSourceType[];
+
+ return Array.from(new Set(normalized));
+};
+
+const normalizeLayers = (layers?: string[]): LayersEnum[] => {
+ if (!layers) return [];
+
+ const normalized = layers
+ .map((layer) => layer.toLowerCase() as LayersEnum)
+ .filter((layer) => LAYER_ALIAS.has(layer));
+
+ return Array.from(new Set(normalized));
+};
+
+export const normalizeMemoryExtractionPayload = (
+ payload: MemoryExtractionPayloadInput,
+ fallbackBaseUrl?: string,
+): MemoryExtractionNormalizedPayload => {
+ const parsed = memoryExtractionPayloadSchema.parse(payload);
+ const baseUrl = parsed.baseUrl || fallbackBaseUrl;
+ if (!baseUrl) throw new Error('Missing baseUrl for workflow trigger');
+
+ return {
+ baseUrl,
+ forceAll: parsed.forceAll ?? false,
+ forceTopics: parsed.forceTopics ?? false,
+ from: parsed.fromDate,
+ layers: normalizeLayers(parsed.layers),
+ mode: parsed.mode ?? 'workflow',
+ sources: normalizeSources(parsed.sources),
+ to: parsed.toDate,
+ topicCursor: parsed.topicCursor,
+ topicIds: Array.from(new Set(parsed.topicIds || [])).filter(Boolean),
+ userCursor: parsed.userCursor,
+ userId: parsed.userId ?? parsed.userIds?.[0],
+ userIds: Array.from(
+ new Set([...(parsed.userIds || []), ...(parsed.userId ? [parsed.userId] : [])]),
+ ).filter(Boolean),
+ };
+};
+
+export type UserTopicWorkflowPayload = MemoryExtractionPayloadInput;
+
+export interface TopicBatchWorkflowPayload extends MemoryExtractionPayloadInput {
+ topicIds: string[];
+ userId: string;
+}
+
+export const buildWorkflowPayloadInput = (
+ payload: MemoryExtractionNormalizedPayload,
+): MemoryExtractionPayloadInput => ({
+ baseUrl: payload.baseUrl,
+ forceAll: payload.forceAll,
+ forceTopics: payload.forceTopics,
+ fromDate: payload.from,
+ layers: payload.layers,
+ mode: payload.mode,
+ sources: payload.sources,
+ toDate: payload.to,
+ topicCursor: payload.topicCursor,
+ topicIds: payload.topicIds,
+ userCursor: payload.userCursor,
+ userId: payload.userId ?? payload.userIds[0],
+ userIds: payload.userIds,
+});
+
+const normalizeProvider = (provider: string) => provider.toLowerCase() as keyof UserKeyVaults;
+
+const extractCredentialsFromVault = (provider: string, keyVaults?: UserKeyVaults) => {
+ const vault = keyVaults?.[normalizeProvider(provider)];
+
+ if (!vault || typeof vault !== 'object') return {};
+
+ const apiKey = 'apiKey' in vault && typeof vault.apiKey === 'string' ? vault.apiKey : undefined;
+ const baseURL =
+ 'baseURL' in vault && typeof vault.baseURL === 'string' ? vault.baseURL : undefined;
+
+ return { apiKey, baseURL };
+};
+
+const serializeError = (error: unknown): MemoryExtractionTraceError => {
+ if (error instanceof Error) {
+ return { message: error.message, name: error.name, stack: error.stack };
+ }
+
+ try {
+ return { message: JSON.stringify(error) };
+ } catch {
+ return { message: String(error) };
+ }
+};
+
+const resolveLayerModels = (
+ layers: Partial<Record<GlobalMemoryLayer, string>> | undefined,
+ fallback: Record<GlobalMemoryLayer, string>,
+): Record<LayersEnum, string> => ({
+ context: layers?.context ?? fallback.context,
+ experience: layers?.experience ?? fallback.experience,
+ identity: layers?.identity ?? fallback.identity,
+ preference: layers?.preference ?? fallback.preference,
+});
+
+const initRuntimeForAgent = async (agent: MemoryAgentConfig, keyVaults?: UserKeyVaults) => {
+ const provider = agent.provider || 'openai';
+ const { apiKey: userApiKey, baseURL: userBaseURL } = extractCredentialsFromVault(
+ provider,
+ keyVaults,
+ );
+
+ const apiKey = userApiKey || agent.apiKey;
+ if (!apiKey) throw new Error(`Missing API key for ${provider} memory extraction runtime`);
+
+ return ModelRuntime.initializeWithProvider(provider, {
+ apiKey,
+ baseURL: userBaseURL || agent.baseURL,
+ });
+};
+
+const isTopicExtracted = (metadata: any): boolean => {
+ const extractStatus = metadata?.memory_user_memory_extract?.extract_status;
+ if (extractStatus) return extractStatus === 'completed';
+
+ const state = metadata?.memoryExtraction?.sources?.chat_topic;
+ return state?.status === 'completed' && !!state?.lastRunAt;
+};
+
+type RuntimeBundle = {
+ embeddings: ModelRuntime;
+ gatekeeper: ModelRuntime;
+ layerExtractor: ModelRuntime;
+};
+
+export interface TopicExtractionJob {
+ forceAll: boolean;
+ forceTopics: boolean;
+ from?: Date;
+ layers: LayersEnum[];
+ source: MemoryExtractionSourceType;
+ to?: Date;
+ topicId: string;
+ userId: string;
+}
+
+export interface TopicPaginationJob {
+ cursor?: ListTopicsForMemoryExtractorCursor;
+ forceAll: boolean;
+ forceTopics: boolean;
+ from?: Date;
+ to?: Date;
+ userId: string;
+}
+
+export interface UserPaginationResult {
+ cursor?: ListUsersForMemoryExtractorCursor;
+ ids: string[];
+}
+
+type MemoryExtractionConfig = ReturnType<typeof parseMemoryExtractionConfig>;
+type ServerConfig = Awaited<ReturnType<typeof getServerGlobalConfig>>;
+
+export class MemoryExtractionExecutor {
+ private readonly privateConfig: MemoryExtractionConfig;
+ private readonly modelConfig: {
+ embeddingsModel: string;
+ gateModel: string;
+ layerModels: Partial<Record<LayersEnum, string>>;
+ observabilityS3: MemoryExtractionConfig['observabilityS3'];
+ };
+ private readonly embeddingContextLimit?: number;
+
+ private readonly runtimeCache = new Map<string, RuntimeBundle>();
+ private readonly db = getServerDB();
+
+ private constructor(serverConfig: ServerConfig, privateConfig: MemoryExtractionConfig) {
+ this.privateConfig = privateConfig;
+
+ const publicMemoryConfig = serverConfig.memory?.userMemory;
+
+ this.modelConfig = {
+ embeddingsModel:
+ publicMemoryConfig?.embedding?.model ??
+ privateConfig.embedding?.model ??
+ privateConfig.agentLayerExtractor.model ??
+ DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM.model,
+ gateModel: publicMemoryConfig?.agentGateKeeper?.model ?? privateConfig.agentGateKeeper.model,
+ layerModels: resolveLayerModels(
+ publicMemoryConfig?.agentLayerExtractor.layers,
+ privateConfig.agentLayerExtractor.layers,
+ ),
+ observabilityS3: privateConfig.observabilityS3,
+ };
+
+ this.embeddingContextLimit =
+ privateConfig.embedding?.contextLimit ?? privateConfig.agentLayerExtractor.contextLimit;
+ }
+
+ static async create() {
+ const [serverConfig, privateConfig] = await Promise.all([
+ getServerGlobalConfig(),
+ Promise.resolve(parseMemoryExtractionConfig()),
+ ]);
+
+ return new MemoryExtractionExecutor(serverConfig, privateConfig);
+ }
+
+ private buildBaseMetadata(
+ job: MemoryExtractionJob,
+ messageIds: string[],
+ layer: LayersEnum,
+ labels?: string[] | null,
+ ) {
+ return {
+ labels: labels ?? undefined,
+ layer,
+ messageIds,
+ source: job.source,
+ sourceId: job.sourceId,
+ };
+ }
+
+ private async countTokens(text: string) {
+ const normalized = text.trim();
+ if (!normalized) return 0;
+
+ return await encodeAsync(normalized);
+ }
+
+ private trimTextToTokenLimit(text: string, tokenLimit?: number) {
+ if (!tokenLimit || tokenLimit <= 0) return text;
+
+ const tokens = text.split(/\s+/);
+ if (tokens.length <= tokenLimit) return text;
+
+ return tokens.slice(Math.max(tokens.length - tokenLimit, 0)).join(' ');
+ }
+
+ private async trimConversationsToTokenLimit<T extends OpenAIChatMessage>(
+ conversations: (T & { createdAt: Date })[],
+ tokenLimit?: number,
+ ) {
+ if (!tokenLimit || tokenLimit <= 0) return conversations;
+
+ let remaining = tokenLimit;
+ const trimmed: (T & { createdAt: Date })[] = [];
+
+ for (let i = conversations.length - 1; i >= 0 && remaining > 0; i -= 1) {
+ const conversation = conversations[i];
+ // TODO: we might need to think about how to deal with non-string contents
+ // as multi-modal models become more prevalent
+ const content =
+ typeof conversation.content === 'string'
+ ? conversation.content
+ : JSON.stringify(conversation.content);
+
+ const tokenCount = await this.countTokens(content);
+ if (tokenCount <= remaining) {
+ trimmed.push(conversation);
+ remaining -= tokenCount;
+ continue;
+ }
+
+ const trimmedContent =
+ typeof conversation.content === 'string'
+ ? this.trimTextToTokenLimit(conversation.content, remaining)
+ : conversation.content;
+
+ if (trimmedContent && remaining > 0) {
+ trimmed.push({ ...conversation, content: trimmedContent });
+ }
+
+ break;
+ }
+
+ return trimmed.reverse();
+ }
+
+ private async generateEmbeddings(
+ runtimes: ModelRuntime,
+ model: string,
+ texts: Array<string | undefined | null>,
+ tokenLimit?: number,
+ ) {
+ const attributes = {
+ [ATTR_GEN_AI_OPERATION_NAME]: 'embed',
+ [ATTR_GEN_AI_REQUEST_MODEL]: model,
+ memory_embedding_token_limit: tokenLimit ?? undefined,
+ ...attributesCommon(),
+ };
+
+ return tracer.startActiveSpan('gen_ai.embed', { attributes }, async (span) => {
+ const requests = texts
+ .map((text, index) => {
+ if (typeof text !== 'string') return null;
+
+ const trimmed = this.trimTextToTokenLimit(text, tokenLimit);
+ if (!trimmed.trim()) return null;
+
+ return { index, text: trimmed };
+ })
+ .filter(Boolean);
+
+ span.setAttribute('memory.embedding.text_count', texts.length);
+ span.setAttribute('memory.embedding.request_count', requests.length);
+
+ if (requests.length === 0) {
+ span.setStatus({ code: SpanStatusCode.OK, message: 'empty_requests' });
+ span.end();
+ return texts.map(() => null);
+ }
+
+ try {
+ const response = await runtimes.embeddings(
+ {
+ dimensions: DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,
+ input: requests.map((item) => item!.text),
+ model,
+ },
+ { user: 'memory-extraction' },
+ );
+
+ const vectors = texts.map<Embeddings | null>(() => null);
+ response?.forEach((embedding, idx) => {
+ const request = requests[idx];
+ if (request) {
+ vectors[request.index] = embedding;
+ }
+ });
+
+ span.setAttribute('memory.embedding.response_count', response?.length ?? 0);
+ span.setStatus({ code: SpanStatusCode.OK });
+
+ return vectors;
+ } catch (error) {
+ span.setStatus({
+ code: SpanStatusCode.ERROR,
+ message: error instanceof Error ? error.message : 'Failed to generate embeddings',
+ });
+ span.recordException(error as Error);
+
+ return texts.map(() => null);
+ } finally {
+ span.end();
+ }
+ });
+ }
+
+ async persistContextMemories(
+ job: MemoryExtractionJob,
+ messageIds: string[],
+ result: NonNullable<MemoryExtractionResult['outputs']['context']>['data'],
+ runtime: ModelRuntime,
+ model: string,
+ tokenLimit: number | undefined,
+ db: Awaited<ReturnType<typeof getServerDB>>,
+ ) {
+ const insertedIds: string[] = [];
+ const userMemoryModel = new UserMemoryModel(db, job.userId);
+
+ for (const item of result?.memories ?? []) {
+ const [summaryVector, detailsVector, descriptionVector] = await this.generateEmbeddings(
+ runtime,
+ model,
+ [item.summary, item.details, item.withContext?.description],
+ tokenLimit,
+ );
+ const baseMetadata = this.buildBaseMetadata(
+ job,
+ messageIds,
+ LayersEnum.Context,
+ item.withContext?.labels,
+ );
+
+ const { memory } = await userMemoryModel.createContextMemory({
+ capturedAt: job.sourceUpdatedAt,
+ context: {
+ associatedObjects: UserMemoryModel.parseAssociatedObjects(
+ item.withContext?.associatedObjects,
+ ),
+ associatedSubjects: UserMemoryModel.parseAssociatedObjects(
+ item.withContext?.associatedSubjects,
+ ),
+ capturedAt: job.sourceUpdatedAt,
+ currentStatus: item.withContext?.currentStatus ?? null,
+ description: item.withContext?.description ?? null,
+ descriptionVector: descriptionVector || null,
+ metadata: baseMetadata,
+ scoreImpact: item.withContext?.scoreImpact ?? null,
+ scoreUrgency: item.withContext?.scoreUrgency ?? null,
+ tags: item.withContext?.labels ?? null,
+ title: item.withContext?.title ?? null,
+ type: item.withContext?.type ?? null,
+ },
+ details: item.details ?? '',
+ detailsEmbedding: detailsVector ?? undefined,
+ memoryCategory: item.memoryCategory ?? null,
+ memoryLayer: (item.memoryLayer as LayersEnum) ?? LayersEnum.Context,
+ memoryType: (item.memoryType as TypesEnum) ?? TypesEnum.Context,
+ summary: item.summary ?? '',
+ summaryEmbedding: summaryVector ?? undefined,
+ title: item.title ?? '',
+ });
+
+ insertedIds.push(memory.id);
+ }
+
+ return insertedIds;
+ }
+
+ async persistExperienceMemories(
+ job: MemoryExtractionJob,
+ messageIds: string[],
+ result: NonNullable<MemoryExtractionResult['outputs']['experience']>['data'],
+ runtime: ModelRuntime,
+ model: string,
+ tokenLimit: number | undefined,
+ db: Awaited<ReturnType<typeof getServerDB>>,
+ ) {
+ const insertedIds: string[] = [];
+ const userMemoryModel = new UserMemoryModel(db, job.userId);
+
+ for (const item of result?.memories ?? []) {
+ const [summaryVector, detailsVector, situationVector, actionVector, keyLearningVector] =
+ await this.generateEmbeddings(
+ runtime,
+ model,
+ [
+ item.summary,
+ item.details,
+ item.withExperience?.situation,
+ item.withExperience?.action,
+ item.withExperience?.keyLearning,
+ ],
+ tokenLimit,
+ );
+ const baseMetadata = this.buildBaseMetadata(
+ job,
+ messageIds,
+ LayersEnum.Experience,
+ item.withExperience?.labels,
+ );
+
+ const { memory } = await userMemoryModel.createExperienceMemory({
+ capturedAt: job.sourceUpdatedAt,
+ details: item.details ?? '',
+ detailsEmbedding: detailsVector ?? undefined,
+ experience: {
+ action: item.withExperience?.action ?? null,
+ actionVector: actionVector || null,
+ capturedAt: job.sourceUpdatedAt,
+ keyLearning: item.withExperience?.keyLearning ?? null,
+ keyLearningVector: keyLearningVector || null,
+ metadata: baseMetadata,
+ possibleOutcome: item.withExperience?.possibleOutcome ?? null,
+ reasoning: item.withExperience?.reasoning ?? null,
+ scoreConfidence: item.withExperience?.scoreConfidence ?? null,
+ situation: item.withExperience?.situation ?? null,
+ situationVector: situationVector || null,
+ tags: item.withExperience?.labels ?? null,
+ type: item.withExperience?.type ?? null,
+ },
+ memoryCategory: item.memoryCategory ?? null,
+ memoryLayer: (item.memoryLayer as LayersEnum) ?? LayersEnum.Experience,
+ memoryType: (item.memoryType as TypesEnum) ?? TypesEnum.Activity,
+ summary: item.summary ?? '',
+ summaryEmbedding: summaryVector ?? undefined,
+ title: item.title ?? '',
+ });
+
+ insertedIds.push(memory.id);
+ }
+
+ return insertedIds;
+ }
+
+ async persistPreferenceMemories(
+ job: MemoryExtractionJob,
+ messageIds: string[],
+ result: NonNullable<MemoryExtractionResult['outputs']['preference']>['data'],
+ runtime: ModelRuntime,
+ model: string,
+ tokenLimit: number | undefined,
+ db: Awaited<ReturnType<typeof getServerDB>>,
+ ) {
+ const insertedIds: string[] = [];
+ const userMemoryModel = new UserMemoryModel(db, job.userId);
+
+ for (const item of result?.memories ?? []) {
+ const [summaryVector, detailsVector, directiveVector] = await this.generateEmbeddings(
+ runtime,
+ model,
+ [item.summary, item.details, item.withPreference?.conclusionDirectives],
+ tokenLimit,
+ );
+ const baseMetadata = this.buildBaseMetadata(
+ job,
+ messageIds,
+ LayersEnum.Preference,
+ item.withPreference?.extractedLabels,
+ );
+
+ const { memory } = await userMemoryModel.createPreferenceMemory({
+ capturedAt: job.sourceUpdatedAt,
+ details: item.details ?? '',
+ detailsEmbedding: detailsVector ?? undefined,
+ memoryCategory: item.memoryCategory ?? null,
+ memoryLayer: (item.memoryLayer as LayersEnum) ?? LayersEnum.Preference,
+ memoryType: (item.memoryType as TypesEnum) ?? TypesEnum.Preference,
+ preference: {
+ capturedAt: job.sourceUpdatedAt,
+ conclusionDirectives: item.withPreference?.conclusionDirectives ?? null,
+ conclusionDirectivesVector: directiveVector ?? null,
+ metadata: {
+ ...baseMetadata,
+ scopes: item.withPreference?.extractedScopes ?? undefined,
+ },
+ scorePriority: item.withPreference?.scorePriority ?? null,
+ suggestions: item.withPreference?.suggestions?.join('\n') ?? null,
+ tags: item.withPreference?.extractedLabels ?? null,
+ type: item.withPreference?.type ?? null,
+ },
+ summary: item.summary ?? '',
+ summaryEmbedding: summaryVector ?? undefined,
+ title: item.title ?? '',
+ });
+
+ insertedIds.push(memory.id);
+ }
+
+ return insertedIds;
+ }
+
+ async persistIdentityMemories(
+ job: MemoryExtractionJob,
+ messageIds: string[],
+ result: NonNullable<MemoryExtractionResult['outputs']['identity']>['data'],
+ runtime: ModelRuntime,
+ model: string,
+ tokenLimit: number | undefined,
+ db: Awaited<ReturnType<typeof getServerDB>>,
+ ) {
+ const insertedIds: string[] = [];
+ const userMemoryModel = new UserMemoryModel(db, job.userId);
+
+ const addActions = result?.add ?? [];
+ const updateActions = result?.update ?? [];
+ const removeActions = result?.remove ?? [];
+
+ for (const action of addActions) {
+ const [summaryVector, detailsVector, descriptionVector] = await this.generateEmbeddings(
+ runtime,
+ model,
+ [action.summary, action.details, action.withIdentity.description],
+ tokenLimit,
+ );
+ const metadata = this.buildBaseMetadata(
+ job,
+ messageIds,
+ LayersEnum.Identity,
+ action.withIdentity?.extractedLabels,
+ );
+
+ const res = await userMemoryModel.addIdentityEntry({
+ base: {
+ capturedAt: job.sourceUpdatedAt,
+ details: action.withIdentity.description,
+ detailsVector1024: detailsVector ?? undefined,
+ memoryCategory: 'people',
+ memoryLayer: LayersEnum.Identity,
+ memoryType: TypesEnum.People,
+ metadata,
+ summary: action.withIdentity.description,
+ summaryVector1024: summaryVector ?? undefined,
+ },
+ identity: {
+ capturedAt: job.sourceUpdatedAt,
+ description: action.withIdentity.description,
+ descriptionVector: descriptionVector ?? undefined,
+ metadata,
+ relationship: action.withIdentity.relationship ?? undefined,
+ role: action.withIdentity.role ?? undefined,
+ tags: action.withIdentity.extractedLabels ?? undefined,
+ type: action.withIdentity.type ?? undefined,
+ },
+ });
+
+ insertedIds.push(res.userMemoryId);
+ }
+
+ for (const action of updateActions) {
+ const { set } = action;
+
+ const [summaryVector, detailsVector, descriptionVector] = set.withIdentity?.description
+ ? await this.generateEmbeddings(
+ runtime,
+ model,
+ [set.summary, set.details, set.withIdentity.description],
+ tokenLimit,
+ )
+ : [];
+
+ await userMemoryModel.updateIdentityEntry({
+ base: {
+ capturedAt: job.sourceUpdatedAt,
+ details: set.details,
+ detailsVector1024: detailsVector ?? undefined,
+ memoryCategory: set.memoryCategory,
+ memoryType: set.memoryType,
+ summary: set.summary,
+ summaryVector1024: summaryVector ?? undefined,
+ tags: set.tags,
+ title: set.title,
+ },
+ identity: {
+ capturedAt: job.sourceUpdatedAt,
+ description: set.withIdentity?.description,
+ descriptionVector: descriptionVector ?? undefined,
+ metadata: set.withIdentity.extractedLabels
+ ? this.buildBaseMetadata(
+ job,
+ messageIds,
+ LayersEnum.Identity,
+ set.withIdentity.extractedLabels,
+ )
+ : undefined,
+ relationship: set.withIdentity.relationship ?? undefined,
+ role: set.withIdentity.role ?? undefined,
+ type: set.withIdentity.type ?? undefined,
+ },
+ identityId: action.id,
+ mergeStrategy: action.mergeStrategy as MergeStrategyEnum,
+ });
+ }
+
+ for (const action of removeActions) {
+ await userMemoryModel.removeIdentityEntry(action.id);
+ }
+
+ return insertedIds;
+ }
+
+ async listConversationsForTopic(userId: string, topicId: string, topicUpdatedAt: Date) {
+ const db = await this.db;
+ const rows = await db
+ .select({
+ content: messages.content,
+ createdAt: messages.createdAt,
+ id: messages.id,
+ role: messages.role,
+ })
+ .from(messages)
+ .where(and(eq(messages.userId, userId), eq(messages.topicId, topicId)))
+ .orderBy(asc(messages.createdAt));
+
+ const conversation = rows
+ .filter((row) => typeof row.content === 'string' && row.content.trim().length > 0)
+ .map(
+ (row) =>
+ ({
+ content: row.content as string,
+ createdAt: row.createdAt ?? topicUpdatedAt,
+ id: row.id,
+ role: (row.role ?? 'assistant') as LLMRoleType,
+ }) satisfies OpenAIChatMessage & { createdAt: Date; id: string },
+ );
+
+ if (conversation.length === 0) {
+ return [];
+ }
+
+ return conversation;
+ }
+
+ async listRelevantUserMemories(
+ job: MemoryExtractionJob,
+ runtime: ModelRuntime,
+ embeddingModel: string,
+ userId: string,
+ conversations: OpenAIChatMessage[],
+ tokenLimit?: number,
+ ) {
+ const db = await this.db;
+ const userMemoryModel = new UserMemoryModel(db, userId);
+ // TODO: make topK configurable
+ const topK = 10;
+ const aggregatedContent = this.trimTextToTokenLimit(
+ conversations.map((msg) => `${msg.role.toUpperCase()}: ${msg.content}`).join('\n\n'),
+ tokenLimit,
+ );
+
+ const embeddings = await runtime.embeddings({
+ dimensions: DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,
+ input: [aggregatedContent],
+ model: embeddingModel,
+ });
+
+ const vector = embeddings?.[0];
+ if (vector) {
+ const retrieved = await userMemoryModel.searchWithEmbedding({
+ embedding: vector,
+ limits: { contexts: topK, experiences: topK, preferences: topK },
+ });
+
+ return retrieved;
+ }
+
+ return {
+ contexts: [],
+ experiences: [],
+ preferences: [],
+ };
+ }
+
+ async listUserMemoryIdentities(job: MemoryExtractionJob, userId: string) {
+ const db = await this.db;
+ const userMemoryModel = new UserMemoryModel(db, userId);
+
+ return userMemoryModel.getAllIdentities();
+ }
+
+ async extractTopic(job: TopicExtractionJob) {
+ const attributes = {
+ source: job.source,
+ source_id: job.topicId,
+ user_id: job.userId,
+ };
+
+ let observabilityS3: S3 | undefined;
+ if (this.modelConfig.observabilityS3?.enabled) {
+ observabilityS3 = new S3(
+ this.modelConfig.observabilityS3?.accessKeyId,
+ this.modelConfig.observabilityS3?.secretAccessKey,
+ this.modelConfig.observabilityS3?.endpoint,
+ {
+ bucket: this.modelConfig.observabilityS3?.bucketName,
+ forcePathStyle: this.modelConfig.observabilityS3?.forcePathStyle,
+ region: this.modelConfig.observabilityS3?.region,
+ setAcl: false,
+ },
+ );
+ }
+
+ return tracer.startActiveSpan(
+ 'Memory User Memory: Extract Chat Topic',
+ { attributes },
+ async (span) => {
+ const startTime = Date.now();
+ let extractionJob: MemoryExtractionJob | null = null;
+ let extraction: MemoryExtractionResult | null = null;
+ let resultRecorder: LobeChatTopicResultRecorder | null = null;
+ let tracePayload: MemoryExtractionTracePayload<
+ MemoryExtractionResult,
+ MemoryExtractionJob | null,
+ GenerateObjectPayload
+ > | null = null;
+
+ try {
+ const db = await this.db;
+ const topic = await db.query.topics.findFirst({
+ columns: { createdAt: true, id: true, metadata: true, updatedAt: true, userId: true },
+ where: and(eq(topics.id, job.topicId), eq(topics.userId, job.userId)),
+ });
+
+ if (!topic) {
+ console.warn(
+ `[memory-extraction] topic ${job.topicId} not found for user ${job.userId}`,
+ );
+ span.setStatus({ code: SpanStatusCode.OK, message: 'topic_not_found' });
+ return {
+ extracted: false,
+ layers: {},
+ memoryIds: [],
+ traceId: span.spanContext().traceId,
+ };
+ }
+ if ((job.from && topic.createdAt < job.from) || (job.to && topic.createdAt > job.to)) {
+ span.setStatus({ code: SpanStatusCode.OK, message: 'topic_out_of_range' });
+ return {
+ extracted: false,
+ layers: {},
+ memoryIds: [],
+ traceId: span.spanContext().traceId,
+ };
+ }
+ if (!job.forceAll && !job.forceTopics && isTopicExtracted(topic.metadata)) {
+ span.setStatus({ code: SpanStatusCode.OK, message: 'already_extracted' });
+ return {
+ extracted: false,
+ layers: {},
+ memoryIds: [],
+ traceId: span.spanContext().traceId,
+ };
+ }
+
+ extractionJob = {
+ force: job.forceAll || job.forceTopics,
+ layers: job.layers,
+ source: job.source,
+ sourceId: topic.id,
+ sourceUpdatedAt: topic.updatedAt,
+ userId: job.userId,
+ };
+
+ const userModel = new UserModel(db, job.userId);
+ const userState = await userModel.getUserState(KeyVaultsGateKeeper.getUserKeyVaults);
+ const keyVaults = userState.settings?.keyVaults as UserKeyVaults | undefined;
+ const language = userState.settings?.general?.responseLanguage;
+
+ const runtimes = await this.getRuntime(job.userId, keyVaults);
+
+ const conversations = await this.listConversationsForTopic(
+ job.userId,
+ topic.id,
+ topic.updatedAt,
+ );
+ if (!conversations || conversations.length === 0) {
+ if (extractionJob) {
+ this.recordJobMetrics(extractionJob, 'completed', Date.now() - startTime);
+ }
+ span.setStatus({ code: SpanStatusCode.OK, message: 'empty_conversations' });
+ return {
+ extracted: false,
+ layers: {},
+ memoryIds: [],
+ traceId: span.spanContext().traceId,
+ };
+ }
+
+ const extractorContextLimit = this.privateConfig.agentLayerExtractor.contextLimit;
+ const embeddingContextLimit = this.embeddingContextLimit ?? extractorContextLimit;
+ const extractorConversations = await this.trimConversationsToTokenLimit(
+ conversations,
+ extractorContextLimit,
+ );
+ const embeddingConversations = await this.trimConversationsToTokenLimit(
+ conversations,
+ embeddingContextLimit,
+ );
+
+ const messageIds = extractorConversations.map((item) => item.id);
+
+ const topicContextProvider = new LobeChatTopicContextProvider({
+ conversations: extractorConversations,
+ topic: topic,
+ topicId: topic.id,
+ });
+ const topicContext = await topicContextProvider.buildContext(extractionJob);
+
+ resultRecorder = new LobeChatTopicResultRecorder({
+ currentMetadata: topic.metadata || {},
+ database: db,
+ lastMessageAt: (conversations?.at(-1)?.createdAt || topic.updatedAt).toISOString(),
+ messageCount: conversations.length,
+ topicId: topic.id,
+ traceId: span.spanContext().traceId,
+ });
+
+ const retrievedMemories = await this.listRelevantUserMemories(
+ extractionJob,
+ runtimes.embeddings,
+ this.modelConfig.embeddingsModel,
+ job.userId,
+ embeddingConversations,
+ embeddingContextLimit,
+ );
+ const retrievedMemoryContextProvider = new RetrievalUserMemoryContextProvider({
+ retrievedMemories,
+ });
+ const retrievalMemoryContext =
+ await retrievedMemoryContextProvider.buildContext(extractionJob);
+
+ const retrievedMemoryIdentities = await this.listUserMemoryIdentities(
+ extractionJob,
+ job.userId,
+ );
+ const retrievedMemoryIdentitiesContextProvider =
+ new RetrievalUserMemoryIdentitiesProvider({
+ retrievedIdentities: retrievedMemoryIdentities,
+ });
+ const retrievedIdentityContext =
+ await retrievedMemoryIdentitiesContextProvider.buildContext(extractionJob);
+ const trimmedRetrievedContexts = [
+ topicContext.context,
+ retrievalMemoryContext.context,
+ ].map((context) => this.trimTextToTokenLimit(context, extractorContextLimit));
+ const trimmedRetrievedIdentitiesContext = this.trimTextToTokenLimit(
+ retrievedIdentityContext.context,
+ extractorContextLimit,
+ );
+
+ const agentCalls: Partial<
+ Record<MemoryExtractionAgent, MemoryExtractionAgentCallTrace<GenerateObjectPayload>>
+ > = {};
+ const agentStartedAt: Partial<Record<MemoryExtractionAgent, number>> = {};
+
+ const recordRequest = (agent: MemoryExtractionAgent, request: GenerateObjectPayload) => {
+ agentStartedAt[agent] = Date.now();
+ agentCalls[agent] = { ...agentCalls[agent], request };
+ };
+
+ const recordResponse = (agent: MemoryExtractionAgent, response: unknown) => {
+ const duration = agentStartedAt[agent]
+ ? Date.now() - agentStartedAt[agent]!
+ : undefined;
+ agentCalls[agent] = { ...agentCalls[agent], durationMs: duration, response };
+ };
+
+ const recordError = (agent: MemoryExtractionAgent, error: unknown) => {
+ const duration = agentStartedAt[agent]
+ ? Date.now() - agentStartedAt[agent]!
+ : undefined;
+ agentCalls[agent] = {
+ ...agentCalls[agent],
+ durationMs: duration,
+ error: serializeError(error),
+ };
+ };
+
+ tracePayload = {
+ agentCalls,
+ contexts: {
+ built: {
+ retrievalMemoryContext,
+ retrievedIdentityContext,
+ topicContext,
+ },
+ trimmed: {
+ retrievedContexts: trimmedRetrievedContexts,
+ retrievedIdentitiesContext: trimmedRetrievedIdentitiesContext,
+ },
+ },
+ extractionJob,
+ memories: {
+ identities: retrievedMemoryIdentities,
+ layers: retrievedMemories,
+ },
+ source: {
+ chatTopic: {
+ conversations: extractorConversations,
+ topic,
+ },
+ },
+ sourceType: extractionJob.source,
+ userId: job.userId,
+ };
+
+ const service = new MemoryExtractionService({
+ config: this.modelConfig,
+ db,
+ language,
+ runtimes,
+ });
+
+ const shouldRecordTrace = Boolean(observabilityS3);
+
+ extraction = await service.run(extractionJob, {
+ callbacks: shouldRecordTrace
+ ? {
+ onExtractError: async (agent, error) => {
+ recordError(agent, error);
+ },
+ onExtractRequest: async (agent, payload) => {
+ recordRequest(agent, payload);
+ },
+ onExtractResponse: async (agent, response) => {
+ recordResponse(agent, response);
+ },
+ }
+ : undefined,
+ contextProvider: topicContextProvider,
+ gatekeeperLanguage: this.privateConfig.agentGateKeeper.language || 'English',
+ language: language,
+ resultRecorder: resultRecorder,
+ retrievedContexts: trimmedRetrievedContexts,
+ retrievedIdentitiesContext: trimmedRetrievedIdentitiesContext,
+
+ sessionDate: topic.updatedAt.toISOString(),
+ // TODO: make topK configurable
+ topK: 10,
+ username:
+ userState.fullName || `${userState.firstName} ${userState.lastName}`.trim() || 'User',
+ });
+ if (!extraction) {
+ this.recordJobMetrics(extractionJob, 'completed', Date.now() - startTime);
+ span.setStatus({ code: SpanStatusCode.OK, message: 'no_extraction' });
+ return {
+ extracted: false,
+ layers: {},
+ memoryIds: [],
+ traceId: span.spanContext().traceId,
+ };
+ }
+
+ const persistedRes = await this.persistExtraction(
+ extractionJob,
+ messageIds,
+ extraction,
+ runtimes,
+ db,
+ );
+ if (tracePayload) {
+ tracePayload.result = { extraction, persisted: persistedRes };
+ }
+ await resultRecorder.recordComplete(extractionJob, {
+ ...persistedRes,
+ processedMemoryCount: persistedRes.createdIds.length,
+ });
+ this.recordJobMetrics(extractionJob, 'completed', Date.now() - startTime);
+ span.setStatus({ code: SpanStatusCode.OK });
+ span.setAttribute('memory.processed_memory_count', persistedRes.createdIds.length);
+
+ return {
+ extracted: true,
+ layers: persistedRes.layers,
+ memoryIds: persistedRes.createdIds,
+ traceId: span.spanContext().traceId,
+ };
+ } catch (error) {
+ if (extraction && extractionJob && resultRecorder) {
+ await resultRecorder.recordFail?.(extractionJob, error as Error);
+ }
+ if (extractionJob) {
+ this.recordJobMetrics(extractionJob, 'failed', Date.now() - startTime);
+ }
+ span.setStatus({
+ code: SpanStatusCode.ERROR,
+ message: error instanceof Error ? error.message : 'Extraction failed',
+ });
+ span.recordException(error as Error);
+
+ if (tracePayload) {
+ tracePayload.error = serializeError(error);
+ }
+ throw error;
+ } finally {
+ if (observabilityS3 && tracePayload) {
+ try {
+ await this.uploadExtractionTrace(
+ tracePayload,
+ job.userId,
+ extractionJob?.source ?? job.source,
+ extractionJob?.sourceId ?? job.topicId,
+ observabilityS3,
+ );
+ } catch (err) {
+ console.error('[memory-extraction] failed to upload extraction trace', err);
+ }
+ }
+ span.end();
+ }
+ },
+ );
+ }
+
+ private getOnExtractHooksPath(
+ userId: string,
+ source: string,
+ sourceId: string,
+ ): string | undefined {
+ if (!this.modelConfig.observabilityS3?.enabled) {
+ return undefined;
+ }
+
+ const withoutBase = `memory-extraction/${userId}/${source}/${sourceId}/`;
+ const base = this.modelConfig.observabilityS3?.pathPrefix
+ ? this.modelConfig.observabilityS3?.pathPrefix.startsWith('/')
+ ? this.modelConfig.observabilityS3?.pathPrefix.slice(1)
+ : this.modelConfig.observabilityS3?.pathPrefix
+ : '';
+
+ const key = join(`${base}`, withoutBase);
+ return key;
+ }
+
+ private async uploadExtractionTrace(
+ payload: MemoryExtractionTracePayload<
+ MemoryExtractionResult,
+ MemoryExtractionJob | null,
+ GenerateObjectPayload
+ >,
+ userId: string,
+ source: string,
+ sourceId: string,
+ s3: S3,
+ ) {
+ if (!this.modelConfig.observabilityS3?.enabled) return;
+
+ const key = join(
+ this.getOnExtractHooksPath(userId, source, sourceId)!,
+ 'trace',
+ `${new Date().toISOString()}.json`,
+ );
+
+ await s3.uploadContent(key, JSON.stringify(payload, null, 2));
+ }
+
+ async runDirect(payload: MemoryExtractionNormalizedPayload) {
+ if (!payload.sources.includes('chat_topic')) {
+ return { message: 'Direct execution currently supports chat_topic only.', processed: 0 };
+ }
+ if (!payload.userIds.length) {
+ throw new Error('Direct execution requires at least one user id.');
+ }
+ if (!payload.topicIds.length) {
+ throw new Error('Direct execution requires topicIds for chat_topic sources.');
+ }
+
+ const results: {
+ extracted: boolean;
+ layers: Record<string, number>;
+ memoryIds: string[];
+ topicId: string;
+ userId: string;
+ }[] = [];
+
+ for (const userId of payload.userIds) {
+ const topicIds = await this.filterTopicIdsForUser(userId, payload.topicIds);
+ for (const topicId of topicIds) {
+ const extracted = await this.extractTopic({
+ forceAll: payload.forceAll,
+ forceTopics: payload.forceTopics,
+ from: payload.from,
+ layers: payload.layers,
+ source: 'chat_topic',
+ to: payload.to,
+ topicId,
+ userId,
+ });
+
+ results.push({ ...extracted, topicId, userId });
+ }
+ }
+
+ return { processed: results.length, results };
+ }
+
+ async getTopicsForUser(
+ job: TopicPaginationJob,
+ pageSize: number,
+ ): Promise<{ cursor?: ListTopicsForMemoryExtractorCursor; ids: string[] }> {
+ const db = await this.db;
+ const topicModel = new TopicModel(db, job.userId);
+ const rows = await topicModel.listTopicsForMemoryExtractor({
+ cursor: job.cursor,
+ endDate: job.to,
+ ignoreExtracted: job.forceAll || job.forceTopics,
+ limit: pageSize,
+ startDate: job.from,
+ });
+ if (!rows?.length) {
+ return { ids: [] };
+ }
+
+ const last = rows.at(-1);
+ const nextCursor = last
+ ? {
+ createdAt: last.createdAt,
+ id: last.id,
+ }
+ : undefined;
+
+ return {
+ cursor: nextCursor,
+ ids: rows.map((topic) => topic.id),
+ };
+ }
+
+ async getUsers(
+ limit: number,
+ cursor?: ListUsersForMemoryExtractorCursor,
+ ): Promise<UserPaginationResult> {
+ const db = await this.db;
+
+ const rows = await UserModel.listUsersForMemoryExtractor(db, {
+ cursor,
+ limit,
+ whitelist: this.privateConfig.whitelistUsers,
+ });
+ if (!rows?.length) {
+ return { ids: [] };
+ }
+
+ const last = rows.at(-1);
+ const nextCursor = last
+ ? {
+ createdAt: last.createdAt,
+ id: last.id,
+ }
+ : undefined;
+
+ return {
+ cursor: nextCursor,
+ ids: rows.map((row) => row.id),
+ };
+ }
+
+ async filterTopicIdsForUser(userId: string, topicIds: string[]) {
+ if (!topicIds.length) return [];
+
+ const db = await this.db;
+ const rows = await db.query.topics.findMany({
+ columns: { id: true },
+ where: and(eq(topics.userId, userId), inArray(topics.id, topicIds)),
+ });
+
+ return rows.map((row) => row.id);
+ }
+
+ private recordJobMetrics(
+ job: MemoryExtractionJob,
+ status: 'completed' | 'failed',
+ durationMs: number,
+ ) {
+ processedSourceCounter.add(1, {
+ source: job.source,
+ status,
+ user_id: job.userId,
+ ...attributesCommon(),
+ });
+ processedDurationHistogram.record(durationMs, {
+ source: job.source,
+ user_id: job.userId,
+ ...attributesCommon(),
+ });
+ }
+
+ private recordLayerEntries(job: MemoryExtractionJob, layer: LayersEnum, count: number) {
+ layerEntriesHistogram.record(count, {
+ layer: LAYER_LABEL_MAP[layer],
+ source: job.source,
+ user_id: job.userId,
+ ...attributesCommon(),
+ });
+ }
+
+ private normalizeLayerError(layer: LayersEnum, stage: 'extract' | 'persist', error: unknown) {
+ const message = error instanceof Error ? error.message : String(error);
+ return new Error(`[${stage}] ${LAYER_LABEL_MAP[layer]}: ${message}`);
+ }
+
+ private async persistExtraction(
+ job: MemoryExtractionJob,
+ messageIds: string[],
+ extraction: MemoryExtractionResult,
+ runtimes: RuntimeBundle,
+ db: Awaited<ReturnType<typeof getServerDB>>,
+ ): Promise<PersistedMemoryResult> {
+ const createdIds: string[] = [];
+ const perLayer: Partial<Record<LayersEnum, number>> = {};
+ const errors: Error[] = [];
+ const appendError = (layer: LayersEnum, stage: 'extract' | 'persist', error: unknown) => {
+ errors.push(this.normalizeLayerError(layer, stage, error));
+ };
+
+ const persistWithSpan = async (
+ layer: LayersEnum,
+ persist: () => Promise<string[]>,
+ ): Promise<void> => {
+ const attributes = {
+ layer: LAYER_LABEL_MAP[layer],
+ source: job.source,
+ source_id: job.sourceId,
+ user_id: job.userId,
+ ...attributesCommon(),
+ };
+
+ await tracer.startActiveSpan(
+ `Memory User Memory: Persist ${LAYER_LABEL_MAP[layer]}`,
+ { attributes },
+ async (span) => {
+ try {
+ const ids = await persist();
+
+ createdIds.push(...ids);
+ perLayer[layer] = ids.length;
+ this.recordLayerEntries(job, layer, ids.length);
+ span.setStatus({ code: SpanStatusCode.OK });
+ span.setAttribute('memory.persisted_count', ids.length);
+ } catch (error) {
+ appendError(layer, 'persist', error);
+ span.setStatus({
+ code: SpanStatusCode.ERROR,
+ message:
+ error instanceof Error ? error.message : 'Failed to persist extracted memories',
+ });
+ span.recordException(error as Error);
+ } finally {
+ span.end();
+ }
+ },
+ );
+ };
+
+ const contextOutput = extraction.outputs.context;
+ if (contextOutput?.error) {
+ appendError(LayersEnum.Context, 'extract', contextOutput.error);
+ }
+ if (contextOutput?.data) {
+ await persistWithSpan(LayersEnum.Context, () =>
+ this.persistContextMemories(
+ job,
+ messageIds,
+ contextOutput.data,
+ runtimes.embeddings,
+ this.modelConfig.embeddingsModel,
+ this.embeddingContextLimit,
+ db,
+ ),
+ );
+ }
+
+ const experienceOutput = extraction.outputs.experience;
+ if (experienceOutput?.error) {
+ appendError(LayersEnum.Experience, 'extract', experienceOutput.error);
+ }
+ if (experienceOutput?.data) {
+ await persistWithSpan(LayersEnum.Experience, () =>
+ this.persistExperienceMemories(
+ job,
+ messageIds,
+ experienceOutput.data,
+ runtimes.embeddings,
+ this.modelConfig.embeddingsModel,
+ this.embeddingContextLimit,
+ db,
+ ),
+ );
+ }
+
+ const preferenceOutput = extraction.outputs.preference;
+ if (preferenceOutput?.error) {
+ appendError(LayersEnum.Preference, 'extract', preferenceOutput.error);
+ }
+ if (preferenceOutput?.data) {
+ await persistWithSpan(LayersEnum.Preference, () =>
+ this.persistPreferenceMemories(
+ job,
+ messageIds,
+ preferenceOutput.data,
+ runtimes.embeddings,
+ this.modelConfig.embeddingsModel,
+ this.embeddingContextLimit,
+ db,
+ ),
+ );
+ }
+
+ const identityOutput = extraction.outputs.identity;
+ if (identityOutput?.error) {
+ appendError(LayersEnum.Identity, 'extract', identityOutput.error);
+ }
+ if (identityOutput?.data) {
+ await persistWithSpan(LayersEnum.Identity, () =>
+ this.persistIdentityMemories(
+ job,
+ messageIds,
+ identityOutput.data,
+ runtimes.embeddings,
+ this.modelConfig.embeddingsModel,
+ this.embeddingContextLimit,
+ db,
+ ),
+ );
+ }
+
+ if (errors.length) {
+ const detail = errors.map((error) => error.message).join('; ');
+ throw new AggregateError(errors, `Memory extraction encountered layer errors: ${detail}`);
+ }
+
+ return {
+ createdIds,
+ layers: perLayer,
+ };
+ }
+
+ private async getRuntime(userId: string, keyVaults?: UserKeyVaults): Promise<RuntimeBundle> {
+ // TODO: implement a better cache eviction strategy
+ // TODO: make cache size configurable
+ if (this.runtimeCache.keys.length > 200) {
+ this.runtimeCache.clear();
+ }
+
+ const cached = this.runtimeCache.get(userId);
+ if (cached) return cached;
+
+ const runtimes: RuntimeBundle = {
+ embeddings: await initRuntimeForAgent(this.privateConfig.embedding, keyVaults),
+ gatekeeper: await initRuntimeForAgent(this.privateConfig.agentGateKeeper, keyVaults),
+ layerExtractor: await initRuntimeForAgent(this.privateConfig.agentLayerExtractor, keyVaults),
+ };
+
+ this.runtimeCache.set(userId, runtimes);
+
+ return runtimes;
+ }
+}
+
+const WORKFLOW_PATHS = {
+ topicBatch: '/api/workflows/memory-user-memory/pipelines/process-topic',
+ userTopics: '/api/workflows/memory-user-memory/pipelines/process-user-topics',
+ users: '/api/workflows/memory-user-memory/pipelines/process-users',
+} as const;
+
+const getWorkflowUrl = (path: string, baseUrl: string) => {
+ const url = new URL(path, baseUrl);
+
+ return url.toString();
+};
+
+const getWorkflowClient = () => {
+ const token = process.env.QSTASH_TOKEN;
+ if (!token) throw new Error('QSTASH_TOKEN is required to trigger workflows');
+
+ const config: ConstructorParameters<typeof Client>[0] = { token };
+
+ if (process.env.QSTASH_URL) {
+ (config as Record<string, unknown>).url = process.env.QSTASH_URL;
+ }
+
+ return new Client(config);
+};
+
+export class MemoryExtractionWorkflowService {
+ private static client: Client;
+
+ private static getClient() {
+ if (!this.client) {
+ this.client = getWorkflowClient();
+ }
+
+ return this.client;
+ }
+
+ static triggerProcessUsers(payload: MemoryExtractionPayloadInput) {
+ if (!payload.baseUrl) {
+ throw new Error('Missing baseUrl for workflow trigger');
+ }
+
+ const url = getWorkflowUrl(WORKFLOW_PATHS.users, payload.baseUrl);
+ return this.getClient().trigger({ body: payload, url });
+ }
+
+ static triggerProcessUserTopics(payload: UserTopicWorkflowPayload) {
+ if (!payload.baseUrl) {
+ throw new Error('Missing baseUrl for workflow trigger');
+ }
+
+ const url = getWorkflowUrl(WORKFLOW_PATHS.userTopics, payload.baseUrl);
+ return this.getClient().trigger({ body: payload, url });
+ }
+
+ static triggerProcessTopicBatch(payload: TopicBatchWorkflowPayload) {
+ if (!payload.baseUrl) {
+ throw new Error('Missing baseUrl for workflow trigger');
+ }
+
+ const url = getWorkflowUrl(WORKFLOW_PATHS.topicBatch, payload.baseUrl);
+ return this.getClient().trigger({ body: payload, url });
+ }
+}