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.

🐛 fix(runtime,memory): 记忆抽取容忍可修复的模型输出,并修复关闭信号与运行状态持久化问题 (#22642)

Mochabae8d0f24d4f
diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
index 7c22ebcab74..2ecfcce0659 100644
--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
@@ -221,7 +221,11 @@ export class AgentStateManager {
messages?: unknown;
operationToolSet?: unknown;
};
- if (hasNonPersistedMessage(persistable.messages)) {
+ if (
+ !state.origin?.agentId ||
+ !state.origin.topicId ||
+ hasNonPersistedMessage(persistable.messages)
+ ) {
return JSON.stringify(persistable);
}
const { messages: _messages, ...rest } = persistable;
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
index 1af15770468..e6b1a26c9a8 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
@@ -100,6 +100,7 @@ describe('AgentStateManager', () => {
const state = {
cost: { total: 1 },
messages: [{ content: 'x'.repeat(1000), id: 'msg-1', role: 'user' }],
+ origin: { agentId: 'agent-1', topicId: 'topic-1' },
status: 'running' as const,
stepCount: 1,
};
@@ -112,6 +113,25 @@ describe('AgentStateManager', () => {
expect(JSON.parse(serialized).status).toBe('running');
});
+ it.each([undefined, { agentId: 'agent-1' }, { topicId: 'topic-1' }])(
+ 'keeps private transcripts without a rehydratable origin: %j',
+ async (origin) => {
+ const messages = [{ content: 'private transcript', id: 'private-1', role: 'user' }];
+ const state = { messages, origin, status: 'running', stepCount: 1 };
+ await stateManager.saveAgentState('private-op', state as any);
+ const serialized = redisMock.setex.mock.calls.at(-1)?.[2] as string;
+ expect(JSON.parse(serialized).messages).toEqual(messages);
+
+ await stateManager.saveStepResult('private-op', {
+ executionTime: 1,
+ newState: state as any,
+ stepIndex: 1,
+ });
+ const stepState = pipelineMock.setex.mock.calls.at(-1)?.[2] as string;
+ expect(JSON.parse(stepState).messages).toEqual(messages);
+ },
+ );
+
it('keeps the full messages array when an ephemeral (id-less) message is present', async () => {
const state = {
cost: { total: 1 },
@@ -184,6 +204,7 @@ describe('AgentStateManager', () => {
newState: {
cost: { total: 1 },
messages: [{ content: 'x'.repeat(1000), id: 'msg-1', role: 'user' }],
+ origin: { agentId: 'agent-1', topicId: 'topic-1' },
status: 'done' as const,
stepCount: 1,
},
diff --git a/apps/server/src/utils/__tests__/tempFileManager.test.ts b/apps/server/src/utils/__tests__/tempFileManager.test.ts
index 352321012e3..5ad6f63dc77 100644
--- a/apps/server/src/utils/__tests__/tempFileManager.test.ts
+++ b/apps/server/src/utils/__tests__/tempFileManager.test.ts
@@ -90,16 +90,6 @@ describe('TempFileManager', () => {
expect(existsSync).toHaveBeenCalledWith(mockFullTmpDir);
expect(rmSync).not.toHaveBeenCalled();
});
-
- it('should register cleanup hooks on process events', () => {
- const processOnSpy = vi.spyOn(process, 'on');
- new TempFileManager(mockDirname);
-
- expect(processOnSpy).toHaveBeenCalledWith('exit', expect.any(Function));
- expect(processOnSpy).toHaveBeenCalledWith('uncaughtException', expect.any(Function));
- expect(processOnSpy).toHaveBeenCalledWith('SIGINT', expect.any(Function));
- expect(processOnSpy).toHaveBeenCalledWith('SIGTERM', expect.any(Function));
- });
});
// Path traversal regression tests
diff --git a/apps/server/src/utils/tempFileManager.ts b/apps/server/src/utils/tempFileManager.ts
index a3865b8ee00..05fbcf6e600 100644
--- a/apps/server/src/utils/tempFileManager.ts
+++ b/apps/server/src/utils/tempFileManager.ts
@@ -3,7 +3,11 @@ import { tmpdir } from 'node:os';
import { basename, join, resolve } from 'node:path';
/**
- * Utility class for safely storing temporary files
+ * Utility class for safely storing temporary files. Callers clean up in `finally`.
+ *
+ * It installs no process hooks: an exiting SIGTERM listener would cut short the
+ * runtime's graceful shutdown, and an exiting `uncaughtException` listener turns
+ * any later stray error into a crash. Callers own cleanup; the host owns termination.
*/
export class TempFileManager {
private readonly tempDir: string;
@@ -12,8 +16,6 @@ export class TempFileManager {
constructor(dirname: string) {
// Create unique temporary directory (cross-platform safe)
this.tempDir = mkdtempSync(join(tmpdir(), dirname));
- // Register cleanup hook for process exit
- this.registerCleanupHook();
}
/**
@@ -45,25 +47,4 @@ export class TempFileManager {
this.filePaths.clear();
}
}
-
- /**
- * Register automatic cleanup on process exit/exception
- */
- private registerCleanupHook(): void {
- // Normal exit
- process.on('exit', () => this.cleanup());
- // Exception exit
- process.on('uncaughtException', (err) => {
- console.error('Uncaught exception, cleaning temp files:', err);
- this.cleanup();
- process.exit(1);
- });
- // Signal termination
- ['SIGINT', 'SIGTERM'].forEach((signal) => {
- process.on(signal, () => {
- this.cleanup();
- process.exit(0);
- });
- });
- }
}
diff --git a/packages/database/src/models/userMemory/query/hybrid.test.ts b/packages/database/src/models/userMemory/query/hybrid.test.ts
new file mode 100644
index 00000000000..f0d71037647
--- /dev/null
+++ b/packages/database/src/models/userMemory/query/hybrid.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment node
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { UserMemoryQueryContext } from './context';
+import type * as HybridModule from './hybrid';
+import type { scoreHybridCandidates as ScoreHybridCandidates } from './scoring';
+
+vi.mock('./scoring', () => ({ scoreHybridCandidates: vi.fn(() => []) }));
+
+// The server-db suite runs with `isolate: false`, so another file may already have loaded
+// `./hybrid` with the real scoring module; load a fresh copy that sees the mock.
+let hybrid: typeof HybridModule;
+let scoreHybridCandidates: typeof ScoreHybridCandidates;
+
+beforeAll(async () => {
+ vi.resetModules();
+ hybrid = await import('./hybrid');
+ ({ scoreHybridCandidates } = await import('./scoring'));
+});
+
+// Leave no mocked module behind for the files that share this module registry.
+afterAll(() => {
+ vi.doUnmock('./scoring');
+ vi.resetModules();
+});
+
+describe('hybrid query budget', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it.each([
+ ['activities', 'searchHybridActivities'],
+ ['contexts', 'searchHybridContexts'],
+ ['experiences', 'searchHybridExperiences'],
+ ['identities', 'searchHybridIdentities'],
+ ['preferences', 'searchHybridPreferences'],
+ ] as const)('skips fuzzy comparison of long contexts for %s', async (layer, name) => {
+ const search = hybrid[name];
+ const prefix = layer[0].toUpperCase() + layer.slice(1);
+ const lexical = vi.fn(async () => []);
+ const context = {
+ getSearchOverfetchLimit: () => 10,
+ hasSearchFilters: () => false,
+ loadBaseSignals: async () => new Map(),
+ [`search${prefix}Lexical`]: lexical,
+ } as unknown as UserMemoryQueryContext;
+ const queries = ['conversation context '.repeat(1000)];
+ await search(context, { embeddings: [], lexicalSearch: false, params: {}, queries });
+ expect(lexical).not.toHaveBeenCalled();
+ expect(scoreHybridCandidates).toHaveBeenLastCalledWith(
+ expect.objectContaining({ queries: [] }),
+ );
+
+ const shortQueries = ['short phrase'];
+ await search(context, {
+ embeddings: [],
+ lexicalSearch: true,
+ params: {},
+ queries: shortQueries,
+ });
+ expect(lexical).toHaveBeenCalled();
+ expect(scoreHybridCandidates).toHaveBeenLastCalledWith(
+ expect.objectContaining({ queries: shortQueries }),
+ );
+ });
+});
diff --git a/packages/database/src/models/userMemory/query/hybrid.ts b/packages/database/src/models/userMemory/query/hybrid.ts
index 778ad8c1664..e8d7f4e042f 100644
--- a/packages/database/src/models/userMemory/query/hybrid.ts
+++ b/packages/database/src/models/userMemory/query/hybrid.ts
@@ -4,6 +4,14 @@ import type { UserMemoryQueryContext } from './context';
import { scoreHybridCandidates } from './scoring';
import { buildRetrievalQuery, combineEmbeddings } from './utils';
+/**
+ * Context too long for the lexical leg is too long to fuzzy-match as well: comparing a whole
+ * conversation with every field of every candidate says little and blocks the event loop for
+ * seconds.
+ */
+const fuzzyQueries = (params: { lexicalSearch: boolean; queries: string[] }) =>
+ params.lexicalSearch ? params.queries : [];
+
export async function searchHybridActivities(
ctx: UserMemoryQueryContext,
params: {
@@ -38,7 +46,7 @@ export async function searchHybridActivities(
baseSignals: await ctx.loadBaseSignals(items),
items,
lexicalLists,
- queries: params.queries,
+ queries: fuzzyQueries(params),
queryParams: params.params,
semanticLists,
});
@@ -78,7 +86,7 @@ export async function searchHybridContexts(
baseSignals: await ctx.loadBaseSignals(items),
items,
lexicalLists,
- queries: params.queries,
+ queries: fuzzyQueries(params),
queryParams: params.params,
semanticLists,
});
@@ -118,7 +126,7 @@ export async function searchHybridExperiences(
baseSignals: await ctx.loadBaseSignals(items),
items,
lexicalLists,
- queries: params.queries,
+ queries: fuzzyQueries(params),
queryParams: params.params,
semanticLists,
});
@@ -158,7 +166,7 @@ export async function searchHybridIdentities(
baseSignals: await ctx.loadBaseSignals(items),
items,
lexicalLists,
- queries: params.queries,
+ queries: fuzzyQueries(params),
queryParams: params.params,
semanticLists,
});
@@ -198,7 +206,7 @@ export async function searchHybridPreferences(
baseSignals: await ctx.loadBaseSignals(items),
items,
lexicalLists,
- queries: params.queries,
+ queries: fuzzyQueries(params),
queryParams: params.params,
semanticLists,
});
diff --git a/packages/memory-user-memory/src/extractors/base.ts b/packages/memory-user-memory/src/extractors/base.ts
index 28a384ca538..edacd2ecf95 100644
--- a/packages/memory-user-memory/src/extractors/base.ts
+++ b/packages/memory-user-memory/src/extractors/base.ts
@@ -20,6 +20,7 @@ import type {
MemoryExtractionAgent,
TemplateProps,
} from '../types';
+import { parseLenient } from '../utils/lenientParse';
import { buildGenerateObjectSchema } from '../utils/zod';
const serializeForSpan = (value: unknown, limit = 4000) => {
@@ -35,6 +36,32 @@ const serializeForSpan = (value: unknown, limit = 4000) => {
}
};
+/**
+ * Validates an extractor's answer, repairing what models get slightly wrong (see
+ * {@link parseLenient}) and logging what was repaired, so new kinds of drift show up in the
+ * logs rather than as failed topics.
+ */
+export const parseModelOutput = <T>(
+ schema: z.ZodType<T, unknown>,
+ output: unknown,
+ agent: string,
+ model: string,
+): T => {
+ const { data, repairs } = parseLenient(schema, output);
+ if (repairs.length > 0) {
+ console.info(
+ JSON.stringify({
+ agent,
+ event: 'memory.output.repaired',
+ model,
+ repairs: repairs.slice(0, 20),
+ total: repairs.length,
+ }),
+ );
+ }
+ return data;
+};
+
export interface BaseMemoryExtractorConfig {
agent: MemoryExtractionAgent;
model: string;
@@ -185,7 +212,9 @@ export abstract class BaseMemoryExtractor<
}
const schema = this.getResultSchema();
- const parsedResult = (schema ? schema.parse(result) : result) as TOutput;
+ const parsedResult = (
+ schema ? parseModelOutput(schema, result, this.agent, this.model) : result
+ ) as TOutput;
span.setStatus({ code: SpanStatusCode.OK });
diff --git a/packages/memory-user-memory/src/extractors/context.test.ts b/packages/memory-user-memory/src/extractors/context.test.ts
index 092091912d3..7c4df48bb08 100644
--- a/packages/memory-user-memory/src/extractors/context.test.ts
+++ b/packages/memory-user-memory/src/extractors/context.test.ts
@@ -77,4 +77,43 @@ describe('ContextExtractor', () => {
expect(result).not.toBe('');
expect(result).toBe(renderPlaceholderTemplate(contextPrompt, expectedProps));
});
+
+ it('keeps a memory whose type the model made up, filed under other', async () => {
+ const info = vi.spyOn(console, 'info').mockImplementation(() => {});
+ vi.mocked(runtimeMock.generateObject).mockResolvedValue({
+ memories: [
+ {
+ details: '',
+ memoryCategory: 'work',
+ memoryType: 'project',
+ summary: 'Migrating search',
+ tags: [],
+ title: 'Search migration',
+ withContext: {
+ associatedObjects: [],
+ associatedSubjects: [],
+ currentStatus: 'ongoing',
+ description: 'Moving search to Elasticsearch',
+ labels: [],
+ scoreImpact: 0.5,
+ scoreUrgency: 0.5,
+ title: 'Search migration',
+ type: 'project',
+ },
+ },
+ ],
+ });
+
+ const result = await new ContextExtractor(extractorConfig).structuredCall(templateOptions);
+
+ expect(result.memories).toEqual([
+ expect.objectContaining({ memoryType: 'other', title: 'Search migration' }),
+ ]);
+ expect(JSON.parse(info.mock.calls.at(-1)![0])).toMatchObject({
+ agent: 'layer-context',
+ event: 'memory.output.repaired',
+ repairs: ['memories.0.memoryType: other'],
+ });
+ info.mockRestore();
+ });
});
diff --git a/packages/memory-user-memory/src/extractors/gatekeeper.test.ts b/packages/memory-user-memory/src/extractors/gatekeeper.test.ts
index a094a1a248e..cf4e89f9700 100644
--- a/packages/memory-user-memory/src/extractors/gatekeeper.test.ts
+++ b/packages/memory-user-memory/src/extractors/gatekeeper.test.ts
@@ -98,4 +98,26 @@ describe('UserMemoryGateKeeper', () => {
expect.objectContaining({ metadata: { trigger: 'memory' } }),
);
});
+
+ it('reads a bare yes/no or a missing decision instead of failing the whole topic', async () => {
+ const extractor = new UserMemoryGateKeeper(extractorConfig);
+ // Shapes deepseek-v4.1-flash returned in production: booleans, strings, and the retired
+ // experience layer left out.
+ runtimeMock.generateObject = vi.fn().mockResolvedValue({
+ activity: true,
+ context: 'false',
+ identity: { reasoning: 'r', shouldExtract: true },
+ preference: false,
+ }) as any;
+
+ const result = await extractor.check(templateOptions);
+
+ expect(result).toEqual({
+ activity: { reasoning: '', shouldExtract: true },
+ context: { reasoning: 'false', shouldExtract: false },
+ experience: { reasoning: '', shouldExtract: false },
+ identity: { reasoning: 'r', shouldExtract: true },
+ preference: { reasoning: '', shouldExtract: false },
+ });
+ });
});
diff --git a/packages/memory-user-memory/src/extractors/identity.test.ts b/packages/memory-user-memory/src/extractors/identity.test.ts
index 1ef9822457e..989ce40cea1 100644
--- a/packages/memory-user-memory/src/extractors/identity.test.ts
+++ b/packages/memory-user-memory/src/extractors/identity.test.ts
@@ -115,4 +115,34 @@ describe('IdentityExtractor', () => {
expect(result).not.toBe('');
expect(result).toBe(renderPlaceholderTemplate(identityPrompt, expectedProps));
});
+
+ it('keeps an identity whose role the model left as null', async () => {
+ const extractor = new IdentityExtractor(extractorConfig);
+ const identity = {
+ details: null,
+ memoryCategory: 'personal',
+ memoryType: 'fact',
+ summary: 'Summary',
+ tags: [],
+ title: 'Identity',
+ withIdentity: {
+ description: 'Description',
+ episodicDate: null,
+ extractedLabels: [],
+ relationship: 'self',
+ role: null,
+ scoreConfidence: 0.8,
+ sourceIds: [],
+ sourceEvidence: null,
+ type: 'personal',
+ },
+ };
+ (runtimeMock.generateObject as any) = vi
+ .fn()
+ .mockResolvedValue({ add: [identity], remove: null, update: null });
+
+ const result = await extractor.structuredCall(templateOptions);
+
+ expect(result.add?.[0]?.withIdentity.role).toBeNull();
+ });
});
diff --git a/packages/memory-user-memory/src/extractors/persona.ts b/packages/memory-user-memory/src/extractors/persona.ts
index 8e45a48e9a9..45be821f49e 100644
--- a/packages/memory-user-memory/src/extractors/persona.ts
+++ b/packages/memory-user-memory/src/extractors/persona.ts
@@ -8,7 +8,7 @@ import type {
PersonaTemplateProps,
UserPersonaExtractionResult,
} from '../types';
-import { BaseMemoryExtractor } from './base';
+import { BaseMemoryExtractor, parseModelOutput } from './base';
const resultSchema = z.object({
diff: z.string().optional(),
@@ -132,10 +132,10 @@ export class UserPersonaExtractor extends BaseMemoryExtractor<
? JSON.parse(firstCall.arguments || '{}')
: firstCall?.arguments;
- return resultSchema.parse(args || {});
+ return parseModelOutput(resultSchema, args || {}, this.agent, this.model);
}
- return resultSchema.parse(result);
+ return parseModelOutput(resultSchema, result, this.agent, this.model);
}
async structuredCall(options?: PersonaExtractorOptions): Promise<UserPersonaExtractionResult> {
diff --git a/packages/memory-user-memory/src/schemas/gatekeeper.ts b/packages/memory-user-memory/src/schemas/gatekeeper.ts
index 8d6e17b4815..bea575d231d 100644
--- a/packages/memory-user-memory/src/schemas/gatekeeper.ts
+++ b/packages/memory-user-memory/src/schemas/gatekeeper.ts
@@ -10,15 +10,31 @@ export const LayerDecisionSchema = z.object({
export type LayerDecision = z.infer<typeof LayerDecisionSchema>;
+/**
+ * Models sometimes answer a layer with a bare yes/no, or leave a layer out (notably the retired
+ * experience one). Read those as the decision they state, a missing one as "do not extract",
+ * rather than failing the whole topic.
+ */
+const toLayerDecision = (value: unknown) => {
+ if (value === undefined || value === null) return { reasoning: '', shouldExtract: false };
+ if (typeof value === 'boolean') return { reasoning: '', shouldExtract: value };
+ if (typeof value === 'string') {
+ return { reasoning: value, shouldExtract: value.trim().toLowerCase() === 'true' };
+ }
+ return value;
+};
+
+const LenientLayerDecisionSchema = z.preprocess(toLayerDecision, LayerDecisionSchema);
+
/**
* Gatekeeper result schema for memory layers
*/
export const GatekeeperResultSchema = z.object({
- activity: LayerDecisionSchema,
- context: LayerDecisionSchema,
- experience: LayerDecisionSchema,
- identity: LayerDecisionSchema,
- preference: LayerDecisionSchema,
+ activity: LenientLayerDecisionSchema,
+ context: LenientLayerDecisionSchema,
+ experience: LenientLayerDecisionSchema,
+ identity: LenientLayerDecisionSchema,
+ preference: LenientLayerDecisionSchema,
});
export type GatekeeperResult = z.infer<typeof GatekeeperResultSchema>;
diff --git a/packages/memory-user-memory/src/schemas/identity.ts b/packages/memory-user-memory/src/schemas/identity.ts
index 85dbe221cac..816eedbff04 100644
--- a/packages/memory-user-memory/src/schemas/identity.ts
+++ b/packages/memory-user-memory/src/schemas/identity.ts
@@ -59,8 +59,9 @@ export const AddIdentityActionSchema = z
relationship: RelationshipEnum,
role: z
.string()
+ .nullable()
.describe(
- 'Role explicitly mentioned for this identity entry (e.g., "platform engineer", "caregiver"); keep neutral and only use when evidence exists',
+ 'Role explicitly mentioned for this identity entry (e.g., "platform engineer", "caregiver"); keep neutral and only use when evidence exists, otherwise null',
),
scoreConfidence: z.number(),
sourceIds: z
diff --git a/packages/memory-user-memory/src/utils/__tests__/lenientParse.test.ts b/packages/memory-user-memory/src/utils/__tests__/lenientParse.test.ts
new file mode 100644
index 00000000000..922a070a319
--- /dev/null
+++ b/packages/memory-user-memory/src/utils/__tests__/lenientParse.test.ts
@@ -0,0 +1,170 @@
+import { describe, expect, it } from 'vitest';
+import { z } from 'zod';
+
+import { ContextMemorySchema } from '../../schemas/context';
+import { IdentityActionsSchema } from '../../schemas/identity';
+import { parseLenient } from '../lenientParse';
+
+const identity = (withIdentity: Record<string, unknown>, extra: Record<string, unknown> = {}) => ({
+ details: null,
+ memoryCategory: 'work',
+ memoryType: 'people',
+ summary: 'Works on payments',
+ tags: ['work'],
+ title: 'Payments engineer',
+ withIdentity: {
+ description: 'Builds the payments service',
+ episodicDate: null,
+ extractedLabels: ['payments'],
+ relationship: 'self',
+ role: 'engineer',
+ scoreConfidence: 0.9,
+ sourceEvidence: null,
+ sourceIds: ['msg_1'],
+ type: 'professional',
+ ...withIdentity,
+ },
+ ...extra,
+});
+
+describe('parseLenient', () => {
+ it('returns valid output untouched, with no repairs', () => {
+ const schema = z.object({ items: z.array(z.object({ a: z.string() })) });
+
+ expect(parseLenient(schema, { items: [{ a: 'x' }] })).toEqual({
+ data: { items: [{ a: 'x' }] },
+ repairs: [],
+ });
+ });
+
+ it('files an off-list memoryType under "other" instead of failing the topic', () => {
+ const { data, repairs } = parseLenient(IdentityActionsSchema, {
+ add: [identity({}, { memoryType: 'career' })],
+ remove: [],
+ update: [],
+ });
+
+ expect(data.add![0].memoryType).toBe('other');
+ expect(repairs).toEqual(['add.0.memoryType: other']);
+ });
+
+ it('moves fields the model lifted out of a nested object back into it', () => {
+ const item = identity({});
+ const { extractedLabels, scoreConfidence, sourceEvidence, sourceIds, ...withIdentity } =
+ item.withIdentity;
+
+ const { data } = parseLenient(IdentityActionsSchema, {
+ add: [{ ...item, extractedLabels, scoreConfidence, sourceEvidence, sourceIds, withIdentity }],
+ remove: [],
+ update: [],
+ });
+
+ expect(data.add![0].withIdentity).toMatchObject({
+ extractedLabels: ['payments'],
+ scoreConfidence: 0.9,
+ sourceIds: ['msg_1'],
+ });
+ expect(data.add![0]).not.toHaveProperty('scoreConfidence');
+ });
+
+ it('moves a lifted field back even when the nested object reports it missing', () => {
+ const { type, ...withIdentity } = identity({}).withIdentity;
+
+ const { data } = parseLenient(IdentityActionsSchema, {
+ add: [{ ...identity({}), type, withIdentity }],
+ remove: [],
+ update: [],
+ });
+
+ expect(data.add![0].withIdentity.type).toBe('professional');
+ });
+
+ it('drops keys that belong nowhere', () => {
+ const { data, repairs } = parseLenient(IdentityActionsSchema, {
+ add: [identity({ mood: 'happy' }, { confidence: 'high' })],
+ remove: [],
+ update: [],
+ });
+
+ expect(data.add![0]).not.toHaveProperty('confidence');
+ expect(data.add![0].withIdentity).not.toHaveProperty('mood');
+ expect(repairs).toEqual(expect.arrayContaining(['add.0: dropped key confidence']));
+ });
+
+ it('drops only the entry it cannot repair and keeps the others', () => {
+ const { data, repairs } = parseLenient(IdentityActionsSchema, {
+ add: [identity({ type: 'astrological' }), identity({}, { title: 'Kept' })],
+ remove: [],
+ update: [],
+ });
+
+ expect(data.add).toHaveLength(1);
+ expect(data.add![0].title).toBe('Kept');
+ expect(repairs).toContain('add.0: dropped entry');
+ });
+
+ it('reads strings as the numbers and booleans they spell, and null as absent', () => {
+ const schema = z.object({
+ count: z.number(),
+ enabled: z.boolean(),
+ note: z.string().optional(),
+ });
+
+ expect(parseLenient(schema, { count: '3', enabled: 'false', note: null }).data).toEqual({
+ count: 3,
+ enabled: false,
+ });
+ });
+
+ it('repairs context memories the way production output went wrong', () => {
+ const context = {
+ details: 'details',
+ memoryCategory: 'work',
+ memoryType: 'project',
+ summary: 'Migrating search',
+ tags: [],
+ title: 'Search migration',
+ withContext: {
+ associatedObjects: [],
+ associatedSubjects: [],
+ currentStatus: 'ongoing',
+ description: 'Moving search to Elasticsearch',
+ labels: [],
+ scoreImpact: 0.5,
+ scoreUrgency: 0.5,
+ title: 'Search migration',
+ type: 'project',
+ },
+ };
+ const parsed = ContextMemorySchema.safeParse({ memories: [context] });
+ // The fixture only fails on the field under test.
+ expect(parsed.success ? [] : parsed.error.issues.map((issue) => issue.path.join('.'))).toEqual([
+ 'memories.0.memoryType',
+ ]);
+
+ expect(
+ parseLenient(ContextMemorySchema, { memories: [context] }).data.memories[0],
+ ).toMatchObject({ memoryType: 'other', title: 'Search migration' });
+ });
+
+ it('still fails when the output as a whole is unusable', () => {
+ const schema = z.object({ memories: z.array(z.object({ a: z.string() })) });
+
+ expect(() => parseLenient(schema, { nothing: true })).toThrow();
+ expect(() => parseLenient(schema, 'not an object')).toThrow();
+ });
+
+ it('keeps preprocessing schemas working', () => {
+ const schema = z.object({
+ decision: z.preprocess(
+ (value) => (typeof value === 'boolean' ? { ok: value } : value),
+ z.object({ ok: z.boolean() }).strict(),
+ ),
+ });
+
+ expect(parseLenient(schema, { decision: true }).data).toEqual({ decision: { ok: true } });
+ expect(parseLenient(schema, { decision: { extra: 1, ok: 'true' } }).data).toEqual({
+ decision: { ok: true },
+ });
+ });
+});
diff --git a/packages/memory-user-memory/src/utils/lenientParse.ts b/packages/memory-user-memory/src/utils/lenientParse.ts
new file mode 100644
index 00000000000..ae73ca65f8a
--- /dev/null
+++ b/packages/memory-user-memory/src/utils/lenientParse.ts
@@ -0,0 +1,189 @@
+import type { z } from 'zod';
+
+/** Repairs are applied in passes; each pass fixes every issue the previous parse reported. */
+const MAX_PASSES = 20;
+
+type Path = PropertyKey[];
+type Container = Record<PropertyKey, unknown>;
+
+const isRecord = (value: unknown): value is Container =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const at = (root: unknown, path: Path): unknown =>
+ path.reduce<unknown>((value, key) => (value as Container | undefined)?.[key], root);
+
+/** The object schema behind wrappers (optional, nullable, default, preprocess…), if any. */
+const objectShape = (schema: z.ZodType | undefined): Record<string, z.ZodType> | undefined => {
+ const def = (schema as any)?._zod?.def;
+ if (!def) return undefined;
+ if (def.type === 'object') return def.shape;
+ if (def.type === 'pipe') return objectShape(def.out) ?? objectShape(def.in);
+ if (def.type === 'lazy') return objectShape(def.getter());
+ if (def.innerType) return objectShape(def.innerType);
+ return undefined;
+};
+
+/** The schema that validates the value at `path`, following object keys and array items. */
+const schemaAt = (schema: z.ZodType | undefined, path: Path): z.ZodType | undefined => {
+ let current = schema;
+ for (const key of path) {
+ const def = (current as any)?._zod?.def;
+ if (!def) return undefined;
+ if (typeof key === 'number') {
+ let inner = current as any;
+ while (inner?._zod?.def && inner._zod.def.type !== 'array') {
+ const d = inner._zod.def;
+ inner = d.type === 'pipe' ? d.out : d.type === 'lazy' ? d.getter() : d.innerType;
+ }
+ current = inner?._zod?.def?.element;
+ } else {
+ current = objectShape(current)?.[key as string];
+ }
+ }
+ return current;
+};
+
+const coerce = (expected: string | undefined, value: unknown): { value: unknown } | undefined => {
+ if (expected === 'number' && typeof value === 'string' && value.trim() !== '') {
+ const number = Number(value);
+ if (Number.isFinite(number)) return { value: number };
+ }
+ if (expected === 'boolean' && typeof value === 'string') {
+ const text = value.trim().toLowerCase();
+ if (text === 'true' || text === 'false') return { value: text === 'true' };
+ }
+ if (expected === 'string' && (typeof value === 'number' || typeof value === 'boolean'))
+ return { value: String(value) };
+ if (expected === 'array' && value !== null && value !== undefined && !Array.isArray(value))
+ return { value: [value] };
+ return undefined;
+};
+
+/**
+ * Parses model output against a strict extraction schema, repairing the ways models drift
+ * instead of rejecting the whole answer: keys outside the schema are dropped (or moved back
+ * into the nested object they belong to), an off-list value goes under `other` when the list
+ * has one, numbers that overshoot a bound are clamped, scalars spelled as strings are read as
+ * such, and null counts as absent. An entry still invalid after that is dropped from its list,
+ * so one bad memory does not cost the topic its others.
+ *
+ * Throws the original validation error when nothing can be repaired, e.g. the output is not
+ * the expected object at all.
+ */
+export const parseLenient = <T>(
+ schema: z.ZodType<T>,
+ value: unknown,
+): { data: T; repairs: string[] } => {
+ const repairs: string[] = [];
+ const current: unknown = structuredClone(value);
+ let firstError: z.ZodError | undefined;
+
+ for (let pass = 0; pass < MAX_PASSES; pass++) {
+ const result = schema.safeParse(current);
+ if (result.success) return { data: result.data, repairs };
+ firstError ??= result.error;
+
+ let changed = false;
+ /** Entries to drop, per list, applied after the other repairs so indexes stay valid. */
+ const drops = new Map<unknown[], { indexes: Set<number>; path: Path }>();
+
+ const drop = (path: Path) => {
+ const index = path.findLastIndex((key) => typeof key === 'number');
+ if (index < 0) return;
+ const listPath = path.slice(0, index);
+ const list = at(current, listPath);
+ if (!Array.isArray(list)) return;
+ const entry = drops.get(list) ?? { indexes: new Set<number>(), path: listPath };
+ entry.indexes.add(path[index] as number);
+ drops.set(list, entry);
+ };
+
+ const set = (path: Path, next: unknown, note: string) => {
+ const parent = at(current, path.slice(0, -1));
+ if (!isRecord(parent) && !Array.isArray(parent)) return drop(path);
+ const key = path.at(-1)!;
+ if (next === undefined && isRecord(parent)) delete parent[key];
+ else (parent as Container)[key] = next;
+ repairs.push(`${path.join('.')}: ${note}`);
+ changed = true;
+ };
+
+ for (const issue of result.error.issues) {
+ const path = issue.path as Path;
+ const actual = at(current, path);
+
+ if (issue.code === 'unrecognized_keys') {
+ const target = at(current, path);
+ if (!isRecord(target)) continue;
+ const shape = objectShape(schemaAt(schema, path)) ?? {};
+ for (const key of issue.keys) {
+ // A field lifted out of its nested object goes back where the schema has it.
+ const home = Object.keys(shape).find((name) => {
+ const nested = objectShape(shape[name]);
+ const child = target[name];
+ return (
+ nested &&
+ key in nested &&
+ (child === undefined || isRecord(child)) &&
+ (child as Container | undefined)?.[key] === undefined
+ );
+ });
+ if (home) {
+ target[home] = { ...(target[home] as Container | undefined), [key]: target[key] };
+ repairs.push(`${[...path, key].join('.')}: moved into ${home}`);
+ } else {
+ repairs.push(`${path.join('.') || '(root)'}: dropped key ${key}`);
+ }
+ delete target[key];
+ changed = true;
+ }
+ continue;
+ }
+
+ if (path.length === 0) continue;
+
+ if (issue.code === 'invalid_value' && issue.values.includes('other')) {
+ set(path, 'other', 'other');
+ continue;
+ }
+
+ if ((issue.code === 'too_big' || issue.code === 'too_small') && typeof actual === 'number') {
+ const bound = Number(issue.code === 'too_big' ? issue.maximum : issue.minimum);
+ if (Number.isFinite(bound)) {
+ set(path, bound, `clamped to ${bound}`);
+ continue;
+ }
+ }
+
+ if (issue.code === 'invalid_type') {
+ const coerced = coerce(issue.expected, actual);
+ if (coerced) {
+ set(path, coerced.value, `read as ${issue.expected}`);
+ continue;
+ }
+ // Null for a field that does not take it: treat it as left out (a default may fill it).
+ if (actual === null && isRecord(at(current, path.slice(0, -1)))) {
+ set(path, undefined, 'null left out');
+ continue;
+ }
+ }
+
+ drop(path);
+ }
+
+ // A repair can settle issues reported next to it (a moved field fills the gap it left), so
+ // entries are dropped only once a pass has nothing else to repair.
+ if (changed) continue;
+ for (const [list, { indexes, path }] of drops) {
+ for (const index of [...indexes].sort((a, b) => b - a)) {
+ list.splice(index, 1);
+ repairs.push(`${[...path, index].join('.')}: dropped entry`);
+ }
+ changed = true;
+ }
+
+ if (!changed) break;
+ }
+
+ throw firstError ?? new Error('Output could not be repaired');
+};