🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(memory): keep a context's current state when consolidation files older evidence (#22820)
Arvin Xu8d05ded95196
diff --git a/packages/database/src/models/userMemory/__tests__/consolidation.test.ts b/packages/database/src/models/userMemory/__tests__/consolidation.test.tsindex 8ad77bcee5b..f3425341d55 100644--- a/packages/database/src/models/userMemory/__tests__/consolidation.test.ts+++ b/packages/database/src/models/userMemory/__tests__/consolidation.test.ts@@ -222,6 +222,132 @@ describe('UserMemoryConsolidationModel', () => {expect(await model.listPendingLegacyContexts()).toHaveLength(1);});+ it('reactivates a closed dossier when fresh evidence extends it', async () => {+ const daysAgo = (days: number) =>+ new Date(Date.now() - days * 86_400_000).toISOString().slice(0, 10);+ const old = await createLegacy('billing migration', daysAgo(400));+ const first = await model.applyContextPlan('run_closed', {+ dossiers: [{ memberIds: [old.context.id], now: 'v1', title: 'Billing' }],+ nextSteps: [],+ now: 'v1',+ openQuestions: [],+ title: 'Billing',+ });+ const [closed] = await serverDB+ .select()+ .from(userMemoriesDossiers)+ .where(eq(userMemoriesDossiers.id, first.dossierIds[0]));+ expect(closed.status).toBe('closed');++ const fresh = await createLegacy('billing migration resumed', daysAgo(1));+ await model.applyContextPlan('run_resumed', {+ dossiers: [+ {+ existingDossierId: first.dossierIds[0],+ memberIds: [fresh.context.id],+ now: 'v2',+ title: 'Billing',+ },+ ],+ existingContextId: first.contextId,+ nextSteps: [],+ now: 'v2',+ openQuestions: [],+ title: 'Billing',+ });+ const [resumed] = await serverDB+ .select()+ .from(userMemoriesDossiers)+ .where(eq(userMemoriesDossiers.id, first.dossierIds[0]));+ expect(resumed.status).toBe('active');++ await model.revertRun('run_resumed');+ const [restored] = await serverDB+ .select()+ .from(userMemoriesDossiers)+ .where(eq(userMemoriesDossiers.id, first.dossierIds[0]));+ expect(restored.status).toBe('closed');+ });++ it('files older evidence without rewriting the current state', async () => {+ const fresh = await createLegacy('pricing launched', '2026-09-01');+ const first = await model.applyContextPlan('run_fresh', {+ dossiers: [{ memberIds: [fresh.context.id], now: 'launched', title: 'Pricing' }],+ nextSteps: ['watch churn'],+ now: 'launched',+ openQuestions: [],+ title: 'Pricing',+ });++ const old = await createLegacy('pricing draft', '2026-04-01');+ const second = await model.applyContextPlan('run_old', {+ dossiers: [+ {+ existingDossierId: first.dossierIds[0],+ memberIds: [old.context.id],+ now: 'drafting',+ title: 'Pricing',+ },+ ],+ existingContextId: first.contextId,+ nextSteps: ['write the draft'],+ now: 'drafting',+ openQuestions: [],+ title: 'Pricing',+ });+ expect(second.activities).toBe(1);++ const [ctx] = await serverDB+ .select()+ .from(userMemoriesContexts)+ .where(eq(userMemoriesContexts.id, first.contextId!));+ expect(ctx.now).toBe('launched');+ expect(ctx.description).toBe('launched');+ expect(ctx.nextSteps).toEqual(['watch churn']);+ expect(ctx.lastEvidenceAt?.toISOString().slice(0, 10)).toBe('2026-09-01');+ const [ctxParent] = await serverDB+ .select()+ .from(userMemories)+ .where(eq(userMemories.id, ctx.userMemoryId!));+ expect(ctxParent.summary).toBe('launched');++ const [dossier] = await serverDB+ .select()+ .from(userMemoriesDossiers)+ .where(eq(userMemoriesDossiers.id, first.dossierIds[0]));+ expect(dossier.now).toBe('launched');+ expect(dossier.summary).toBe('launched');+ expect(dossier.activityCount).toBe(2);++ // Evidence newer than the stored state still rewrites it.+ const newer = await createLegacy('pricing v2', '2026-10-01');+ await model.applyContextPlan('run_newer', {+ dossiers: [+ {+ existingDossierId: first.dossierIds[0],+ memberIds: [newer.context.id],+ now: 'v2 live',+ title: 'Pricing',+ },+ ],+ existingContextId: first.contextId,+ nextSteps: [],+ now: 'v2 live',+ openQuestions: [],+ title: 'Pricing',+ });+ const [updated] = await serverDB+ .select()+ .from(userMemoriesContexts)+ .where(eq(userMemoriesContexts.id, first.contextId!));+ expect(updated.now).toBe('v2 live');+ const [updatedDossier] = await serverDB+ .select()+ .from(userMemoriesDossiers)+ .where(eq(userMemoriesDossiers.id, first.dossierIds[0]));+ expect(updatedDossier.now).toBe('v2 live');+ });+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', createInitialContextPlan(a.context.id));diff --git a/packages/database/src/models/userMemory/consolidation.ts b/packages/database/src/models/userMemory/consolidation.tsindex e6be8f18b9b..04deb4cef39 100644--- a/packages/database/src/models/userMemory/consolidation.ts+++ b/packages/database/src/models/userMemory/consolidation.ts@@ -559,27 +559,41 @@ export class UserMemoryConsolidationModel {if (!before) {contextId = undefined;} else {- const last =- before.lastEvidenceAt && before.lastEvidenceAt > lastEvidence- ? before.lastEvidenceAt- : lastEvidence;+ // NOTICE: A plan only describes the evidence it was given. When all of it is older than+ // what the context already holds (a later chunk of an unsorted domain, a late-extracted+ // memory), its `now` is a past state, so the evidence is filed but the current state stays.+ const stale = !!before.lastEvidenceAt && before.lastEvidenceAt > lastEvidence;+ const last = stale ? before.lastEvidenceAt! : lastEvidence;+ const state = stale+ ? {+ nextSteps: before.nextSteps,+ now: before.now,+ openQuestions: before.openQuestions,+ }+ : { nextSteps: plan.nextSteps, now: plan.now, openQuestions: plan.openQuestions };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,+ ...(stale+ ? {}+ : {+ description: plan.now,+ // Without a fresh embedding, the old vector still ranks better than none.+ ...(plan.descriptionVector+ ? { descriptionVector: plan.descriptionVector }+ : {}),+ nextSteps: plan.nextSteps,+ now: plan.now,+ openQuestions: plan.openQuestions,+ synthesizedAt: now,+ }),}).where(eq(userMemoriesContexts.id, contextId));// Unified search reads the parent memory, so its summary follows the description.- if (before.userMemoryId)+ if (before.userMemoryId && !stale)await tx.update(userMemories).set({ summary: plan.now, updatedAt: now })@@ -587,7 +601,7 @@ export class UserMemoryConsolidationModel {and(eq(userMemories.id, before.userMemoryId), eq(userMemories.userId, this.userId)),);await op({- after: { nextSteps: plan.nextSteps, now: plan.now, openQuestions: plan.openQuestions },+ after: state,before,op: 'status',targets: { context: contextId },@@ -668,20 +682,20 @@ export class UserMemoryConsolidationModel {else {const logBefore = !updatedDossiers.has(dossierId);updatedDossiers.add(dossierId);+ // Same rule as the context above: older evidence is filed without rewriting `now`.+ const stale = !!existing.lastEvidenceAt && existing.lastEvidenceAt > dLast;+ const last = stale ? existing.lastEvidenceAt! : dLast;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,+ lastEvidenceAt: last,+ status: deriveContextStatus(last, now),updatedAt: now,+ ...(stale ? {} : { now: d.now, summary: d.now }),}).where(eq(userMemoriesDossiers.id, dossierId));- if (existing.userMemoryId)+ if (existing.userMemoryId && !stale)await tx.update(userMemories).set({ summary: d.now, updatedAt: now })@@ -694,7 +708,7 @@ export class UserMemoryConsolidationModel {// A second group placed on the same dossier would log an intermediate before-image.if (logBefore) {await op({- after: { now: d.now },+ after: { now: stale ? existing.now : d.now },before: existing,op: 'status',targets: { dossier: dossierId },