Skip to content

Commit 2ceb44b

Browse files
feat(memory-lancedb): scope memory_recall and memory_forget + configurable thresholds
In a shared LanceDB memory store, the explicit memory tools operate across the whole store: memory_recall selects the top-K nearest vectors globally, and memory_forget (query mode) runs an unfiltered search that can auto-delete the wrong context's copy once the same fact exists in more than one context. Add an optional per-row scope column and a native LanceDB .where() prefilter in both tools, constraining results to the requested scope before the vector search returns — no separate store per context needed. .where() is already used on the --filter CLI path but not on these tools. Scope is an opaque partition key, not a fixed concept: it is whatever the caller partitions by (a project, a person, a channel, a tenant). A memory is tagged by prefixing its text with [SCOPE:<value>], and both tools take a scope parameter. The tag is a routing prefix: it is parsed into the scope column and stripped from the text before embedding and storing (both the explicit store tool and the auto-capture path), so the vector reflects the fact rather than the synthetic prefix and the tag is never echoed back on recall. A scope key is a slug ([A-Za-z0-9_-]+); a tag or scope argument whose key is not a valid slug is rejected rather than silently transformed, so a punctuated key (e.g. a raw channel/room id) can never be canonicalized into another partition nor silently stored global. A tag with no fact after it ([SCOPE:<value>] alone, or only whitespace) is rejected on store and skipped on auto-capture, so the control tag is never embedded or persisted as a memory on its own. Auto-capture strips the tag before its capture heuristics run, so a long routing tag cannot change a message's eligibility (neither pushing short content over the length floor nor valid content past captureMaxChars) — the decision is made on the fact, not the prefix. OpenClaw builds the .where() clause internally from the validated slug — no raw filter expression is accepted from the caller. Scope is enforced as a partition, not an optional label: a tagged memory is hidden from any operation that does not ask for its scope. A scoped memory_recall returns that scope's matches first with global rows filling the rest (scope and global are retrieved in separate ANN passes, each with its own candidate budget, so strong global neighbors cannot crowd the scope out of a shared top-K); an unscoped recall is global-only, so scoped rows never bleed into a plain recall. memory_forget is symmetric: a scoped forget is restricted to that exact scope, and an unscoped forget is global-only — and this holds for both delete paths, the query path (scope filter) and the memoryId path (fenced by checking the target row's scope before deleting), so a known id from another partition cannot bypass the fence. The automatic before-prompt recall is also global-only — it has no active-scope signal, so it injects only global/untagged memories and never auto-recalls a scoped row into an unrelated session. The ltm search CLI mirrors the tools: unscoped it is global-only (never a table-wide scan that would expose scoped rows), and an opt-in --scope <slug> restricts the vector search to a single partition. Make duplicate detection scope-aware: the scope is applied as a .where() prefilter before the near-exact top-K, so a duplicate only counts within the same scope and a same-scope duplicate is never pushed out of the candidate window by other scopes. The same fact can coexist under different scopes; same-scope and global-vs-global writes still dedup. A self-healing migration adds the column to pre-existing tables, preserving rows and vectors. Surface recall selectivity as configuration (recallMinScore, recallResultCap, autoRecallOverfetch), with matching manifest uiHints, and defaults equal to the previously hardcoded values. These fields are threaded through the live-config merge so operator values take effect at the before-prompt hook, not only at startup. Deferred (non-goal): this does not target the automatic before-prompt injection at a specific scope — the hook has no active-scope signal, so it cannot know which partition the current turn belongs to. Rather than leak, it fails safe by injecting only global/untagged memories. Scope-targeted auto-injection is future work; the scope column and .where() prefilter added here are the foundation for it. Behavior-preserving until a memory is tagged: every pre-existing row has an empty scope, so it stays global and is returned by unscoped recall and the automatic injection exactly as before; thresholds default to today's values. A memory becomes partitioned only when explicitly tagged [SCOPE:<value>], so installs that never use scope tags see no change. Add regression tests: the [SCOPE:<value>] tag survives hyphens and underscores (no truncation/mis-scoping) and is stripped from the embedded input and stored text; dedup is scope-aware and prefilters by scope before the top-K; scoped memory_recall prioritizes its scope over many strong global matches; operator recall thresholds survive the live-config merge into auto-recall; an unscoped memory_recall returns only global rows; an unscoped memory_forget cannot delete a scoped row; auto-recall injects only global memories; a scoped memory_forget deletes only within its scope; a store tag with a non-slug key is rejected (no silent global fallback); a memoryId forget is fenced to the row's scope; a tag-only [SCOPE:<value>] store is rejected (and auto-capture skips it) rather than persisting the bare tag; ltm search is global-only unless an explicit --scope slug is given; and auto-capture eligibility is evaluated on the scope-stripped text, so a long routing tag cannot flip a message's memory-worthiness. Document the scope contract (tag/slug shape, global-vs-scoped recall and forget, memoryId fence, global-only auto-recall) and the recall-selectivity settings in docs/plugins/memory-lancedb.md, and regenerate docs/docs_map.md for the new headings. The added tests are lint-clean under the type-aware oxlint config CI runs (--tsconfig: restrict-template-expressions, no-unnecessary-type-conversion) and carry no unchecked `any` casts, so the extensions lint and type-suppression-inventory gates stay green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 parent 4e78d91 commit 2ceb44b

6 files changed

Lines changed: 1983 additions & 79 deletions

File tree

‎docs/docs_map.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5915,7 +5915,9 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
59155915
- H3: Dimensions
59165916
- H2: Ollama embeddings
59175917
- H2: Recall and capture limits
5918+
- H3: Recall selectivity (auto-recall)
59185919
- H2: Commands
5920+
- H2: Scope (partitioning a shared store)
59195921
- H2: Storage
59205922
- H2: Runtime dependencies and platform support
59215923
- H2: Troubleshooting

‎docs/plugins/memory-lancedb.md‎

Lines changed: 59 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -206,14 +206,28 @@ Auto-capture also rejects text that looks like envelope/transport metadata,
206206
prompt-injection payloads, or already-injected `<relevant-memories>` context,
207207
and caps at 3 captured memories per agent turn.
208208

209+
### Recall selectivity (auto-recall)
210+
211+
These tune the automatic `before_prompt_build` recall — how many candidates it
212+
fetches, how strict the similarity cutoff is, and how many memories it injects.
213+
Defaults equal the previously hardcoded values, so leaving them unset preserves
214+
current behavior. They take effect at the before-prompt hook (not only at
215+
startup).
216+
217+
| Setting | Default | Range | Applies to |
218+
| --------------------- | ------- | ----- | -------------------------------------------------------------------- |
219+
| `recallMinScore` | `0.3` | 0-1 | Minimum similarity score for a memory to be injected by auto-recall. |
220+
| `autoRecallOverfetch` | `10` | 1-200 | Candidate pool size fetched before scoring/capping in auto-recall. |
221+
| `recallResultCap` | `3` | 1-50 | Maximum memories injected per turn by auto-recall. |
222+
209223
## Commands
210224

211225
`memory-lancedb` registers the `ltm` CLI namespace whenever it is installed
212226
(not only when it owns the active memory slot):
213227

214228
```bash
215229
openclaw ltm list [--limit <n>] [--order-by-created-at]
216-
openclaw ltm search <query> [--limit <n>]
230+
openclaw ltm search <query> [--limit <n>] [--scope <slug>]
217231
openclaw ltm stats
218232
```
219233

@@ -233,11 +247,53 @@ openclaw ltm query --filter "category = 'preference'" --order-by createdAt:desc
233247

234248
Agents get three tools from the active memory plugin:
235249

236-
- `memory_recall`: vector search over stored memories.
250+
- `memory_recall`: vector search over stored memories. Takes an optional `scope`
251+
to read one partition (see [Scope](#scope-partitioning-a-shared-store));
252+
unscoped, it reads global memories only.
237253
- `memory_store`: save a fact, preference, decision, or entity (rejects text
238254
that looks like a prompt-injection payload; skips near-duplicate stores).
255+
Prefix the text with `[SCOPE:<slug>]` to partition the memory.
239256
- `memory_forget`: delete by `memoryId`, or by `query` (auto-deletes a single
240-
match above 90% score, otherwise lists candidate IDs to disambiguate).
257+
match above 90% score, otherwise lists candidate IDs to disambiguate). Takes an
258+
optional `scope`; unscoped, it only deletes global memories, and a `memoryId`
259+
delete is fenced to the target row's scope.
260+
261+
## Scope (partitioning a shared store)
262+
263+
By default every memory is **global**: visible to recall, auto-recall, and forget
264+
across the whole store. A memory can instead be tagged with an opaque **scope** —
265+
a partition key such as a project, person, channel, or tenant — so it is only
266+
visible to operations that ask for that scope. This partitions one shared store
267+
without splitting it into a separate store per context.
268+
269+
- **Tagging.** Prefix the stored text with `[SCOPE:<slug>]` (via the
270+
`memory_store` tool or a tagged user message). The tag is parsed into a `scope`
271+
column and stripped before embedding, so the vector reflects the fact, not the
272+
prefix, and the tag is never echoed back on recall. A scope key must be a slug
273+
matching `[A-Za-z0-9_-]+`; a tag whose key is not a valid slug (for example a
274+
raw channel/room id with punctuation) is **rejected**, not silently stored
275+
global — map it to a slug first. A tag with no text after it (`[SCOPE:<slug>]`
276+
alone) is likewise rejected on store and skipped on auto-capture, so the control
277+
tag is never embedded or persisted as a memory on its own.
278+
- **Scoped vs unscoped recall.** `memory_recall` takes an optional `scope`. A
279+
scoped call returns that scope's matches first, with global rows filling the
280+
rest (scope and global are retrieved in separate vector passes so strong global
281+
neighbors cannot crowd the scope out). An unscoped call returns global rows
282+
only, so a scoped memory never surfaces in a plain recall.
283+
- **Scoped vs unscoped forget.** `memory_forget` takes the same `scope`. A scoped
284+
forget only deletes within that scope; an unscoped forget only deletes global
285+
rows. This holds for both delete paths: a `query` forget filters by scope, and a
286+
`memoryId` forget is fenced by first checking the target row's scope — so a
287+
known id from another partition cannot bypass it.
288+
- **Automatic recall is global-only.** The `before_prompt_build` auto-recall has
289+
no active-scope signal, so it injects only global/untagged memories; a scoped
290+
memory is never auto-recalled into an unrelated turn.
291+
- **CLI search mirrors the tool.** `ltm search` is global-only by default; pass
292+
`--scope <slug>` to vector-search within one partition. Unscoped, it never scans
293+
across partitions, so scoped rows do not leak into a plain `ltm search`.
294+
295+
Scope is behavior-preserving until you use it: pre-existing rows migrate to an
296+
empty (global) scope, and installs that never tag a memory see no change.
241297

242298
## Storage
243299

‎extensions/memory-lancedb/config.ts‎

Lines changed: 52 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;
@@ -152,6 +155,9 @@ export const memoryConfigSchema = {
152155
"customTriggers",
153156
"recallMaxChars",
154157
"storageOptions",
158+
"recallMinScore",
159+
"recallResultCap",
160+
"autoRecallOverfetch",
155161
],
156162
"memory config",
157163
);
@@ -186,6 +192,31 @@ export const memoryConfigSchema = {
186192
max: 10_000,
187193
label: "recallMaxChars",
188194
});
195+
const recallMinScore = ((): number => {
196+
if (cfg.recallMinScore === undefined) {
197+
return 0.3;
198+
}
199+
const parsed =
200+
typeof cfg.recallMinScore === "number" ? parseFiniteNumber(cfg.recallMinScore) : undefined;
201+
if (parsed === undefined || parsed < 0 || parsed > 1) {
202+
throw new Error("recallMinScore must be a number between 0 and 1");
203+
}
204+
return parsed;
205+
})();
206+
const recallResultCap = resolveBoundedIntegerConfig({
207+
value: cfg.recallResultCap,
208+
fallback: 3,
209+
min: 1,
210+
max: 50,
211+
label: "recallResultCap",
212+
});
213+
const autoRecallOverfetch = resolveBoundedIntegerConfig({
214+
value: cfg.autoRecallOverfetch,
215+
fallback: 10,
216+
min: 1,
217+
max: 200,
218+
label: "autoRecallOverfetch",
219+
});
189220
let customTriggers: string[] | undefined;
190221
if (cfg.customTriggers !== undefined) {
191222
if (!Array.isArray(cfg.customTriggers)) {
@@ -251,6 +282,9 @@ export const memoryConfigSchema = {
251282
captureMaxChars,
252283
...(customTriggers ? { customTriggers } : {}),
253284
recallMaxChars,
285+
recallMinScore,
286+
recallResultCap,
287+
autoRecallOverfetch,
254288
...(storageOptions ? { storageOptions } : {}),
255289
};
256290
},
@@ -314,6 +348,24 @@ export const memoryConfigSchema = {
314348
advanced: true,
315349
placeholder: String(DEFAULT_RECALL_MAX_CHARS),
316350
},
351+
recallMinScore: {
352+
label: "Recall Min Score",
353+
help: "Minimum similarity (0-1) for a memory to be eligible for auto-recall injection. Higher = stricter.",
354+
advanced: true,
355+
placeholder: "0.3",
356+
},
357+
recallResultCap: {
358+
label: "Recall Result Cap",
359+
help: "Maximum number of memories auto-recall injects into context.",
360+
advanced: true,
361+
placeholder: "3",
362+
},
363+
autoRecallOverfetch: {
364+
label: "Auto-Recall Overfetch",
365+
help: "Candidates fetched before sludge-filtering and capping. Keep a few multiples above the result cap.",
366+
advanced: true,
367+
placeholder: "10",
368+
},
317369
storageOptions: {
318370
label: "Storage Options",
319371
sensitive: true,

0 commit comments

Comments
 (0)