Skip to content

Commit 248eeec

Browse files
feat(memory-lancedb): make auto-recall selectivity configurable
Auto-recall selectivity is hardcoded: minimum similarity 0.3, a candidate overfetch of 10, and an injection cap of 3. Operators cannot tune precision/recall for their own data without editing plugin source. Surface the three knobs as config (recallMinScore, recallResultCap, autoRecallOverfetch) with manifest uiHints and defaults equal to the previous hardcoded values, and thread them through the live-config merge so operator values take effect at the before_prompt_build hook, not only at startup. Behavior-preserving when unset. The two count settings are declared `integer` in the manifest and the runtime parser rejects (rather than silently floors) non-integer values for them, so both validation layers enforce the same contract; a parity test pins manifest and runtime to the same bounds and failure modes. Add a regression test proving configured values survive the live-config merge into auto-recall (an overfetch of 4 and a minScore of 0.85 reach the search instead of silently reparsing as defaults), and document the three settings including the prompt-budget note for elevated caps. Extracted from the scope PR (#108782) following its review recommendation to split the tuning improvement from the partitioning contract. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 parent c4b2183 commit 248eeec

7 files changed

Lines changed: 366 additions & 2 deletions

File tree

‎docs/docs_map.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5919,6 +5919,7 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
59195919
- H3: Dimensions
59205920
- H2: Ollama embeddings
59215921
- H2: Recall and capture limits
5922+
- H3: Recall selectivity (auto-recall)
59225923
- H2: Commands
59235924
- H2: Storage
59245925
- H2: Runtime dependencies and platform support

‎docs/plugins/memory-lancedb.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,26 @@ or via `agents.defaults`) also gets none of the `memory_recall`, `memory_store`,
213213
or `memory_forget` tools and does not participate in automatic recall or
214214
capture, even when the plugin-level `autoRecall`/`autoCapture` flags are on.
215215

216+
### Recall selectivity (auto-recall)
217+
218+
These tune the automatic `before_prompt_build` recall — how many candidates it
219+
fetches, how strict the similarity cutoff is, and how many memories it injects.
220+
Defaults equal the previously hardcoded values, so leaving them unset preserves
221+
current behavior. They take effect at the before-prompt hook (not only at
222+
startup).
223+
224+
| Setting | Default | Range | Applies to |
225+
| --------------------- | ------- | ----- | -------------------------------------------------------------------- |
226+
| `recallMinScore` | `0.3` | 0-1 | Minimum similarity score for a memory to be injected by auto-recall. |
227+
| `autoRecallOverfetch` | `10` | 1-200 | Candidate pool size fetched before scoring/capping in auto-recall. |
228+
| `recallResultCap` | `3` | 1-50 | Maximum memories injected per turn by auto-recall. |
229+
230+
The two count settings are integers (fractional values are rejected, not
231+
rounded). Raising `recallResultCap` grows the injected `<relevant-memories>`
232+
block accordingly — budget prompt space before setting it far above the
233+
default. `autoRecallOverfetch` only widens the internal candidate pool and does
234+
not increase injected content.
235+
216236
## Commands
217237

218238
`memory-lancedb` registers the `ltm` CLI namespace whenever it is installed

‎extensions/memory-lancedb/config.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,4 +213,64 @@ describe("memory-lancedb config", () => {
213213
});
214214
}).toThrow("dreaming config must be an object");
215215
});
216+
217+
it("aligns recall tuning constraints between the manifest schema and runtime parsing", () => {
218+
// Fractional counts must fail identically in both layers: the manifest
219+
// declares the two count fields as `integer`, and the runtime parser
220+
// rejects (rather than silently floors) non-integer values for them — a
221+
// config can never validate in one layer and be reinterpreted by the
222+
// other.
223+
for (const overrides of [{ recallResultCap: 2.5 }, { autoRecallOverfetch: 4.5 }]) {
224+
const manifestResult = validateJsonSchemaValue({
225+
schema: manifest.configSchema,
226+
cacheKey: "memory-lancedb.manifest.recall-tuning",
227+
value: { embedding: { apiKey: "sk-test" }, ...overrides },
228+
});
229+
expect(manifestResult.ok).toBe(false);
230+
expect(() => {
231+
memoryConfigSchema.parse({ embedding: { apiKey: "sk-test" }, ...overrides });
232+
}).toThrow(/must be an integer between/);
233+
}
234+
235+
// Out-of-range values fail in both layers with the same bounds.
236+
const outOfRange: Array<[Record<string, number>, string]> = [
237+
[{ recallResultCap: 0 }, "recallResultCap must be an integer between 1 and 50"],
238+
[{ recallResultCap: 51 }, "recallResultCap must be an integer between 1 and 50"],
239+
[{ autoRecallOverfetch: 0 }, "autoRecallOverfetch must be an integer between 1 and 200"],
240+
[{ autoRecallOverfetch: 201 }, "autoRecallOverfetch must be an integer between 1 and 200"],
241+
[{ recallMinScore: -0.1 }, "recallMinScore must be a number between 0 and 1"],
242+
[{ recallMinScore: 1.5 }, "recallMinScore must be a number between 0 and 1"],
243+
];
244+
for (const [overrides, message] of outOfRange) {
245+
const manifestResult = validateJsonSchemaValue({
246+
schema: manifest.configSchema,
247+
cacheKey: "memory-lancedb.manifest.recall-tuning",
248+
value: { embedding: { apiKey: "sk-test" }, ...overrides },
249+
});
250+
expect(manifestResult.ok).toBe(false);
251+
expect(() => {
252+
memoryConfigSchema.parse({ embedding: { apiKey: "sk-test" }, ...overrides });
253+
}).toThrow(message);
254+
}
255+
256+
// Boundary values pass both layers and are preserved verbatim.
257+
const boundary = {
258+
recallMinScore: 0.85,
259+
recallResultCap: 1,
260+
autoRecallOverfetch: 200,
261+
};
262+
const manifestOk = validateJsonSchemaValue({
263+
schema: manifest.configSchema,
264+
cacheKey: "memory-lancedb.manifest.recall-tuning",
265+
value: { embedding: { apiKey: "sk-test" }, ...boundary },
266+
});
267+
expect(manifestOk.ok).toBe(true);
268+
const parsed = memoryConfigSchema.parse({
269+
embedding: { apiKey: "sk-test" },
270+
...boundary,
271+
});
272+
expect(parsed.recallMinScore).toBe(0.85);
273+
expect(parsed.recallResultCap).toBe(1);
274+
expect(parsed.autoRecallOverfetch).toBe(200);
275+
});
216276
});

‎extensions/memory-lancedb/config.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ export type MemoryConfig = {
2020
customTriggers?: string[];
2121
recallMaxChars?: number;
2222
storageOptions?: Record<string, string>;
23+
recallMinScore?: number;
24+
recallResultCap?: number;
25+
autoRecallOverfetch?: number;
2326
};
2427

2528
export const MEMORY_CATEGORIES = ["preference", "fact", "decision", "entity", "other"] as const;
@@ -122,6 +125,30 @@ function resolveBoundedIntegerConfig(params: {
122125
return resolved;
123126
}
124127

128+
// Strict variant for newly introduced count settings: rejects non-integer
129+
// values instead of silently flooring them, so runtime validation matches the
130+
// manifest's `integer` schema exactly (a config cannot pass one layer and be
131+
// reinterpreted by the other). Pre-existing fields keep the tolerant resolver
132+
// above for backward compatibility.
133+
function resolveBoundedStrictIntegerConfig(params: {
134+
value: unknown;
135+
fallback: number;
136+
min: number;
137+
max: number;
138+
label: string;
139+
}): number {
140+
if (params.value === undefined) {
141+
return params.fallback;
142+
}
143+
if (typeof params.value !== "number" || !Number.isInteger(params.value)) {
144+
throw new Error(`${params.label} must be an integer between ${params.min} and ${params.max}`);
145+
}
146+
if (params.value < params.min || params.value > params.max) {
147+
throw new Error(`${params.label} must be an integer between ${params.min} and ${params.max}`);
148+
}
149+
return params.value;
150+
}
151+
125152
function resolveEmbeddingDimensions(embedding: Record<string, unknown>): number | undefined {
126153
if (embedding.dimensions === undefined) {
127154
return undefined;
@@ -152,6 +179,9 @@ export const memoryConfigSchema = {
152179
"customTriggers",
153180
"recallMaxChars",
154181
"storageOptions",
182+
"recallMinScore",
183+
"recallResultCap",
184+
"autoRecallOverfetch",
155185
],
156186
"memory config",
157187
);
@@ -186,6 +216,31 @@ export const memoryConfigSchema = {
186216
max: 10_000,
187217
label: "recallMaxChars",
188218
});
219+
const recallMinScore = ((): number => {
220+
if (cfg.recallMinScore === undefined) {
221+
return 0.3;
222+
}
223+
const parsed =
224+
typeof cfg.recallMinScore === "number" ? parseFiniteNumber(cfg.recallMinScore) : undefined;
225+
if (parsed === undefined || parsed < 0 || parsed > 1) {
226+
throw new Error("recallMinScore must be a number between 0 and 1");
227+
}
228+
return parsed;
229+
})();
230+
const recallResultCap = resolveBoundedStrictIntegerConfig({
231+
value: cfg.recallResultCap,
232+
fallback: 3,
233+
min: 1,
234+
max: 50,
235+
label: "recallResultCap",
236+
});
237+
const autoRecallOverfetch = resolveBoundedStrictIntegerConfig({
238+
value: cfg.autoRecallOverfetch,
239+
fallback: 10,
240+
min: 1,
241+
max: 200,
242+
label: "autoRecallOverfetch",
243+
});
189244
let customTriggers: string[] | undefined;
190245
if (cfg.customTriggers !== undefined) {
191246
if (!Array.isArray(cfg.customTriggers)) {
@@ -251,6 +306,9 @@ export const memoryConfigSchema = {
251306
captureMaxChars,
252307
...(customTriggers ? { customTriggers } : {}),
253308
recallMaxChars,
309+
recallMinScore,
310+
recallResultCap,
311+
autoRecallOverfetch,
254312
...(storageOptions ? { storageOptions } : {}),
255313
};
256314
},
@@ -314,6 +372,24 @@ export const memoryConfigSchema = {
314372
advanced: true,
315373
placeholder: String(DEFAULT_RECALL_MAX_CHARS),
316374
},
375+
recallMinScore: {
376+
label: "Recall Min Score",
377+
help: "Minimum similarity (0-1) for a memory to be eligible for auto-recall injection. Higher = stricter.",
378+
advanced: true,
379+
placeholder: "0.3",
380+
},
381+
recallResultCap: {
382+
label: "Recall Result Cap",
383+
help: "Maximum number of memories auto-recall injects into context.",
384+
advanced: true,
385+
placeholder: "3",
386+
},
387+
autoRecallOverfetch: {
388+
label: "Auto-Recall Overfetch",
389+
help: "Candidates fetched before sludge-filtering and capping. Keep a few multiples above the result cap.",
390+
advanced: true,
391+
placeholder: "10",
392+
},
317393
storageOptions: {
318394
label: "Storage Options",
319395
sensitive: true,

‎extensions/memory-lancedb/index.test.ts‎

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1526,6 +1526,172 @@ describe("memory plugin e2e", () => {
15261526
}
15271527
});
15281528

1529+
test("threads operator recall thresholds through live config into auto-recall", async () => {
1530+
// Regression: resolveCurrentHookConfig() must carry the new
1531+
// recallMinScore / recallResultCap / autoRecallOverfetch fields from the
1532+
// registration config before spreading the live runtime config. Without
1533+
// that, once a live runtime config object is present (the normal case)
1534+
// these three are dropped and reparsed as defaults, and operator-configured
1535+
// values never take effect in before_prompt_build. Here the knobs live only
1536+
// in the registration pluginConfig; the live config omits them, so they
1537+
// survive only via that baseline. autoRecallOverfetch=4 (not the default
1538+
// 10) and recallMinScore=0.85 (not the default 0.3, which would keep the
1539+
// weak 0.5-score row).
1540+
const embeddingsCreate = vi.fn(async () => ({
1541+
data: [{ embedding: [0.1, 0.2, 0.3] }],
1542+
}));
1543+
const ensureGlobalUndiciEnvProxyDispatcher = vi.fn();
1544+
const toArray = vi.fn(async () => [
1545+
{
1546+
id: "memory-strong",
1547+
text: "I prefer Helix for editing code.",
1548+
vector: [0.1, 0.2, 0.3],
1549+
importance: 0.8,
1550+
category: "preference",
1551+
createdAt: 1,
1552+
_distance: 0.1, // score = 1/1.1 ≈ 0.91 -> passes 0.85
1553+
},
1554+
{
1555+
id: "memory-weak",
1556+
text: "A weakly related note.",
1557+
vector: [0.1, 0.2, 0.3],
1558+
importance: 0.8,
1559+
category: "other",
1560+
createdAt: 1,
1561+
_distance: 1, // score = 1/2 = 0.50 -> passes default 0.3, fails 0.85
1562+
},
1563+
]);
1564+
const limit = vi.fn(() => ({ toArray }));
1565+
const vectorSearch = vi.fn(() => createAgentScopedVectorQuery(limit));
1566+
const openTable = vi.fn(async () => ({
1567+
schema: createAgentScopedSchemaMock(),
1568+
vectorSearch,
1569+
countRows: vi.fn(async () => 0),
1570+
add: vi.fn(async () => undefined),
1571+
delete: vi.fn(async () => undefined),
1572+
}));
1573+
const loadLanceDbModule = vi.fn(async () => ({
1574+
connect: vi.fn(async () => ({
1575+
tableNames: vi.fn(async () => ["memories"]),
1576+
openTable,
1577+
})),
1578+
}));
1579+
let configFile: Record<string, unknown> = {
1580+
plugins: {
1581+
entries: {
1582+
"memory-lancedb": {
1583+
config: {
1584+
embedding: {
1585+
apiKey: OPENAI_API_KEY,
1586+
model: "text-embedding-3-small",
1587+
},
1588+
dbPath: getDbPath(),
1589+
autoCapture: false,
1590+
autoRecall: false,
1591+
},
1592+
},
1593+
},
1594+
},
1595+
};
1596+
1597+
vi.resetModules();
1598+
vi.doMock("openclaw/plugin-sdk/runtime-env", () => ({
1599+
ensureGlobalUndiciEnvProxyDispatcher,
1600+
}));
1601+
vi.doMock("openai", () => ({
1602+
default: class MockOpenAI {
1603+
post = vi.fn((_path: string, opts: { body?: unknown }) =>
1604+
invokeEmbeddingCreate(embeddingsCreate, opts.body),
1605+
);
1606+
},
1607+
}));
1608+
vi.doMock("./lancedb-runtime.js", () => ({
1609+
loadLanceDbModule,
1610+
}));
1611+
1612+
try {
1613+
const { default: dynamicMemoryPlugin } = await import("./index.js");
1614+
const on = vi.fn();
1615+
const logger = {
1616+
info: vi.fn(),
1617+
warn: vi.fn(),
1618+
error: vi.fn(),
1619+
debug: vi.fn(),
1620+
};
1621+
const mockApi = {
1622+
id: "memory-lancedb",
1623+
name: "Memory (LanceDB)",
1624+
source: "test",
1625+
config: {},
1626+
// Thresholds live ONLY in the registration config (-> cfg baseline).
1627+
pluginConfig: {
1628+
embedding: {
1629+
apiKey: OPENAI_API_KEY,
1630+
model: "text-embedding-3-small",
1631+
},
1632+
dbPath: getDbPath(),
1633+
autoCapture: false,
1634+
autoRecall: false,
1635+
recallMinScore: 0.85,
1636+
autoRecallOverfetch: 4,
1637+
},
1638+
runtime: {
1639+
config: {
1640+
current: () => configFile,
1641+
},
1642+
},
1643+
logger,
1644+
registerTool: vi.fn(),
1645+
registerCli: vi.fn(),
1646+
registerService: vi.fn(),
1647+
on,
1648+
resolvePath: (p: string) => p,
1649+
};
1650+
1651+
registerTestPlugin(dynamicMemoryPlugin, mockApi);
1652+
1653+
// Live config enables auto-recall but omits the threshold knobs.
1654+
configFile = {
1655+
plugins: {
1656+
entries: {
1657+
"memory-lancedb": {
1658+
config: {
1659+
embedding: {
1660+
apiKey: OPENAI_API_KEY,
1661+
model: "text-embedding-3-small",
1662+
},
1663+
dbPath: getDbPath(),
1664+
autoCapture: false,
1665+
autoRecall: true,
1666+
},
1667+
},
1668+
},
1669+
},
1670+
};
1671+
1672+
const beforePromptBuild = on.mock.calls.find(
1673+
([hookName]) => hookName === "before_prompt_build",
1674+
)?.[1];
1675+
expect(beforePromptBuild).toBeTypeOf("function");
1676+
1677+
const result = await beforePromptBuild?.(
1678+
{ prompt: "what editor should i use?", messages: [] },
1679+
{ agentId: "main" },
1680+
);
1681+
1682+
// autoRecallOverfetch reached the search (not the default 10).
1683+
expect(limit).toHaveBeenCalledWith(4);
1684+
// recallMinScore=0.85 filtered the weak row; the default 0.3 would keep it.
1685+
expect(result?.prependContext).toContain("I prefer Helix for editing code.");
1686+
expect(result?.prependContext).not.toContain("A weakly related note.");
1687+
} finally {
1688+
vi.doUnmock("openclaw/plugin-sdk/runtime-env");
1689+
vi.doUnmock("openai");
1690+
vi.doUnmock("./lancedb-runtime.js");
1691+
vi.resetModules();
1692+
}
1693+
});
1694+
15291695
test("uses live runtime config to skip auto-recall after registration", async () => {
15301696
const embeddingsCreate = vi.fn(async () => ({
15311697
data: [{ embedding: [0.1, 0.2, 0.3] }],

0 commit comments

Comments
 (0)