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.

♻️ refactor(database): add structured user memory tables (context, dossier, entity, operation log) (#21611)

Arvin Xu0ebfcefb9417
diff --git a/alint.config.toml b/alint.config.toml
index 9f0963d1dc6..9bf41a84309 100644
--- a/alint.config.toml
+++ b/alint.config.toml
@@ -80,6 +80,26 @@ lobehub = "./packages/alint/rules"
[config.group.rules]
"lobehub/no-inferred-service-types" = "warn"
+# Row types: declared in @lobechat/types, not inferred from a Drizzle table
+# (typeof table.$inferSelect / $inferInsert) or imported from a schema module.
+# Schema files are excluded: they own the tables and the compile-time checks.
+[[config.group]]
+files = [ "packages/*/src/**/*.ts", "packages/*/src/**/*.tsx", "apps/server/src/**/*.ts", "src/**/*.ts", "src/**/*.tsx" ]
+ignores = [ "packages/database/src/schemas/**", "packages/database/migrations/**", "packages/alint/**", "**/*.test.ts", "**/*.test.tsx", "**/__tests__/**", "**/__mocks__/**", "**/fixtures/**", "**/*.stories.tsx" ]
+
+[config.group.plugins]
+lobehub = "./packages/alint/rules"
+
+[config.group.rules]
+"lobehub/no-inferred-schema-types" = "warn"
+
+[[config.group]]
+files = [ "packages/alint/fixtures/no-inferred-schema-types/**" ]
+[config.group.plugins]
+lobehub = "./packages/alint/rules"
+[config.group.rules]
+"lobehub/no-inferred-schema-types" = "warn"
+
# Fixed product images and App-owned resource requests have different namespaces.
[[config.group]]
files = [ "src/**/*.{ts,tsx,css}", "packages/const/src/**/*.ts", "apps/*/app/**/*.{ts,tsx,css}", "apps/{share,workbench}/src/**/*.{ts,tsx,css}", "apps/desktop/vite.*.config.{ts,mts}", "scripts/**/*.{ts,mts}" ]
diff --git a/apps/server/src/services/memory/userMemory/persona/service.ts b/apps/server/src/services/memory/userMemory/persona/service.ts
index 8e43ee39628..94c688c89ce 100644
--- a/apps/server/src/services/memory/userMemory/persona/service.ts
+++ b/apps/server/src/services/memory/userMemory/persona/service.ts
@@ -1,7 +1,3 @@
-import {
- type UserPersonaDocument,
- type UserPersonaDocumentHistoriesItem,
-} from '@lobechat/database/schemas';
import { userMemories } from '@lobechat/database/schemas';
import { type UserPersonaExtractionResult } from '@lobechat/memory-user-memory';
import {
@@ -9,7 +5,11 @@ import {
RetrievalUserMemoryIdentitiesProvider,
UserPersonaExtractor,
} from '@lobechat/memory-user-memory';
-import type { UserServiceModelConfig } from '@lobechat/types';
+import type {
+ UserPersonaDocument,
+ UserPersonaDocumentHistory,
+ UserServiceModelConfig,
+} from '@lobechat/types';
import { and, desc, eq } from 'drizzle-orm';
import { getBusinessModelRuntimeHooks } from '@/business/server/model-runtime';
@@ -48,7 +48,7 @@ interface UserPersonaAgentPayload {
interface UserPersonaAgentResult {
agentResult: UserPersonaExtractionResult;
- diff?: UserPersonaDocumentHistoriesItem;
+ diff?: UserPersonaDocumentHistory;
document: UserPersonaDocument;
}
diff --git a/packages/alint/README.md b/packages/alint/README.md
index a1e1d4ebb6b..6aad94c106c 100644
--- a/packages/alint/README.md
+++ b/packages/alint/README.md
@@ -15,6 +15,7 @@ This is Phase 0: the rule set is a private workspace package (`@lobechat/alint`)
| `no-mode-flags` | warn | `src/**/*.tsx` | `compose-atoms` skill |
| `no-unguarded-response-field` | error | `src/**/*.tsx` | a newer client must survive an older server omitting a response field |
| `no-inferred-service-types` | warn | `src/**/*.{ts,tsx}` | payload types live in `@lobechat/types`, not `Awaited<ReturnType<…>>` |
+| `no-inferred-schema-types` | warn | `packages/*/src`, `apps/server/src`, `src` (not `schemas/`) | row types live in `@lobechat/types`, not `typeof table.$inferSelect` |
| `no-node-in-browser` | error | browser code in `src/` (not `app/`, `libs/`), package `*.tsx` | no Node-only npm package where the SPA runs it (paths: ESLint) |
| `no-benchmark-in-tests` | warn | `**/*.test.ts(x)` except `packages/database` | a unit test asserts on behaviour, not on a wall-clock measurement |
| `no-unsafe-user-url-fetch` | warn | `apps/server/src` | user-controlled URLs must use SSRF-safe transport (#16601) |
diff --git a/packages/alint/fixtures/no-inferred-schema-types/bad-infer-model.ts b/packages/alint/fixtures/no-inferred-schema-types/bad-infer-model.ts
new file mode 100644
index 00000000000..e796f49129a
--- /dev/null
+++ b/packages/alint/fixtures/no-inferred-schema-types/bad-infer-model.ts
@@ -0,0 +1,10 @@
+// Fixture: drizzle's InferSelectModel over a concrete table.
+import type { InferInsertModel, InferSelectModel } from 'drizzle-orm';
+
+import type { topics } from '@/database/schemas';
+
+// alint-expect
+export type TopicRow = InferSelectModel<typeof topics>;
+
+// alint-expect
+export const buildTopic = (input: Partial<InferInsertModel<typeof topics>>) => ({ ...input });
diff --git a/packages/alint/fixtures/no-inferred-schema-types/bad-interface-fields.ts b/packages/alint/fixtures/no-inferred-schema-types/bad-interface-fields.ts
new file mode 100644
index 00000000000..ad7b0cc12c3
--- /dev/null
+++ b/packages/alint/fixtures/no-inferred-schema-types/bad-interface-fields.ts
@@ -0,0 +1,12 @@
+// Fixture: a service result type is carved out of the persona tables.
+import type { UserPersonaExtractionResult } from '@lobechat/memory-user-memory';
+
+import type { userPersonaDocumentHistories, userPersonaDocuments } from '@/database/schemas';
+
+export interface UserPersonaAgentResult {
+ agentResult: UserPersonaExtractionResult;
+ // alint-expect
+ diff?: typeof userPersonaDocumentHistories.$inferSelect;
+ // alint-expect
+ document: typeof userPersonaDocuments.$inferSelect;
+}
diff --git a/packages/alint/fixtures/no-inferred-schema-types/bad-omit-and-satisfies.ts b/packages/alint/fixtures/no-inferred-schema-types/bad-omit-and-satisfies.ts
new file mode 100644
index 00000000000..16708431563
--- /dev/null
+++ b/packages/alint/fixtures/no-inferred-schema-types/bad-omit-and-satisfies.ts
@@ -0,0 +1,22 @@
+// Fixture: a model annotates a vector-free row and checks an insert against the table.
+import type { userMemoriesActivities, userMemoriesContexts } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+
+export const listActivities = async (
+ db: LobeChatDatabase,
+ userId: string,
+ // alint-expect
+): Promise<
+ Omit<typeof userMemoriesActivities.$inferSelect, 'narrativeVector' | 'feedbackVector'>[]
+> =>
+ db.query.userMemoriesActivities.findMany({
+ where: (table, { eq }) => eq(table.userId, userId),
+ });
+
+export const contextValues = (userId: string, memoryId: string) =>
+ ({
+ title: 'CITIC enterprise deal',
+ userId,
+ userMemoryId: memoryId,
+ // alint-expect
+ }) satisfies typeof userMemoriesContexts.$inferInsert;
diff --git a/packages/alint/fixtures/no-inferred-schema-types/bad-schema-type-import.ts b/packages/alint/fixtures/no-inferred-schema-types/bad-schema-type-import.ts
new file mode 100644
index 00000000000..cf3ace147aa
--- /dev/null
+++ b/packages/alint/fixtures/no-inferred-schema-types/bad-schema-type-import.ts
@@ -0,0 +1,7 @@
+// Fixture: a router imports row types that the schema module infers and re-exports.
+// alint-expect
+import type { NewTask, TaskItem } from '@/database/schemas';
+
+export const toListItem = (task: TaskItem) => ({ id: task.id, title: task.name });
+
+export const draftTask = (name: string): NewTask => ({ name }) as NewTask;
diff --git a/packages/alint/fixtures/no-inferred-schema-types/good-generic-helper.ts b/packages/alint/fixtures/no-inferred-schema-types/good-generic-helper.ts
new file mode 100644
index 00000000000..698e2811c3a
--- /dev/null
+++ b/packages/alint/fixtures/no-inferred-schema-types/good-generic-helper.ts
@@ -0,0 +1,18 @@
+// Fixture: generic helpers over any table and table-object types are not row inference.
+import type { InferSelectModel, SQL } from 'drizzle-orm';
+import type { PgTable } from 'drizzle-orm/pg-core';
+
+import type { tasks, userMemories } from '@/database/schemas';
+
+export const firstRow = async <T extends PgTable>(
+ rows: Promise<InferSelectModel<T>[]>,
+): Promise<InferSelectModel<T> | undefined> => (await rows)[0];
+
+export const pickInsertable = <TTable extends PgTable>(
+ value: Partial<TTable['$inferInsert']>,
+): Partial<TTable['$inferInsert']> => value;
+
+export const scopedTo = (table: typeof userMemories | typeof tasks, where: SQL) => ({
+ table,
+ where,
+});
diff --git a/packages/alint/fixtures/no-inferred-schema-types/good-types-package.ts b/packages/alint/fixtures/no-inferred-schema-types/good-types-package.ts
new file mode 100644
index 00000000000..84d06eb1143
--- /dev/null
+++ b/packages/alint/fixtures/no-inferred-schema-types/good-types-package.ts
@@ -0,0 +1,26 @@
+// Fixture: row types come from the types package; the schema module only provides tables.
+import type {
+ UserMemoryActivityWithoutVectors,
+ UserMemoryContextInsert,
+ UserPersonaDocument,
+ UserPersonaDocumentHistory,
+} from '@lobechat/types';
+
+import { userMemoriesActivities } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+
+export interface UserPersonaAgentResult {
+ diff?: UserPersonaDocumentHistory;
+ document: UserPersonaDocument;
+}
+
+export const listActivities = async (
+ db: LobeChatDatabase,
+ userId: string,
+): Promise<UserMemoryActivityWithoutVectors[]> =>
+ db
+ .select()
+ .from(userMemoriesActivities)
+ .where((t) => t.userId === userId) as unknown as Promise<UserMemoryActivityWithoutVectors[]>;
+
+export const contextValues = (userId: string): UserMemoryContextInsert => ({ userId });
diff --git a/packages/alint/rules/no-inferred-schema-types/rule.alint.toml b/packages/alint/rules/no-inferred-schema-types/rule.alint.toml
new file mode 100644
index 00000000000..543118ee8a6
--- /dev/null
+++ b/packages/alint/rules/no-inferred-schema-types/rule.alint.toml
@@ -0,0 +1,27 @@
+name = "no-inferred-schema-types"
+builtInAgent = "basic-structured"
+instruction = """
+You are reviewing one TypeScript file from LobeHub that is NOT a database schema file (`packages/database/src/schemas/**` is out of scope).
+
+Team rule, from the owner's review rejection of `diff?: typeof userPersonaDocumentHistories.$inferSelect; document: typeof userPersonaDocuments.$inferSelect;`: "这种写法不对,应该都换成放在 types 包里面的导入,而不是用 db schema。"
+
+Why: a row type carved out of a Drizzle table has no name and no home. Every model, service, router and client re-derives it, the shape silently follows whatever the table happens to contain, and code far from the database ends up depending on the schema module. The shape of a row is a contract, so it is declared once in the types package (`packages/types/src/<domain>`, imported as `@lobechat/types`) and code imports that name. The schema package keeps the declared types honest with a compile-time check next to the tables (for user memory: `packages/database/src/schemas/userMemories/rowTypes.check.ts`).
+
+Report every type position in this file whose type is INFERRED from a concrete Drizzle table:
+1. `typeof <table>.$inferSelect` or `typeof <table>.$inferInsert` — alone or wrapped in `Omit<…>`, `Pick<…>`, `Partial<…>`, `NonNullable<…>`, an array, a `Promise<…>` argument, or indexed (`['metadata']`), where `<table>` is a table object (`userMemoriesActivities`, `tasks`, `topics`, any value created with `pgTable(…)` or imported from a `schemas` module);
+2. `InferSelectModel<typeof <table>>` / `InferInsertModel<typeof <table>>` (from `drizzle-orm`) and `typeof <table>._.inferSelect` / `._.inferInsert` for a concrete table;
+3. a type-only import of a row type from a database schema module — `import type { TaskItem, NewTopic } from '@/database/schemas'`, `'@lobechat/database/schemas'`, `'../../schemas'`, `'../schemas/<file>'` — i.e. a PascalCase type name imported from a path that ends in `schemas` or points into `database/src/schemas`. Tables themselves are camelCase values and are not findings when imported to build queries.
+This covers type aliases, interface fields, variable and parameter annotations, function return annotations, generic arguments, `as` casts and `satisfies` clauses (`} satisfies typeof userMemoriesContexts.$inferInsert`).
+Anchor each finding on the line that contains `$inferSelect` / `$inferInsert` / `InferSelectModel` / `InferInsertModel` / `_.infer…`, or on the import line for case 3 — one finding per occurrence, never folded into the first one. A later line that merely uses an alias declared above is not another finding.
+The message must name the table (or the imported schema type). The suggestion must name the type to use from `@lobechat/types` (the row name, e.g. `UserMemoryActivity`, its insert shape `UserMemoryActivityInsert`, or the vector-free view `UserMemoryActivityWithoutVectors` when the code omits vector columns) and say that, if it does not exist yet, it is declared in `packages/types/src/<domain>` and checked against the table in the schema package.
+
+Do not report — these are not inferred row types:
+- types already imported from `@lobechat/types`, from another `@lobechat/*` package that is not the database package, or a local `interface` / `type` literal written field by field;
+- generic helpers over ANY table: `InferSelectModel<T>`, `T['$inferSelect']`, `TTable['$inferInsert']` where `T` / `TTable` is a type parameter (`<T extends PgTable>`), not a concrete table;
+- the type of a table OBJECT rather than of a row: `typeof userMemories`, `table: typeof tasks`, `PgTable`, `AnyPgColumn`, `SQL`, column types;
+- Drizzle's own query result inference that is never written down as a type (`const rows = await db.select().from(tasks)`), `ReturnType<typeof someModel.method>` (another rule's concern), and `z.infer<typeof schema>` for zod schemas;
+- value imports of tables, relations or enums from a schemas module (`import { userMemories, tasks } from '../../schemas'`);
+- test files, `__tests__`, fixtures, mocks, seed and migration scripts.
+
+If an exclusion applies, return no finding. If you cannot tell from this file whether a name is a concrete Drizzle table, return no finding rather than a low-confidence guess.
+"""
diff --git a/packages/database/src/models/userMemory/__tests__/activity.test.ts b/packages/database/src/models/userMemory/__tests__/activity.test.ts
index 1adae9f0587..c47e5304b2e 100644
--- a/packages/database/src/models/userMemory/__tests__/activity.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/activity.test.ts
@@ -1,8 +1,8 @@
+import type { UserMemoryActivityInsert } from '@lobechat/types';
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
-import type { NewUserMemoryActivity } from '../../../schemas';
import { userMemories, userMemoriesActivities, users } from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { UserMemoryActivityModel } from '../activity';
@@ -27,7 +27,7 @@ beforeEach(async () => {
describe('UserMemoryActivityModel', () => {
describe('create', () => {
it('should create a new activity', async () => {
- const activityData: Omit<NewUserMemoryActivity, 'userId'> = {
+ const activityData: Omit<UserMemoryActivityInsert, 'userId'> = {
type: 'event',
narrative: 'User attended a conference',
notes: 'Met interesting people',
diff --git a/packages/database/src/models/userMemory/__tests__/context.test.ts b/packages/database/src/models/userMemory/__tests__/context.test.ts
index f846edbb142..492b5941a05 100644
--- a/packages/database/src/models/userMemory/__tests__/context.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/context.test.ts
@@ -1,8 +1,8 @@
+import type { UserMemoryContextInsert } from '@lobechat/types';
// @vitest-environment node
import { beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
-import type { NewUserMemoryContext } from '../../../schemas';
import { userMemories, userMemoriesContexts, users } from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { UserMemoryContextModel } from '../context';
@@ -27,7 +27,7 @@ beforeEach(async () => {
describe('UserMemoryContextModel', () => {
describe('create', () => {
it('should create a new context', async () => {
- const contextData: Omit<NewUserMemoryContext, 'userId'> = {
+ const contextData: Omit<UserMemoryContextInsert, 'userId'> = {
title: 'Test Context',
description: 'Test context description',
type: 'work',
diff --git a/packages/database/src/models/userMemory/__tests__/experience.test.ts b/packages/database/src/models/userMemory/__tests__/experience.test.ts
index 2a455836315..acf33de574b 100644
--- a/packages/database/src/models/userMemory/__tests__/experience.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/experience.test.ts
@@ -1,8 +1,8 @@
+import type { UserMemoryExperienceInsert } from '@lobechat/types';
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
-import type { NewUserMemoryExperience } from '../../../schemas';
import { userMemories, userMemoriesExperiences, users } from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { UserMemoryExperienceModel } from '../experience';
@@ -27,7 +27,7 @@ beforeEach(async () => {
describe('UserMemoryExperienceModel', () => {
describe('create', () => {
it('should create a new experience', async () => {
- const experienceData: Omit<NewUserMemoryExperience, 'userId'> = {
+ const experienceData: Omit<UserMemoryExperienceInsert, 'userId'> = {
type: 'lesson',
situation: 'When debugging code',
reasoning: 'Checking logs helps identify issues',
diff --git a/packages/database/src/models/userMemory/__tests__/identity.test.ts b/packages/database/src/models/userMemory/__tests__/identity.test.ts
index 4e281b14049..6564ee96114 100644
--- a/packages/database/src/models/userMemory/__tests__/identity.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/identity.test.ts
@@ -1,10 +1,10 @@
+import type { UserMemoryIdentityInsert } from '@lobechat/types';
// @vitest-environment node
import { RelationshipEnum } from '@lobechat/types';
import { eq } from 'drizzle-orm';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
-import type { NewUserMemoryIdentity } from '../../../schemas';
import { userMemories, userMemoriesIdentities, users } from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { UserMemoryIdentityModel } from '../identity';
@@ -29,7 +29,7 @@ beforeEach(async () => {
describe('UserMemoryIdentityModel', () => {
describe('create', () => {
it('should create a new identity', async () => {
- const identityData: Omit<NewUserMemoryIdentity, 'userId'> = {
+ const identityData: Omit<UserMemoryIdentityInsert, 'userId'> = {
type: 'personal',
description: 'Software developer',
role: 'developer',
diff --git a/packages/database/src/models/userMemory/__tests__/model.create-contract.test.ts b/packages/database/src/models/userMemory/__tests__/model.create-contract.test.ts
new file mode 100644
index 00000000000..a98f48701a8
--- /dev/null
+++ b/packages/database/src/models/userMemory/__tests__/model.create-contract.test.ts
@@ -0,0 +1,132 @@
+// @vitest-environment node
+import { ActivityTypeEnum, LayersEnum, TypesEnum } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ userMemories,
+ userMemoriesActivities,
+ userMemoriesContexts,
+ userMemoriesExperiences,
+ userMemoriesIdentities,
+ userMemoriesPreferences,
+ users,
+} from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { UserMemoryModel } from '../model';
+
+/**
+ * Bounded scenario file for the create contract: every optional column the
+ * `create*Memory` params accept must reach the insert instead of falling back to
+ * the column default. Kept out of `model.test.ts` because that file is already
+ * past the size cap.
+ */
+const userId = 'memory-create-contract-user';
+
+let memoryModel: UserMemoryModel;
+const serverDB: LobeChatDatabase = await getTestDB();
+
+beforeEach(async () => {
+ await serverDB.delete(userMemoriesActivities);
+ await serverDB.delete(userMemoriesContexts);
+ await serverDB.delete(userMemoriesExperiences);
+ await serverDB.delete(userMemoriesIdentities);
+ await serverDB.delete(userMemoriesPreferences);
+ await serverDB.delete(userMemories);
+ await serverDB.delete(users);
+
+ await serverDB.insert(users).values([{ id: userId }]);
+ memoryModel = new UserMemoryModel(serverDB, userId);
+});
+
+describe('UserMemoryModel create contract', () => {
+ it('should persist the structured fields accepted by the activity create params', async () => {
+ const result = await memoryModel.createActivityMemory({
+ activity: {
+ injectable: false,
+ narrative: 'Did a thing',
+ status: 'completed',
+ type: ActivityTypeEnum.Other,
+ },
+ details: 'Activity details',
+ memoryLayer: LayersEnum.Activity,
+ memoryType: TypesEnum.Activity,
+ summary: 'Activity summary',
+ title: 'Activity structured fields',
+ });
+
+ const persisted = await serverDB.query.userMemoriesActivities.findFirst({
+ where: eq(userMemoriesActivities.id, result.activity.id),
+ });
+
+ // `injectable` defaults to true, so false proves the param reached the insert.
+ expect(persisted?.injectable).toBe(false);
+ });
+
+ it('should persist the structured fields accepted by the context create params', async () => {
+ const firstSeenAt = new Date('2025-01-01T00:00:00.000Z');
+ const lastEvidenceAt = new Date('2025-01-05T00:00:00.000Z');
+ const synthesizedAt = new Date('2025-01-06T00:00:00.000Z');
+
+ const result = await memoryModel.createContextMemory({
+ context: {
+ description: 'A test context',
+ firstSeenAt,
+ lastEvidenceAt,
+ nextSteps: ['ship the schema'],
+ now: 'wiring the create path',
+ openQuestions: ['who owns the extraction?'],
+ synthesizedAt,
+ title: 'Test Context',
+ type: 'project',
+ },
+ details: 'Context details',
+ memoryLayer: LayersEnum.Context,
+ memoryType: TypesEnum.Context,
+ summary: 'Context summary',
+ title: 'Context structured fields',
+ });
+
+ const persisted = await serverDB.query.userMemoriesContexts.findFirst({
+ where: eq(userMemoriesContexts.id, result.context.id),
+ });
+
+ expect(persisted?.now).toBe('wiring the create path');
+ expect(persisted?.nextSteps).toEqual(['ship the schema']);
+ expect(persisted?.openQuestions).toEqual(['who owns the extraction?']);
+ expect(persisted?.firstSeenAt).toEqual(firstSeenAt);
+ expect(persisted?.lastEvidenceAt).toEqual(lastEvidenceAt);
+ expect(persisted?.synthesizedAt).toEqual(synthesizedAt);
+ });
+
+ it('should persist the structured fields accepted by the preference create params', async () => {
+ const lastEvidenceAt = new Date('2025-01-07T00:00:00.000Z');
+
+ const result = await memoryModel.createPreferenceMemory({
+ details: 'Preference details',
+ memoryLayer: LayersEnum.Preference,
+ memoryType: TypesEnum.Other,
+ preference: {
+ conclusionDirectives: 'Use compact cards',
+ evidenceCount: 4,
+ evidenceSource: 'reported',
+ lastEvidenceAt,
+ scope: 'ui-copy',
+ suggestions: 'Prefer short answers',
+ type: 'style',
+ },
+ summary: 'Preference summary',
+ title: 'Preference structured fields',
+ });
+
+ const persisted = await serverDB.query.userMemoriesPreferences.findFirst({
+ where: eq(userMemoriesPreferences.id, result.preference.id),
+ });
+
+ expect(persisted?.evidenceCount).toBe(4);
+ expect(persisted?.evidenceSource).toBe('reported');
+ expect(persisted?.scope).toBe('ui-copy');
+ expect(persisted?.lastEvidenceAt).toEqual(lastEvidenceAt);
+ });
+});
diff --git a/packages/database/src/models/userMemory/__tests__/preference.test.ts b/packages/database/src/models/userMemory/__tests__/preference.test.ts
index 5e5b12ef2a2..39e123ebd54 100644
--- a/packages/database/src/models/userMemory/__tests__/preference.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/preference.test.ts
@@ -1,8 +1,8 @@
+import type { UserMemoryPreferenceInsert } from '@lobechat/types';
// @vitest-environment node
import { beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
-import type { NewUserMemoryPreference } from '../../../schemas';
import { userMemories, userMemoriesPreferences, users } from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { UserMemoryPreferenceModel } from '../preference';
@@ -27,7 +27,7 @@ beforeEach(async () => {
describe('UserMemoryPreferenceModel', () => {
describe('create', () => {
it('should create a new preference', async () => {
- const preferenceData: Omit<NewUserMemoryPreference, 'userId'> = {
+ const preferenceData: Omit<UserMemoryPreferenceInsert, 'userId'> = {
type: 'communication',
conclusionDirectives: 'Prefer concise responses',
suggestions: 'Use bullet points when possible',
diff --git a/packages/database/src/models/userMemory/__tests__/query.extended.test.ts b/packages/database/src/models/userMemory/__tests__/query.extended.test.ts
index 3bc93c45f5a..fa6617641d5 100644
--- a/packages/database/src/models/userMemory/__tests__/query.extended.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/query.extended.test.ts
@@ -1,3 +1,10 @@
+import type {
+ UserMemoryActivityInsert,
+ UserMemoryContextInsert,
+ UserMemoryExperienceInsert,
+ UserMemoryIdentityInsert,
+ UserMemoryPreferenceInsert,
+} from '@lobechat/types';
// @vitest-environment node
import { LayersEnum, RelationshipEnum, UserMemoryContextObjectType } from '@lobechat/types';
import { beforeEach, describe, expect, it } from 'vitest';
@@ -113,7 +120,7 @@ const createActivityPair = async (opts: {
type: opts.type ?? 'task',
userId: owner,
userMemoryId: memory.id,
- } as typeof userMemoriesActivities.$inferInsert)
+ } as UserMemoryActivityInsert)
.returning();
return { activity, memory };
@@ -156,7 +163,7 @@ const createContextPair = async (opts: {
type: opts.type ?? 'project',
userId,
userMemoryIds: [memory.id],
- } as typeof userMemoriesContexts.$inferInsert)
+ } as UserMemoryContextInsert)
.returning();
return { context, memory };
@@ -198,7 +205,7 @@ const createExperiencePair = async (opts: {
type: opts.type ?? 'lesson',
userId,
userMemoryId: memory.id,
- } as typeof userMemoriesExperiences.$inferInsert)
+ } as UserMemoryExperienceInsert)
.returning();
return { experience, memory };
@@ -238,7 +245,7 @@ const createPreferencePair = async (opts: {
type: opts.type ?? 'coding-style',
userId,
userMemoryId: memory.id,
- } as typeof userMemoriesPreferences.$inferInsert)
+ } as UserMemoryPreferenceInsert)
.returning();
return { memory, preference };
@@ -283,7 +290,7 @@ const createIdentityPair = async (opts: {
type: opts.type ?? 'personal',
userId,
userMemoryId: memory.id,
- } as typeof userMemoriesIdentities.$inferInsert)
+ } as UserMemoryIdentityInsert)
.returning();
return { identity, memory };
diff --git a/packages/database/src/models/userMemory/activity.ts b/packages/database/src/models/userMemory/activity.ts
index 17c25f22fb4..7d85b9496ed 100644
--- a/packages/database/src/models/userMemory/activity.ts
+++ b/packages/database/src/models/userMemory/activity.ts
@@ -1,9 +1,13 @@
-import type { ActivityListParams, ActivityListResult } from '@lobechat/types';
+import type {
+ ActivityListParams,
+ ActivityListResult,
+ UserMemoryActivity,
+ UserMemoryActivityInsert,
+} from '@lobechat/types';
import type { SQL } from 'drizzle-orm';
import { and, asc, desc, eq, inArray, or, sql } from 'drizzle-orm';
import type { FtsSearchCandidateSource } from '../../repositories/ftsSearch';
-import type { NewUserMemoryActivity, UserMemoryActivity } from '../../schemas';
import { userMemories, userMemoriesActivities } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { normalizeBm25MatchQuery, SAFE_BM25_QUERY_OPTIONS } from '../../utils/bm25';
@@ -29,7 +33,7 @@ export class UserMemoryActivityModel {
return buildUserMemoryWhere(this.db, this.userId, table);
}
- create = async (params: Omit<NewUserMemoryActivity, 'userId'>) => {
+ create = async (params: Omit<UserMemoryActivityInsert, 'userId'>) => {
const [result] = await this.db
.insert(userMemoriesActivities)
.values({ ...params, userId: this.userId })
diff --git a/packages/database/src/models/userMemory/context.ts b/packages/database/src/models/userMemory/context.ts
index 1819a66ea56..9d98c1c7f62 100644
--- a/packages/database/src/models/userMemory/context.ts
+++ b/packages/database/src/models/userMemory/context.ts
@@ -1,6 +1,6 @@
+import type { UserMemoryContext, UserMemoryContextInsert } from '@lobechat/types';
import { and, desc, eq } from 'drizzle-orm';
-import type { NewUserMemoryContext, UserMemoryContext } from '../../schemas';
import { userMemories, userMemoriesContexts } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { buildUserMemoryWhere } from './where';
@@ -18,7 +18,7 @@ export class UserMemoryContextModel {
return buildUserMemoryWhere(this.db, this.userId, table);
}
- create = async (params: Omit<NewUserMemoryContext, 'userId'>) => {
+ create = async (params: Omit<UserMemoryContextInsert, 'userId'>) => {
const [result] = await this.db
.insert(userMemoriesContexts)
.values({ ...params, userId: this.userId })
diff --git a/packages/database/src/models/userMemory/experience.ts b/packages/database/src/models/userMemory/experience.ts
index e64a68ad347..3bff8b90a45 100644
--- a/packages/database/src/models/userMemory/experience.ts
+++ b/packages/database/src/models/userMemory/experience.ts
@@ -1,9 +1,13 @@
-import type { ExperienceListParams, ExperienceListResult } from '@lobechat/types';
+import type {
+ ExperienceListParams,
+ ExperienceListResult,
+ UserMemoryExperience,
+ UserMemoryExperienceInsert,
+} from '@lobechat/types';
import type { SQL } from 'drizzle-orm';
import { and, asc, desc, eq, inArray, or, sql } from 'drizzle-orm';
import type { FtsSearchCandidateSource } from '../../repositories/ftsSearch';
-import type { NewUserMemoryExperience, UserMemoryExperience } from '../../schemas';
import { userMemories, userMemoriesExperiences } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { normalizeBm25MatchQuery, SAFE_BM25_QUERY_OPTIONS } from '../../utils/bm25';
@@ -29,7 +33,7 @@ export class UserMemoryExperienceModel {
return buildUserMemoryWhere(this.db, this.userId, table);
}
- create = async (params: Omit<NewUserMemoryExperience, 'userId'>) => {
+ create = async (params: Omit<UserMemoryExperienceInsert, 'userId'>) => {
const [result] = await this.db
.insert(userMemoriesExperiences)
.values({ ...params, userId: this.userId })
diff --git a/packages/database/src/models/userMemory/identity.ts b/packages/database/src/models/userMemory/identity.ts
index c32f59f9fc6..05d6c7ed8e9 100644
--- a/packages/database/src/models/userMemory/identity.ts
+++ b/packages/database/src/models/userMemory/identity.ts
@@ -1,10 +1,14 @@
-import type { IdentityListParams, IdentityListResult } from '@lobechat/types';
+import type {
+ IdentityListParams,
+ IdentityListResult,
+ UserMemoryIdentity,
+ UserMemoryIdentityInsert,
+} from '@lobechat/types';
import { RelationshipEnum } from '@lobechat/types';
import type { SQL } from 'drizzle-orm';
import { and, asc, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm';
import type { FtsSearchCandidateSource } from '../../repositories/ftsSearch';
-import type { NewUserMemoryIdentity, UserMemoryIdentity } from '../../schemas';
import { userMemories, userMemoriesIdentities } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { normalizeBm25MatchQuery, SAFE_BM25_QUERY_OPTIONS } from '../../utils/bm25';
@@ -30,7 +34,7 @@ export class UserMemoryIdentityModel {
return buildUserMemoryWhere(this.db, this.userId, table);
}
- create = async (params: Omit<NewUserMemoryIdentity, 'userId'>) => {
+ create = async (params: Omit<UserMemoryIdentityInsert, 'userId'>) => {
const [result] = await this.db
.insert(userMemoriesIdentities)
.values({ ...params, userId: this.userId })
diff --git a/packages/database/src/models/userMemory/model/context.ts b/packages/database/src/models/userMemory/model/context.ts
index be46d53577f..d892206264c 100644
--- a/packages/database/src/models/userMemory/model/context.ts
+++ b/packages/database/src/models/userMemory/model/context.ts
@@ -1,13 +1,14 @@
import type {
MemorySourceType,
+ UserMemoryActivityWithoutVectors,
UserMemoryContextWithoutVectors,
UserMemoryExperienceWithoutVectors,
+ UserMemoryInsert,
UserMemoryPreferenceWithoutVectors,
UserMemoryWithoutVectors,
} from '@lobechat/types';
import type { FtsSearchCandidateSource } from '../../../repositories/ftsSearch';
-import type { userMemories, UserMemoryActivitiesWithoutVectors } from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import type { TopicModel } from '../../topic';
import type { buildUserMemoryWhere } from '../where';
@@ -31,7 +32,7 @@ export interface UserMemoryModelContext {
status?: string | null;
tags?: string[] | null;
},
- ) => typeof userMemories.$inferInsert;
+ ) => UserMemoryInsert;
readonly db: LobeChatDatabase;
extractSourceMetadata: (metadata?: Record<string, unknown> | null) => {
sourceId?: string;
@@ -42,7 +43,7 @@ export interface UserMemoryModelContext {
memoryWhere: (
table: Parameters<typeof buildUserMemoryWhere>[2],
) => ReturnType<typeof buildUserMemoryWhere>;
- searchActivities: (params: SearchLayerParams) => Promise<UserMemoryActivitiesWithoutVectors[]>;
+ searchActivities: (params: SearchLayerParams) => Promise<UserMemoryActivityWithoutVectors[]>;
searchContexts: (params: SearchLayerParams) => Promise<UserMemoryContextWithoutVectors[]>;
searchExperiences: (params: SearchLayerParams) => Promise<UserMemoryExperienceWithoutVectors[]>;
searchPreferences: (params: SearchLayerParams) => Promise<UserMemoryPreferenceWithoutVectors[]>;
diff --git a/packages/database/src/models/userMemory/model/create.ts b/packages/database/src/models/userMemory/model/create.ts
index 89a430a4f28..e35a10a8de0 100644
--- a/packages/database/src/models/userMemory/model/create.ts
+++ b/packages/database/src/models/userMemory/model/create.ts
@@ -1,12 +1,16 @@
-import { ActivityTypeEnum } from '@lobechat/types';
-
import type {
+ UserMemory,
UserMemoryActivity,
+ UserMemoryActivityInsert,
UserMemoryContext,
+ UserMemoryContextInsert,
UserMemoryExperience,
- UserMemoryItem,
+ UserMemoryExperienceInsert,
UserMemoryPreference,
-} from '../../../schemas';
+ UserMemoryPreferenceInsert,
+} from '@lobechat/types';
+import { ActivityTypeEnum } from '@lobechat/types';
+
import {
userMemories,
userMemoriesActivities,
@@ -27,7 +31,7 @@ import { coerceDate } from './utils';
export const create = async (
ctx: UserMemoryModelContext,
params: CreateUserMemoryParams,
-): Promise<UserMemoryItem> => {
+): Promise<UserMemory> => {
const [result] = await ctx.db
.insert(userMemories)
.values(ctx.buildBaseMemoryInsertValues(params))
@@ -39,7 +43,10 @@ export const create = async (
export const createContextMemory = async (
ctx: UserMemoryModelContext,
params: CreateUserMemoryContextParams,
-): Promise<{ context: UserMemoryContext; memory: UserMemoryItem }> => {
+): Promise<{
+ context: UserMemoryContext;
+ memory: UserMemory;
+}> => {
return ctx.db.transaction(async (tx) => {
const baseValues = ctx.buildBaseMemoryInsertValues(params, {
metadata: params.context.metadata ?? null,
@@ -56,16 +63,22 @@ export const createContextMemory = async (
currentStatus: params.context.currentStatus ?? null,
description: params.context.description ?? null,
descriptionVector: params.context.descriptionVector ?? null,
+ firstSeenAt: params.context.firstSeenAt ?? null,
+ lastEvidenceAt: params.context.lastEvidenceAt ?? null,
metadata: params.context.metadata ?? null,
+ nextSteps: params.context.nextSteps ?? null,
+ now: params.context.now ?? null,
+ openQuestions: params.context.openQuestions ?? null,
scoreImpact: params.context.scoreImpact ?? null,
scoreUrgency: params.context.scoreUrgency ?? null,
+ synthesizedAt: params.context.synthesizedAt ?? null,
tags: params.context.tags ?? [],
title: params.context.title ?? null,
type: params.context.type ?? null,
userId: ctx.userId,
userMemoryId: memory.id,
userMemoryIds: [memory.id],
- } satisfies typeof userMemoriesContexts.$inferInsert;
+ } satisfies UserMemoryContextInsert;
const [context] = await tx.insert(userMemoriesContexts).values(contextValues).returning();
@@ -76,7 +89,10 @@ export const createContextMemory = async (
export const createExperienceMemory = async (
ctx: UserMemoryModelContext,
params: CreateUserMemoryExperienceParams,
-): Promise<{ experience: UserMemoryExperience; memory: UserMemoryItem }> => {
+): Promise<{
+ experience: UserMemoryExperience;
+ memory: UserMemory;
+}> => {
return ctx.db.transaction(async (tx) => {
const baseValues = ctx.buildBaseMemoryInsertValues(params, {
metadata: params.experience.metadata ?? null,
@@ -102,7 +118,7 @@ export const createExperienceMemory = async (
type: params.experience.type ?? params.memoryType ?? null,
userId: ctx.userId,
userMemoryId: memory.id,
- } satisfies typeof userMemoriesExperiences.$inferInsert;
+ } satisfies UserMemoryExperienceInsert;
const [experience] = await tx
.insert(userMemoriesExperiences)
@@ -116,7 +132,10 @@ export const createExperienceMemory = async (
export const createActivityMemory = async (
ctx: UserMemoryModelContext,
params: CreateUserMemoryActivityParams,
-): Promise<{ activity: UserMemoryActivity; memory: UserMemoryItem }> => {
+): Promise<{
+ activity: UserMemoryActivity;
+ memory: UserMemory;
+}> => {
return ctx.db.transaction(async (tx) => {
const baseValues = ctx.buildBaseMemoryInsertValues(params, {
metadata: params.activity.metadata ?? null,
@@ -132,9 +151,11 @@ export const createActivityMemory = async (
associatedObjects: params.activity.associatedObjects ?? [],
associatedSubjects: params.activity.associatedSubjects ?? [],
capturedAt: params.activity.capturedAt,
+ dossierId: params.activity.dossierId ?? null,
endsAt: coerceDate(params.activity.endsAt),
feedback: params.activity.feedback ?? null,
feedbackVector: params.activity.feedbackVector ?? null,
+ injectable: params.activity.injectable ?? true,
metadata: params.activity.metadata ?? null,
narrative: params.activity.narrative ?? null,
narrativeVector: params.activity.narrativeVector ?? null,
@@ -146,7 +167,7 @@ export const createActivityMemory = async (
type: params.activity.type ?? ActivityTypeEnum.Other,
userId: ctx.userId,
userMemoryId: memory.id,
- } satisfies typeof userMemoriesActivities.$inferInsert;
+ } satisfies UserMemoryActivityInsert;
const [activity] = await tx.insert(userMemoriesActivities).values(activityValues).returning();
@@ -157,7 +178,10 @@ export const createActivityMemory = async (
export const createPreferenceMemory = async (
ctx: UserMemoryModelContext,
params: CreateUserMemoryPreferenceParams,
-): Promise<{ memory: UserMemoryItem; preference: UserMemoryPreference }> => {
+): Promise<{
+ memory: UserMemory;
+ preference: UserMemoryPreference;
+}> => {
return ctx.db.transaction(async (tx) => {
const baseValues = ctx.buildBaseMemoryInsertValues(params, {
metadata: params.preference.metadata ?? null,
@@ -168,17 +192,23 @@ export const createPreferenceMemory = async (
if (!memory) throw new Error('Failed to create user memory preference');
const preferenceValues = {
+ appliesToEntityId: params.preference.appliesToEntityId ?? null,
capturedAt: params.preference.capturedAt,
conclusionDirectives: params.preference.conclusionDirectives ?? null,
conclusionDirectivesVector: params.preference.conclusionDirectivesVector ?? null,
+ evidenceCount: params.preference.evidenceCount ?? 1,
+ evidenceSource: params.preference.evidenceSource ?? null,
+ holderEntityId: params.preference.holderEntityId ?? null,
+ lastEvidenceAt: params.preference.lastEvidenceAt ?? null,
metadata: params.preference.metadata ?? null,
scorePriority: params.preference.scorePriority ?? null,
+ scope: params.preference.scope ?? null,
suggestions: params.preference.suggestions ?? null,
tags: params.preference.tags ?? [],
type: params.preference.type ?? params.memoryType ?? null,
userId: ctx.userId,
userMemoryId: memory.id,
- } satisfies typeof userMemoriesPreferences.$inferInsert;
+ } satisfies UserMemoryPreferenceInsert;
const [preference] = await tx
.insert(userMemoriesPreferences)
diff --git a/packages/database/src/models/userMemory/model/detail.ts b/packages/database/src/models/userMemory/model/detail.ts
index 5bb3b62f2c0..8d265be9ce5 100644
--- a/packages/database/src/models/userMemory/model/detail.ts
+++ b/packages/database/src/models/userMemory/model/detail.ts
@@ -1,4 +1,5 @@
import type {
+ UserMemory,
UserMemoryContextWithoutVectors,
UserMemoryDetail,
UserMemoryWithoutVectors,
@@ -6,7 +7,6 @@ import type {
import { LayersEnum } from '@lobechat/types';
import { and, eq } from 'drizzle-orm';
-import type { UserMemoryItem } from '../../../schemas';
import {
userMemories,
userMemoriesActivities,
@@ -28,6 +28,13 @@ export const getMemoryDetail = async (
case LayersEnum.Context: {
const [context] = await ctx.db
.select({
+ userMemoryId: userMemoriesContexts.userMemoryId,
+ now: userMemoriesContexts.now,
+ nextSteps: userMemoriesContexts.nextSteps,
+ openQuestions: userMemoriesContexts.openQuestions,
+ firstSeenAt: userMemoriesContexts.firstSeenAt,
+ lastEvidenceAt: userMemoriesContexts.lastEvidenceAt,
+ synthesizedAt: userMemoriesContexts.synthesizedAt,
accessedAt: userMemoriesContexts.accessedAt,
associatedObjects: userMemoriesContexts.associatedObjects,
associatedSubjects: userMemoriesContexts.associatedSubjects,
@@ -84,6 +91,8 @@ export const getMemoryDetail = async (
case LayersEnum.Activity: {
const [activity] = await ctx.db
.select({
+ dossierId: userMemoriesActivities.dossierId,
+ injectable: userMemoriesActivities.injectable,
accessedAt: userMemoriesActivities.accessedAt,
associatedLocations: userMemoriesActivities.associatedLocations,
associatedObjects: userMemoriesActivities.associatedObjects,
@@ -134,6 +143,7 @@ export const getMemoryDetail = async (
case LayersEnum.Experience: {
const [experience] = await ctx.db
.select({
+ capturedAt: userMemoriesExperiences.capturedAt,
accessedAt: userMemoriesExperiences.accessedAt,
action: userMemoriesExperiences.action,
createdAt: userMemoriesExperiences.createdAt,
@@ -179,6 +189,7 @@ export const getMemoryDetail = async (
case LayersEnum.Identity: {
const [identity] = await ctx.db
.select({
+ entityId: userMemoriesIdentities.entityId,
accessedAt: userMemoriesIdentities.accessedAt,
capturedAt: userMemoriesIdentities.capturedAt,
createdAt: userMemoriesIdentities.createdAt,
@@ -223,6 +234,12 @@ export const getMemoryDetail = async (
case LayersEnum.Preference: {
const [preference] = await ctx.db
.select({
+ lastEvidenceAt: userMemoriesPreferences.lastEvidenceAt,
+ evidenceCount: userMemoriesPreferences.evidenceCount,
+ holderEntityId: userMemoriesPreferences.holderEntityId,
+ appliesToEntityId: userMemoriesPreferences.appliesToEntityId,
+ scope: userMemoriesPreferences.scope,
+ evidenceSource: userMemoriesPreferences.evidenceSource,
accessedAt: userMemoriesPreferences.accessedAt,
capturedAt: userMemoriesPreferences.capturedAt,
conclusionDirectives: userMemoriesPreferences.conclusionDirectives,
@@ -272,6 +289,10 @@ export const findUserMemoryRawById = async (
): Promise<UserMemoryWithoutVectors | undefined> => {
const [memory] = await ctx.db
.select({
+ state: userMemories.state,
+ userLocked: userMemories.userLocked,
+ deletedAt: userMemories.deletedAt,
+ isDeleted: userMemories.isDeleted,
accessedAt: userMemories.accessedAt,
accessedCount: userMemories.accessedCount,
capturedAt: userMemories.capturedAt,
@@ -303,7 +324,7 @@ export const findUserMemoryRawById = async (
export const findById = async (
ctx: UserMemoryModelContext,
id: string,
-): Promise<UserMemoryItem | undefined> => {
+): Promise<UserMemory | undefined> => {
const result = await ctx.db.query.userMemories.findFirst({
where: and(eq(userMemories.id, id), ctx.memoryWhere(userMemories)),
});
diff --git a/packages/database/src/models/userMemory/model/identities.ts b/packages/database/src/models/userMemory/model/identities.ts
index 0f2c06d3502..156d476a26c 100644
--- a/packages/database/src/models/userMemory/model/identities.ts
+++ b/packages/database/src/models/userMemory/model/identities.ts
@@ -1,4 +1,8 @@
-import type { UserMemoryIdentityWithoutVectors } from '@lobechat/types';
+import type {
+ UserMemoryIdentityInsert,
+ UserMemoryIdentityWithoutVectors,
+ UserMemoryInsert,
+} from '@lobechat/types';
import { IdentityTypeEnum, RelationshipEnum } from '@lobechat/types';
import type { AnyColumn } from 'drizzle-orm';
import { and, desc, eq, sql } from 'drizzle-orm';
@@ -55,7 +59,7 @@ export const addIdentityEntry = async (
return ctx.db.transaction(async (tx) => {
const base = params.base ?? {};
- const baseValues: typeof userMemories.$inferInsert = {
+ const baseValues: UserMemoryInsert = {
accessedCount: 0,
capturedAt: base.capturedAt,
details: base.details ?? null,
@@ -79,7 +83,7 @@ export const addIdentityEntry = async (
.returning({ id: userMemories.id });
const identity = params.identity ?? {};
- const identityValues: typeof userMemoriesIdentities.$inferInsert = {
+ const identityValues: UserMemoryIdentityInsert = {
capturedAt: identity.capturedAt,
description: identity.description ?? null,
descriptionVector: identity.descriptionVector ?? null,
@@ -132,8 +136,8 @@ export const updateIdentityEntry = async (
return false;
}
- let baseUpdate: Partial<typeof userMemories.$inferInsert> = {};
- let identityUpdate: Partial<typeof userMemoriesIdentities.$inferInsert> = {};
+ let baseUpdate: Partial<UserMemoryInsert> = {};
+ let identityUpdate: Partial<UserMemoryIdentityInsert> = {};
if (params.base) {
baseUpdate = merge(baseUpdate, params.base);
diff --git a/packages/database/src/models/userMemory/model/index.ts b/packages/database/src/models/userMemory/model/index.ts
index 0d1bd6b01f8..0d0907da5ac 100644
--- a/packages/database/src/models/userMemory/model/index.ts
+++ b/packages/database/src/models/userMemory/model/index.ts
@@ -5,11 +5,11 @@ import type {
QueryTaxonomyOptionsResult,
SearchMemoryParams,
UserMemoryDetail,
+ UserMemoryInsert,
} from '@lobechat/types';
import { MemorySourceType } from '@lobechat/types';
import type { FtsSearchCandidateSource } from '../../../repositories/ftsSearch';
-import type { userMemories } from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { TopicModel } from '../../topic';
import type { UserMemoryHybridSearchAggregatedResult } from '../query';
@@ -288,7 +288,7 @@ export class UserMemoryModel {
status?: string | null;
tags?: string[] | null;
},
- ): typeof userMemories.$inferInsert {
+ ): UserMemoryInsert {
const now = new Date();
return {
@@ -307,7 +307,7 @@ export class UserMemoryModel {
tags: options?.tags ?? null,
title: params.title ?? null,
userId: this.userId,
- } satisfies typeof userMemories.$inferInsert;
+ } satisfies UserMemoryInsert;
}
create = (params: CreateUserMemoryParams) => create(this.context, params);
diff --git a/packages/database/src/models/userMemory/model/listMemories.ts b/packages/database/src/models/userMemory/model/listMemories.ts
index a50f3a297b3..0e82383f2b9 100644
--- a/packages/database/src/models/userMemory/model/listMemories.ts
+++ b/packages/database/src/models/userMemory/model/listMemories.ts
@@ -1,15 +1,15 @@
-import type { UserMemoryDetail } from '@lobechat/types';
-import { LayersEnum } from '@lobechat/types';
-import type { AnyColumn, SQL } from 'drizzle-orm';
-import { and, asc, desc, eq, sql } from 'drizzle-orm';
-
import type {
UserMemoryActivity,
UserMemoryContext,
+ UserMemoryDetail,
UserMemoryExperience,
UserMemoryIdentity,
UserMemoryPreference,
-} from '../../../schemas';
+} from '@lobechat/types';
+import { LayersEnum } from '@lobechat/types';
+import type { AnyColumn, SQL } from 'drizzle-orm';
+import { and, asc, desc, eq, sql } from 'drizzle-orm';
+
import {
userMemories,
userMemoriesContexts,
@@ -21,15 +21,30 @@ import { selectNonVectorColumns } from '../../../utils/columns';
import type { UserMemoryModelContext } from './context';
export type ListMemoriesItem<L extends LayersEnum> = L extends LayersEnum.Context
- ? UserMemoryDetail & { context: UserMemoryContext; layer: LayersEnum.Context }
+ ? UserMemoryDetail & {
+ context: UserMemoryContext;
+ layer: LayersEnum.Context;
+ }
: L extends LayersEnum.Experience
- ? UserMemoryDetail & { experience: UserMemoryExperience; layer: LayersEnum.Experience }
+ ? UserMemoryDetail & {
+ experience: UserMemoryExperience;
+ layer: LayersEnum.Experience;
+ }
: L extends LayersEnum.Identity
- ? UserMemoryDetail & { identity: UserMemoryIdentity; layer: LayersEnum.Identity }
+ ? UserMemoryDetail & {
+ identity: UserMemoryIdentity;
+ layer: LayersEnum.Identity;
+ }
: L extends LayersEnum.Preference
- ? UserMemoryDetail & { layer: LayersEnum.Preference; preference: UserMemoryPreference }
+ ? UserMemoryDetail & {
+ layer: LayersEnum.Preference;
+ preference: UserMemoryPreference;
+ }
: L extends LayersEnum.Activity
- ? UserMemoryDetail & { activity: UserMemoryActivity; layer: LayersEnum.Activity }
+ ? UserMemoryDetail & {
+ activity: UserMemoryActivity;
+ layer: LayersEnum.Activity;
+ }
: never;
export interface ListMemoriesParams<L extends LayersEnum> {
diff --git a/packages/database/src/models/userMemory/model/search.ts b/packages/database/src/models/userMemory/model/search.ts
index 8a0dc843068..0b092ec3fc5 100644
--- a/packages/database/src/models/userMemory/model/search.ts
+++ b/packages/database/src/models/userMemory/model/search.ts
@@ -1,11 +1,11 @@
import type {
+ UserMemoryActivityWithoutVectors,
UserMemoryContextWithoutVectors,
UserMemoryExperienceWithoutVectors,
UserMemoryPreferenceWithoutVectors,
} from '@lobechat/types';
import { and, cosineDistance, desc, eq, sql } from 'drizzle-orm';
-import type { UserMemoryActivitiesWithoutVectors } from '../../../schemas';
import {
userMemoriesActivities,
userMemoriesContexts,
@@ -86,7 +86,7 @@ export const searchActivities = async (
limit?: number;
type?: string;
},
-): Promise<UserMemoryActivitiesWithoutVectors[]> => {
+): Promise<UserMemoryActivityWithoutVectors[]> => {
const { embedding, limit = 5, type } = params;
if (limit <= 0) {
return [];
@@ -135,7 +135,7 @@ export const searchActivities = async (
} else {
query = query.orderBy(desc(userMemoriesActivities.createdAt));
}
- return query.limit(limit) as Promise<UserMemoryActivitiesWithoutVectors[]>;
+ return query.limit(limit) as Promise<UserMemoryActivityWithoutVectors[]>;
};
export const searchContexts = async (
diff --git a/packages/database/src/models/userMemory/model/types.ts b/packages/database/src/models/userMemory/model/types.ts
index 8fe222f01b4..16f6176484e 100644
--- a/packages/database/src/models/userMemory/model/types.ts
+++ b/packages/database/src/models/userMemory/model/types.ts
@@ -5,23 +5,20 @@ import type {
Optional,
RelationshipEnum,
TypesEnum,
+ UserMemoryActivity,
+ UserMemoryActivityWithoutVectors,
+ UserMemoryContext,
UserMemoryContextObjectType,
UserMemoryContextSubjectType,
UserMemoryContextWithoutVectors,
+ UserMemoryExperience,
UserMemoryExperienceWithoutVectors,
+ UserMemoryIdentity,
UserMemoryItemSimple,
+ UserMemoryPreference,
UserMemoryPreferenceWithoutVectors,
} from '@lobechat/types';
-import type {
- UserMemoryActivitiesWithoutVectors,
- UserMemoryActivity,
- UserMemoryContext,
- UserMemoryExperience,
- UserMemoryIdentity,
- UserMemoryPreference,
-} from '../../../schemas';
-
export interface BaseCreateUserMemoryParams {
capturedAt?: Date;
details: string;
@@ -121,7 +118,7 @@ export interface SearchUserMemoryWithEmbeddingParams {
}
export interface UserMemorySearchAggregatedResult {
- activities: UserMemoryActivitiesWithoutVectors[];
+ activities: UserMemoryActivityWithoutVectors[];
contexts: UserMemoryContextWithoutVectors[];
experiences: UserMemoryExperienceWithoutVectors[];
preferences: UserMemoryPreferenceWithoutVectors[];
diff --git a/packages/database/src/models/userMemory/model/vectors.ts b/packages/database/src/models/userMemory/model/vectors.ts
index 06d680404f2..8cc222004ed 100644
--- a/packages/database/src/models/userMemory/model/vectors.ts
+++ b/packages/database/src/models/userMemory/model/vectors.ts
@@ -1,3 +1,11 @@
+import type {
+ UserMemoryActivityInsert,
+ UserMemoryContextInsert,
+ UserMemoryExperienceInsert,
+ UserMemoryIdentityInsert,
+ UserMemoryInsert,
+ UserMemoryPreferenceInsert,
+} from '@lobechat/types';
import { and, eq } from 'drizzle-orm';
import {
@@ -34,7 +42,7 @@ export const updateUserMemoryVectors = async (
id: string,
vectors: UpdateUserMemoryVectorsParams,
): Promise<void> => {
- const vectorUpdates: Partial<typeof userMemories.$inferInsert> = {};
+ const vectorUpdates: Partial<UserMemoryInsert> = {};
if (vectors.detailsVector1024 !== undefined) {
vectorUpdates.detailsVector1024 = vectors.detailsVector1024;
}
@@ -60,7 +68,7 @@ export const updateContextVectors = async (
id: string,
vectors: UpdateContextVectorsParams,
): Promise<void> => {
- const vectorUpdates: Partial<typeof userMemoriesContexts.$inferInsert> = {};
+ const vectorUpdates: Partial<UserMemoryContextInsert> = {};
if (vectors.descriptionVector !== undefined) {
vectorUpdates.descriptionVector = vectors.descriptionVector;
}
@@ -82,7 +90,7 @@ export const updatePreferenceVectors = async (
id: string,
vectors: UpdatePreferenceVectorsParams,
): Promise<void> => {
- const vectorUpdates: Partial<typeof userMemoriesPreferences.$inferInsert> = {};
+ const vectorUpdates: Partial<UserMemoryPreferenceInsert> = {};
if (vectors.conclusionDirectivesVector !== undefined) {
vectorUpdates.conclusionDirectivesVector = vectors.conclusionDirectivesVector;
}
@@ -105,7 +113,7 @@ export const updateIdentityVectors = async (
id: string,
vectors: UpdateIdentityVectorsParams,
): Promise<void> => {
- const vectorUpdates: Partial<typeof userMemoriesIdentities.$inferInsert> = {};
+ const vectorUpdates: Partial<UserMemoryIdentityInsert> = {};
if (vectors.descriptionVector !== undefined) {
vectorUpdates.descriptionVector = vectors.descriptionVector;
}
@@ -128,7 +136,7 @@ export const updateExperienceVectors = async (
id: string,
vectors: UpdateExperienceVectorsParams,
): Promise<void> => {
- const vectorUpdates: Partial<typeof userMemoriesExperiences.$inferInsert> = {};
+ const vectorUpdates: Partial<UserMemoryExperienceInsert> = {};
if (vectors.actionVector !== undefined) {
vectorUpdates.actionVector = vectors.actionVector;
}
@@ -157,7 +165,7 @@ export const updateActivityVectors = async (
id: string,
vectors: { feedbackVector?: number[] | null; narrativeVector?: number[] | null },
): Promise<void> => {
- const vectorUpdates: Partial<typeof userMemoriesActivities.$inferInsert> = {};
+ const vectorUpdates: Partial<UserMemoryActivityInsert> = {};
if (vectors.feedbackVector !== undefined) {
vectorUpdates.feedbackVector = vectors.feedbackVector;
}
diff --git a/packages/database/src/models/userMemory/persona.ts b/packages/database/src/models/userMemory/persona.ts
index d92d6282509..400008c1ac0 100644
--- a/packages/database/src/models/userMemory/persona.ts
+++ b/packages/database/src/models/userMemory/persona.ts
@@ -1,13 +1,13 @@
+import type {
+ UserPersonaDocument,
+ UserPersonaDocumentHistory,
+ UserPersonaDocumentHistoryInsert,
+ UserPersonaDocumentInsert,
+} from '@lobechat/types';
import { isPlainRecord } from '@lobechat/utils/object';
import { and, desc, eq } from 'drizzle-orm';
import isEqual from 'fast-deep-equal';
-import type {
- NewUserPersonaDocument,
- NewUserPersonaDocumentHistoriesItem,
- UserPersonaDocument,
- UserPersonaDocumentHistoriesItem,
-} from '../../schemas';
import { userPersonaDocumentHistories, userPersonaDocuments, users } from '../../schemas';
import type { LobeChatDatabase, Transaction } from '../../type';
@@ -68,7 +68,10 @@ export const upsertUserPersonaInTransaction = async (
tx: Transaction,
userId: string,
params: UpsertUserPersonaParams,
-): Promise<{ diff?: UserPersonaDocumentHistoriesItem; document: UserPersonaDocument }> => {
+): Promise<{
+ diff?: UserPersonaDocumentHistory;
+ document: UserPersonaDocument;
+}> => {
await lockUserPersonaOwner(tx, userId);
const nextProfile = params.profile ?? 'default';
@@ -83,7 +86,7 @@ export const upsertUserPersonaInTransaction = async (
const nextSourceIds = params.sourceIds ?? existing?.sourceIds ?? undefined;
const nextTagline = params.tagline === undefined ? existing?.tagline : params.tagline;
- const baseDocument: Omit<NewUserPersonaDocument, 'id' | 'userId'> = {
+ const baseDocument: Omit<UserPersonaDocumentInsert, 'id' | 'userId'> = {
capturedAt: params.capturedAt,
memoryIds: nextMemoryIds,
metadata: nextMetadata,
@@ -141,7 +144,7 @@ export const upsertUserPersonaInTransaction = async (
.returning();
}
- let diff: UserPersonaDocumentHistoriesItem | undefined;
+ let diff: UserPersonaDocumentHistory | undefined;
const hasDiff =
params.diffPersona ||
params.diffTagline ||
@@ -235,8 +238,10 @@ export class UserPersonaModel {
};
appendDiff = async (
- params: Omit<NewUserPersonaDocumentHistoriesItem, 'id' | 'userId'> & { personaId: string },
- ): Promise<UserPersonaDocumentHistoriesItem> => {
+ params: Omit<UserPersonaDocumentHistoryInsert, 'id' | 'userId'> & {
+ personaId: string;
+ },
+ ): Promise<UserPersonaDocumentHistory> => {
const [result] = await this.db
.insert(userPersonaDocumentHistories)
.values({ ...params, userId: this.userId })
@@ -261,7 +266,10 @@ export class UserPersonaModel {
upsertPersona = async (
params: UpsertUserPersonaParams,
- ): Promise<{ diff?: UserPersonaDocumentHistoriesItem; document: UserPersonaDocument }> => {
+ ): Promise<{
+ diff?: UserPersonaDocumentHistory;
+ document: UserPersonaDocument;
+ }> => {
return this.db.transaction((tx) => upsertUserPersonaInTransaction(tx, this.userId, params));
};
diff --git a/packages/database/src/models/userMemory/preference.ts b/packages/database/src/models/userMemory/preference.ts
index 619ee2d5dca..4997906a7a9 100644
--- a/packages/database/src/models/userMemory/preference.ts
+++ b/packages/database/src/models/userMemory/preference.ts
@@ -1,6 +1,6 @@
+import type { UserMemoryPreference, UserMemoryPreferenceInsert } from '@lobechat/types';
import { and, desc, eq } from 'drizzle-orm';
-import type { NewUserMemoryPreference, UserMemoryPreference } from '../../schemas';
import { userMemories, userMemoriesPreferences } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { buildUserMemoryWhere } from './where';
@@ -18,7 +18,7 @@ export class UserMemoryPreferenceModel {
return buildUserMemoryWhere(this.db, this.userId, table);
}
- create = async (params: Omit<NewUserMemoryPreference, 'userId'>) => {
+ create = async (params: Omit<UserMemoryPreferenceInsert, 'userId'>) => {
const [result] = await this.db
.insert(userMemoriesPreferences)
.values({ ...params, userId: this.userId })
diff --git a/packages/database/src/models/userMemory/query/index.ts b/packages/database/src/models/userMemory/query/index.ts
index df012103cdd..b0988108665 100644
--- a/packages/database/src/models/userMemory/query/index.ts
+++ b/packages/database/src/models/userMemory/query/index.ts
@@ -3,6 +3,7 @@ import type {
QueryTaxonomyOptionsParams,
QueryTaxonomyOptionsResult,
SearchMemoryParams,
+ UserMemoryIdentityWithoutVectors,
} from '@lobechat/types';
import type { AnyColumn, SQL } from 'drizzle-orm';
@@ -18,7 +19,6 @@ import type {
userMemoriesExperiences,
userMemoriesIdentities,
userMemoriesPreferences,
- UserMemoryIdentitiesWithoutVectors,
} from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { buildUserMemoryWhere } from '../where';
@@ -413,7 +413,7 @@ export class UserMemoryQueryModel {
embedding: number[],
limit: number,
params: SearchMemoryParams,
- ): Promise<UserMemoryIdentitiesWithoutVectors[]> {
+ ): Promise<UserMemoryIdentityWithoutVectors[]> {
return searchIdentitiesSemantic(this.context, embedding, limit, params);
}
diff --git a/packages/database/src/models/userMemory/query/lexical.ts b/packages/database/src/models/userMemory/query/lexical.ts
index 4b38ee8b610..3e6f4e6d5af 100644
--- a/packages/database/src/models/userMemory/query/lexical.ts
+++ b/packages/database/src/models/userMemory/query/lexical.ts
@@ -1,14 +1,14 @@
-import type { SearchMemoryParams } from '@lobechat/types';
+import type {
+ SearchMemoryParams,
+ UserMemoryActivityWithoutVectors,
+ UserMemoryContextWithoutVectors,
+ UserMemoryExperienceWithoutVectors,
+ UserMemoryIdentityWithoutVectors,
+ UserMemoryPreferenceWithoutVectors,
+} from '@lobechat/types';
import type { SQL } from 'drizzle-orm';
import { and, desc, eq, inArray, or, sql } from 'drizzle-orm';
-import type {
- UserMemoryActivitiesWithoutVectors,
- UserMemoryContextsWithoutVectors,
- UserMemoryExperiencesWithoutVectors,
- UserMemoryIdentitiesWithoutVectors,
- UserMemoryPreferencesWithoutVectors,
-} from '../../../schemas';
import {
userMemories,
userMemoriesActivities,
@@ -126,7 +126,7 @@ export async function searchActivitiesLexical(
.orderBy(desc(userMemoriesActivities.capturedAt), desc(userMemoriesActivities.createdAt))
.limit(limit);
- return rowsQuery as Promise<UserMemoryActivitiesWithoutVectors[]>;
+ return rowsQuery as Promise<UserMemoryActivityWithoutVectors[]>;
}
export async function searchContextsLexical(
@@ -255,7 +255,7 @@ export async function searchContextsLexical(
.orderBy(desc(contextCandidates.capturedAt), desc(contextCandidates.createdAt))
.limit(limit);
- return rowsQuery as Promise<UserMemoryContextsWithoutVectors[]>;
+ return rowsQuery as Promise<UserMemoryContextWithoutVectors[]>;
}
export async function searchExperiencesLexical(
@@ -335,7 +335,7 @@ export async function searchExperiencesLexical(
.orderBy(desc(userMemoriesExperiences.capturedAt), desc(userMemoriesExperiences.createdAt))
.limit(limit);
- return rowsQuery as Promise<UserMemoryExperiencesWithoutVectors[]>;
+ return rowsQuery as Promise<UserMemoryExperienceWithoutVectors[]>;
}
export async function searchPreferencesLexical(
@@ -415,7 +415,7 @@ export async function searchPreferencesLexical(
.orderBy(desc(userMemoriesPreferences.capturedAt), desc(userMemoriesPreferences.createdAt))
.limit(limit);
- return rowsQuery as Promise<UserMemoryPreferencesWithoutVectors[]>;
+ return rowsQuery as Promise<UserMemoryPreferenceWithoutVectors[]>;
}
export async function searchIdentitiesLexical(
@@ -486,5 +486,5 @@ export async function searchIdentitiesLexical(
.orderBy(desc(userMemoriesIdentities.capturedAt), desc(userMemoriesIdentities.createdAt))
.limit(limit);
- return rowsQuery as Promise<UserMemoryIdentitiesWithoutVectors[]>;
+ return rowsQuery as Promise<UserMemoryIdentityWithoutVectors[]>;
}
diff --git a/packages/database/src/models/userMemory/query/semantic.ts b/packages/database/src/models/userMemory/query/semantic.ts
index 4f2aee27739..0a7caab25f0 100644
--- a/packages/database/src/models/userMemory/query/semantic.ts
+++ b/packages/database/src/models/userMemory/query/semantic.ts
@@ -1,14 +1,14 @@
-import type { SearchMemoryParams } from '@lobechat/types';
+import type {
+ SearchMemoryParams,
+ UserMemoryActivityWithoutVectors,
+ UserMemoryContextWithoutVectors,
+ UserMemoryExperienceWithoutVectors,
+ UserMemoryIdentityWithoutVectors,
+ UserMemoryPreferenceWithoutVectors,
+} from '@lobechat/types';
import type { SQL } from 'drizzle-orm';
import { and, cosineDistance, desc, eq, inArray, sql } from 'drizzle-orm';
-import type {
- UserMemoryActivitiesWithoutVectors,
- UserMemoryContextsWithoutVectors,
- UserMemoryExperiencesWithoutVectors,
- UserMemoryIdentitiesWithoutVectors,
- UserMemoryPreferencesWithoutVectors,
-} from '../../../schemas';
import {
userMemories,
userMemoriesActivities,
@@ -75,7 +75,7 @@ export async function searchActivitiesSemantic(
.orderBy(desc(sql`1 - (${cosineDistance(userMemoriesActivities.narrativeVector, embedding)})`))
.limit(limit);
- return rowsQuery as Promise<UserMemoryActivitiesWithoutVectors[]>;
+ return rowsQuery as Promise<UserMemoryActivityWithoutVectors[]>;
}
export async function searchContextsSemantic(
@@ -186,7 +186,7 @@ export async function searchContextsSemantic(
.orderBy(desc(contextCandidates.similarity), desc(contextCandidates.createdAt))
.limit(limit);
- return rowsQuery as Promise<UserMemoryContextsWithoutVectors[]>;
+ return rowsQuery as Promise<UserMemoryContextWithoutVectors[]>;
}
export async function searchExperiencesSemantic(
@@ -236,7 +236,7 @@ export async function searchExperiencesSemantic(
.orderBy(desc(sql`1 - (${cosineDistance(userMemoriesExperiences.situationVector, embedding)})`))
.limit(limit);
- return rowsQuery as Promise<UserMemoryExperiencesWithoutVectors[]>;
+ return rowsQuery as Promise<UserMemoryExperienceWithoutVectors[]>;
}
export async function searchPreferencesSemantic(
@@ -293,7 +293,7 @@ export async function searchPreferencesSemantic(
)
.limit(limit);
- return rowsQuery as Promise<UserMemoryPreferencesWithoutVectors[]>;
+ return rowsQuery as Promise<UserMemoryPreferenceWithoutVectors[]>;
}
export async function searchIdentitiesSemantic(
@@ -301,7 +301,7 @@ export async function searchIdentitiesSemantic(
embedding: number[],
limit: number,
params: SearchMemoryParams,
-): Promise<UserMemoryIdentitiesWithoutVectors[]> {
+): Promise<UserMemoryIdentityWithoutVectors[]> {
const conditions = [
ctx.memoryWhere(userMemoriesIdentities),
ctx.memoryWhere(userMemories),
@@ -348,5 +348,5 @@ export async function searchIdentitiesSemantic(
)
.limit(limit);
- return rowsQuery as Promise<UserMemoryIdentitiesWithoutVectors[]>;
+ return rowsQuery as Promise<UserMemoryIdentityWithoutVectors[]>;
}
diff --git a/packages/database/src/models/userMemory/query/types.ts b/packages/database/src/models/userMemory/query/types.ts
index 5495a36db30..39ed01b31c2 100644
--- a/packages/database/src/models/userMemory/query/types.ts
+++ b/packages/database/src/models/userMemory/query/types.ts
@@ -1,13 +1,12 @@
-import type { SearchMemoryParams } from '@lobechat/types';
-import type { AnyColumn } from 'drizzle-orm';
-
import type {
- UserMemoryActivitiesWithoutVectors,
- UserMemoryContextsWithoutVectors,
- UserMemoryExperiencesWithoutVectors,
- UserMemoryIdentitiesWithoutVectors,
- UserMemoryPreferencesWithoutVectors,
-} from '../../../schemas';
+ SearchMemoryParams,
+ UserMemoryActivityWithoutVectors,
+ UserMemoryContextWithoutVectors,
+ UserMemoryExperienceWithoutVectors,
+ UserMemoryIdentityWithoutVectors,
+ UserMemoryPreferenceWithoutVectors,
+} from '@lobechat/types';
+import type { AnyColumn } from 'drizzle-orm';
export interface Bm25MatchFieldGroup {
fields: string[];
@@ -47,15 +46,15 @@ export interface RankedSearchCandidate<T> {
}
export interface UserMemoryHybridSearchAggregatedResult {
- activities: UserMemoryActivitiesWithoutVectors[];
- contexts: UserMemoryContextsWithoutVectors[];
- experiences: UserMemoryExperiencesWithoutVectors[];
- identities: UserMemoryIdentitiesWithoutVectors[];
+ activities: UserMemoryActivityWithoutVectors[];
+ contexts: UserMemoryContextWithoutVectors[];
+ experiences: UserMemoryExperienceWithoutVectors[];
+ identities: UserMemoryIdentityWithoutVectors[];
meta: {
appliedFilters: Omit<SearchMemoryParams, 'effort' | 'topK'>;
appliedQueries: string[];
layers: Record<SearchLayerKey, HybridSearchLayerMeta>;
ranking: Partial<Record<SearchLayerKey, Record<string, RecommendationScoreBreakdown>>>;
};
- preferences: UserMemoryPreferencesWithoutVectors[];
+ preferences: UserMemoryPreferenceWithoutVectors[];
}
diff --git a/packages/database/src/repositories/userMemory/index.ts b/packages/database/src/repositories/userMemory/index.ts
index b22d47c1a06..e9c069edcbc 100644
--- a/packages/database/src/repositories/userMemory/index.ts
+++ b/packages/database/src/repositories/userMemory/index.ts
@@ -1,10 +1,10 @@
import type {
- UserMemoryActivitiesWithoutVectors,
- UserMemoryContextsWithoutVectors,
- UserMemoryExperiencesWithoutVectors,
- UserMemoryIdentitiesWithoutVectors,
- UserMemoryPreferencesWithoutVectors,
-} from '../../schemas';
+ UserMemoryActivityWithoutVectors,
+ UserMemoryContextWithoutVectors,
+ UserMemoryExperienceWithoutVectors,
+ UserMemoryIdentityWithoutVectors,
+ UserMemoryPreferenceWithoutVectors,
+} from '@lobechat/types';
export { UserMemoryTopicRepository } from './UserMemoryTopicRepository';
@@ -15,18 +15,18 @@ export interface MemorySource {
title: string | null;
}
-export interface DisplayExperienceMemory extends UserMemoryExperiencesWithoutVectors {
+export interface DisplayExperienceMemory extends UserMemoryExperienceWithoutVectors {
title: string | null;
}
-export interface DisplayPreferenceMemory extends UserMemoryPreferencesWithoutVectors {
+export interface DisplayPreferenceMemory extends UserMemoryPreferenceWithoutVectors {
title: string | null;
}
-export type DisplayContextMemory = UserMemoryContextsWithoutVectors;
+export type DisplayContextMemory = UserMemoryContextWithoutVectors;
-export type DisplayIdentityMemory = UserMemoryIdentitiesWithoutVectors;
+export type DisplayIdentityMemory = UserMemoryIdentityWithoutVectors;
-export interface DisplayActivityMemory extends UserMemoryActivitiesWithoutVectors {
+export interface DisplayActivityMemory extends UserMemoryActivityWithoutVectors {
title: string | null;
}
diff --git a/packages/database/src/schemas/userMemories/activity.ts b/packages/database/src/schemas/userMemories/activity.ts
index 2956e5ac78c..14c64f74c2c 100644
--- a/packages/database/src/schemas/userMemories/activity.ts
+++ b/packages/database/src/schemas/userMemories/activity.ts
@@ -86,10 +86,3 @@ export const userMemoriesActivities = pgTable(
.where(sql`${table.dossierId} IS NOT NULL`),
],
);
-
-export type UserMemoryActivity = typeof userMemoriesActivities.$inferSelect;
-export type UserMemoryActivitiesWithoutVectors = Omit<
- UserMemoryActivity,
- 'narrativeVector' | 'feedbackVector'
->;
-export type NewUserMemoryActivity = typeof userMemoriesActivities.$inferInsert;
diff --git a/packages/database/src/schemas/userMemories/base.ts b/packages/database/src/schemas/userMemories/base.ts
index 857e3a6a141..a42ddb30309 100644
--- a/packages/database/src/schemas/userMemories/base.ts
+++ b/packages/database/src/schemas/userMemories/base.ts
@@ -51,10 +51,3 @@ export const userMemories = pgTable(
index('user_memories_user_id_index').on(table.userId),
],
);
-
-export type UserMemoryItem = typeof userMemories.$inferSelect;
-export type UserMemoryItemWithoutVectors = Omit<
- UserMemoryItem,
- 'summaryVector1024' | 'detailsVector1024'
->;
-export type NewUserMemory = typeof userMemories.$inferInsert;
diff --git a/packages/database/src/schemas/userMemories/context.ts b/packages/database/src/schemas/userMemories/context.ts
index 508e186952b..41d18b44c2a 100644
--- a/packages/database/src/schemas/userMemories/context.ts
+++ b/packages/database/src/schemas/userMemories/context.ts
@@ -188,10 +188,3 @@ export const userMemoriesContextProjects = pgTable(
index('user_memories_context_projects_user_id_index').on(table.userId),
],
);
-
-export type UserMemoryContext = typeof userMemoriesContexts.$inferSelect;
-export type UserMemoryContextsWithoutVectors = Omit<
- UserMemoryContext,
- 'titleVector' | 'descriptionVector'
->;
-export type NewUserMemoryContext = typeof userMemoriesContexts.$inferInsert;
diff --git a/packages/database/src/schemas/userMemories/experience.ts b/packages/database/src/schemas/userMemories/experience.ts
index 58a61a6ec05..60f57ad2387 100644
--- a/packages/database/src/schemas/userMemories/experience.ts
+++ b/packages/database/src/schemas/userMemories/experience.ts
@@ -59,10 +59,3 @@ export const userMemoriesExperiences = pgTable(
index('user_memories_experiences_user_memory_id_index').on(table.userMemoryId),
],
);
-
-export type UserMemoryExperience = typeof userMemoriesExperiences.$inferSelect;
-export type UserMemoryExperiencesWithoutVectors = Omit<
- UserMemoryExperience,
- 'situationVector' | 'actionVector' | 'keyLearningVector'
->;
-export type NewUserMemoryExperience = typeof userMemoriesExperiences.$inferInsert;
diff --git a/packages/database/src/schemas/userMemories/identity.ts b/packages/database/src/schemas/userMemories/identity.ts
index dcf4501b886..fec29d7605a 100644
--- a/packages/database/src/schemas/userMemories/identity.ts
+++ b/packages/database/src/schemas/userMemories/identity.ts
@@ -48,7 +48,3 @@ export const userMemoriesIdentities = pgTable(
index('user_memories_identities_entity_id_index').on(table.entityId),
],
);
-
-export type UserMemoryIdentity = typeof userMemoriesIdentities.$inferSelect;
-export type UserMemoryIdentitiesWithoutVectors = Omit<UserMemoryIdentity, 'descriptionVector'>;
-export type NewUserMemoryIdentity = typeof userMemoriesIdentities.$inferInsert;
diff --git a/packages/database/src/schemas/userMemories/persona.ts b/packages/database/src/schemas/userMemories/persona.ts
index 2b322e58d92..24c7a13c229 100644
--- a/packages/database/src/schemas/userMemories/persona.ts
+++ b/packages/database/src/schemas/userMemories/persona.ts
@@ -77,9 +77,3 @@ export const userPersonaDocumentHistories = pgTable(
index('user_persona_document_histories_profile_index').on(table.profile),
],
);
-
-export type UserPersonaDocument = typeof userPersonaDocuments.$inferSelect;
-export type NewUserPersonaDocument = typeof userPersonaDocuments.$inferInsert;
-
-export type UserPersonaDocumentHistoriesItem = typeof userPersonaDocumentHistories.$inferSelect;
-export type NewUserPersonaDocumentHistoriesItem = typeof userPersonaDocumentHistories.$inferInsert;
diff --git a/packages/database/src/schemas/userMemories/preference.ts b/packages/database/src/schemas/userMemories/preference.ts
index 4c29714d89e..d7f7ed80b20 100644
--- a/packages/database/src/schemas/userMemories/preference.ts
+++ b/packages/database/src/schemas/userMemories/preference.ts
@@ -60,10 +60,3 @@ export const userMemoriesPreferences = pgTable(
index('user_memories_preferences_applies_to_entity_id_index').on(table.appliesToEntityId),
],
);
-
-export type UserMemoryPreference = typeof userMemoriesPreferences.$inferSelect;
-export type UserMemoryPreferencesWithoutVectors = Omit<
- UserMemoryPreference,
- 'conclusionDirectivesVector'
->;
-export type NewUserMemoryPreference = typeof userMemoriesPreferences.$inferInsert;
diff --git a/packages/database/src/schemas/userMemories/rowTypes.check.ts b/packages/database/src/schemas/userMemories/rowTypes.check.ts
new file mode 100644
index 00000000000..4b0945c0e34
--- /dev/null
+++ b/packages/database/src/schemas/userMemories/rowTypes.check.ts
@@ -0,0 +1,88 @@
+/**
+ * Compile-time check that the row and insert types declared in `@lobechat/types`
+ * (`packages/types/src/userMemory/rows.ts`) are identical to these tables. The rest of the code
+ * base imports those declared types; this file is the only place that infers from the schema.
+ * A mismatch fails `type-check`.
+ */
+import type {
+ UserMemory,
+ UserMemoryActivity,
+ UserMemoryActivityInsert,
+ UserMemoryContext,
+ UserMemoryContextInsert,
+ UserMemoryContextProject,
+ UserMemoryContextProjectInsert,
+ UserMemoryDossier,
+ UserMemoryDossierInsert,
+ UserMemoryEdge,
+ UserMemoryEdgeInsert,
+ UserMemoryEntity,
+ UserMemoryEntityInsert,
+ UserMemoryEntityName,
+ UserMemoryEntityNameInsert,
+ UserMemoryExperience,
+ UserMemoryExperienceInsert,
+ UserMemoryIdentity,
+ UserMemoryIdentityInsert,
+ UserMemoryInsert,
+ UserMemoryOperation,
+ UserMemoryOperationInsert,
+ UserMemoryPreference,
+ UserMemoryPreferenceInsert,
+ UserPersonaDocument,
+ UserPersonaDocumentHistory,
+ UserPersonaDocumentHistoryInsert,
+ UserPersonaDocumentInsert,
+} from '@lobechat/types';
+
+import type {
+ userMemories,
+ userMemoriesActivities,
+ userMemoriesContextProjects,
+ userMemoriesContexts,
+ userMemoriesDossiers,
+ userMemoriesEdges,
+ userMemoriesEntities,
+ userMemoriesEntityNames,
+ userMemoriesExperiences,
+ userMemoriesIdentities,
+ userMemoriesOperations,
+ userMemoriesPreferences,
+ userPersonaDocumentHistories,
+ userPersonaDocuments,
+} from './index';
+
+type Equal<A, B> =
+ (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
+type Assert<T extends true> = T;
+
+export type UserMemoryRowTypesMatchSchema = [
+ Assert<Equal<UserMemory, typeof userMemories.$inferSelect>>,
+ Assert<Equal<UserMemoryInsert, typeof userMemories.$inferInsert>>,
+ Assert<Equal<UserMemoryContext, typeof userMemoriesContexts.$inferSelect>>,
+ Assert<Equal<UserMemoryContextInsert, typeof userMemoriesContexts.$inferInsert>>,
+ Assert<Equal<UserMemoryDossier, typeof userMemoriesDossiers.$inferSelect>>,
+ Assert<Equal<UserMemoryDossierInsert, typeof userMemoriesDossiers.$inferInsert>>,
+ Assert<Equal<UserMemoryContextProject, typeof userMemoriesContextProjects.$inferSelect>>,
+ Assert<Equal<UserMemoryContextProjectInsert, typeof userMemoriesContextProjects.$inferInsert>>,
+ Assert<Equal<UserMemoryActivity, typeof userMemoriesActivities.$inferSelect>>,
+ Assert<Equal<UserMemoryActivityInsert, typeof userMemoriesActivities.$inferInsert>>,
+ Assert<Equal<UserMemoryIdentity, typeof userMemoriesIdentities.$inferSelect>>,
+ Assert<Equal<UserMemoryIdentityInsert, typeof userMemoriesIdentities.$inferInsert>>,
+ Assert<Equal<UserMemoryPreference, typeof userMemoriesPreferences.$inferSelect>>,
+ Assert<Equal<UserMemoryPreferenceInsert, typeof userMemoriesPreferences.$inferInsert>>,
+ Assert<Equal<UserMemoryExperience, typeof userMemoriesExperiences.$inferSelect>>,
+ Assert<Equal<UserMemoryExperienceInsert, typeof userMemoriesExperiences.$inferInsert>>,
+ Assert<Equal<UserMemoryEntity, typeof userMemoriesEntities.$inferSelect>>,
+ Assert<Equal<UserMemoryEntityInsert, typeof userMemoriesEntities.$inferInsert>>,
+ Assert<Equal<UserMemoryEntityName, typeof userMemoriesEntityNames.$inferSelect>>,
+ Assert<Equal<UserMemoryEntityNameInsert, typeof userMemoriesEntityNames.$inferInsert>>,
+ Assert<Equal<UserMemoryEdge, typeof userMemoriesEdges.$inferSelect>>,
+ Assert<Equal<UserMemoryEdgeInsert, typeof userMemoriesEdges.$inferInsert>>,
+ Assert<Equal<UserMemoryOperation, typeof userMemoriesOperations.$inferSelect>>,
+ Assert<Equal<UserMemoryOperationInsert, typeof userMemoriesOperations.$inferInsert>>,
+ Assert<Equal<UserPersonaDocument, typeof userPersonaDocuments.$inferSelect>>,
+ Assert<Equal<UserPersonaDocumentInsert, typeof userPersonaDocuments.$inferInsert>>,
+ Assert<Equal<UserPersonaDocumentHistory, typeof userPersonaDocumentHistories.$inferSelect>>,
+ Assert<Equal<UserPersonaDocumentHistoryInsert, typeof userPersonaDocumentHistories.$inferInsert>>,
+];
diff --git a/packages/types/src/userMemory/activity.ts b/packages/types/src/userMemory/activity.ts
index 83f063e8424..7c80e7d4682 100644
--- a/packages/types/src/userMemory/activity.ts
+++ b/packages/types/src/userMemory/activity.ts
@@ -1,4 +1,4 @@
-import type { UserMemoryActivity } from './layers';
+import type { UserMemoryActivity } from './rows';
import type { BaseListItem, BaseListParams, BaseListResult } from './shared';
export type ActivityListSort = 'capturedAt' | 'startsAt';
diff --git a/packages/types/src/userMemory/base.ts b/packages/types/src/userMemory/base.ts
index 0efeb4fc318..5ca9175edf0 100644
--- a/packages/types/src/userMemory/base.ts
+++ b/packages/types/src/userMemory/base.ts
@@ -1,31 +1,22 @@
-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;
-}
+import type { UserMemory } from './rows';
-export type UserMemoryWithoutVectors = Omit<
- UserMemory,
- 'summaryVector1024' | 'detailsVector1024'
->;
+export type UserMemoryWithoutVectors = Omit<UserMemory, 'summaryVector1024' | 'detailsVector1024'>;
-export type UserMemoryListItem = Omit<
- UserMemoryWithoutVectors,
- 'details' | 'summary' | 'capturedAt'
+/** The fields the list query selects; detail views use the full row. */
+export type UserMemoryListItem = Pick<
+ UserMemory,
+ | 'accessedAt'
+ | 'accessedCount'
+ | 'createdAt'
+ | 'id'
+ | 'lastAccessedAt'
+ | 'memoryCategory'
+ | 'memoryLayer'
+ | 'memoryType'
+ | 'metadata'
+ | 'status'
+ | 'tags'
+ | 'title'
+ | 'updatedAt'
+ | 'userId'
>;
diff --git a/packages/types/src/userMemory/identity.ts b/packages/types/src/userMemory/identity.ts
index 86836a51f4f..b813f0478ad 100644
--- a/packages/types/src/userMemory/identity.ts
+++ b/packages/types/src/userMemory/identity.ts
@@ -1,5 +1,6 @@
import { z } from 'zod';
+import type { UserMemoryIdentity } from './rows';
import type { BaseListItem, BaseListParams, BaseListResult } from './shared';
export type IdentityType = 'personal' | 'professional' | 'demographic';
@@ -29,26 +30,26 @@ export interface IdentityListItem extends BaseListItem {
export type IdentityListResult = BaseListResult<IdentityListItem>;
-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;
+/** The fields the list query selects; detail views use the full row. */
+export type UserMemoryIdentitiesListItem = Pick<
+ UserMemoryIdentity,
+ | 'accessedAt'
+ | 'capturedAt'
+ | 'createdAt'
+ | 'description'
+ | 'episodicDate'
+ | 'id'
+ | 'metadata'
+ | 'relationship'
+ | 'role'
+ | 'tags'
+ | 'type'
+ | 'updatedAt'
+ | 'userId'
+ | 'userMemoryId'
+>;
export interface NewUserMemoryIdentity {
description?: string;
diff --git a/packages/types/src/userMemory/index.ts b/packages/types/src/userMemory/index.ts
index a0ec2c2d15a..4d25f6832cd 100644
--- a/packages/types/src/userMemory/index.ts
+++ b/packages/types/src/userMemory/index.ts
@@ -4,6 +4,7 @@ export * from './experience';
export * from './identity';
export * from './layers';
export * from './list';
+export * from './rows';
export * from './shared';
export * from './structure';
export * from './tools';
diff --git a/packages/types/src/userMemory/layers.ts b/packages/types/src/userMemory/layers.ts
index 23249e4cfdd..0e0df8eee86 100644
--- a/packages/types/src/userMemory/layers.ts
+++ b/packages/types/src/userMemory/layers.ts
@@ -1,3 +1,10 @@
+import type {
+ UserMemoryActivity,
+ UserMemoryContext,
+ UserMemoryExperience,
+ UserMemoryPreference,
+} from './rows';
+
export interface UserMemoryTimestamps {
accessedAt: Date;
createdAt: Date;
@@ -42,121 +49,99 @@ export interface UserMemoryAssociatedSubject {
type?: string | null;
}
-export interface UserMemoryContext extends UserMemoryTimestamps {
- 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;
- id: string;
- metadata: Record<string, unknown> | null;
- scoreImpact: number | null;
- scoreUrgency: number | null;
- tags: string[] | null;
- title: string | null;
- titleVector: number[] | null;
- type: string | null;
- userId: string | null;
- userMemoryIds: string[] | null;
-}
-
export type UserMemoryContextWithoutVectors = Omit<
UserMemoryContext,
'descriptionVector' | 'titleVector'
>;
-export type UserMemoryContextsListItem = Omit<
- UserMemoryContextWithoutVectors,
- 'associatedObjects' | 'associatedSubjects'
+/** The fields the list query selects; detail views use the full row. */
+export type UserMemoryContextsListItem = Pick<
+ UserMemoryContext,
+ | 'accessedAt'
+ | 'createdAt'
+ | 'currentStatus'
+ | 'description'
+ | 'id'
+ | 'metadata'
+ | 'scoreImpact'
+ | 'scoreUrgency'
+ | 'tags'
+ | 'title'
+ | 'type'
+ | 'updatedAt'
+ | 'userId'
+ | 'userMemoryIds'
>;
-export interface UserMemoryExperience extends UserMemoryTimestamps {
- action: string | null;
- actionVector: number[] | null;
- id: string;
- keyLearning: string | null;
- keyLearningVector: number[] | null;
- metadata: Record<string, unknown> | null;
- possibleOutcome: string | null;
- reasoning: string | null;
- scoreConfidence: number | null;
- situation: string | null;
- situationVector: number[] | null;
- tags: string[] | null;
- type: string | null;
- userId: string | null;
- userMemoryId: string | null;
-}
-
export type UserMemoryExperienceWithoutVectors = Omit<
UserMemoryExperience,
'actionVector' | 'keyLearningVector' | 'situationVector'
>;
-export type UserMemoryExperiencesListItem = Omit<
- UserMemoryExperienceWithoutVectors,
- 'possibleOutcome' | 'reasoning'
+/** The fields the list query selects; detail views use the full row. */
+export type UserMemoryExperiencesListItem = Pick<
+ UserMemoryExperience,
+ | 'accessedAt'
+ | 'action'
+ | 'createdAt'
+ | 'id'
+ | 'keyLearning'
+ | 'metadata'
+ | 'scoreConfidence'
+ | 'situation'
+ | 'tags'
+ | 'type'
+ | 'updatedAt'
+ | 'userId'
+ | 'userMemoryId'
>;
-export interface UserMemoryPreference extends UserMemoryTimestamps {
- conclusionDirectives: string | null;
- conclusionDirectivesVector: number[] | null;
- id: string;
- metadata: Record<string, unknown> | null;
- scorePriority: number | null;
- suggestions: string | null;
- tags: string[] | null;
- type: string | null;
- userId: string | null;
- userMemoryId: string | null;
-}
-
export type UserMemoryPreferenceWithoutVectors = Omit<
UserMemoryPreference,
'conclusionDirectivesVector'
>;
-export type UserMemoryPreferencesListItem = Omit<UserMemoryPreferenceWithoutVectors, 'suggestions'>;
-
-export interface UserMemoryActivity extends UserMemoryTimestamps {
- associatedLocations: UserMemoryAssociatedLocation[] | null;
- associatedObjects: UserMemoryAssociatedObject[] | null;
- associatedSubjects: UserMemoryAssociatedSubject[] | null;
- endsAt: Date | null;
- feedback: string | null;
- feedbackVector: number[] | null;
- id: string;
- metadata: Record<string, unknown> | null;
- narrative: string | null;
- narrativeVector: number[] | null;
- notes: string | null;
- startsAt: Date | null;
- status: string | null;
- tags: string[] | null;
- timezone: string | null;
- type: string | null;
- userId: string | null;
- userMemoryId: string | null;
-}
+/** The fields the list query selects; detail views use the full row. */
+export type UserMemoryPreferencesListItem = Pick<
+ UserMemoryPreference,
+ | 'accessedAt'
+ | 'conclusionDirectives'
+ | 'createdAt'
+ | 'id'
+ | 'metadata'
+ | 'scorePriority'
+ | 'tags'
+ | 'type'
+ | 'updatedAt'
+ | 'userId'
+ | 'userMemoryId'
+>;
export type UserMemoryActivityWithoutVectors = Omit<
UserMemoryActivity,
'narrativeVector' | 'feedbackVector'
>;
-export type UserMemoryActivitiesListItem = Omit<
- UserMemoryActivityWithoutVectors,
- 'feedback' | 'narrative' | 'notes'
+/** The fields the list query selects; detail views use the full row. */
+export type UserMemoryActivitiesListItem = Pick<
+ UserMemoryActivity,
+ | 'accessedAt'
+ | 'associatedLocations'
+ | 'associatedObjects'
+ | 'associatedSubjects'
+ | 'capturedAt'
+ | 'createdAt'
+ | 'endsAt'
+ | 'feedback'
+ | 'id'
+ | 'metadata'
+ | 'narrative'
+ | 'startsAt'
+ | 'status'
+ | 'tags'
+ | 'timezone'
+ | 'type'
+ | 'updatedAt'
+ | 'userId'
+ | 'userMemoryId'
>;
diff --git a/packages/types/src/userMemory/rows.ts b/packages/types/src/userMemory/rows.ts
new file mode 100644
index 00000000000..2970b4f4185
--- /dev/null
+++ b/packages/types/src/userMemory/rows.ts
@@ -0,0 +1,638 @@
+/**
+ * Row and insert shapes of the user memory tables. These are the types the rest of the code base
+ * imports; database code annotates its queries with them instead of inferring from the schema.
+ * `packages/database/src/schemas/userMemories/rowTypes.check.ts` asserts they are identical to the
+ * tables, so a schema change that is not mirrored here fails `type-check`.
+ */
+import type {
+ UserMemoryContextProjectSource,
+ UserMemoryDossierDecision,
+ UserMemoryDossierStatus,
+ UserMemoryEdgeRelation,
+ UserMemoryEntityNameKind,
+ UserMemoryEntityType,
+ UserMemoryEvidenceSource,
+ UserMemoryOperationActor,
+ UserMemoryOperationGate,
+ UserMemoryOperationState,
+ UserMemoryOperationType,
+ UserMemoryState,
+ UserMemoryVisibility,
+} from './structure';
+
+/** Row of `user_memories` — the parent row every layer hangs off. */
+export interface UserMemory {
+ accessedAt: Date;
+ accessedCount: number | null;
+ capturedAt: Date;
+ createdAt: Date;
+ deletedAt: Date | null;
+ details: string | null;
+ detailsVector1024: number[] | null;
+ id: string;
+ isDeleted: boolean | null;
+ lastAccessedAt: Date;
+ memoryCategory: string | null;
+ memoryLayer: string | null;
+ memoryType: string | null;
+ metadata: Record<string, unknown> | null;
+ state: UserMemoryState | null;
+ status: string | null;
+ summary: string | null;
+ summaryVector1024: number[] | null;
+ tags: string[] | null;
+ title: string | null;
+ updatedAt: Date;
+ userId: string | null;
+ userLocked: boolean | null;
+}
+
+/** Insert shape of `UserMemory`: required columns have no database default. */
+export interface UserMemoryInsert {
+ accessedAt?: Date;
+ accessedCount?: number | null;
+ capturedAt?: Date;
+ createdAt?: Date;
+ deletedAt?: Date | null;
+ details?: string | null;
+ detailsVector1024?: number[] | null;
+ id?: string;
+ isDeleted?: boolean | null;
+ lastAccessedAt: Date;
+ memoryCategory?: string | null;
+ memoryLayer?: string | null;
+ memoryType?: string | null;
+ metadata?: Record<string, unknown> | null;
+ state?: UserMemoryState | null;
+ status?: string | null;
+ summary?: string | null;
+ summaryVector1024?: number[] | null;
+ tags?: string[] | null;
+ title?: string | null;
+ updatedAt?: Date;
+ userId?: string | null;
+ userLocked?: boolean | null;
+}
+
+/** Row of `user_memories_contexts` — level 1: a long-running situation. */
+export interface UserMemoryContext {
+ accessedAt: Date;
+ associatedObjects: { extra?: Record<string, unknown>; name?: string; type?: string }[] | null;
+ associatedSubjects: { extra?: Record<string, unknown>; name?: string; type?: string }[] | null;
+ capturedAt: Date;
+ createdAt: Date;
+ currentStatus: string | null;
+ description: string | null;
+ descriptionVector: number[] | null;
+ firstSeenAt: Date | null;
+ id: string;
+ lastEvidenceAt: Date | null;
+ metadata: Record<string, unknown> | null;
+ nextSteps: string[] | null;
+ now: string | null;
+ openQuestions: string[] | null;
+ scoreImpact: number | null;
+ scoreUrgency: number | null;
+ synthesizedAt: Date | null;
+ tags: string[] | null;
+ title: string | null;
+ type: string | null;
+ updatedAt: Date;
+ userId: string | null;
+ userMemoryId: string | null;
+ userMemoryIds: string[] | null;
+}
+
+/** Insert shape of `UserMemoryContext`: required columns have no database default. */
+export interface UserMemoryContextInsert {
+ accessedAt?: Date;
+ associatedObjects?: { extra?: Record<string, unknown>; name?: string; type?: string }[] | null;
+ associatedSubjects?: { extra?: Record<string, unknown>; name?: string; type?: string }[] | null;
+ capturedAt?: Date;
+ createdAt?: Date;
+ currentStatus?: string | null;
+ description?: string | null;
+ descriptionVector?: number[] | null;
+ firstSeenAt?: Date | null;
+ id?: string;
+ lastEvidenceAt?: Date | null;
+ metadata?: Record<string, unknown> | null;
+ nextSteps?: string[] | null;
+ now?: string | null;
+ openQuestions?: string[] | null;
+ scoreImpact?: number | null;
+ scoreUrgency?: number | null;
+ synthesizedAt?: Date | null;
+ tags?: string[] | null;
+ title?: string | null;
+ type?: string | null;
+ updatedAt?: Date;
+ userId?: string | null;
+ userMemoryId?: string | null;
+ userMemoryIds?: string[] | null;
+}
+
+/** Row of `user_memories_dossiers` — level 2: a concrete item inside a context. */
+export interface UserMemoryDossier {
+ accessedAt: Date;
+ activityCount: number;
+ agentId: string | null;
+ contextId: string | null;
+ createdAt: Date;
+ decisions: UserMemoryDossierDecision[] | null;
+ firstSeenAt: Date | null;
+ id: string;
+ lastEvidenceAt: Date | null;
+ metadata: Record<string, unknown> | null;
+ now: string | null;
+ projectId: string | null;
+ status: UserMemoryDossierStatus;
+ summary: string | null;
+ summaryVector: number[] | null;
+ title: string | null;
+ updatedAt: Date;
+ userId: string | null;
+ userMemoryId: string | null;
+ visibility: UserMemoryVisibility;
+ workspaceId: string | null;
+}
+
+/** Insert shape of `UserMemoryDossier`: required columns have no database default. */
+export interface UserMemoryDossierInsert {
+ accessedAt?: Date;
+ activityCount?: number;
+ agentId?: string | null;
+ contextId?: string | null;
+ createdAt?: Date;
+ decisions?: UserMemoryDossierDecision[] | null;
+ firstSeenAt?: Date | null;
+ id?: string;
+ lastEvidenceAt?: Date | null;
+ metadata?: Record<string, unknown> | null;
+ now?: string | null;
+ projectId?: string | null;
+ status?: UserMemoryDossierStatus;
+ summary?: string | null;
+ summaryVector?: number[] | null;
+ title?: string | null;
+ updatedAt?: Date;
+ userId?: string | null;
+ userMemoryId?: string | null;
+ visibility?: UserMemoryVisibility;
+ workspaceId?: string | null;
+}
+
+/** Row of `user_memories_context_projects` — a context linked to a project. */
+export interface UserMemoryContextProject {
+ accessedAt: Date;
+ contextId: string;
+ createdAt: Date;
+ evidenceCount: number;
+ id: string;
+ isPrimary: boolean;
+ metadata: Record<string, unknown> | null;
+ projectId: string;
+ source: UserMemoryContextProjectSource;
+ updatedAt: Date;
+ userId: string | null;
+}
+
+/** Insert shape of `UserMemoryContextProject`: required columns have no database default. */
+export interface UserMemoryContextProjectInsert {
+ accessedAt?: Date;
+ contextId: string;
+ createdAt?: Date;
+ evidenceCount?: number;
+ id?: string;
+ isPrimary?: boolean;
+ metadata?: Record<string, unknown> | null;
+ projectId: string;
+ source: UserMemoryContextProjectSource;
+ updatedAt?: Date;
+ userId?: string | null;
+}
+
+/** Row of `user_memories_activities` — evidence: something that happened in one conversation. */
+export interface UserMemoryActivity {
+ accessedAt: Date;
+ associatedLocations: { address?: string; name?: string; tags?: string[]; type?: string }[] | null;
+ associatedObjects: { extra?: Record<string, unknown>; name?: string; type?: string }[] | null;
+ associatedSubjects: { extra?: Record<string, unknown>; name?: string; type?: string }[] | null;
+ capturedAt: Date;
+ createdAt: Date;
+ dossierId: string | null;
+ endsAt: Date | null;
+ feedback: string | null;
+ feedbackVector: number[] | null;
+ id: string;
+ injectable: boolean;
+ metadata: Record<string, unknown> | null;
+ narrative: string | null;
+ narrativeVector: number[] | null;
+ notes: string | null;
+ startsAt: Date | null;
+ status: string;
+ tags: string[] | null;
+ timezone: string | null;
+ type: string;
+ updatedAt: Date;
+ userId: string | null;
+ userMemoryId: string | null;
+}
+
+/** Insert shape of `UserMemoryActivity`: required columns have no database default. */
+export interface UserMemoryActivityInsert {
+ accessedAt?: Date;
+ associatedLocations?:
+ { address?: string; name?: string; tags?: string[]; type?: string }[] | null;
+ associatedObjects?: { extra?: Record<string, unknown>; name?: string; type?: string }[] | null;
+ associatedSubjects?: { extra?: Record<string, unknown>; name?: string; type?: string }[] | null;
+ capturedAt?: Date;
+ createdAt?: Date;
+ dossierId?: string | null;
+ endsAt?: Date | null;
+ feedback?: string | null;
+ feedbackVector?: number[] | null;
+ id?: string;
+ injectable?: boolean;
+ metadata?: Record<string, unknown> | null;
+ narrative?: string | null;
+ narrativeVector?: number[] | null;
+ notes?: string | null;
+ startsAt?: Date | null;
+ status?: string;
+ tags?: string[] | null;
+ timezone?: string | null;
+ type: string;
+ updatedAt?: Date;
+ userId?: string | null;
+ userMemoryId?: string | null;
+}
+
+/** Row of `user_memories_identities` — a fact about an entity. */
+export interface UserMemoryIdentity {
+ accessedAt: Date;
+ capturedAt: Date;
+ createdAt: Date;
+ description: string | null;
+ descriptionVector: number[] | null;
+ entityId: string | 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;
+}
+
+/** Insert shape of `UserMemoryIdentity`: required columns have no database default. */
+export interface UserMemoryIdentityInsert {
+ accessedAt?: Date;
+ capturedAt?: Date;
+ createdAt?: Date;
+ description?: string | null;
+ descriptionVector?: number[] | null;
+ entityId?: string | 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;
+}
+
+/** Row of `user_memories_preferences` — a preference held by the user or another entity. */
+export interface UserMemoryPreference {
+ accessedAt: Date;
+ appliesToEntityId: string | null;
+ capturedAt: Date;
+ conclusionDirectives: string | null;
+ conclusionDirectivesVector: number[] | null;
+ createdAt: Date;
+ evidenceCount: number;
+ evidenceSource: UserMemoryEvidenceSource | null;
+ holderEntityId: string | null;
+ id: string;
+ lastEvidenceAt: Date | null;
+ metadata: Record<string, unknown> | null;
+ scope: string | null;
+ scorePriority: number | null;
+ suggestions: string | null;
+ tags: string[] | null;
+ type: string | null;
+ updatedAt: Date;
+ userId: string | null;
+ userMemoryId: string | null;
+}
+
+/** Insert shape of `UserMemoryPreference`: required columns have no database default. */
+export interface UserMemoryPreferenceInsert {
+ accessedAt?: Date;
+ appliesToEntityId?: string | null;
+ capturedAt?: Date;
+ conclusionDirectives?: string | null;
+ conclusionDirectivesVector?: number[] | null;
+ createdAt?: Date;
+ evidenceCount?: number;
+ evidenceSource?: UserMemoryEvidenceSource | null;
+ holderEntityId?: string | null;
+ id?: string;
+ lastEvidenceAt?: Date | null;
+ metadata?: Record<string, unknown> | null;
+ scope?: string | null;
+ scorePriority?: number | null;
+ suggestions?: string | null;
+ tags?: string[] | null;
+ type?: string | null;
+ updatedAt?: Date;
+ userId?: string | null;
+ userMemoryId?: string | null;
+}
+
+/** Row of `user_memories_experiences` (deprecated layer). */
+export interface UserMemoryExperience {
+ accessedAt: Date;
+ action: string | null;
+ actionVector: number[] | null;
+ capturedAt: Date;
+ createdAt: Date;
+ id: string;
+ keyLearning: string | null;
+ keyLearningVector: number[] | null;
+ metadata: Record<string, unknown> | null;
+ possibleOutcome: string | null;
+ reasoning: string | null;
+ scoreConfidence: number | null;
+ situation: string | null;
+ situationVector: number[] | null;
+ tags: string[] | null;
+ type: string | null;
+ updatedAt: Date;
+ userId: string | null;
+ userMemoryId: string | null;
+}
+
+/** Insert shape of `UserMemoryExperience`: required columns have no database default. */
+export interface UserMemoryExperienceInsert {
+ accessedAt?: Date;
+ action?: string | null;
+ actionVector?: number[] | null;
+ capturedAt?: Date;
+ createdAt?: Date;
+ id?: string;
+ keyLearning?: string | null;
+ keyLearningVector?: number[] | null;
+ metadata?: Record<string, unknown> | null;
+ possibleOutcome?: string | null;
+ reasoning?: string | null;
+ scoreConfidence?: number | null;
+ situation?: string | null;
+ situationVector?: number[] | null;
+ tags?: string[] | null;
+ type?: string | null;
+ updatedAt?: Date;
+ userId?: string | null;
+ userMemoryId?: string | null;
+}
+
+/** Row of `user_memories_entities` — a person, organization, product, repository or place. */
+export interface UserMemoryEntity {
+ accessedAt: Date;
+ agentId: string | null;
+ createdAt: Date;
+ description: string | null;
+ descriptionVector: number[] | null;
+ id: string;
+ isSelf: boolean;
+ metadata: Record<string, unknown> | null;
+ name: string;
+ parentEntityId: string | null;
+ projectId: string | null;
+ relationship: string | null;
+ role: string | null;
+ type: UserMemoryEntityType;
+ updatedAt: Date;
+ userId: string | null;
+ userMemoryId: string | null;
+ visibility: UserMemoryVisibility;
+ workspaceId: string | null;
+}
+
+/** Insert shape of `UserMemoryEntity`: required columns have no database default. */
+export interface UserMemoryEntityInsert {
+ accessedAt?: Date;
+ agentId?: string | null;
+ createdAt?: Date;
+ description?: string | null;
+ descriptionVector?: number[] | null;
+ id?: string;
+ isSelf?: boolean;
+ metadata?: Record<string, unknown> | null;
+ name: string;
+ parentEntityId?: string | null;
+ projectId?: string | null;
+ relationship?: string | null;
+ role?: string | null;
+ type?: UserMemoryEntityType;
+ updatedAt?: Date;
+ userId?: string | null;
+ userMemoryId?: string | null;
+ visibility?: UserMemoryVisibility;
+ workspaceId?: string | null;
+}
+
+/** Row of `user_memories_entity_names` — a name an entity goes by. */
+export interface UserMemoryEntityName {
+ accessedAt: Date;
+ createdAt: Date;
+ entityId: string;
+ id: string;
+ kind: UserMemoryEntityNameKind;
+ metadata: Record<string, unknown> | null;
+ name: string;
+ normalized: string;
+ sourceMemoryId: string | null;
+ updatedAt: Date;
+ userId: string | null;
+ workspaceId: string | null;
+}
+
+/** Insert shape of `UserMemoryEntityName`: required columns have no database default. */
+export interface UserMemoryEntityNameInsert {
+ accessedAt?: Date;
+ createdAt?: Date;
+ entityId: string;
+ id?: string;
+ kind?: UserMemoryEntityNameKind;
+ metadata?: Record<string, unknown> | null;
+ name: string;
+ normalized: string;
+ sourceMemoryId?: string | null;
+ updatedAt?: Date;
+ userId?: string | null;
+ workspaceId?: string | null;
+}
+
+/** Row of `user_memories_edges` — a graph relation between two memories. */
+export interface UserMemoryEdge {
+ accessedAt: Date;
+ createdAt: Date;
+ evidenceCount: number;
+ id: string;
+ metadata: Record<string, unknown> | null;
+ relation: UserMemoryEdgeRelation;
+ sourceMemoryId: string;
+ targetMemoryId: string;
+ updatedAt: Date;
+ userId: string | null;
+ workspaceId: string | null;
+}
+
+/** Insert shape of `UserMemoryEdge`: required columns have no database default. */
+export interface UserMemoryEdgeInsert {
+ accessedAt?: Date;
+ createdAt?: Date;
+ evidenceCount?: number;
+ id?: string;
+ metadata?: Record<string, unknown> | null;
+ relation: UserMemoryEdgeRelation;
+ sourceMemoryId: string;
+ targetMemoryId: string;
+ updatedAt?: Date;
+ userId?: string | null;
+ workspaceId?: string | null;
+}
+
+/** Row of `user_memories_operations` — one structural change, with what is needed to undo it. */
+export interface UserMemoryOperation {
+ accessedAt: Date;
+ actor: UserMemoryOperationActor;
+ after: Record<string, unknown> | null;
+ before: Record<string, unknown> | null;
+ confidence: number | null;
+ createdAt: Date;
+ gate: UserMemoryOperationGate;
+ id: string;
+ metadata: Record<string, unknown> | null;
+ op: UserMemoryOperationType;
+ reason: string | null;
+ resolvedAt: Date | null;
+ state: UserMemoryOperationState;
+ targets: Record<string, string | string[]>;
+ updatedAt: Date;
+ userId: string | null;
+ workspaceId: string | null;
+}
+
+/** Insert shape of `UserMemoryOperation`: required columns have no database default. */
+export interface UserMemoryOperationInsert {
+ accessedAt?: Date;
+ actor: UserMemoryOperationActor;
+ after?: Record<string, unknown> | null;
+ before?: Record<string, unknown> | null;
+ confidence?: number | null;
+ createdAt?: Date;
+ gate: UserMemoryOperationGate;
+ id?: string;
+ metadata?: Record<string, unknown> | null;
+ op: UserMemoryOperationType;
+ reason?: string | null;
+ resolvedAt?: Date | null;
+ state: UserMemoryOperationState;
+ targets: Record<string, string | string[]>;
+ updatedAt?: Date;
+ userId?: string | null;
+ workspaceId?: string | null;
+}
+
+/** Row of `user_memory_persona_documents` — the current persona of a user. */
+export interface UserPersonaDocument {
+ accessedAt: Date;
+ capturedAt: Date;
+ createdAt: Date;
+ id: string;
+ memoryIds: string[] | null;
+ metadata: Record<string, unknown> | null;
+ persona: string | null;
+ profile: string;
+ sourceIds: string[] | null;
+ tagline: string | null;
+ updatedAt: Date;
+ userId: string | null;
+ version: number;
+}
+
+/** Insert shape of `UserPersonaDocument`: required columns have no database default. */
+export interface UserPersonaDocumentInsert {
+ accessedAt?: Date;
+ capturedAt?: Date;
+ createdAt?: Date;
+ id?: string;
+ memoryIds?: string[] | null;
+ metadata?: Record<string, unknown> | null;
+ persona?: string | null;
+ profile?: string;
+ sourceIds?: string[] | null;
+ tagline?: string | null;
+ updatedAt?: Date;
+ userId?: string | null;
+ version?: number;
+}
+
+/** Row of `user_memory_persona_document_histories` — one persona revision. */
+export interface UserPersonaDocumentHistory {
+ accessedAt: Date;
+ capturedAt: Date;
+ createdAt: Date;
+ diffPersona: string | null;
+ diffTagline: string | null;
+ editedBy: string | null;
+ id: string;
+ memoryIds: string[] | null;
+ metadata: Record<string, unknown> | null;
+ nextVersion: number | null;
+ personaId: string | null;
+ previousVersion: number | null;
+ profile: string;
+ reasoning: string | null;
+ snapshot: string | null;
+ snapshotPersona: string | null;
+ snapshotTagline: string | null;
+ sourceIds: string[] | null;
+ summary: string | null;
+ updatedAt: Date;
+ userId: string | null;
+}
+
+/** Insert shape of `UserPersonaDocumentHistory`: required columns have no database default. */
+export interface UserPersonaDocumentHistoryInsert {
+ accessedAt?: Date;
+ capturedAt?: Date;
+ createdAt?: Date;
+ diffPersona?: string | null;
+ diffTagline?: string | null;
+ editedBy?: string | null;
+ id?: string;
+ memoryIds?: string[] | null;
+ metadata?: Record<string, unknown> | null;
+ nextVersion?: number | null;
+ personaId?: string | null;
+ previousVersion?: number | null;
+ profile?: string;
+ reasoning?: string | null;
+ snapshot?: string | null;
+ snapshotPersona?: string | null;
+ snapshotTagline?: string | null;
+ sourceIds?: string[] | null;
+ summary?: string | null;
+ updatedAt?: Date;
+ userId?: string | null;
+}
diff --git a/packages/types/src/userMemory/tools.ts b/packages/types/src/userMemory/tools.ts
index e7128e5721e..87377e1c8dd 100644
--- a/packages/types/src/userMemory/tools.ts
+++ b/packages/types/src/userMemory/tools.ts
@@ -1,13 +1,13 @@
import { z } from 'zod';
import type { StrictOnly } from '../zodStrict';
-import type { UserMemoryIdentity } from './identity';
import type {
UserMemoryActivity,
UserMemoryContext,
UserMemoryExperience,
+ UserMemoryIdentity,
UserMemoryPreference,
-} from './layers';
+} from './rows';
import { LayersEnum } from './shared';
const stringArrayFieldSchema = z.preprocess(