Skip to content

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

✨ feat(memory): consolidate legacy contexts into contexts and dossiers (#21968)

Arvin Xu77e07fd22075
diff --git a/apps/server/src/globalConfig/parseMemoryExtractionConfig.ts b/apps/server/src/globalConfig/parseMemoryExtractionConfig.ts
index bb61f57b754..f1dd3bca510 100644
--- a/apps/server/src/globalConfig/parseMemoryExtractionConfig.ts
+++ b/apps/server/src/globalConfig/parseMemoryExtractionConfig.ts
@@ -65,6 +65,8 @@ export type MemoryLayerExtractorConfig = MemoryLayerExtractorPublicConfig &
export interface MemoryExtractionPrivateConfig {
agentBenchmarkLoCoMo: MemoryAgentConfig;
+ /** Memory consolidation (contexts / dossiers); falls back to the persona writer. */
+ agentConsolidation: MemoryAgentConfig;
agentGateKeeper: MemoryAgentConfig;
agentGateKeeperPreferredModels?: string[];
agentGateKeeperPreferredProviders?: string[];
@@ -73,6 +75,11 @@ export interface MemoryExtractionPrivateConfig {
agentLayerExtractorPreferredProviders?: string[];
agentPersonaWriter: MemoryAgentConfig;
concurrency?: number;
+ /**
+ * UTC hour at which the hourly run also starts the incremental consolidation of every
+ * consolidated user; undefined disables it.
+ */
+ consolidationNightlyHourUtc?: number;
embedding: MemoryAgentConfig;
embeddingPreferredModels?: string[];
embeddingPreferredProviders?: string[];
@@ -212,6 +219,25 @@ const parsePersonaWriterAgent = (
};
};
+const parseConsolidationAgent = (fallback: MemoryAgentConfig): MemoryAgentConfig => {
+ const provider = process.env.MEMORY_USER_MEMORY_CONSOLIDATION_PROVIDER;
+ // Credentials only carry over when the provider is not overridden to a different one.
+ const inherit = !provider || provider.toLowerCase() === (fallback.provider || '').toLowerCase();
+
+ return {
+ apiKey:
+ process.env.MEMORY_USER_MEMORY_CONSOLIDATION_API_KEY ??
+ (inherit ? fallback.apiKey : undefined),
+ baseURL:
+ process.env.MEMORY_USER_MEMORY_CONSOLIDATION_BASE_URL ??
+ (inherit ? fallback.baseURL : undefined),
+ contextLimit: fallback.contextLimit,
+ language: process.env.MEMORY_USER_MEMORY_CONSOLIDATION_LANGUAGE ?? fallback.language,
+ model: process.env.MEMORY_USER_MEMORY_CONSOLIDATION_MODEL || fallback.model,
+ provider: provider || fallback.provider,
+ };
+};
+
const parseExtractorAgentObservabilityS3 = () => {
const accessKeyId = process.env.MEMORY_USER_MEMORY_EXTRACTOR_S3_ACCESS_KEY_ID;
const secretAccessKey = process.env.MEMORY_USER_MEMORY_EXTRACTOR_S3_SECRET_ACCESS_KEY;
@@ -258,6 +284,12 @@ export const parseMemoryExtractionConfig = (): MemoryExtractionPrivateConfig =>
const agentBenchmarkLoCoMo = parseBenchmarkLoCoMoAgent(agentGateKeeper);
const agentLayerExtractor = parseLayerExtractorAgent(agentGateKeeper.model);
const agentPersonaWriter = parsePersonaWriterAgent(agentGateKeeper.model);
+ const agentConsolidation = parseConsolidationAgent(agentPersonaWriter);
+ const nightlyHourRaw = process.env.MEMORY_USER_MEMORY_CONSOLIDATION_NIGHTLY_HOUR ?? '18';
+ const consolidationNightlyHourUtc =
+ /^\d+$/.test(nightlyHourRaw) && Number(nightlyHourRaw) < 24
+ ? Number(nightlyHourRaw)
+ : undefined;
const embedding = parseEmbeddingAgent(
agentLayerExtractor.model,
agentLayerExtractor.provider || DEFAULT_MINI_PROVIDER,
@@ -336,6 +368,8 @@ export const parseMemoryExtractionConfig = (): MemoryExtractionPrivateConfig =>
agentLayerExtractor,
agentLayerExtractorPreferredModels,
agentLayerExtractorPreferredProviders,
+ agentConsolidation,
+ consolidationNightlyHourUtc,
agentPersonaWriter,
concurrency,
embedding,
diff --git a/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts b/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts
index 655e4d374df..32785d51e3c 100644
--- a/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts
+++ b/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts
@@ -105,6 +105,7 @@ describe('webhooks hono routes', () => {
'/api/webhooks/logto',
'/api/webhooks/memory-extraction',
'/api/webhooks/memory-extraction/benchmark-locomo',
+ '/api/webhooks/memory-user-memory/consolidation',
'/api/webhooks/memory-user-memory/persona/update-writing',
'/api/webhooks/memory-user-memory/pipelines/extract/chat-topic/cancel',
'/api/webhooks/video/:provider',
diff --git a/apps/server/src/router-hono/webhooks/handlers/memoryUserMemoryConsolidation.ts b/apps/server/src/router-hono/webhooks/handlers/memoryUserMemoryConsolidation.ts
new file mode 100644
index 00000000000..60bbcdd568b
--- /dev/null
+++ b/apps/server/src/router-hono/webhooks/handlers/memoryUserMemoryConsolidation.ts
@@ -0,0 +1,71 @@
+import type { Context } from 'hono';
+import pMap from 'p-map';
+import { z } from 'zod';
+
+import { UserMemoryConsolidationModel } from '@/database/models/userMemory/consolidation';
+import { getServerDB } from '@/database/server';
+import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
+import { MemoryExtractionWorkflowService } from '@/server/services/memory/userMemory/extract';
+
+const schema = z.discriminatedUnion('action', [
+ z.object({
+ action: z.literal('run'),
+ model: z.string().optional(),
+ provider: z.string().optional(),
+ userIds: z.array(z.string().min(1)).min(1).max(100),
+ }),
+ z.object({
+ action: z.literal('revert'),
+ runId: z.string().min(1),
+ userId: z.string().min(1),
+ }),
+]);
+
+/**
+ * Starts a memory consolidation run per user (`action: run`), or undoes one run
+ * (`action: revert`). Header auth is applied by the `memoryWebhookAuth` middleware.
+ */
+export const memoryUserMemoryConsolidation = async (c: Context) => {
+ const { upstashWorkflowExtraHeaders, webhook } = parseMemoryExtractionConfig();
+
+ try {
+ const params = schema.parse(await c.req.json());
+
+ if (params.action === 'revert') {
+ const db = await getServerDB();
+ const result = await new UserMemoryConsolidationModel(db, params.userId).revertRun(
+ params.runId,
+ );
+ if (result.blockedBy)
+ return c.json(
+ { message: 'Later runs extended this run; revert them first.', ...result },
+ 409,
+ );
+ return c.json({ message: 'Consolidation run reverted.', ...result }, 200);
+ }
+
+ // The workflow destination comes from admin config or this request's origin, never the body.
+ const baseUrl = webhook.baseUrl || new URL(c.req.url).origin;
+ const results = await pMap(
+ [...new Set(params.userIds)],
+ async (userId) => {
+ const { workflowRunId } = await MemoryExtractionWorkflowService.triggerConsolidation(
+ userId,
+ baseUrl,
+ {
+ extraHeaders: upstashWorkflowExtraHeaders,
+ model: params.model,
+ provider: params.provider,
+ },
+ );
+ return { userId, workflowRunId };
+ },
+ { concurrency: 5 },
+ );
+
+ return c.json({ message: 'Memory consolidation scheduled via workflow.', results }, 202);
+ } catch (error) {
+ console.error('[memory-consolidation] failed', error);
+ return c.json({ error: (error as Error).message }, 500);
+ }
+};
diff --git a/apps/server/src/router-hono/webhooks/index.ts b/apps/server/src/router-hono/webhooks/index.ts
index 12c9f407863..2e7d2edf19a 100644
--- a/apps/server/src/router-hono/webhooks/index.ts
+++ b/apps/server/src/router-hono/webhooks/index.ts
@@ -10,6 +10,7 @@ import { logtoWebhook } from './handlers/logto';
import { memoryExtractionWebhook } from './handlers/memoryExtraction';
import { memoryExtractionBenchmarkLocomo } from './handlers/memoryExtractionBenchmarkLocomo';
import { memoryUserMemoryChatTopicCancel } from './handlers/memoryUserMemoryChatTopicCancel';
+import { memoryUserMemoryConsolidation } from './handlers/memoryUserMemoryConsolidation';
import { memoryUserMemoryPersonaUpdateWriting } from './handlers/memoryUserMemoryPersonaUpdateWriting';
import { videoWebhook } from './handlers/video';
import { memoryWebhookAuth } from './middlewares/memoryWebhookAuth';
@@ -27,6 +28,7 @@ app.post(
memoryWebhookAuth(),
memoryExtractionBenchmarkLocomo,
);
+app.post('/memory-user-memory/consolidation', memoryWebhookAuth(), memoryUserMemoryConsolidation);
app.post(
'/memory-user-memory/persona/update-writing',
memoryWebhookAuth(),
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/index.ts b/apps/server/src/router-hono/workflows/memory-user-memory/index.ts
index 9a0aaab0d03..8ac7a193ed2 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/index.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/index.ts
@@ -3,6 +3,7 @@ import { serve } from '@upstash/workflow/hono';
import { Hono } from 'hono';
import { createWorkflowQstashClient } from '../qstashClient';
+import { consolidationHandler, consolidationWorkflowOptions } from './workflows/consolidation';
import { hourlyWorkflowHandler, hourlyWorkflowOptions } from './workflows/hourly';
import { personaUpdateHandler, personaUpdateWorkflowOptions } from './workflows/personaUpdate';
import { processTopicHandler, processTopicWorkflowOptions } from './workflows/processTopic';
@@ -28,6 +29,16 @@ app.post(
),
);
+app.post(
+ '/pipelines/consolidation/run',
+ serve(
+ withOtelMetricsForUpstashWorkflows(consolidationHandler, {
+ url: '/api/workflows/memory-user-memory/pipelines/consolidation/run',
+ }),
+ { ...consolidationWorkflowOptions, qstashClient: createWorkflowQstashClient() },
+ ),
+);
+
app.post(
'/pipelines/persona/update-writing',
serve(
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/hourly.test.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/hourly.test.ts
index 9fe4b554af5..1c2f93a2922 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/hourly.test.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/hourly.test.ts
@@ -7,6 +7,9 @@ import { hourlyWorkflowHandler } from '../hourly';
const mocks = vi.hoisted(() => ({
appendUserMemoryWorkflowRunIds: vi.fn(),
+ config: { consolidationNightlyHourUtc: undefined as number | undefined },
+ listConsolidatedUserIds: vi.fn(),
+ triggerConsolidation: vi.fn(),
createExecutor: vi.fn(),
getUsersForHourlyExtraction: vi.fn(),
isHourlyMemoryExtractionCancellationRequested: vi.fn(),
@@ -25,6 +28,7 @@ vi.mock('@/envs/app', () => ({
vi.mock('@/server/globalConfig/parseMemoryExtractionConfig', () => ({
parseMemoryExtractionConfig: () => ({
+ consolidationNightlyHourUtc: mocks.config.consolidationNightlyHourUtc,
upstashWorkflowExtraHeaders: {},
webhook: { baseUrl: 'https://app.example.com' },
}),
@@ -36,6 +40,7 @@ vi.mock('@/server/services/memory/userMemory/extract', () => ({
create: mocks.createExecutor,
},
MemoryExtractionWorkflowService: {
+ triggerConsolidation: mocks.triggerConsolidation,
triggerHourly: mocks.triggerHourly,
triggerHourlyTracked: mocks.triggerHourlyTracked,
triggerProcessUsers: mocks.triggerProcessUsers,
@@ -64,6 +69,10 @@ vi.mock('@/database/server', () => ({
})),
}));
+vi.mock('@/database/models/userMemory/consolidation', () => ({
+ listConsolidatedUserIds: mocks.listConsolidatedUserIds,
+}));
+
vi.mock('../runGuard', () => ({
checkGuard: vi.fn().mockResolvedValue({ result: true }),
ensureWorkflowStarted: vi.fn().mockResolvedValue({ started: true }),
@@ -72,6 +81,9 @@ vi.mock('../runGuard', () => ({
describe('hourlyWorkflowHandler', () => {
beforeEach(() => {
vi.clearAllMocks();
+ mocks.config.consolidationNightlyHourUtc = undefined;
+ mocks.listConsolidatedUserIds.mockResolvedValue(['user-a', 'user-b']);
+ mocks.triggerConsolidation.mockResolvedValue({ workflowRunId: 'consolidation-run' });
mocks.createExecutor.mockResolvedValue({
getUsersForHourlyExtraction: mocks.getUsersForHourlyExtraction,
});
@@ -247,4 +259,46 @@ describe('hourlyWorkflowHandler', () => {
},
);
});
+
+ it('starts the incremental consolidation of consolidated users at the nightly hour only', async () => {
+ mocks.getUsersForHourlyExtraction.mockResolvedValue({ ids: ['user-1'] });
+ const run = () =>
+ hourlyWorkflowHandler({
+ requestPayload: { hourlyTaskId: '00000000-0000-4000-8000-000000000001' },
+ run: createStepRunner(),
+ } as never);
+
+ mocks.config.consolidationNightlyHourUtc = (new Date().getUTCHours() + 1) % 24;
+ await run();
+ expect(mocks.triggerConsolidation).not.toHaveBeenCalled();
+
+ mocks.config.consolidationNightlyHourUtc = new Date().getUTCHours();
+ await run();
+ expect(mocks.triggerConsolidation.mock.calls.map((call) => call[0])).toEqual([
+ 'user-a',
+ 'user-b',
+ ]);
+ expect(mocks.triggerConsolidation).toHaveBeenCalledWith('user-a', 'https://app.example.com', {
+ extraHeaders: {},
+ });
+ });
+
+ it('starts the nightly consolidation on the empty page that ends a real cursor chain', async () => {
+ mocks.config.consolidationNightlyHourUtc = new Date().getUTCHours();
+ // The real executor returns a cursor for every nonempty page, so the chain ends on an empty one.
+ mocks.getUsersForHourlyExtraction.mockResolvedValue({ ids: [] });
+
+ await hourlyWorkflowHandler({
+ requestPayload: {
+ cursor: { createdAt: new Date().toISOString(), id: 'user-last' },
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ },
+ run: createStepRunner(),
+ } as never);
+
+ expect(mocks.triggerConsolidation.mock.calls.map((call) => call[0])).toEqual([
+ 'user-a',
+ 'user-b',
+ ]);
+ });
});
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/consolidation.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/consolidation.ts
new file mode 100644
index 00000000000..4890bcbc086
--- /dev/null
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/consolidation.ts
@@ -0,0 +1,269 @@
+import { type WorkflowContext } from '@upstash/workflow';
+import { z } from 'zod';
+
+import {
+ type ConsolidationRoute,
+ UserMemoryConsolidationModel,
+} from '@/database/models/userMemory/consolidation';
+import { getServerDB } from '@/database/server';
+import {
+ CLASSIFY_BATCH,
+ MemoryConsolidationService,
+ SYNTH_CHUNK,
+ toContextPlans,
+} from '@/server/services/memory/userMemory/consolidation/service';
+import { runStep } from '@/server/workflows/step';
+
+import { checkGuard, ensureWorkflowStarted } from './runGuard';
+
+const WORKFLOW_PATH = 'api/workflows/memory-user-memory/pipelines/consolidation/run';
+const ROUTE_BATCH = 10;
+
+const payloadSchema = z.object({
+ /** `revert` undoes the run `revertRunId` instead of consolidating. */
+ action: z.enum(['run', 'revert']).optional(),
+ model: z.string().optional(),
+ provider: z.string().optional(),
+ revertRunId: z.string().optional(),
+ userId: z.string().min(1),
+});
+
+const STEP = 'memory:pipelines:consolidation';
+
+/**
+ * Consolidates one user's memory into contexts and dossiers.
+ *
+ * - backfill (the user has no consolidated context yet): classify every legacy per-topic context,
+ * normalize domain keys, then synthesize each domain into contexts + dossiers in time-ordered
+ * chunks, writing as it goes.
+ * - incremental (afterwards): route each new legacy context to a consolidated context (or a new
+ * one), then synthesize each touched context with its existing dossiers.
+ *
+ * Decisions travel through the database (`consolidationQueue` on the legacy rows), so step results
+ * stay small; every write carries the workflow run id and can be reverted.
+ */
+export const consolidationHandler = async (context: WorkflowContext) => {
+ await ensureWorkflowStarted(context, WORKFLOW_PATH);
+ const empty = { contexts: 0, mode: 'none' as const, processed: 0 };
+ const entry = await checkGuard(context, WORKFLOW_PATH, { response: empty });
+ if (!entry.result) return entry.response;
+
+ const payload = await runStep(context, `${STEP}:parse-payload`, () =>
+ payloadSchema.parse(context.requestPayload || {}),
+ );
+ const runId = context.workflowRunId;
+ const db = await getServerDB();
+
+ if (payload.action === 'revert') {
+ // Return rather than throw: a throw makes Upstash retry a request that can never succeed.
+ if (!payload.revertRunId)
+ return { ...empty, error: 'revertRunId is required', mode: 'revert' as const };
+ const revertRunId = payload.revertRunId;
+ const reverted = await runStep(context, `${STEP}:revert`, () =>
+ new UserMemoryConsolidationModel(db, payload.userId).revertRun(revertRunId),
+ );
+ return { ...empty, mode: 'revert' as const, reverted, revertRunId };
+ }
+
+ const service = () =>
+ new MemoryConsolidationService(db, payload.userId, runId, {
+ model: payload.model,
+ provider: payload.provider,
+ });
+
+ const pending = await runStep(context, `${STEP}:list-pending`, async () => {
+ const s = service();
+ const [items, consolidated] = await Promise.all([
+ s.model.listPendingLegacyContexts(),
+ s.model.listConsolidated(),
+ ]);
+ return {
+ ids: items.map((i) => i.id),
+ mode: consolidated.contexts.length === 0 ? ('backfill' as const) : ('incremental' as const),
+ };
+ });
+ if (pending.ids.length === 0) return { ...empty, mode: pending.mode };
+
+ // ---------- stage 1: decide route + queue key ----------
+ if (pending.mode === 'backfill') {
+ const domainCounts: Record<string, number> = {};
+ for (let i = 0; i < pending.ids.length; i += CLASSIFY_BATCH) {
+ const batch = pending.ids.slice(i, i + CLASSIFY_BATCH);
+ const counts = await runStep(context, `${STEP}:classify:${i / CLASSIFY_BATCH}`, async () => {
+ const s = service();
+ const items = await s.classify(batch);
+ await s.model.enqueue(
+ runId,
+ items.map((x) => ({ id: x.id, key: x.domain || 'misc', route: x.route })),
+ );
+ const routed: Record<string, ConsolidationRoute> = {};
+ for (const x of items) if (x.route !== 'evidence') routed[x.id] = x.route;
+ await s.markRouted(routed);
+ const out: Record<string, number> = {};
+ for (const x of items)
+ if (x.route === 'evidence') out[x.domain || 'misc'] = (out[x.domain || 'misc'] ?? 0) + 1;
+ return out;
+ });
+ for (const [k, n] of Object.entries(counts)) domainCounts[k] = (domainCounts[k] ?? 0) + n;
+ }
+ const domainMap = await runStep(context, `${STEP}:normalize`, () =>
+ service().normalizeDomains(domainCounts),
+ );
+
+ const groups = await runStep(context, `${STEP}:group`, async () => {
+ const queued = await service().model.listQueued(runId);
+ const out: Record<string, string[]> = {};
+ for (const q of queued) (out[domainMap[q.key] ?? q.key] ??= []).push(q.id);
+ return out;
+ });
+
+ let contexts = 0;
+ for (const [d, [domain, ids]] of Object.entries(groups).entries()) {
+ let domainContexts: string[] = [];
+ for (let c = 0; c * SYNTH_CHUNK < ids.length; c += 1) {
+ const chunk = ids.slice(c * SYNTH_CHUNK, (c + 1) * SYNTH_CHUNK);
+ const known = domainContexts;
+ const res = await runStep(context, `${STEP}:synthesize:${d}:${c}`, () =>
+ synthesizeAndApply(service(), domain, chunk, known),
+ );
+ domainContexts = [...new Set([...domainContexts, ...res.contextIds])];
+ }
+ contexts += domainContexts.length;
+ }
+ return { contexts, mode: 'backfill', processed: pending.ids.length, runId };
+ }
+
+ for (let i = 0; i < pending.ids.length; i += ROUTE_BATCH) {
+ const batch = pending.ids.slice(i, i + ROUTE_BATCH);
+ await runStep(context, `${STEP}:route:${i / ROUTE_BATCH}`, async () => {
+ const s = service();
+ const [items, consolidated] = await Promise.all([
+ s.model.getLegacyContextsByIds(batch),
+ s.model.listConsolidated(),
+ ]);
+ const titles = await s.model.listDossierEvidenceTitles(
+ consolidated.dossiers.map((d) => d.id),
+ 2,
+ );
+ const dossierTitles = new Map<string, string[]>();
+ const recallText = new Map<string, string[]>();
+ for (const d of consolidated.dossiers) {
+ if (!d.contextId) continue;
+ dossierTitles.set(d.contextId, [...(dossierTitles.get(d.contextId) ?? []), d.title ?? '']);
+ recallText.set(d.contextId, [
+ ...(recallText.get(d.contextId) ?? []),
+ d.title ?? '',
+ ...(titles[d.id] ?? []),
+ ]);
+ }
+ const candidates = consolidated.contexts.map((c) => ({
+ id: c.id,
+ lastEvidenceAt: c.lastEvidenceAt,
+ recall: `${c.title ?? ''} ${(recallText.get(c.id) ?? []).join(' ')}`,
+ text: `${c.title ?? ''} | 档案:${(dossierTitles.get(c.id) ?? []).slice(0, 8).join(';')}`,
+ title: c.title,
+ }));
+ const entries: { id: string; key: string; route: ConsolidationRoute }[] = [];
+ const routed: Record<string, ConsolidationRoute> = {};
+ for (const item of items) {
+ const r = await s.route(item, candidates);
+ const key =
+ r.context === 'new' ? `new:${r.new_context_title || item.title || item.id}` : r.context;
+ entries.push({ id: item.id, key, route: r.route });
+ if (r.route !== 'evidence') routed[item.id] = r.route;
+ }
+ await s.model.enqueue(runId, entries);
+ await s.markRouted(routed);
+ return entries.length;
+ });
+ }
+
+ const groups = await runStep(context, `${STEP}:group`, async () => {
+ const queued = await service().model.listQueued(runId);
+ const out: Record<string, string[]> = {};
+ for (const q of queued) (out[q.key] ??= []).push(q.id);
+ return out;
+ });
+ let contexts = 0;
+ for (const [g, [key, ids]] of Object.entries(groups).entries()) {
+ const isNew = key.startsWith('new:');
+ // Later chunks of one group must see the contexts earlier chunks created, as in backfill.
+ let groupContexts: string[] = isNew ? [] : [key];
+ const touched = new Set<string>();
+ for (let c = 0; c * SYNTH_CHUNK < ids.length; c += 1) {
+ const chunk = ids.slice(c * SYNTH_CHUNK, (c + 1) * SYNTH_CHUNK);
+ const known = groupContexts;
+ const res = await runStep(context, `${STEP}:synthesize:${g}:${c}`, () =>
+ synthesizeAndApply(service(), isNew ? key.slice(4) : key, chunk, known),
+ );
+ for (const id of res.contextIds) touched.add(id);
+ groupContexts = [...new Set([...groupContexts, ...res.contextIds])];
+ }
+ contexts += touched.size;
+ }
+ return { contexts, mode: 'incremental', processed: pending.ids.length, runId };
+};
+
+/** One synthesis call plus its writes; `contextIds` are consolidated contexts it may extend. */
+const synthesizeAndApply = async (
+ s: MemoryConsolidationService,
+ label: string,
+ chunkIds: string[],
+ contextIds: string[],
+) => {
+ const out = { activities: 0, contextIds: [] as string[], dossiers: 0, unplaced: 0 };
+ // A retried step re-reads its chunk: evidence a committed plan already filed drops out here.
+ const ids = (await s.model.getLegacyContextsByIds(chunkIds)).map((i) => i.id);
+ // ...and the contexts it filed them into stay known, so the rest extends them.
+ const filed = ids.length < chunkIds.length ? await s.filedContextIds(chunkIds) : [];
+ out.contextIds.push(...filed);
+ if (ids.length === 0) return out;
+ const knownIds = new Set([...contextIds, ...filed]);
+
+ const consolidated = await s.model.listConsolidated();
+ const known = consolidated.contexts.filter((c) => knownIds.has(c.id));
+ const dossiers = consolidated.dossiers.filter((d) => d.contextId && knownIds.has(d.contextId));
+ const titles = await s.model.listDossierEvidenceTitles(
+ dossiers.map((d) => d.id),
+ 3,
+ );
+ const stubs = known.flatMap((c) => [
+ `context id=${c.id}:${c.title ?? ''}`,
+ ...dossiers
+ .filter((d) => d.contextId === c.id)
+ .map(
+ (d) =>
+ ` 档案 id=${d.id}:${d.title ?? ''}(${d.activityCount} 条,现在:${(d.now ?? '').slice(0, 60)},近期:${(titles[d.id] ?? []).join(';')})`,
+ ),
+ ]);
+ const result = await s.synthesize(label, ids, stubs);
+ const { placed, plans } = toContextPlans(
+ result,
+ new Set(ids),
+ new Set(known.map((c) => c.id)),
+ new Set(dossiers.map((d) => d.id)),
+ );
+ // When there is a single known context, the model may describe it without echoing its id.
+ if (known.length === 1) for (const p of plans) p.existingContextId ??= known[0].id;
+
+ for (const plan of plans) {
+ const r = await s.applyPlan(plan);
+ out.activities += r.activities;
+ out.dossiers += r.dossiersCreated;
+ if (r.contextId) out.contextIds.push(r.contextId);
+ }
+ const unplaced = ids.filter((id) => !placed.has(id));
+ if (unplaced.length > 0) {
+ // Not part of any ongoing matter: keep the legacy row as it is, but do not route it again.
+ await s.markRouted(Object.fromEntries(unplaced.map((id) => [id, 'drop' as const])));
+ out.unplaced = unplaced.length;
+ }
+ return out;
+};
+
+export const consolidationWorkflowOptions = {
+ flowControl: {
+ key: 'memory-user-memory.pipelines.consolidation',
+ parallelism: 2,
+ },
+};
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/hourly.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/hourly.ts
index 174c5626f8e..4208ca12626 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/hourly.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/hourly.ts
@@ -2,6 +2,8 @@ import { MemorySourceType } from '@lobechat/types';
import { type WorkflowContext } from '@upstash/workflow';
import { chunk } from 'es-toolkit/compat';
+import { listConsolidatedUserIds } from '@/database/models/userMemory/consolidation';
+import { getServerDB } from '@/database/server';
import { appEnv } from '@/envs/app';
import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
import {
@@ -29,6 +31,49 @@ const { webhook, upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();
const resolveBaseUrl = () => webhook.baseUrl || appEnv.INTERNAL_APP_URL || appEnv.APP_URL;
+/**
+ * Starts the nightly incremental consolidation of every consolidated user, once per day, on the
+ * page that ends the hourly chain. With the real executor that is the empty page after the last
+ * nonempty one, because a nonempty page always returns a cursor.
+ */
+const scheduleNightlyConsolidation = async (
+ context: WorkflowContext<MemoryExtractionHourlyWorkflowPayload>,
+ baseUrl: string,
+) => {
+ // NOTICE: The window decision is time-dependent, so it must be evaluated inside a step that
+ // Upstash can replay with the same result. Reading the clock before branching would let a
+ // replayed page that crosses the hour boundary skip the fan-out it already committed to.
+ const inNightlyWindow = await runStep(
+ context,
+ 'memory:user-memory:hourly:consolidation-window',
+ () => {
+ const { consolidationNightlyHourUtc } = parseMemoryExtractionConfig();
+ if (consolidationNightlyHourUtc === undefined) return false;
+
+ return new Date().getUTCHours() === consolidationNightlyHourUtc;
+ },
+ );
+ if (!inNightlyWindow) return;
+
+ const stepName = 'memory:user-memory:hourly:schedule-consolidation';
+ const guard = await checkGuard(context, WORKFLOW_PATH, {
+ response: { processedUsers: 0 },
+ stepName,
+ });
+ if (!guard.result) return guard.response;
+
+ await runStep(context, stepName, async () => {
+ const db = await getServerDB();
+ const userIdsToConsolidate = await listConsolidatedUserIds(db);
+ for (const userId of userIdsToConsolidate) {
+ await MemoryExtractionWorkflowService.triggerConsolidation(userId, baseUrl, {
+ extraHeaders: upstashWorkflowExtraHeaders,
+ });
+ }
+ return userIdsToConsolidate.length;
+ });
+};
+
export const hourlyWorkflowHandler = async (
context: WorkflowContext<MemoryExtractionHourlyWorkflowPayload>,
) => {
@@ -122,6 +167,11 @@ export const hourlyWorkflowHandler = async (
const userIds = userBatch.ids;
if (userIds.length === 0) {
+ if (!dryRun) {
+ const response = await scheduleNightlyConsolidation(context, baseUrl);
+ if (response) return response;
+ }
+
await markHourlyMemoryExtractionSuccess(hourlyTaskId, {
processedUsers: 0,
scheduledBatches: 0,
@@ -206,6 +256,11 @@ export const hourlyWorkflowHandler = async (
await appendHourlyWorkflowRunId(hourlyTaskId, result.workflowRunId);
}
+ if (!nextCursor && !dryRun) {
+ const response = await scheduleNightlyConsolidation(context, baseUrl);
+ if (response) return response;
+ }
+
if (!nextCursor) {
await markHourlyMemoryExtractionSuccess(hourlyTaskId, {
processedUsers: userIds.length,
diff --git a/apps/server/src/services/memory/userMemory/__tests__/extract.surface.test.ts b/apps/server/src/services/memory/userMemory/__tests__/extract.surface.test.ts
index d6f17d3f5cf..cb53b7ff99f 100644
--- a/apps/server/src/services/memory/userMemory/__tests__/extract.surface.test.ts
+++ b/apps/server/src/services/memory/userMemory/__tests__/extract.surface.test.ts
@@ -118,6 +118,7 @@ describe('extract module surface', () => {
expect(functionMembers(MemoryExtractionExecutor)).toEqual(['create']);
expect(functionMembers(MemoryExtractionWorkflowService)).toEqual([
'getClient',
+ 'triggerConsolidation',
'triggerHourly',
'triggerHourlyTracked',
'triggerPersonaUpdate',
diff --git a/apps/server/src/services/memory/userMemory/consolidation/__tests__/toContextPlans.test.ts b/apps/server/src/services/memory/userMemory/consolidation/__tests__/toContextPlans.test.ts
new file mode 100644
index 00000000000..228551475d3
--- /dev/null
+++ b/apps/server/src/services/memory/userMemory/consolidation/__tests__/toContextPlans.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+
+import { toContextPlans } from '../service';
+
+describe('toContextPlans', () => {
+ it('keeps only members of this batch, files each memory once and validates existing ids', () => {
+ const { placed, plans } = toContextPlans(
+ {
+ contexts: [
+ {
+ dossiers: [
+ {
+ existing_dossier: 'dos_known',
+ members: ['a', 'b', 'outside'],
+ now: 'n1',
+ title: 'Scheduler',
+ },
+ { existing_dossier: 'dos_made_up', members: ['b', 'c'], now: 'n2', title: 'Panel' },
+ { existing_dossier: '', members: ['outside'], now: '', title: 'Empty' },
+ ],
+ existing_context: 'ctx_made_up',
+ next_steps: ['ship'],
+ now: 'live',
+ open_questions: [],
+ title: 'Task system',
+ },
+ // Malformed entries from a non-strict provider are skipped, not thrown on.
+ null as never,
+ ],
+ unplaced: [],
+ },
+ new Set(['a', 'b', 'c']),
+ new Set(['ctx_known']),
+ new Set(['dos_known']),
+ );
+
+ expect([...placed].sort()).toEqual(['a', 'b', 'c']);
+ expect(plans).toHaveLength(1);
+ expect(plans[0].existingContextId).toBeUndefined();
+ expect(plans[0].dossiers).toEqual([
+ { existingDossierId: 'dos_known', memberIds: ['a', 'b'], now: 'n1', title: 'Scheduler' },
+ { existingDossierId: undefined, memberIds: ['c'], now: 'n2', title: 'Panel' },
+ ]);
+ });
+
+ it('files a repeated evidence id only once inside one dossier', () => {
+ const { placed, plans } = toContextPlans(
+ {
+ contexts: [
+ {
+ dossiers: [{ existing_dossier: '', members: ['a', 'a', 'b'], now: 'n1', title: 'One' }],
+ existing_context: '',
+ next_steps: [],
+ now: 'live',
+ open_questions: [],
+ title: 'Task system',
+ },
+ ],
+ unplaced: [],
+ },
+ new Set(['a', 'b']),
+ new Set(),
+ new Set(),
+ );
+
+ expect([...placed].sort()).toEqual(['a', 'b']);
+ expect(plans[0].dossiers[0].memberIds).toEqual(['a', 'b']);
+ });
+});
diff --git a/apps/server/src/services/memory/userMemory/consolidation/prompts.ts b/apps/server/src/services/memory/userMemory/consolidation/prompts.ts
new file mode 100644
index 00000000000..f67dfbffbd3
--- /dev/null
+++ b/apps/server/src/services/memory/userMemory/consolidation/prompts.ts
@@ -0,0 +1,182 @@
+/**
+ * Prompts and output schemas for memory consolidation. Calibrated on a 200-memory replay and a
+ * full 1586-memory run with DeepSeek flash: a blind judge rated 91% of online placements
+ * reasonable and dossier coherence 4.7 / 5. An English translation scored lower on the same
+ * replay (4.4 / 5, 88%), so the prompts stay in the wording they were calibrated in; titles and
+ * summaries follow the language of the memories.
+ */
+
+export const CLASSIFY_SYSTEM = [
+ '你在整理一个用户的历史记忆。每条记忆是从一次对话里抽出来的。逐条判断它该去哪里:',
+ '- evidence:某件持续推进的事(项目、功能、客户合作、融资、交易)的一次进展或经过,包括单次开发流水;',
+ '- fact:关于某个人、公司、产品的稳定事实(身份、关系、改名、定位),不随事情推进而变;',
+ '- preference:某人(通常是用户本人,也可能是客户/投资人)的偏好、习惯、要求;',
+ '- drop:一次性技术问答、调研/论文解读、闲聊、与任何持续事项无关的内容。',
+ 'domain 用「大类/方向」写一个简短的领域键(如 product/task-system、customer/acme、company/fundraising),同一件事用同一个键。entities 列出提到的具体人、公司、产品、仓库(不要写 User/用户)。preference 时 holder 填偏好的持有者(用户本人填 self)。',
+ '每条输入记忆都要返回一项,保留它的 id。',
+].join('\n');
+
+export const CLASSIFY_SCHEMA = {
+ name: 'memory_consolidation_classify',
+ schema: {
+ additionalProperties: false,
+ properties: {
+ items: {
+ items: {
+ additionalProperties: false,
+ properties: {
+ domain: { type: 'string' },
+ entities: { items: { type: 'string' }, type: 'array' },
+ holder: { type: 'string' },
+ id: { type: 'string' },
+ route: { enum: ['evidence', 'fact', 'preference', 'drop'], type: 'string' },
+ value: { enum: ['high', 'medium', 'low'], type: 'string' },
+ },
+ required: ['id', 'route', 'value', 'domain', 'entities', 'holder'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ },
+ required: ['items'],
+ type: 'object' as const,
+ },
+ strict: true,
+};
+
+export const NORMALIZE_SYSTEM = [
+ '下面是从记忆里得到的领域键和条数,其中很多是同一个领域的不同写法或过细的拆分。把它们归并成一份统一的领域列表:同一个项目方向、同一个客户、同一件公司事务归成一个领域;不同的项目方向不要硬并。每个原始键都必须映射到一个统一键。',
+].join('\n');
+
+export const NORMALIZE_SCHEMA = {
+ name: 'memory_consolidation_normalize',
+ schema: {
+ additionalProperties: false,
+ properties: {
+ mapping: {
+ items: {
+ additionalProperties: false,
+ properties: { domain: { type: 'string' }, raw: { type: 'string' } },
+ required: ['raw', 'domain'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ },
+ required: ['mapping'],
+ type: 'object' as const,
+ },
+ strict: true,
+};
+
+export const SYNTHESIZE_SYSTEM = [
+ '你在为一个用户把同一领域下的历史记忆整理成两级结构:',
+ '- context(第一级):一个项目方向 / 一个客户合作 / 一件公司事务,例如「某产品的任务系统」「与某客户的合作」「种子轮融资」。一个领域通常只有 1–3 个 context,不要把同一个项目方向拆成多个 context;',
+ '- 档案(第二级):context 下的一个功能、一笔交易或一个持续子任务,例如「任务调度后端(heartbeat/cron)」「任务详情页与路由」「一笔过桥借款」。档案通常跨多次对话:同一功能的每次开发、修 bug、提 PR、rebase 都是这份档案的经过,必须放进同一份档案,不要按会话、按 PR、按单个 bug 拆档案。只有和其它记忆确实无关的才单独成一份档案。',
+ '每条记忆必须且只能放进一份档案(members 写记忆 id),或放进 unplaced(与这个领域的持续事项都无关)。已有结构(来自更早的记忆)给出时,属于已有档案的记忆用 existing_dossier 填那份档案的 id,不要另开。now 写这件事现在的状态(基于最新的记忆,一两句),next_steps / open_questions 只写记忆里明确出现的。',
+ '标题和摘要使用记忆原文的语言书写。',
+].join('\n');
+
+export const SYNTHESIZE_SCHEMA = {
+ name: 'memory_consolidation_synthesize',
+ schema: {
+ additionalProperties: false,
+ properties: {
+ contexts: {
+ items: {
+ additionalProperties: false,
+ properties: {
+ dossiers: {
+ items: {
+ additionalProperties: false,
+ properties: {
+ existing_dossier: { type: 'string' },
+ members: { items: { type: 'string' }, type: 'array' },
+ now: { type: 'string' },
+ title: { type: 'string' },
+ },
+ required: ['existing_dossier', 'title', 'now', 'members'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ existing_context: { type: 'string' },
+ next_steps: { items: { type: 'string' }, type: 'array' },
+ now: { type: 'string' },
+ open_questions: { items: { type: 'string' }, type: 'array' },
+ title: { type: 'string' },
+ },
+ required: [
+ 'existing_context',
+ 'title',
+ 'now',
+ 'next_steps',
+ 'open_questions',
+ 'dossiers',
+ ],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ unplaced: { items: { type: 'string' }, type: 'array' },
+ },
+ required: ['contexts', 'unplaced'],
+ type: 'object' as const,
+ },
+ strict: true,
+};
+
+export const ROUTE_SYSTEM = [
+ '你在维护一个用户的记忆。结构:context(一个项目方向/客户合作/公司事务)→ 档案(一个功能、一笔交易或一个持续子任务)→ 证据(每次对话的进展)。',
+ '新来一条从对话里抽出的记忆。先判断 route:evidence(某件持续推进的事的进展,包括单次开发流水)/ fact(关于人或公司的稳定事实)/ preference(某人的偏好或要求)/ drop(一次性技术问答、调研、闲聊)。',
+ '如果是 evidence,从下面的 context 列表里选出它所属的 context(context 填 id);确实没有任何一个相关时填 new,并给 new_context_title。同一项目方向的工作都属于同一个 context,不要因为是新的子功能就新开 context。confidence 是你对 context 选择的把握。',
+ '标题和摘要使用记忆原文的语言书写。',
+].join('\n');
+
+export const ROUTE_SCHEMA = {
+ name: 'memory_consolidation_route',
+ schema: {
+ additionalProperties: false,
+ properties: {
+ confidence: { type: 'number' },
+ context: { type: 'string' },
+ new_context_title: { type: 'string' },
+ reason: { type: 'string' },
+ route: { enum: ['evidence', 'fact', 'preference', 'drop'], type: 'string' },
+ },
+ required: ['route', 'context', 'new_context_title', 'confidence', 'reason'],
+ type: 'object' as const,
+ },
+ strict: true,
+};
+
+export interface ClassifiedItem {
+ domain: string;
+ entities: string[];
+ holder: string;
+ id: string;
+ route: 'drop' | 'evidence' | 'fact' | 'preference';
+ value: 'high' | 'low' | 'medium';
+}
+
+export interface SynthesizedContext {
+ dossiers: { existing_dossier: string; members: string[]; now: string; title: string }[];
+ existing_context: string;
+ next_steps: string[];
+ now: string;
+ open_questions: string[];
+ title: string;
+}
+
+export interface SynthesisResult {
+ contexts: SynthesizedContext[];
+ unplaced: string[];
+}
+
+export interface RouteResult {
+ confidence: number;
+ context: string;
+ new_context_title: string;
+ reason: string;
+ route: 'drop' | 'evidence' | 'fact' | 'preference';
+}
diff --git a/apps/server/src/services/memory/userMemory/consolidation/service.ts b/apps/server/src/services/memory/userMemory/consolidation/service.ts
new file mode 100644
index 00000000000..9a1a10ebcfe
--- /dev/null
+++ b/apps/server/src/services/memory/userMemory/consolidation/service.ts
@@ -0,0 +1,363 @@
+import { BRANDING_PROVIDER, ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
+import { DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM } from '@lobechat/const';
+import type { ModelRuntime } from '@lobechat/model-runtime';
+import { RequestTrigger } from '@lobechat/types';
+import debug from 'debug';
+
+import { getBusinessModelRuntimeHooks } from '@/business/server/model-runtime';
+import {
+ type ConsolidationContextPlan,
+ type ConsolidationRoute,
+ type LegacyContextItem,
+ UserMemoryConsolidationModel,
+} from '@/database/models/userMemory/consolidation';
+import { AiInfraRepos } from '@/database/repositories/aiInfra';
+import type { LobeChatDatabase } from '@/database/type';
+import { getServerDefaultFilesConfig } from '@/server/globalConfig';
+import {
+ type MemoryAgentConfig,
+ parseMemoryExtractionConfig,
+} from '@/server/globalConfig/parseMemoryExtractionConfig';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
+import { getUserScopedAiProviderRuntimeState } from '@/server/services/aiProviderAccess';
+import {
+ embedUserMemoryTexts,
+ type UserMemoryEmbeddingRuntime,
+} from '@/server/services/memory/userMemory/embedding';
+import {
+ type ProviderKeyVaultMap,
+ resolveRuntimeAgentConfig,
+} from '@/server/services/memory/userMemory/extract';
+
+import {
+ type ClassifiedItem,
+ CLASSIFY_SCHEMA,
+ CLASSIFY_SYSTEM,
+ NORMALIZE_SCHEMA,
+ NORMALIZE_SYSTEM,
+ ROUTE_SCHEMA,
+ ROUTE_SYSTEM,
+ type RouteResult,
+ type SynthesisResult,
+ SYNTHESIZE_SCHEMA,
+ SYNTHESIZE_SYSTEM,
+} from './prompts';
+
+const log = debug('lobe-server:memory:consolidation');
+
+/** Memories per classification call. */
+export const CLASSIFY_BATCH = 20;
+/** Memories per synthesis call; larger domains are synthesized in time-ordered chunks. */
+export const SYNTH_CHUNK = 40;
+/** The online step shows the model this many recalled contexts plus the most recently active. */
+const ROUTE_TOP_CONTEXTS = 30;
+const ROUTE_RECENT_CONTEXTS = 10;
+
+export interface ConsolidationModelOverride {
+ model?: string;
+ provider?: string;
+}
+
+const subjectNames = (item: LegacyContextItem) =>
+ [...(item.associatedSubjects ?? []), ...(item.associatedObjects ?? [])]
+ .map((s) => s.name)
+ .filter((n): n is string => !!n && !['User', 'user', 'Assistant'].includes(n));
+
+export const itemLine = (item: LegacyContextItem, max = 400) =>
+ `[${item.id}] ${item.capturedAt.toISOString().slice(0, 10)} | ${item.title ?? ''} | ${(item.description ?? '').slice(0, max)} | 涉及:${subjectNames(item).join('、') || '无'}`;
+
+/** Character-bigram overlap, enough to shortlist contexts for the online step. */
+const grams = (text: string) => {
+ const t = (text || '').toLowerCase();
+ const out = new Map<string, number>();
+ for (const w of t.match(/[\da-z]{2,}/g) ?? []) out.set(w, (out.get(w) ?? 0) + 1);
+ const han = t.replaceAll(/\P{Script=Han}/gu, '');
+ for (let i = 0; i < han.length - 1; i += 1) {
+ const g = han.slice(i, i + 2);
+ out.set(g, (out.get(g) ?? 0) + 1);
+ }
+ return out;
+};
+const overlap = (a: Map<string, number>, b: Map<string, number>) => {
+ let dot = 0;
+ let na = 0;
+ let nb = 0;
+ for (const [k, v] of a) {
+ na += v * v;
+ dot += v * (b.get(k) ?? 0);
+ }
+ for (const v of b.values()) nb += v * v;
+ return na && nb ? dot / Math.sqrt(na * nb) : 0;
+};
+
+export class MemoryConsolidationService {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+ private readonly agentConfig: MemoryAgentConfig;
+ private readonly runId: string;
+ readonly model: UserMemoryConsolidationModel;
+ private runtime?: { model: string; runtime: ModelRuntime };
+ private embeddingRuntime?: { model: string; runtime: UserMemoryEmbeddingRuntime };
+
+ constructor(
+ db: LobeChatDatabase,
+ userId: string,
+ runId: string,
+ override?: ConsolidationModelOverride,
+ ) {
+ const { agentConsolidation } = parseMemoryExtractionConfig();
+ this.db = db;
+ this.userId = userId;
+ this.runId = runId;
+ this.agentConfig = {
+ ...agentConsolidation,
+ model: override?.model || agentConsolidation.model,
+ provider: override?.provider || agentConsolidation.provider,
+ };
+ this.model = new UserMemoryConsolidationModel(db, userId);
+ }
+
+ private async getRuntime() {
+ if (this.runtime) return this.runtime;
+ // workspace-audit: intentionally personal-scoped. Memory belongs to the user, so provider
+ // access resolves against the user's personal scope, as the persona writer does.
+ const aiInfraRepos = new AiInfraRepos(this.db, this.userId, {});
+ const runtimeState = await getUserScopedAiProviderRuntimeState(
+ this.userId,
+ () => aiInfraRepos.getAiProviderRuntimeState(KeyVaultsGateKeeper.getUserKeyVaults),
+ { throwOnUnresolvedAccess: true },
+ );
+ const providerId = await AiInfraRepos.tryMatchingProviderFrom(runtimeState, {
+ fallbackProvider: this.agentConfig.provider,
+ label: 'memory consolidation',
+ modelId: this.agentConfig.model,
+ });
+ const keyVaults = Object.entries(runtimeState.runtimeConfig || {}).reduce<ProviderKeyVaultMap>(
+ (acc, [provider, config]) => {
+ acc[provider.toLowerCase()] = config?.keyVaults;
+ return acc;
+ },
+ {},
+ );
+ const runtime = await resolveRuntimeAgentConfig(
+ this.agentConfig,
+ keyVaults,
+ {
+ fallback: { apiKey: this.agentConfig.apiKey, baseURL: this.agentConfig.baseURL },
+ preferred: { providerIds: [providerId] },
+ userId: this.userId,
+ },
+ getBusinessModelRuntimeHooks(this.userId, 'lobehub'),
+ );
+ this.runtime = { model: this.agentConfig.model, runtime };
+ return this.runtime;
+ }
+
+ private async generate<T>(
+ schema: { name: string; schema: Record<string, unknown>; strict: boolean },
+ system: string,
+ prompt: string,
+ stage: string,
+ ): Promise<T> {
+ const { model, runtime } = await this.getRuntime();
+ const started = Date.now();
+ const result = await runtime.generateObject(
+ {
+ messages: [
+ { content: system, role: 'system' },
+ { content: prompt, role: 'user' },
+ ] as never,
+ model,
+ schema: schema as never,
+ },
+ {
+ metadata: {
+ consolidationRunId: this.runId,
+ consolidationStage: stage,
+ trigger: RequestTrigger.Memory,
+ },
+ },
+ );
+ log('%s %s in %dms', this.userId, stage, Date.now() - started);
+ return result as T;
+ }
+
+ // ---------- backfill ----------
+
+ async classify(ids: string[]): Promise<ClassifiedItem[]> {
+ const items = await this.model.getLegacyContextsByIds(ids);
+ const order = new Map(ids.map((id, i) => [id, i]));
+ items.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0));
+ const out = await this.generate<{ items: ClassifiedItem[] }>(
+ CLASSIFY_SCHEMA,
+ CLASSIFY_SYSTEM,
+ items.map((i) => itemLine(i, 420)).join('\n'),
+ 'classify',
+ );
+ const got = new Map((out.items ?? []).filter((x) => ids.includes(x.id)).map((x) => [x.id, x]));
+ // An item the model skipped is kept in place for the next run rather than guessed.
+ return ids.map((id) => got.get(id)).filter((x): x is ClassifiedItem => !!x);
+ }
+
+ async normalizeDomains(counts: Record<string, number>): Promise<Record<string, string>> {
+ const keys = Object.entries(counts).sort((a, b) => b[1] - a[1]);
+ if (keys.length <= 1) return Object.fromEntries(keys.map(([k]) => [k, k]));
+ const out = await this.generate<{ mapping: { domain: string; raw: string }[] }>(
+ NORMALIZE_SCHEMA,
+ NORMALIZE_SYSTEM,
+ keys.map(([k, n]) => `- ${k} (${n})`).join('\n'),
+ 'normalize',
+ );
+ const map: Record<string, string> = {};
+ for (const { domain, raw } of out.mapping ?? []) map[raw] = domain;
+ for (const [k] of keys) map[k] ??= k;
+ return map;
+ }
+
+ /**
+ * Synthesize one chunk of a domain. `existing` is the structure earlier chunks (or earlier runs)
+ * built, as plans keyed by synthetic ids, so later chunks can extend it.
+ */
+ async synthesize(
+ label: string,
+ ids: string[],
+ existingStubs: string[],
+ ): Promise<SynthesisResult> {
+ const items = await this.model.getLegacyContextsByIds(ids);
+ items.sort((a, b) => a.capturedAt.getTime() - b.capturedAt.getTime());
+ const prompt =
+ `领域:${label}\n` +
+ (existingStubs.length > 0 ? `已有结构:\n${existingStubs.join('\n')}\n\n` : '') +
+ `记忆(按时间):\n${items.map((i) => itemLine(i, 360)).join('\n')}`;
+ const out = await this.generate<SynthesisResult>(
+ SYNTHESIZE_SCHEMA,
+ SYNTHESIZE_SYSTEM,
+ prompt,
+ 'synthesize',
+ );
+ return {
+ contexts: Array.isArray(out.contexts) ? out.contexts : [],
+ unplaced: out.unplaced ?? [],
+ };
+ }
+
+ // ---------- online (incremental) ----------
+
+ /** Pick route and context for one new memory, showing recalled + recent consolidated contexts. */
+ async route(
+ item: LegacyContextItem,
+ contexts: {
+ id: string;
+ lastEvidenceAt: Date | null;
+ /** Text recall runs on; `text` is what the model is shown. */
+ recall: string;
+ text: string;
+ title: string | null;
+ }[],
+ ) {
+ const q = grams(
+ `${item.title ?? ''} ${(item.description ?? '').slice(0, 500)} ${subjectNames(item).join(' ')}`,
+ );
+ const recalled = [...contexts]
+ .map((c) => ({ c, s: overlap(q, grams(c.recall)) }))
+ .sort((a, b) => b.s - a.s)
+ .slice(0, ROUTE_TOP_CONTEXTS)
+ .map((x) => x.c);
+ const recent = [...contexts]
+ .sort((a, b) => (b.lastEvidenceAt?.getTime() ?? 0) - (a.lastEvidenceAt?.getTime() ?? 0))
+ .slice(0, ROUTE_RECENT_CONTEXTS);
+ const shown = [...new Map([...recalled, ...recent].map((c) => [c.id, c])).values()];
+ const prompt =
+ `新记忆(${item.capturedAt.toISOString().slice(0, 10)}):\n标题:${item.title ?? ''}\n` +
+ `内容:${(item.description ?? '').slice(0, 900)}\n涉及:${subjectNames(item).join('、') || '无'}\n\n` +
+ `context 列表:\n${shown.map((c) => `- context id=${c.id}:${c.text}`).join('\n') || '(无)'}`;
+ const out = await this.generate<RouteResult>(ROUTE_SCHEMA, ROUTE_SYSTEM, prompt, 'route');
+ const known = new Set(contexts.map((c) => c.id));
+ return { ...out, context: known.has(out.context) ? out.context : 'new' };
+ }
+
+ // ---------- writes ----------
+
+ async applyPlan(plan: ConsolidationContextPlan) {
+ const descriptionVector = await this.embedDescription(plan.now);
+ return this.model.applyContextPlan(this.runId, { ...plan, descriptionVector });
+ }
+
+ /**
+ * Semantic search ranks contexts by `descriptionVector`, so a synthesized description needs one
+ * like the legacy contexts it replaces. Best effort: a failed embedding must not lose the run.
+ */
+ private async embedDescription(text: string) {
+ try {
+ if (!this.embeddingRuntime) {
+ const { provider, model } =
+ getServerDefaultFilesConfig().embeddingModel || DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM;
+ const runtime = await initModelRuntimeFromDB(
+ this.db,
+ this.userId,
+ ENABLE_BUSINESS_FEATURES ? BRANDING_PROVIDER : provider,
+ );
+ this.embeddingRuntime = { model, runtime };
+ }
+ const [vector] = await embedUserMemoryTexts({
+ input: [text],
+ model: this.embeddingRuntime.model,
+ runtime: this.embeddingRuntime.runtime,
+ source: 'memory:consolidation',
+ userId: this.userId,
+ });
+ return vector ?? null;
+ } catch (error) {
+ log('embedding context description failed: %O', error);
+ return null;
+ }
+ }
+
+ filedContextIds(ids: string[]) {
+ return this.model.listFiledContextIds(this.runId, ids);
+ }
+
+ markRouted(routes: Record<string, ConsolidationRoute>) {
+ return this.model.markRouted(this.runId, routes);
+ }
+}
+
+/** Turn a synthesis result into context plans, keeping only members from `allowed`. */
+export const toContextPlans = (
+ result: SynthesisResult,
+ allowed: Set<string>,
+ knownContexts: Set<string>,
+ knownDossiers: Set<string>,
+): { plans: ConsolidationContextPlan[]; placed: Set<string> } => {
+ const placed = new Set<string>();
+ const plans: ConsolidationContextPlan[] = [];
+ for (const cx of result.contexts) {
+ if (!cx || typeof cx !== 'object' || !Array.isArray(cx.dossiers)) continue;
+ const dossiers = cx.dossiers
+ .filter((d) => d && Array.isArray(d.members))
+ .map((d) => {
+ // Synthesis may repeat one evidence id inside a dossier; keep the first occurrence only,
+ // otherwise the plan inserts one activity per repetition.
+ const memberIds = [...new Set(d.members)].filter((m) => allowed.has(m) && !placed.has(m));
+ for (const m of memberIds) placed.add(m);
+ return {
+ existingDossierId: knownDossiers.has(d.existing_dossier) ? d.existing_dossier : undefined,
+ memberIds,
+ now: d.now ?? '',
+ title: d.title || 'Untitled',
+ };
+ })
+ .filter((d) => d.memberIds.length > 0);
+ if (dossiers.length === 0) continue;
+ plans.push({
+ dossiers,
+ existingContextId: knownContexts.has(cx.existing_context) ? cx.existing_context : undefined,
+ nextSteps: Array.isArray(cx.next_steps) ? cx.next_steps : [],
+ now: cx.now ?? '',
+ openQuestions: Array.isArray(cx.open_questions) ? cx.open_questions : [],
+ title: cx.title || 'Untitled',
+ });
+ }
+ return { placed, plans };
+};
diff --git a/apps/server/src/services/memory/userMemory/extract/workflow.ts b/apps/server/src/services/memory/userMemory/extract/workflow.ts
index a5a426b9681..cf4139feaab 100644
--- a/apps/server/src/services/memory/userMemory/extract/workflow.ts
+++ b/apps/server/src/services/memory/userMemory/extract/workflow.ts
@@ -24,6 +24,7 @@ import type {
} from './payload';
const WORKFLOW_PATHS = {
+ consolidation: '/api/workflows/memory-user-memory/pipelines/consolidation/run',
hourly: '/api/workflows/memory-user-memory/call-cron-hourly-analysis',
personaUpdate: '/api/workflows/memory-user-memory/pipelines/persona/update-writing',
topic: '/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',
@@ -284,6 +285,28 @@ export class MemoryExtractionWorkflowService {
});
}
+ /** One consolidation run per user at a time: the flow-control key is per user. */
+ static triggerConsolidation(
+ userId: string,
+ baseUrl: string,
+ options?: { extraHeaders?: Record<string, string>; model?: string; provider?: string },
+ ) {
+ if (!baseUrl) {
+ throw new Error('Missing baseUrl for workflow trigger');
+ }
+
+ const url = getWorkflowUrl(WORKFLOW_PATHS.consolidation, baseUrl);
+ return this.getClient().trigger({
+ body: { model: options?.model, provider: options?.provider, userId },
+ flowControl: {
+ key: `memory-user-memory.pipelines.consolidation.${userId}`,
+ parallelism: 1,
+ } satisfies FlowControl,
+ headers: options?.extraHeaders,
+ url,
+ });
+ }
+
static triggerPersonaUpdate(
userId: string,
baseUrl: string,
diff --git a/apps/server/src/services/memory/userMemory/persona/service.ts b/apps/server/src/services/memory/userMemory/persona/service.ts
index f54c89502a6..8e43ee39628 100644
--- a/apps/server/src/services/memory/userMemory/persona/service.ts
+++ b/apps/server/src/services/memory/userMemory/persona/service.ts
@@ -18,6 +18,7 @@ import { UserMemoryModel } from '@/database/models/userMemory';
import { UserPersonaModel } from '@/database/models/userMemory/persona';
import { AiInfraRepos } from '@/database/repositories/aiInfra';
import { type LobeChatDatabase } from '@/database/type';
+import { visibleMemoryState } from '@/database/utils/memoryVisibility';
import { notTrashed } from '@/database/utils/softDelete';
import { type MemoryAgentConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
@@ -198,7 +199,11 @@ export const buildUserPersonaJobInput = async (db: LobeChatDatabase, userId: str
db.query.userMemories.findMany({
limit: 20,
orderBy: [desc(userMemories.capturedAt)],
- where: and(eq(userMemories.userId, userId), notTrashed(userMemories.isDeleted)),
+ where: and(
+ eq(userMemories.userId, userId),
+ notTrashed(userMemories.isDeleted),
+ visibleMemoryState(userMemories.state),
+ ),
}),
]);
diff --git a/packages/database/src/models/agentSignal/reviewContext.ts b/packages/database/src/models/agentSignal/reviewContext.ts
index baadc2477b0..0ff74f0eaa2 100644
--- a/packages/database/src/models/agentSignal/reviewContext.ts
+++ b/packages/database/src/models/agentSignal/reviewContext.ts
@@ -12,6 +12,7 @@ import {
userMemories,
} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
+import { visibleMemoryState } from '../../utils/memoryVisibility';
import { notShareVisitorMessage } from '../../utils/shareVisitor';
import { notTrashed } from '../../utils/softDelete';
import { notChannelTopicRef } from '../../utils/topicVisibility';
@@ -144,7 +145,13 @@ export class AgentSignalReviewContextModel {
updatedAt: userMemories.updatedAt,
})
.from(userMemories)
- .where(and(eq(userMemories.userId, this.userId), notTrashed(userMemories.isDeleted)))
+ .where(
+ and(
+ eq(userMemories.userId, this.userId),
+ notTrashed(userMemories.isDeleted),
+ visibleMemoryState(userMemories.state),
+ ),
+ )
.orderBy(desc(userMemories.updatedAt))
.limit(options.limit);
};
diff --git a/packages/database/src/models/userMemory/__tests__/consolidation.test.ts b/packages/database/src/models/userMemory/__tests__/consolidation.test.ts
new file mode 100644
index 00000000000..03db457d2c8
--- /dev/null
+++ b/packages/database/src/models/userMemory/__tests__/consolidation.test.ts
@@ -0,0 +1,416 @@
+// @vitest-environment node
+import { eq, inArray } from 'drizzle-orm';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ userMemories,
+ userMemoriesActivities,
+ userMemoriesContexts,
+ userMemoriesDossiers,
+ userMemoriesOperations,
+ users,
+} from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { deriveContextStatus, UserMemoryConsolidationModel } from '../consolidation';
+import { UserMemoryContextModel } from '../context';
+
+const userId = 'consolidation-test-user';
+const serverDB: LobeChatDatabase = await getTestDB();
+
+/** A legacy per-topic context: parent row + context row linked through `user_memory_ids`. */
+const createLegacy = async (
+ title: string,
+ day: string,
+ { singleParent = false, sourceId = `tpc_${title}` } = {},
+) => {
+ const capturedAt = new Date(`${day}T08:00:00.000Z`);
+ const [memory] = await serverDB
+ .insert(userMemories)
+ .values({
+ capturedAt,
+ lastAccessedAt: capturedAt,
+ memoryLayer: 'context',
+ metadata: { sourceId },
+ title,
+ userId,
+ })
+ .returning();
+ const [context] = await serverDB
+ .insert(userMemoriesContexts)
+ .values({
+ capturedAt,
+ description: `${title} details`,
+ title,
+ userId,
+ // Current extraction (`createContextMemory`) writes the single parent as well.
+ userMemoryId: singleParent ? memory.id : null,
+ userMemoryIds: [memory.id],
+ })
+ .returning();
+ return { context, memory };
+};
+
+let model: UserMemoryConsolidationModel;
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values({ id: userId });
+ model = new UserMemoryConsolidationModel(serverDB, userId);
+});
+
+describe('UserMemoryConsolidationModel', () => {
+ it('lists pending legacy contexts oldest first and reads queued evidence back', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const b = await createLegacy('scheduler panel', '2026-04-01');
+ const c = await createLegacy('one-off question', '2026-05-02', { singleParent: true });
+
+ const pending = await model.listPendingLegacyContexts();
+ expect(pending.map((p) => p.id)).toEqual([b.context.id, a.context.id, c.context.id]);
+ expect(pending[0]).toMatchObject({ memoryId: b.memory.id, sourceId: 'tpc_scheduler panel' });
+ // A context written by current extraction (single parent set) is still legacy evidence.
+ expect(pending[2]).toMatchObject({ id: c.context.id, memoryId: c.memory.id });
+
+ await model.enqueue('run_1', [
+ { id: a.context.id, key: 'product/task', route: 'evidence' },
+ { id: b.context.id, key: 'product/task', route: 'evidence' },
+ { id: c.context.id, key: 'misc', route: 'drop' },
+ ]);
+ await model.markRouted('run_1', { [c.context.id]: 'drop' });
+
+ const queued = await model.listQueued('run_1');
+ expect(queued.map((q) => [q.id, q.key])).toEqual([
+ [b.context.id, 'product/task'],
+ [a.context.id, 'product/task'],
+ ]);
+ // A routed (kept) row is no longer pending.
+ expect((await model.listPendingLegacyContexts()).map((p) => p.id)).not.toContain(c.context.id);
+ });
+
+ it('files evidence into a new context and dossier, hides the legacy rows, and reverts', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const b = await createLegacy('scheduler panel', '2026-05-03');
+ const contextModel = new UserMemoryContextModel(serverDB, userId);
+ expect(await contextModel.query()).toHaveLength(2);
+
+ const result = await model.applyContextPlan('run_2', {
+ dossiers: [
+ {
+ memberIds: [a.context.id, b.context.id],
+ now: 'Backend and panel shipped',
+ title: 'Scheduler',
+ },
+ ],
+ nextSteps: ['Ship cron mode'],
+ now: 'Scheduler is live',
+ openQuestions: [],
+ title: 'Task system',
+ });
+ expect(result).toMatchObject({ activities: 2, contextsCreated: 1, dossiersCreated: 1 });
+
+ const [dossier] = await serverDB
+ .select()
+ .from(userMemoriesDossiers)
+ .where(eq(userMemoriesDossiers.userId, userId));
+ expect(dossier).toMatchObject({
+ activityCount: 2,
+ contextId: result.contextId,
+ title: 'Scheduler',
+ });
+ expect(dossier.lastEvidenceAt?.toISOString()).toBe('2026-05-03T08:00:00.000Z');
+
+ const activities = await serverDB
+ .select()
+ .from(userMemoriesActivities)
+ .where(eq(userMemoriesActivities.userId, userId));
+ expect(activities.map((x) => x.dossierId)).toEqual([dossier.id, dossier.id]);
+ expect(activities[0].metadata).toMatchObject({
+ consolidationRunId: 'run_2',
+ legacyContextId: expect.any(String),
+ });
+
+ // Readers now see the consolidated context only; the legacy rows are superseded, not deleted.
+ const visible = await contextModel.query();
+ expect(visible.map((x) => x.title)).toEqual(['Task system']);
+ // Readers that join parents through the legacy list still find the new context.
+ expect(visible[0].userMemoryIds).toEqual([visible[0].userMemoryId]);
+ const [legacyParent] = await serverDB
+ .select()
+ .from(userMemories)
+ .where(eq(userMemories.id, a.memory.id));
+ expect(legacyParent.state).toBe('superseded');
+ expect(await model.listPendingLegacyContexts()).toHaveLength(0);
+
+ const ops = await serverDB
+ .select()
+ .from(userMemoriesOperations)
+ .where(eq(userMemoriesOperations.userId, userId));
+ expect(ops.map((o) => o.op).sort()).toEqual(['attach', 'create', 'create']);
+
+ const reverted = await model.revertRun('run_2');
+ expect(reverted.restored).toBe(2);
+ expect((await contextModel.query()).map((x) => x.title).sort()).toEqual([
+ 'scheduler backend',
+ 'scheduler panel',
+ ]);
+ expect(
+ await serverDB
+ .select()
+ .from(userMemoriesDossiers)
+ .where(eq(userMemoriesDossiers.userId, userId)),
+ ).toHaveLength(0);
+ expect(await model.listPendingLegacyContexts()).toHaveLength(2);
+ });
+
+ it('extends an existing context and dossier in a later run', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const first = await model.applyContextPlan('run_3', {
+ dossiers: [{ memberIds: [a.context.id], now: 'v1', title: 'Scheduler' }],
+ nextSteps: [],
+ now: 'v1',
+ openQuestions: [],
+ title: 'Task system',
+ });
+ // Written by current extraction: has a single parent, but is still legacy, not consolidated.
+ const b = await createLegacy('scheduler cron mode', '2026-06-01', { singleParent: true });
+ const consolidated = await model.listConsolidated();
+ expect(consolidated.contexts.map((x) => x.id)).toEqual([first.contextId]);
+
+ const second = await model.applyContextPlan('run_4', {
+ dossiers: [
+ {
+ existingDossierId: first.dossierIds[0],
+ memberIds: [b.context.id],
+ now: 'v2',
+ title: 'Scheduler',
+ },
+ ],
+ existingContextId: first.contextId,
+ nextSteps: ['Monitor'],
+ now: 'v2',
+ openQuestions: [],
+ title: 'Task system',
+ });
+ expect(second).toMatchObject({
+ contextId: first.contextId,
+ contextsUpdated: 1,
+ dossiersUpdated: 1,
+ });
+ const [dossier] = await serverDB
+ .select()
+ .from(userMemoriesDossiers)
+ .where(eq(userMemoriesDossiers.userId, userId));
+ expect(dossier).toMatchObject({ activityCount: 2, now: 'v2', summary: 'v2' });
+
+ // Reverting the later run restores the context and dossier it updated in place.
+ await model.revertRun('run_4');
+ const [restored] = await serverDB
+ .select()
+ .from(userMemoriesDossiers)
+ .where(eq(userMemoriesDossiers.id, dossier.id));
+ expect(restored).toMatchObject({ activityCount: 1, now: 'v1', summary: 'v1' });
+ expect(restored.lastEvidenceAt?.toISOString()).toBe('2026-05-01T08:00:00.000Z');
+ const [ctx] = await serverDB
+ .select()
+ .from(userMemoriesContexts)
+ .where(eq(userMemoriesContexts.id, first.contextId!));
+ expect(ctx).toMatchObject({ description: 'v1', now: 'v1' });
+ expect(await model.listPendingLegacyContexts()).toHaveLength(1);
+ });
+
+ it('reverts a run that updated the same context and dossier in several chunks', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const first = await model.applyContextPlan('run_5', {
+ dossiers: [{ memberIds: [a.context.id], now: 'v1', title: 'Scheduler' }],
+ nextSteps: [],
+ now: 'v1',
+ openQuestions: [],
+ title: 'Task system',
+ });
+ const chunk = async (title: string, day: string, version: string) => {
+ const legacy = await createLegacy(title, day);
+ await model.applyContextPlan('run_6', {
+ dossiers: [
+ {
+ existingDossierId: first.dossierIds[0],
+ memberIds: [legacy.context.id],
+ now: version,
+ title: 'Scheduler',
+ },
+ ],
+ existingContextId: first.contextId,
+ nextSteps: [],
+ now: version,
+ openQuestions: [],
+ title: 'Task system',
+ });
+ };
+ await chunk('scheduler cron mode', '2026-06-01', 'v2');
+ await chunk('scheduler retries', '2026-06-02', 'v3');
+
+ await model.revertRun('run_6');
+ const [dossier] = await serverDB
+ .select()
+ .from(userMemoriesDossiers)
+ .where(eq(userMemoriesDossiers.id, first.dossierIds[0]));
+ expect(dossier).toMatchObject({ activityCount: 1, now: 'v1', summary: 'v1' });
+ const [ctx] = await serverDB
+ .select()
+ .from(userMemoriesContexts)
+ .where(eq(userMemoriesContexts.id, first.contextId!));
+ expect(ctx).toMatchObject({ description: 'v1', now: 'v1' });
+ });
+
+ it('stores the description embedding and keeps it when an update has none', async () => {
+ const vector = Array.from({ length: 1024 }, () => 0.01);
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const first = await model.applyContextPlan('run_7', {
+ descriptionVector: vector,
+ dossiers: [{ memberIds: [a.context.id], now: 'v1', title: 'Scheduler' }],
+ nextSteps: [],
+ now: 'v1',
+ openQuestions: [],
+ title: 'Task system',
+ });
+ const b = await createLegacy('scheduler cron mode', '2026-06-01');
+ await model.applyContextPlan('run_8', {
+ dossiers: [{ memberIds: [b.context.id], now: 'v2', title: 'Cron' }],
+ existingContextId: first.contextId,
+ nextSteps: [],
+ now: 'v2',
+ openQuestions: [],
+ title: 'Task system',
+ });
+ const [ctx] = await serverDB
+ .select()
+ .from(userMemoriesContexts)
+ .where(eq(userMemoriesContexts.id, first.contextId!));
+ expect(ctx.descriptionVector).toHaveLength(1024);
+ });
+
+ it('ignores evidence a committed plan already filed when a step is retried', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const plan = {
+ dossiers: [{ memberIds: [a.context.id], now: 'v1', title: 'Scheduler' }],
+ nextSteps: [],
+ now: 'v1',
+ openQuestions: [],
+ title: 'Task system',
+ };
+ const first = await model.applyContextPlan('run_9', plan);
+ expect(first.activities).toBe(1);
+ expect(await model.getLegacyContextsByIds([a.context.id])).toEqual([]);
+
+ const retried = await model.applyContextPlan('run_9', {
+ ...plan,
+ dossiers: [{ ...plan.dossiers[0], existingDossierId: first.dossierIds[0] }],
+ existingContextId: first.contextId,
+ });
+ expect(retried).toMatchObject({ activities: 0, contextsUpdated: 0, dossiersUpdated: 0 });
+ const [dossier] = await serverDB
+ .select()
+ .from(userMemoriesDossiers)
+ .where(eq(userMemoriesDossiers.id, first.dossierIds[0]));
+ expect(dossier.activityCount).toBe(1);
+ });
+
+ it('keeps parent summaries in step with extended contexts and dossiers', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const first = await model.applyContextPlan('run_10', {
+ dossiers: [{ memberIds: [a.context.id], now: 'v1', title: 'Scheduler' }],
+ nextSteps: [],
+ now: 'v1',
+ openQuestions: [],
+ title: 'Task system',
+ });
+ const b = await createLegacy('scheduler cron mode', '2026-06-01');
+ await model.applyContextPlan('run_11', {
+ dossiers: [
+ {
+ existingDossierId: first.dossierIds[0],
+ memberIds: [b.context.id],
+ now: 'dossier v2',
+ title: 'Scheduler',
+ },
+ ],
+ existingContextId: first.contextId,
+ nextSteps: [],
+ now: 'context v2',
+ openQuestions: [],
+ title: 'Task system',
+ });
+ const parentSummaries = async () => {
+ const [ctx] = await serverDB
+ .select()
+ .from(userMemoriesContexts)
+ .where(eq(userMemoriesContexts.id, first.contextId!));
+ const [dossier] = await serverDB
+ .select()
+ .from(userMemoriesDossiers)
+ .where(eq(userMemoriesDossiers.id, first.dossierIds[0]));
+ const parents = await serverDB
+ .select({ id: userMemories.id, summary: userMemories.summary })
+ .from(userMemories)
+ .where(inArray(userMemories.id, [ctx.userMemoryId!, dossier.userMemoryId!]));
+ const byId = new Map(parents.map((p) => [p.id, p.summary]));
+ return [byId.get(ctx.userMemoryId!), byId.get(dossier.userMemoryId!)];
+ };
+ expect(await parentSummaries()).toEqual(['context v2', 'dossier v2']);
+
+ await model.revertRun('run_11');
+ expect(await parentSummaries()).toEqual(['v1', 'v1']);
+ });
+
+ it('refuses to revert a run a later run extended, until the later one is reverted', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const first = await model.applyContextPlan('run_12', {
+ dossiers: [{ memberIds: [a.context.id], now: 'v1', title: 'Scheduler' }],
+ nextSteps: [],
+ now: 'v1',
+ openQuestions: [],
+ title: 'Task system',
+ });
+ expect(await model.listFiledContextIds('run_12', [a.context.id])).toEqual([first.contextId]);
+ const b = await createLegacy('scheduler cron mode', '2026-06-01');
+ await model.applyContextPlan('run_13', {
+ dossiers: [
+ {
+ existingDossierId: first.dossierIds[0],
+ memberIds: [b.context.id],
+ now: 'v2',
+ title: 'Scheduler',
+ },
+ ],
+ existingContextId: first.contextId,
+ nextSteps: [],
+ now: 'v2',
+ openQuestions: [],
+ title: 'Task system',
+ });
+
+ expect(await model.revertRun('run_12')).toEqual({
+ blockedBy: ['run_13'],
+ deleted: 0,
+ restored: 0,
+ });
+ const contexts = await serverDB
+ .select()
+ .from(userMemoriesContexts)
+ .where(eq(userMemoriesContexts.id, first.contextId!));
+ expect(contexts).toHaveLength(1);
+
+ await model.revertRun('run_13');
+ const reverted = await model.revertRun('run_12');
+ expect(reverted.blockedBy).toBeUndefined();
+ expect(await model.listPendingLegacyContexts()).toHaveLength(2);
+ });
+});
+
+describe('deriveContextStatus', () => {
+ it('derives status from the newest evidence', () => {
+ const now = new Date('2026-10-30T00:00:00Z');
+ expect(deriveContextStatus(new Date('2026-10-01T00:00:00Z'), now)).toBe('active');
+ expect(deriveContextStatus(new Date('2026-07-01T00:00:00Z'), now)).toBe('dormant');
+ expect(deriveContextStatus(new Date('2026-01-01T00:00:00Z'), now)).toBe('closed');
+ });
+});
diff --git a/packages/database/src/models/userMemory/consolidation.ts b/packages/database/src/models/userMemory/consolidation.ts
new file mode 100644
index 00000000000..fa5dfd3ed06
--- /dev/null
+++ b/packages/database/src/models/userMemory/consolidation.ts
@@ -0,0 +1,830 @@
+import type { UserMemoryDossierStatus } from '@lobechat/types';
+import { and, asc, eq, inArray, isNotNull, isNull, sql } from 'drizzle-orm';
+
+import {
+ userMemories,
+ userMemoriesActivities,
+ userMemoriesContexts,
+ userMemoriesDossiers,
+ userMemoriesOperations,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { notTrashed } from '../../utils/softDelete';
+
+/**
+ * Memory consolidation: the per-topic context rows written by extraction are evidence. The
+ * consolidation pipeline groups them into contexts (a project direction / customer / company
+ * matter) and dossiers (one feature, deal or ongoing sub-task), and turns each evidence row into an
+ * activity under its dossier. Nothing is deleted: the legacy row's parent memory is marked
+ * `superseded` (hidden from reads) and every write carries the run id, so a run can be reverted.
+ */
+
+/**
+ * A legacy context's parent memory: its single parent when set (extraction now writes both), else
+ * the first id of the legacy list.
+ */
+const legacyParentJoin = sql`${userMemories.id} = COALESCE(${userMemoriesContexts.userMemoryId}, ${userMemoriesContexts.userMemoryIds} ->> 0)`;
+
+/**
+ * Not yet seen by consolidation. Key existence, never `(metadata -> 'x') IS NULL`: an IS [NOT] NULL
+ * test on an extracted jsonb value crashes the pg_search planner on bm25-indexed tables
+ * (`user_memories*`), see `jsonbNullTest.test.ts`.
+ */
+const notConsolidated = sql`NOT COALESCE(jsonb_exists(${userMemories.metadata}, 'consolidation'), false)`;
+
+export type ConsolidationRoute = 'drop' | 'evidence' | 'fact' | 'preference';
+
+export interface LegacyContextItem {
+ associatedObjects: { name?: string; type?: string }[] | null;
+ associatedSubjects: { name?: string; type?: string }[] | null;
+ capturedAt: Date;
+ description: string | null;
+ id: string;
+ memoryId: string;
+ sourceId: string | null;
+ title: string | null;
+}
+
+export interface ConsolidatedDossierSummary {
+ activityCount: number;
+ contextId: string | null;
+ id: string;
+ lastEvidenceAt: Date | null;
+ now: string | null;
+ title: string | null;
+}
+
+export interface ConsolidatedContextSummary {
+ id: string;
+ lastEvidenceAt: Date | null;
+ now: string | null;
+ title: string | null;
+}
+
+export interface ConsolidationDossierPlan {
+ /** Existing dossier to extend; omitted for a new one. */
+ existingDossierId?: string;
+ /** Legacy context ids (evidence) filed under this dossier. */
+ memberIds: string[];
+ now: string;
+ title: string;
+}
+
+export interface ConsolidationContextPlan {
+ /** Embedding of `now`, the context description semantic search ranks by. */
+ descriptionVector?: number[] | null;
+ dossiers: ConsolidationDossierPlan[];
+ /** Existing consolidated context to extend; omitted for a new one. */
+ existingContextId?: string;
+ nextSteps: string[];
+ now: string;
+ openQuestions: string[];
+ title: string;
+}
+
+export interface ConsolidationApplyResult {
+ activities: number;
+ contextId?: string;
+ contextsCreated: number;
+ contextsUpdated: number;
+ dossierIds: string[];
+ dossiersCreated: number;
+ dossiersUpdated: number;
+}
+
+const DAY_MS = 86_400_000;
+
+/** Derived from the newest evidence, never from what an extractor wrote. */
+export const deriveContextStatus = (lastEvidenceAt: Date, now = new Date()) => {
+ const gap = (now.getTime() - lastEvidenceAt.getTime()) / DAY_MS;
+ if (gap <= 45) return 'active';
+ if (gap <= 150) return 'dormant';
+ return 'closed';
+};
+
+const runTag = (runId: string) => ({ consolidationRunId: runId });
+
+/**
+ * Users that have been consolidated at least once, so the nightly run can keep them current.
+ * Reads the dossiers table (new and small), not the large contexts table.
+ */
+export const listConsolidatedUserIds = async (db: LobeChatDatabase): Promise<string[]> => {
+ const rows = await db
+ .selectDistinct({ userId: userMemoriesDossiers.userId })
+ .from(userMemoriesDossiers)
+ .where(isNotNull(userMemoriesDossiers.userId));
+ return rows.map((r) => r.userId).filter((id): id is string => !!id);
+};
+
+export class UserMemoryConsolidationModel {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.db = db;
+ this.userId = userId;
+ }
+
+ /**
+ * Legacy per-topic contexts not yet seen by consolidation, oldest first. A legacy context has no
+ * single parent (`user_memory_id`); its parent is the first id of `user_memory_ids`.
+ */
+ listPendingLegacyContexts = async (limit = 5000): Promise<LegacyContextItem[]> => {
+ const rows = await this.db
+ .select({
+ associatedObjects: userMemoriesContexts.associatedObjects,
+ associatedSubjects: userMemoriesContexts.associatedSubjects,
+ capturedAt: userMemoriesContexts.capturedAt,
+ description: userMemoriesContexts.description,
+ id: userMemoriesContexts.id,
+ memoryId: userMemories.id,
+ memoryMetadata: userMemories.metadata,
+ title: userMemoriesContexts.title,
+ })
+ .from(userMemoriesContexts)
+ .innerJoin(userMemories, legacyParentJoin)
+ .where(
+ and(
+ eq(userMemoriesContexts.userId, this.userId),
+ isNull(userMemoriesContexts.synthesizedAt),
+ eq(userMemories.userId, this.userId),
+ notTrashed(userMemories.isDeleted),
+ isNull(userMemories.state),
+ notConsolidated,
+ ),
+ )
+ .orderBy(asc(userMemoriesContexts.capturedAt), asc(userMemoriesContexts.id))
+ .limit(limit);
+
+ return rows.map(({ memoryMetadata, ...row }) => ({
+ ...row,
+ sourceId: typeof memoryMetadata?.sourceId === 'string' ? memoryMetadata.sourceId : null,
+ }));
+ };
+
+ getLegacyContextsByIds = async (ids: string[]): Promise<LegacyContextItem[]> => {
+ if (ids.length === 0) return [];
+ const items = await this.db
+ .select({
+ associatedObjects: userMemoriesContexts.associatedObjects,
+ associatedSubjects: userMemoriesContexts.associatedSubjects,
+ capturedAt: userMemoriesContexts.capturedAt,
+ description: userMemoriesContexts.description,
+ id: userMemoriesContexts.id,
+ memoryId: userMemories.id,
+ memoryMetadata: userMemories.metadata,
+ title: userMemoriesContexts.title,
+ })
+ .from(userMemoriesContexts)
+ .innerJoin(userMemories, legacyParentJoin)
+ .where(
+ and(
+ eq(userMemoriesContexts.userId, this.userId),
+ inArray(userMemoriesContexts.id, ids),
+ // Rows a run already applied or routed are done: a retried step must not file them again.
+ notConsolidated,
+ ),
+ );
+
+ return items.map(({ memoryMetadata, ...row }) => ({
+ ...row,
+ sourceId: typeof memoryMetadata?.sourceId === 'string' ? memoryMetadata.sourceId : null,
+ }));
+ };
+
+ /**
+ * Contexts this run already filed some of these legacy rows into. A retried synthesis step skips
+ * the filed rows, so it needs these to keep extending the same contexts instead of new ones.
+ */
+ listFiledContextIds = async (runId: string, ids: string[]): Promise<string[]> => {
+ if (ids.length === 0) return [];
+ const rows = await this.db
+ .selectDistinct({ contextId: userMemoriesDossiers.contextId })
+ .from(userMemoriesContexts)
+ .innerJoin(userMemories, legacyParentJoin)
+ .innerJoin(
+ userMemoriesActivities,
+ sql`${userMemoriesActivities.id} = ${userMemories.metadata} -> 'consolidation' ->> 'activityId'`,
+ )
+ .innerJoin(
+ userMemoriesDossiers,
+ eq(userMemoriesDossiers.id, userMemoriesActivities.dossierId),
+ )
+ .where(
+ and(
+ eq(userMemoriesContexts.userId, this.userId),
+ inArray(userMemoriesContexts.id, ids),
+ eq(userMemories.userId, this.userId),
+ sql`${userMemories.metadata} -> 'consolidation' ->> 'runId' = ${runId}`,
+ ),
+ );
+ return rows.map((r) => r.contextId).filter((id): id is string => !!id);
+ };
+
+ /** Consolidated contexts (they have a single parent) with their dossiers, for the online step. */
+ listConsolidated = async (): Promise<{
+ contexts: ConsolidatedContextSummary[];
+ dossiers: ConsolidatedDossierSummary[];
+ }> => {
+ const [contexts, dossiers] = await Promise.all([
+ this.db
+ .select({
+ id: userMemoriesContexts.id,
+ lastEvidenceAt: userMemoriesContexts.lastEvidenceAt,
+ now: userMemoriesContexts.now,
+ title: userMemoriesContexts.title,
+ })
+ .from(userMemoriesContexts)
+ .innerJoin(userMemories, eq(userMemories.id, userMemoriesContexts.userMemoryId))
+ .where(
+ and(
+ eq(userMemoriesContexts.userId, this.userId),
+ isNotNull(userMemoriesContexts.synthesizedAt),
+ notTrashed(userMemories.isDeleted),
+ ),
+ ),
+ this.db
+ .select({
+ activityCount: userMemoriesDossiers.activityCount,
+ contextId: userMemoriesDossiers.contextId,
+ id: userMemoriesDossiers.id,
+ lastEvidenceAt: userMemoriesDossiers.lastEvidenceAt,
+ now: userMemoriesDossiers.now,
+ title: userMemoriesDossiers.title,
+ })
+ .from(userMemoriesDossiers)
+ .where(eq(userMemoriesDossiers.userId, this.userId)),
+ ]);
+
+ return { contexts, dossiers };
+ };
+
+ /** Recent evidence titles per dossier, to show the model what a dossier already holds. */
+ listDossierEvidenceTitles = async (dossierIds: string[], perDossier = 3) => {
+ if (dossierIds.length === 0) return {} as Record<string, string[]>;
+ const rows = await this.db
+ .select({ dossierId: userMemoriesActivities.dossierId, title: userMemories.title })
+ .from(userMemoriesActivities)
+ .innerJoin(userMemories, eq(userMemories.id, userMemoriesActivities.userMemoryId))
+ .where(
+ and(
+ eq(userMemoriesActivities.userId, this.userId),
+ inArray(userMemoriesActivities.dossierId, dossierIds),
+ ),
+ )
+ .orderBy(sql`${userMemoriesActivities.capturedAt} DESC`);
+
+ const out: Record<string, string[]> = {};
+ for (const row of rows) {
+ if (!row.dossierId || !row.title) continue;
+ const list = (out[row.dossierId] ??= []);
+ if (list.length < perDossier) list.push(row.title);
+ }
+ return out;
+ };
+
+ /**
+ * Record a stage decision on the legacy rows (their parent memory's metadata), so later workflow
+ * steps read it back from the database instead of carrying it in step results.
+ */
+ enqueue = async (
+ runId: string,
+ entries: { id: string; key: string; route: ConsolidationRoute }[],
+ ) => {
+ if (entries.length === 0) return;
+ const items = await this.getLegacyContextsByIds(entries.map((e) => e.id));
+ const parentOf = new Map(items.map((i) => [i.id, i.memoryId]));
+ await this.db.transaction(async (tx) => {
+ for (const e of entries) {
+ const memoryId = parentOf.get(e.id);
+ if (!memoryId) continue;
+ await tx
+ .update(userMemories)
+ .set({
+ metadata: sql`coalesce(${userMemories.metadata}, '{}'::jsonb) || ${JSON.stringify({
+ consolidationQueue: { key: e.key, route: e.route, runId },
+ })}::jsonb`,
+ })
+ .where(and(eq(userMemories.id, memoryId), eq(userMemories.userId, this.userId)));
+ }
+ });
+ };
+
+ /** Evidence queued by `runId` and not yet filed, with its queue key (domain or context). */
+ listQueued = async (runId: string): Promise<{ capturedAt: Date; id: string; key: string }[]> => {
+ const rows = await this.db
+ .select({
+ capturedAt: userMemoriesContexts.capturedAt,
+ id: userMemoriesContexts.id,
+ key: sql<string>`${userMemories.metadata} -> 'consolidationQueue' ->> 'key'`,
+ })
+ .from(userMemoriesContexts)
+ .innerJoin(userMemories, legacyParentJoin)
+ .where(
+ and(
+ eq(userMemoriesContexts.userId, this.userId),
+ isNull(userMemoriesContexts.synthesizedAt),
+ eq(userMemories.userId, this.userId),
+ isNull(userMemories.state),
+ notConsolidated,
+ sql`${userMemories.metadata} -> 'consolidationQueue' ->> 'runId' = ${runId}`,
+ sql`${userMemories.metadata} -> 'consolidationQueue' ->> 'route' = 'evidence'`,
+ ),
+ )
+ .orderBy(asc(userMemoriesContexts.capturedAt), asc(userMemoriesContexts.id));
+ return rows;
+ };
+
+ /** Mark legacy rows that consolidation saw but keeps in place (facts, preferences, noise). */
+ markRouted = async (runId: string, routes: Record<string, ConsolidationRoute>) => {
+ const ids = Object.keys(routes);
+ if (ids.length === 0) return;
+ const items = await this.getLegacyContextsByIds(ids);
+ await this.db.transaction(async (tx) => {
+ for (const item of items) {
+ await tx
+ .update(userMemories)
+ .set({
+ metadata: sql`coalesce(${userMemories.metadata}, '{}'::jsonb) || ${JSON.stringify({
+ consolidation: { route: routes[item.id], runId },
+ })}::jsonb`,
+ })
+ .where(and(eq(userMemories.id, item.memoryId), eq(userMemories.userId, this.userId)));
+ }
+ });
+ };
+
+ /**
+ * Write one context plan: create or extend the context and its dossiers, turn every member into
+ * an activity under its dossier, and supersede the legacy rows. One transaction per context.
+ */
+ applyContextPlan = async (
+ runId: string,
+ plan: ConsolidationContextPlan,
+ ): Promise<ConsolidationApplyResult> => {
+ const memberIds = plan.dossiers.flatMap((d) => d.memberIds);
+ const items = await this.getLegacyContextsByIds(memberIds);
+ const byId = new Map(items.map((i) => [i.id, i]));
+ const vectors = await this.db
+ .select({ id: userMemoriesContexts.id, vector: userMemoriesContexts.descriptionVector })
+ .from(userMemoriesContexts)
+ .where(
+ and(
+ eq(userMemoriesContexts.userId, this.userId),
+ inArray(userMemoriesContexts.id, memberIds),
+ ),
+ );
+ const vectorById = new Map(vectors.map((v) => [v.id, v.vector]));
+ const result: ConsolidationApplyResult = {
+ activities: 0,
+ dossierIds: [],
+ contextsCreated: 0,
+ contextsUpdated: 0,
+ dossiersCreated: 0,
+ dossiersUpdated: 0,
+ };
+
+ const placed = plan.dossiers
+ .map((d) => ({
+ ...d,
+ members: d.memberIds.map((id) => byId.get(id)).filter((i): i is LegacyContextItem => !!i),
+ }))
+ .filter((d) => d.members.length > 0);
+ if (placed.length === 0) return result;
+
+ const allDates = placed.flatMap((d) => d.members.map((m) => m.capturedAt.getTime()));
+ const firstSeen = new Date(Math.min(...allDates));
+ const lastEvidence = new Date(Math.max(...allDates));
+ const now = new Date();
+
+ await this.db.transaction(async (tx) => {
+ const op = (
+ values: Omit<
+ typeof userMemoriesOperations.$inferInsert,
+ 'actor' | 'gate' | 'state' | 'userId'
+ >,
+ ) =>
+ tx.insert(userMemoriesOperations).values({
+ actor: 'pipeline',
+ gate: 'auto',
+ state: 'applied',
+ userId: this.userId,
+ ...values,
+ metadata: { ...values.metadata, ...runTag(runId) },
+ });
+
+ // ----- context -----
+ let contextId = plan.existingContextId;
+ if (contextId) {
+ const [before] = await tx
+ .select({
+ currentStatus: userMemoriesContexts.currentStatus,
+ description: userMemoriesContexts.description,
+ descriptionVector: userMemoriesContexts.descriptionVector,
+ firstSeenAt: userMemoriesContexts.firstSeenAt,
+ lastEvidenceAt: userMemoriesContexts.lastEvidenceAt,
+ nextSteps: userMemoriesContexts.nextSteps,
+ now: userMemoriesContexts.now,
+ openQuestions: userMemoriesContexts.openQuestions,
+ synthesizedAt: userMemoriesContexts.synthesizedAt,
+ userMemoryId: userMemoriesContexts.userMemoryId,
+ parentSummary: sql<
+ string | null
+ >`(SELECT ${userMemories.summary} FROM ${userMemories} WHERE ${userMemories.id} = ${userMemoriesContexts.userMemoryId})`,
+ })
+ .from(userMemoriesContexts)
+ .where(
+ and(
+ eq(userMemoriesContexts.id, contextId),
+ eq(userMemoriesContexts.userId, this.userId),
+ ),
+ );
+ if (!before) {
+ contextId = undefined;
+ } else {
+ const last =
+ before.lastEvidenceAt && before.lastEvidenceAt > lastEvidence
+ ? before.lastEvidenceAt
+ : lastEvidence;
+ await tx
+ .update(userMemoriesContexts)
+ .set({
+ currentStatus: deriveContextStatus(last, now),
+ description: plan.now,
+ // Without a fresh embedding, the old vector still ranks better than none.
+ ...(plan.descriptionVector ? { descriptionVector: plan.descriptionVector } : {}),
+ lastEvidenceAt: last,
+ nextSteps: plan.nextSteps,
+ now: plan.now,
+ openQuestions: plan.openQuestions,
+ synthesizedAt: now,
+ updatedAt: now,
+ })
+ .where(eq(userMemoriesContexts.id, contextId));
+ // Unified search reads the parent memory, so its summary follows the description.
+ if (before.userMemoryId)
+ await tx
+ .update(userMemories)
+ .set({ summary: plan.now, updatedAt: now })
+ .where(
+ and(eq(userMemories.id, before.userMemoryId), eq(userMemories.userId, this.userId)),
+ );
+ await op({
+ after: { nextSteps: plan.nextSteps, now: plan.now, openQuestions: plan.openQuestions },
+ before,
+ op: 'status',
+ targets: { context: contextId },
+ });
+ result.contextsUpdated += 1;
+ }
+ }
+ if (!contextId) {
+ const [memory] = await tx
+ .insert(userMemories)
+ .values({
+ capturedAt: now,
+ lastAccessedAt: now,
+ memoryCategory: 'context',
+ memoryLayer: 'context',
+ memoryType: 'context',
+ metadata: runTag(runId),
+ state: 'active',
+ summary: plan.now,
+ title: plan.title.slice(0, 255),
+ userId: this.userId,
+ })
+ .returning({ id: userMemories.id });
+ const [created] = await tx
+ .insert(userMemoriesContexts)
+ .values({
+ capturedAt: now,
+ currentStatus: deriveContextStatus(lastEvidence, now),
+ description: plan.now,
+ descriptionVector: plan.descriptionVector ?? null,
+ firstSeenAt: firstSeen,
+ lastEvidenceAt: lastEvidence,
+ metadata: runTag(runId),
+ nextSteps: plan.nextSteps,
+ now: plan.now,
+ openQuestions: plan.openQuestions,
+ synthesizedAt: now,
+ title: plan.title,
+ userId: this.userId,
+ userMemoryId: memory.id,
+ // Existing context readers still join parents through this list.
+ userMemoryIds: [memory.id],
+ })
+ .returning({ id: userMemoriesContexts.id });
+ contextId = created.id;
+ await op({ after: { title: plan.title }, op: 'create', targets: { context: contextId } });
+ result.contextsCreated += 1;
+ }
+
+ // ----- dossiers + evidence -----
+ const updatedDossiers = new Set<string>();
+ for (const d of placed) {
+ const dates = d.members.map((m) => m.capturedAt.getTime());
+ const dFirst = new Date(Math.min(...dates));
+ const dLast = new Date(Math.max(...dates));
+ let dossierId = d.existingDossierId;
+ if (dossierId) {
+ const [existing] = await tx
+ .select({
+ activityCount: userMemoriesDossiers.activityCount,
+ lastEvidenceAt: userMemoriesDossiers.lastEvidenceAt,
+ now: userMemoriesDossiers.now,
+ status: userMemoriesDossiers.status,
+ summary: userMemoriesDossiers.summary,
+ userMemoryId: userMemoriesDossiers.userMemoryId,
+ parentSummary: sql<
+ string | null
+ >`(SELECT ${userMemories.summary} FROM ${userMemories} WHERE ${userMemories.id} = ${userMemoriesDossiers.userMemoryId})`,
+ })
+ .from(userMemoriesDossiers)
+ .where(
+ and(
+ eq(userMemoriesDossiers.id, dossierId),
+ eq(userMemoriesDossiers.userId, this.userId),
+ ),
+ );
+ if (!existing) dossierId = undefined;
+ else {
+ const logBefore = !updatedDossiers.has(dossierId);
+ updatedDossiers.add(dossierId);
+ await tx
+ .update(userMemoriesDossiers)
+ .set({
+ activityCount: existing.activityCount + d.members.length,
+ lastEvidenceAt:
+ existing.lastEvidenceAt && existing.lastEvidenceAt > dLast
+ ? existing.lastEvidenceAt
+ : dLast,
+ now: d.now,
+ summary: d.now,
+ updatedAt: now,
+ })
+ .where(eq(userMemoriesDossiers.id, dossierId));
+ if (existing.userMemoryId)
+ await tx
+ .update(userMemories)
+ .set({ summary: d.now, updatedAt: now })
+ .where(
+ and(
+ eq(userMemories.id, existing.userMemoryId),
+ eq(userMemories.userId, this.userId),
+ ),
+ );
+ // A second group placed on the same dossier would log an intermediate before-image.
+ if (logBefore) {
+ await op({
+ after: { now: d.now },
+ before: existing,
+ op: 'status',
+ targets: { dossier: dossierId },
+ });
+ result.dossiersUpdated += 1;
+ }
+ }
+ }
+ if (!dossierId) {
+ const [memory] = await tx
+ .insert(userMemories)
+ .values({
+ capturedAt: now,
+ lastAccessedAt: now,
+ memoryCategory: 'context',
+ memoryLayer: 'dossier',
+ memoryType: 'dossier',
+ metadata: runTag(runId),
+ state: 'active',
+ summary: d.now,
+ title: d.title.slice(0, 255),
+ userId: this.userId,
+ })
+ .returning({ id: userMemories.id });
+ const [created] = await tx
+ .insert(userMemoriesDossiers)
+ .values({
+ activityCount: d.members.length,
+ contextId,
+ firstSeenAt: dFirst,
+ lastEvidenceAt: dLast,
+ metadata: runTag(runId),
+ now: d.now,
+ status: deriveContextStatus(dLast, now),
+ summary: d.now,
+ title: d.title,
+ userId: this.userId,
+ userMemoryId: memory.id,
+ })
+ .returning({ id: userMemoriesDossiers.id });
+ dossierId = created.id;
+ await op({
+ after: { title: d.title },
+ op: 'create',
+ targets: { context: contextId, dossier: dossierId },
+ });
+ result.dossiersCreated += 1;
+ }
+
+ result.dossierIds.push(dossierId);
+ const activityIds: string[] = [];
+ for (const m of d.members) {
+ const meta = {
+ ...runTag(runId),
+ legacyContextId: m.id,
+ legacyMemoryId: m.memoryId,
+ ...(m.sourceId ? { sourceId: m.sourceId } : {}),
+ };
+ const [memory] = await tx
+ .insert(userMemories)
+ .values({
+ capturedAt: m.capturedAt,
+ details: m.description,
+ lastAccessedAt: now,
+ memoryCategory: 'activity',
+ memoryLayer: 'activity',
+ memoryType: 'activity',
+ metadata: meta,
+ state: 'active',
+ summary: m.description?.slice(0, 1000) ?? null,
+ title: (m.title ?? '').slice(0, 255) || null,
+ userId: this.userId,
+ })
+ .returning({ id: userMemories.id });
+ const [activity] = await tx
+ .insert(userMemoriesActivities)
+ .values({
+ associatedObjects: (m.associatedObjects ?? []) as never,
+ associatedSubjects: (m.associatedSubjects ?? []) as never,
+ capturedAt: m.capturedAt,
+ dossierId,
+ injectable: true,
+ metadata: meta,
+ narrative: m.description,
+ narrativeVector: vectorById.get(m.id) ?? null,
+ status: 'completed',
+ type: 'context_evidence',
+ userId: this.userId,
+ userMemoryId: memory.id,
+ })
+ .returning({ id: userMemoriesActivities.id });
+ activityIds.push(activity.id);
+ await tx
+ .update(userMemories)
+ .set({
+ metadata: sql`coalesce(${userMemories.metadata}, '{}'::jsonb) || ${JSON.stringify({
+ consolidation: { activityId: activity.id, route: 'evidence', runId },
+ })}::jsonb`,
+ state: 'superseded',
+ updatedAt: now,
+ })
+ .where(and(eq(userMemories.id, m.memoryId), eq(userMemories.userId, this.userId)));
+ result.activities += 1;
+ }
+ await op({ op: 'attach', targets: { activities: activityIds, dossier: dossierId } });
+ }
+ result.contextId = contextId;
+ });
+
+ return result;
+ };
+
+ /**
+ * Undo a run: delete the memories it created (children cascade) and bring the legacy rows back.
+ * In-place updates of pre-existing contexts / dossiers are restored from the operation log.
+ */
+ revertRun = async (
+ runId: string,
+ ): Promise<{ blockedBy?: string[]; deleted: number; restored: number }> => {
+ return this.db.transaction(async (tx) => {
+ // A later run that extended what this run created or updated depends on it: reverting this
+ // one alone would cascade-delete or overwrite that run's work. Revert the later runs first.
+ const dependents = await tx.execute<{ run_id: string }>(sql`
+ WITH mine AS (
+ SELECT targets, created_at FROM ${userMemoriesOperations}
+ WHERE user_id = ${this.userId} AND state = 'applied'
+ AND metadata ->> 'consolidationRunId' = ${runId}
+ ), touched AS (
+ SELECT targets ->> 'context' AS id FROM mine WHERE jsonb_exists(targets, 'context')
+ UNION SELECT targets ->> 'dossier' FROM mine WHERE jsonb_exists(targets, 'dossier')
+ )
+ SELECT DISTINCT o.metadata ->> 'consolidationRunId' AS run_id
+ FROM ${userMemoriesOperations} o
+ WHERE o.user_id = ${this.userId} AND o.state = 'applied'
+ AND COALESCE(o.metadata ->> 'consolidationRunId', '') <> ${runId}
+ AND jsonb_exists(o.metadata, 'consolidationRunId')
+ AND o.created_at > (SELECT min(created_at) FROM mine)
+ AND (o.targets ->> 'context' IN (SELECT id FROM touched)
+ OR o.targets ->> 'dossier' IN (SELECT id FROM touched))
+ `);
+ const blockedBy = dependents.rows.map((r) => r.run_id).filter(Boolean);
+ if (blockedBy.length > 0) return { blockedBy, deleted: 0, restored: 0 };
+
+ const updates = await tx
+ .select()
+ .from(userMemoriesOperations)
+ .where(
+ and(
+ eq(userMemoriesOperations.userId, this.userId),
+ eq(userMemoriesOperations.op, 'status'),
+ eq(userMemoriesOperations.state, 'applied'),
+ sql`${userMemoriesOperations.metadata} ->> 'consolidationRunId' = ${runId}`,
+ ),
+ )
+ .orderBy(asc(userMemoriesOperations.createdAt));
+ // A run can update one context / dossier in several chunks (one transaction each, so
+ // createdAt increases). Only the earliest before-image is the state before the run.
+ const restoredTargets = new Set<string>();
+ for (const u of updates) {
+ const before = (u.before ?? {}) as Record<string, unknown>;
+ const target = u.targets as Record<string, string>;
+ const targetKey = target.dossier
+ ? `dossier:${target.dossier}`
+ : `context:${target.context}`;
+ if (restoredTargets.has(targetKey)) continue;
+ restoredTargets.add(targetKey);
+ // Before-images from older runs have no parent fields; leave those parents as they are.
+ if (typeof before.userMemoryId === 'string' && 'parentSummary' in before)
+ await tx
+ .update(userMemories)
+ .set({ summary: (before.parentSummary as string) ?? null })
+ .where(
+ and(eq(userMemories.id, before.userMemoryId), eq(userMemories.userId, this.userId)),
+ );
+ if (target.context && !target.dossier) {
+ await tx
+ .update(userMemoriesContexts)
+ .set({
+ currentStatus: (before.currentStatus as string) ?? null,
+ description: (before.description as string) ?? null,
+ descriptionVector: (before.descriptionVector as number[]) ?? null,
+ lastEvidenceAt: before.lastEvidenceAt
+ ? new Date(before.lastEvidenceAt as string)
+ : null,
+ nextSteps: (before.nextSteps as string[]) ?? null,
+ now: (before.now as string) ?? null,
+ openQuestions: (before.openQuestions as string[]) ?? null,
+ synthesizedAt: before.synthesizedAt ? new Date(before.synthesizedAt as string) : null,
+ })
+ .where(
+ and(
+ eq(userMemoriesContexts.id, target.context),
+ eq(userMemoriesContexts.userId, this.userId),
+ ),
+ );
+ } else if (target.dossier) {
+ await tx
+ .update(userMemoriesDossiers)
+ .set({
+ activityCount: Number(before.activityCount ?? 0),
+ lastEvidenceAt: before.lastEvidenceAt
+ ? new Date(before.lastEvidenceAt as string)
+ : null,
+ now: (before.now as string) ?? null,
+ status: (before.status as UserMemoryDossierStatus | undefined) ?? 'active',
+ summary: (before.summary as string) ?? null,
+ })
+ .where(
+ and(
+ eq(userMemoriesDossiers.id, target.dossier),
+ eq(userMemoriesDossiers.userId, this.userId),
+ ),
+ );
+ }
+ }
+ const deleted = await tx
+ .delete(userMemories)
+ .where(
+ and(
+ eq(userMemories.userId, this.userId),
+ sql`${userMemories.metadata} ->> 'consolidationRunId' = ${runId}`,
+ ),
+ )
+ .returning({ id: userMemories.id });
+ const restored = await tx
+ .update(userMemories)
+ .set({
+ metadata: sql`${userMemories.metadata} - 'consolidation' - 'consolidationQueue'`,
+ state: null,
+ })
+ .where(
+ and(
+ eq(userMemories.userId, this.userId),
+ sql`(${userMemories.metadata} -> 'consolidation' ->> 'runId' = ${runId} OR ${userMemories.metadata} -> 'consolidationQueue' ->> 'runId' = ${runId})`,
+ ),
+ )
+ .returning({ id: userMemories.id });
+ await tx
+ .update(userMemoriesOperations)
+ .set({ resolvedAt: new Date(), state: 'reverted' })
+ .where(
+ and(
+ eq(userMemoriesOperations.userId, this.userId),
+ sql`${userMemoriesOperations.metadata} ->> 'consolidationRunId' = ${runId}`,
+ ),
+ );
+ return { deleted: deleted.length, restored: restored.length };
+ });
+ };
+}
diff --git a/packages/database/src/models/userMemory/index.ts b/packages/database/src/models/userMemory/index.ts
index 49d199090fe..ca1a2c32f0c 100644
--- a/packages/database/src/models/userMemory/index.ts
+++ b/packages/database/src/models/userMemory/index.ts
@@ -1,4 +1,5 @@
export * from './activity';
+export * from './consolidation';
export * from './context';
export * from './experience';
export * from './identity';
diff --git a/packages/database/src/models/userMemory/where.ts b/packages/database/src/models/userMemory/where.ts
index 9fa14c756f8..8d8cba9f90c 100644
--- a/packages/database/src/models/userMemory/where.ts
+++ b/packages/database/src/models/userMemory/where.ts
@@ -3,12 +3,14 @@ import { alias, type AnyPgColumn } from 'drizzle-orm/pg-core';
import { userMemories } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
+import { visibleMemoryState } from '../../utils/memoryVisibility';
import { notTrashed } from '../../utils/softDelete';
const liveUserMemories = alias(userMemories, 'live_user_memories');
interface UserMemoryScopedTable {
isDeleted?: AnyPgColumn;
+ state?: AnyPgColumn;
userId: AnyPgColumn;
userMemoryId?: AnyPgColumn;
userMemoryIds?: AnyPgColumn;
@@ -18,7 +20,13 @@ const liveMemoryIds = (db: LobeChatDatabase, userId: string) =>
db
.select({ id: liveUserMemories.id })
.from(liveUserMemories)
- .where(and(eq(liveUserMemories.userId, userId), notTrashed(liveUserMemories.isDeleted)));
+ .where(
+ and(
+ eq(liveUserMemories.userId, userId),
+ notTrashed(liveUserMemories.isDeleted),
+ visibleMemoryState(liveUserMemories.state),
+ ),
+ );
const liveParentMemory = (db: LobeChatDatabase, userId: string, userMemoryId: AnyPgColumn): SQL =>
or(isNull(userMemoryId), inArray(userMemoryId, liveMemoryIds(db, userId))) as SQL;
@@ -37,7 +45,10 @@ export const buildUserMemoryWhere = (
table: UserMemoryScopedTable,
): SQL => {
let liveMemory: SQL | undefined;
- if (table.isDeleted) liveMemory = notTrashed(table.isDeleted);
+ if (table.isDeleted)
+ liveMemory = table.state
+ ? (and(notTrashed(table.isDeleted), visibleMemoryState(table.state)) as SQL)
+ : notTrashed(table.isDeleted);
else if (table.userMemoryId && table.userMemoryIds) {
// Contexts carry both while rows move from the legacy id list to a single parent: a row with
// a parent is judged by it, a row without one still by its legacy list.
diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts
index cacfbbe45cd..925aac6bf9f 100644
--- a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts
+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts
@@ -30,6 +30,7 @@ import type { LobeChatDatabase } from '../../../type';
import { notAgentShareDocument } from '../../../utils/documentVisibility';
import { libraryVisibleFile, notAgentShareFileReference } from '../../../utils/fileVisibility';
import { normalizeInboxAgentMeta, normalizeInboxAgentTitle } from '../../../utils/inboxAgent';
+import { visibleMemoryState } from '../../../utils/memoryVisibility';
import { searchableMessage } from '../../../utils/searchableMessage';
import { notShareVisitorMessage, notShareVisitorTopic } from '../../../utils/shareVisitor';
import { notTrashed } from '../../../utils/softDelete';
@@ -118,6 +119,7 @@ export const hydrateUserMemories = async (
// Experience memory is retired and has no page to land on; keep it out of unified search.
ne(userMemories.memoryLayer, LayersEnum.Experience),
notTrashed(userMemories.isDeleted),
+ visibleMemoryState(userMemories.state),
),
);
diff --git a/packages/database/src/repositories/ftsSearch/postgres/memories.ts b/packages/database/src/repositories/ftsSearch/postgres/memories.ts
index a6ccc06c6bc..c2df5d3a3b8 100644
--- a/packages/database/src/repositories/ftsSearch/postgres/memories.ts
+++ b/packages/database/src/repositories/ftsSearch/postgres/memories.ts
@@ -2,6 +2,7 @@ import { LayersEnum } from '@lobechat/types';
import { and, eq, ne, sql } from 'drizzle-orm';
import { userMemories } from '../../../schemas';
+import { visibleMemoryState } from '../../../utils/memoryVisibility';
import { notTrashed } from '../../../utils/softDelete';
import type { FtsSearchBackendResponse, FtsSearchMemoryResult } from '../types';
import type { PostgresFtsSearchContext } from './context';
@@ -43,6 +44,7 @@ export async function searchMemories(
// Experience memory is retired and has no page to land on; keep it out of unified search.
ne(userMemories.memoryLayer, LayersEnum.Experience),
notTrashed(userMemories.isDeleted),
+ visibleMemoryState(userMemories.state),
dialect.match(MEMORY_FIELDS, preparedQuery),
),
)
diff --git a/packages/database/src/utils/memoryVisibility.ts b/packages/database/src/utils/memoryVisibility.ts
new file mode 100644
index 00000000000..f2455bee9c8
--- /dev/null
+++ b/packages/database/src/utils/memoryVisibility.ts
@@ -0,0 +1,10 @@
+import { isNull, notInArray, or, type SQL } from 'drizzle-orm';
+import type { AnyPgColumn } from 'drizzle-orm/pg-core';
+
+/**
+ * Memories readers see, by lifecycle state: unset (rows that predate the lifecycle), hypothesis
+ * and active. Consolidation marks a legacy per-topic context `superseded` once it lives on as an
+ * evidence activity; `rejected` is a memory the user or the pipeline turned down.
+ */
+export const visibleMemoryState = (state: AnyPgColumn): SQL =>
+ or(isNull(state), notInArray(state, ['superseded', 'rejected'])) as SQL;