Skip to content

Commit d0f764c

Browse files
committed
fix(memory): honor configured primary search result limits
1 parent 8b7d685 commit d0f764c

5 files changed

Lines changed: 138 additions & 22 deletions

File tree

‎docs/reference/memory-config.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,11 @@ All under `memory.search.query`:
375375
| `maxResults` | `number` | `6` | Max memory hits returned before injection |
376376
| `minScore` | `number` | `0.35` | Minimum relevance score to include a hit |
377377

378+
Without a per-call `maxResults`, primary-only `memory_search` calls use this
379+
configured limit, including `corpus=memory` and `corpus=sessions`. Wiki and
380+
combined searches (`corpus=wiki` or `corpus=all`) keep their separate default
381+
of 10 results. An explicit tool `maxResults` overrides the applicable default.
382+
378383
Hybrid retrieval remains enabled. The builtin engine always applies a fixed
379384
30-day recency half-life to dated daily notes and a fixed importance
380385
multiplier after hybrid relevance, then applies MMR diversity ordering with a

‎extensions/memory-core/src/memory-tool-contract.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,9 @@ export function resolveMemoryToolContext(options: MemoryToolOptions) {
7474
agentId: options.agentId,
7575
});
7676
const settings = resolveMemorySearchConfig(cfg, agentId);
77-
return settings ? { cfg, agentId, sources: resolveMemorySourceContract(settings) } : null;
77+
return settings
78+
? { cfg, agentId, settings, sources: resolveMemorySourceContract(settings) }
79+
: null;
7880
}
7981

8082
const SEARCH_CORPUS_OUTCOME_GUIDANCE =
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import {
2+
clearMemoryPluginState,
3+
registerMemoryCorpusSupplement,
4+
} from "openclaw/plugin-sdk/memory-host-core";
5+
import { beforeEach, expect, it } from "vitest";
6+
import { resetMemoryToolMockState, setMemorySearchImpl } from "./memory-tool-manager.test-mocks.js";
7+
import { testing } from "./tools.js";
8+
import { createMemorySearchToolOrThrow } from "./tools.test-helpers.js";
9+
10+
type Scenario = {
11+
name: string;
12+
configured: number;
13+
corpus?: "memory" | "wiki" | "all";
14+
maxResults?: number;
15+
memoryCount: number;
16+
wikiCount: number;
17+
};
18+
19+
const scenarios: Scenario[] = [
20+
{ name: "configured primary limit", configured: 12, memoryCount: 12, wikiCount: 0 },
21+
{
22+
name: "explicit memory corpus",
23+
configured: 12,
24+
corpus: "memory",
25+
memoryCount: 12,
26+
wikiCount: 0,
27+
},
28+
{ name: "default primary limit", configured: 6, memoryCount: 6, wikiCount: 0 },
29+
{ name: "smaller tool override", configured: 12, maxResults: 4, memoryCount: 4, wikiCount: 0 },
30+
{ name: "larger tool override", configured: 6, maxResults: 12, memoryCount: 12, wikiCount: 0 },
31+
{ name: "wiki default", configured: 12, corpus: "wiki", memoryCount: 0, wikiCount: 10 },
32+
{
33+
name: "wiki tool override",
34+
configured: 12,
35+
corpus: "wiki",
36+
maxResults: 3,
37+
memoryCount: 0,
38+
wikiCount: 3,
39+
},
40+
{
41+
name: "balanced aggregate default",
42+
configured: 12,
43+
corpus: "all",
44+
memoryCount: 5,
45+
wikiCount: 5,
46+
},
47+
{
48+
name: "aggregate backfills spare memory slots",
49+
configured: 3,
50+
corpus: "all",
51+
memoryCount: 3,
52+
wikiCount: 7,
53+
},
54+
{
55+
name: "aggregate tool override",
56+
configured: 6,
57+
corpus: "all",
58+
maxResults: 12,
59+
memoryCount: 6,
60+
wikiCount: 6,
61+
},
62+
];
63+
64+
beforeEach(() => {
65+
clearMemoryPluginState();
66+
testing.resetMemorySearchToolCooldowns();
67+
resetMemoryToolMockState();
68+
});
69+
70+
it.each(scenarios)("preserves the model-visible $name", async (scenario) => {
71+
const memory = Array.from({ length: 20 }, (_, index) => ({
72+
path: `memory/note-${index + 1}.md`,
73+
startLine: 1,
74+
endLine: 1,
75+
score: 1 - index / 100,
76+
snippet: `Memory ${index + 1}: café 🦞 日本語`,
77+
source: "memory" as const,
78+
}));
79+
const wiki = Array.from({ length: 20 }, (_, index) => ({
80+
corpus: "wiki",
81+
path: `entities/note-${index + 1}.md`,
82+
score: 50 - index,
83+
snippet: `Wiki ${index + 1}: café 🦞 日本語`,
84+
}));
85+
setMemorySearchImpl(async (options) => memory.slice(0, options?.maxResults));
86+
registerMemoryCorpusSupplement("memory-wiki", {
87+
search: async ({ maxResults }) => wiki.slice(0, maxResults ?? 10),
88+
get: async () => null,
89+
});
90+
const tool = createMemorySearchToolOrThrow({
91+
config: {
92+
memory: { citations: "off", search: { query: { maxResults: scenario.configured } } },
93+
plugins: { entries: { "memory-core": { config: { dreaming: { enabled: false } } } } },
94+
},
95+
});
96+
97+
const result = await tool.execute("budget", {
98+
query: "note",
99+
...(scenario.corpus ? { corpus: scenario.corpus } : {}),
100+
...(scenario.maxResults ? { maxResults: scenario.maxResults } : {}),
101+
});
102+
const text = result.content.find((part) => part.type === "text")?.text;
103+
if (!text) {
104+
throw new Error("memory_search returned no model-visible text");
105+
}
106+
const payload = JSON.parse(text) as { results: Array<{ path: string; snippet: string }> };
107+
const expected = [...wiki.slice(0, scenario.wikiCount), ...memory.slice(0, scenario.memoryCount)];
108+
expect(payload.results.map(({ path, snippet }) => ({ path, snippet }))).toEqual(
109+
expected.map(({ path, snippet }) => ({ path, snippet })),
110+
);
111+
});

‎extensions/memory-core/src/tools.shared.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ export async function getMemoryManagerContextWithPurpose(params: {
6262
export function createMemoryTool(params: {
6363
options: MemoryToolOptions;
6464
contract: MemoryToolContract;
65-
execute: (ctx: { cfg: OpenClawConfig; agentId: string }) => AnyAgentTool["execute"];
65+
execute: (
66+
ctx: NonNullable<ReturnType<typeof resolveMemoryToolContext>>,
67+
) => AnyAgentTool["execute"];
6668
}): AnyAgentTool | null {
6769
const ctx = resolveMemoryToolContext(params.options);
6870
if (!ctx) {

‎extensions/memory-core/src/tools.ts‎

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import {
1111
readPositiveIntegerParam,
1212
readStringParam,
1313
resolveMemoryDreamingPluginConfig,
14-
resolveMemorySearchConfig,
1514
type MemoryCorpusSearchResult,
1615
} from "openclaw/plugin-sdk/memory-core-host-runtime-core";
1716
import type { MemorySearchResult } from "openclaw/plugin-sdk/memory-core-host-runtime-files";
@@ -66,7 +65,6 @@ type MemorySearchToolQueryDebug = NonNullable<
6665
>;
6766
type PrimaryMemorySearchValue = {
6867
results: Array<MemorySearchResult & { corpus: MemorySource }>;
69-
rawResults: MemorySearchResult[];
7068
provider?: string;
7169
model?: string;
7270
fallback?: unknown;
@@ -200,8 +198,7 @@ function mergeMemorySearchCorpusResults(params: {
200198
maxResults: number;
201199
balanceCorpora: boolean;
202200
}): MemorySearchToolResult[] {
203-
const memoryResults = params.memoryResults;
204-
const supplementResults = params.supplementResults;
201+
const { memoryResults, supplementResults } = params;
205202
if (!params.balanceCorpora || memoryResults.length === 0 || supplementResults.length === 0) {
206203
return mergeRankedMemorySearchToolStreams(memoryResults, supplementResults).slice(
207204
0,
@@ -278,7 +275,7 @@ export function createMemorySearchTool(options: MemoryToolOptions) {
278275
options,
279276
contract: MEMORY_SEARCH_TOOL_CONTRACT,
280277
execute:
281-
({ cfg, agentId }) =>
278+
({ cfg, agentId, settings }) =>
282279
async (_toolCallId, params, callerSignal) => {
283280
const rawParams = asToolParamsRecord(params);
284281
if (callerSignal?.aborted) {
@@ -299,7 +296,7 @@ export function createMemorySearchTool(options: MemoryToolOptions) {
299296
if (
300297
requestedCorpus === "sessions" &&
301298
!options.conversationRecall &&
302-
!resolveMemorySearchConfig(cfg, agentId)?.searchSources.includes("sessions")
299+
!settings.searchSources.includes("sessions")
303300
) {
304301
return jsonResult(
305302
buildMemorySearchUnavailableResult("Session transcript search is not enabled.", {
@@ -355,11 +352,9 @@ export function createMemorySearchTool(options: MemoryToolOptions) {
355352
if ("error" in memory) {
356353
throw new Error(memory.error ?? "memory search unavailable");
357354
}
358-
const settings = resolveMemorySearchConfig(cfg, agentId);
359-
const defaultSources = settings?.searchSources;
360355
const explicitSources: MemorySource[] | undefined =
361356
requestedCorpus === "sessions" &&
362-
(options.conversationRecall || defaultSources?.includes("sessions"))
357+
(options.conversationRecall || settings.searchSources.includes("sessions"))
363358
? ["sessions"]
364359
: requestedCorpus === "memory"
365360
? ["memory"]
@@ -381,11 +376,11 @@ export function createMemorySearchTool(options: MemoryToolOptions) {
381376
},
382377
query: {
383378
text: query,
384-
resultLimit: maxResults ?? settings?.query.maxResults ?? 10,
379+
resultLimit: maxResults ?? settings.query.maxResults,
385380
minScore,
386381
explicitSources,
387-
defaultSources,
388-
indexedSources: settings?.sources,
382+
defaultSources: settings.searchSources,
383+
indexedSources: settings.sources,
389384
requestedCorpus,
390385
sessionKey: options.agentSessionKey,
391386
activeProjectKeys: options.activeProjectKeys,
@@ -418,7 +413,6 @@ export function createMemorySearchTool(options: MemoryToolOptions) {
418413
"memory",
419414
{
420415
results: [],
421-
rawResults: [],
422416
unavailableResult: buildPausedMemoryIndexUnavailableResult(reason),
423417
},
424418
reason,
@@ -462,7 +456,6 @@ export function createMemorySearchTool(options: MemoryToolOptions) {
462456
results: memoryResults.map((result) =>
463457
Object.assign(result, { corpus: result.source }),
464458
),
465-
rawResults,
466459
provider: status.provider,
467460
model: status.model,
468461
fallback: status.fallback,
@@ -502,12 +495,15 @@ export function createMemorySearchTool(options: MemoryToolOptions) {
502495
);
503496
}
504497
const wikiResults = wiki?.outcome === "not-registered" ? [] : (wiki?.value ?? []);
505-
const results = mergeMemorySearchCorpusResults({
506-
memoryResults: memoryValue?.results ?? [],
507-
supplementResults: wikiResults,
508-
maxResults: Math.max(1, maxResults ?? 10),
509-
balanceCorpora: requestedCorpus === "all",
510-
});
498+
// Primary results already own their configured limit; only wiki/all need aggregation.
499+
const results = searchesWiki
500+
? mergeMemorySearchCorpusResults({
501+
memoryResults: memoryValue?.results ?? [],
502+
supplementResults: wikiResults,
503+
maxResults: maxResults ?? 10,
504+
balanceCorpora: requestedCorpus === "all",
505+
})
506+
: (memoryValue?.results ?? []);
511507
const attempts = [
512508
...(requestedCorpus === "all" && memory ? [memory] : []),
513509
...(wiki ? [wiki] : []),

0 commit comments

Comments
 (0)