Repository navigation
feat(memory-lancedb): scope memory_recall and memory_forget + configurable thresholds - #102966
jgrandguillaume wants to merge 1 commit into
Conversation
|
Codex review: needs real behavior proof before merge. Reviewed July 15, 2026, 11:59 PM ET / July 16, 2026, 03:59 UTC. Summary PR surface: Source +374, Tests +1472, Docs +58. Total +1904 across 6 files. Reproducibility: not applicable. as a strict bug reproduction; current source clearly shows global-only storage and unfiltered vector operations, while this PR proposes a new partitioning mode and configuration contract. Review metrics: 3 noteworthy metrics.
Stored data model Merge readiness Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch. Rank-up moves:
Proof guidance:
Risk before merge
Maintainer options:
Next step before merge
Maintainer decision needed
Security Review findings
Review detailsBest possible solution: Use one canonical scope model: either keep multi-scope behavior in the existing external plugin, or explicitly sponsor bundled support with a trusted session-derived scope contract, rollback-safe schema evolution, and end-to-end live plugin proof. Do we have a high-confidence way to reproduce the issue? Not applicable as a strict bug reproduction; current source clearly shows global-only storage and unfiltered vector operations, while this PR proposes a new partitioning mode and configuration contract. Is this the best way to solve the issue? No, not yet: an existing maintained plugin already supplies multi-scope isolation, and the proposed caller-defined scope is not bound to trusted runtime identity. If bundled parity is sponsored, it should use rollback-safe schema evolution and end-to-end plugin proof. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against de3f7925c4c3. Label changesLabel changes:
Label justifications:
Evidence reviewedPR surface: Source +374, Tests +1472, Docs +58. Total +1904 across 6 files. View PR surface stats
What I checked:
Likely related people:
What the crustacean ranks mean
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics. How this review workflow works
Review history (2 earlier review cycles)
|
663a8b3 to
cb5f012
Compare
cb5f012 to
6b7f973
Compare
…rable 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]>
6b7f973 to
2ceb44b
Compare
|
@clawsweeper re-review Since the last review the |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-run The previous re-review run ( |
|
Closing in favor of a clean re-open on current |
|
Superseding PR: #108782 |
What Problem This Solves
When several contexts share a single LanceDB memory store, the explicit memory
tools operate across the entire store with no way to constrain them to a
subset:
memory_recallselects the top-K nearest vectors globally, so a memory writtenin one context can surface as a recall result in an unrelated one.
memory_forget(query mode) runs an unfiltered vector search and auto-deletes alone high-confidence match — so once the same fact exists in more than one
context, it can delete the wrong context's copy.
turn, with no way to keep one context's memories out of an unrelated
conversation.
Splitting into a separate store per context is the only current workaround, which
defeats the point of a shared store. Two smaller gaps compound this:
contexts is rejected as a duplicate on the second write, so it can never be
recalled within the second context.
auto-recall over-fetch), so operators cannot tune precision/recall for their
own data without editing the plugin source.
Why This Change Was Made
Add an optional per-row scope column and apply a native LanceDB
.where()prefilter in the explicit memory tools, so results are constrained to the
requested scope before the vector search returns — no separate store per context
needed.
.where()is a native LanceDB primitive the plugin already uses on the--filterCLI path but not on these tools.Scope is an opaque partition key, not a fixed concept. It is whatever the
caller wants to partition by — a project, a person, a channel, a tenant. The
plugin never interprets it: a memory is tagged by prefixing its text with
[SCOPE:<value>], and both tools take ascopeparameter. The tag is a routingprefix, not part of the fact: it is parsed into the
scopecolumn and strippedfrom the text before embedding and storing (in both the explicit store tool and
the auto-capture path), so the vector reflects the content rather than the
synthetic prefix and the tag is never echoed back to the model on recall. A scope
key is a slug (
[A-Za-z0-9_-]+); a tag orscopeargument whose key is not a validslug is rejected rather than silently transformed, so a punctuated key (e.g. a
raw channel/room id) can never be canonicalized into — and mixed with — another
partition, nor silently stored global. OpenClaw builds the
.where()clauseinternally from the validated slug — no raw filter expression is ever 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 — it never surfaces in an
unscoped recall, is never auto-recalled into an unrelated session, and can never be
deleted by an unscoped forget. The three read/delete paths:
memory_recall— a scoped call returns that scope's matches first, withuntagged/global rows filling any remaining slots; the scope and the global rows
are retrieved in separate ANN passes (each with its own candidate budget) so
many strong global neighbors cannot crowd the requested scope out of a shared
top-K and make the call miss rows from the very scope it asked for. An unscoped
call is global-only (
scope = '' OR scope IS NULL) — scoped rows stayhidden.
memory_forget— a scoped call is restricted to the exact scope(
scope = '…'); an unscoped call is global-only. This holds for bothdelete paths: a query forget filters by scope, and a memoryId forget is
fenced by first checking the target row's scope — a scoped row can only be deleted
from within its scope, and an unscoped
memoryIddelete only removes global rows— so a known id from another partition cannot bypass the fence.
active-scope signal, so it injects only untagged/global memories; a scoped memory
is never auto-recalled into an unrelated session.
Scope is threaded consistently so it cannot silently mis-behave:
.where()prefilter before the near-exact top-K, so a duplicate only countswithin 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.
scopecolumn to pre-existing tables(guarded on the driver's
schema()/addColumns; a no-op for partial testdoubles), preserving existing rows and vectors.
The recall thresholds are surfaced as configuration (with matching manifest
uiHints, so they appear in setup/config flows) with defaults equal to thepreviously hardcoded values. They are threaded through the live-config merge so
operator values take effect in the before-prompt hook, not only at startup.
What is deferred (explicit non-goal). This PR 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: the automatic path is restricted to global/untagged memories, so a
scoped memory is never auto-injected anywhere. Scope-targeted auto-injection
(surfacing
scope=alphamemories inside an alpha turn) is future work; the scopecolumn and
.where()prefilter added here are the foundation a later change canbuild on once such a signal is available at that hook.
Security model — scope is a partition primitive, not a trust boundary. The
scopevalue is caller-supplied (ascopeargument, or a[SCOPE:<value>]tag inthe text), and OpenClaw deliberately does not bind it to a session/channel
identity: the partition key is caller-defined (a project, a person, a tenant), and
only the caller knows which partition a given turn belongs to. This does not weaken
the current model — today every memory is global, so any turn can already recall,
forget, or write any memory. Scope only adds isolation: a tagged row is hidden
from unscoped operations, so a caller that supplies a consistent scope gains
partitioning it did not have before, and no caller gains a capability it lacked.
Treating a scope as an enforced boundary between mutually-distrusting callers
(checking the requested scope against a trusted active-session signal before every
read/write/delete) is a deployment policy layered on top of this primitive, and is
deferred to the same future work as scope-targeted auto-injection — the
scopecolumn and
.where()prefilter added here are exactly the mechanism such a policywould build on.
The change is behavior-preserving until you tag a memory: 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, and thresholds default to today's
values. A memory becomes partitioned only when it is explicitly tagged
[SCOPE:<value>](via the store tool or a tagged user message) — at which point itis hidden from unscoped and other-scope operations by design. Installs that never
use scope tags see no change at all.
User Impact
recall, never auto-recalled into an unrelated session, and cannot be deleted by
an unscoped forget — real isolation without splitting into multiple stores.
scopetomemory_recallto read one partition (project,person, channel, …): that scope's memories are returned first and untagged/global
ones fill any remaining slots, and a scope with many strong global neighbors is
no longer crowded out of the results.
scopetomemory_forgetto delete safely within onepartition: a scoped forget can never remove a global or other-scope copy of
the same fact, and this fence applies to both the
queryand thememoryIddelete paths (a known id from another partition cannot bypass it).
[A-Za-z0-9_-]+slug) is rejected, not silentlystored global — a punctuated key such as a raw channel/room id cannot leak an
intended-scoped memory into the global partition.
being swallowed as a duplicate.
recallMinScore,recallResultCap,autoRecallOverfetch) instead of requiring a source edit.unscoped recall, forget, and the automatic before-prompt injection behave exactly
as before.
Evidence
Real-behavior proof (real
@lancedb/lancedbdriver, on-disk table)The unit tests mock the LanceDB driver, so the two things they cannot show are the
schema migration and the native prefilter running against the real engine.
The script below drives the real pinned
@lancedb/lancedb(no mock) on a realon-disk table, replaying
MemoryDB's exact persistence operations — the self-healmigration (
schema()→addColumns), the scoped/unscoped.where()recall, andthe scoped delete. Deterministic vectors, no embeddings/network; the only scope
slug is the fictional
demo-shop_euand all memory text is generic.The scoped row (
c) is deliberately given the same nearest vector as a globalrow (
a), so only a real prefilter — not distance ranking — can keep it out of theunscoped recall. The migrated
scopecolumn is non-nullable and defaults to'',so pre-existing rows become global while their vectors are preserved (the
OR scope IS NULLbranch is a defensive belt-and-suspenders for any externallyNULL rows).
Reproducible standalone script (drop at repo root,
node _scope-proof.mjs)Automated checks
pnpm tsgo:extensionsandpnpm tsgo:extensions:testbothexit 0 with no errors.
pnpm test:extension memory-lancedb— 149 tests passing, including fourteenregression tests:
[SCOPE:<value>]tag is captured verbatim (a value with hyphens andunderscores is not truncated and mis-scoped) and is stripped from the
embedded input and the stored text, so the vector reflects the fact and the
tag is not echoed back on recall;
same-scope and global-vs-global writes still dedup;
is still detected even when many other scopes share a near-identical vector;
memory_recallprioritizes its scope — the requested scope's row isreturned (and ranked first) even behind many strong global matches that
would otherwise fill the candidate window;
memory_recallis global-only — a scoped row never surfacesin a plain recall;
memory_forgetdeletes only within its scope — the same fact undera different scope survives;
memory_forgetis global-only — it cannot nominate or deletea scoped row from another partition;
auto-recalled into an unrelated session;
autoRecallOverfetch/recallMinScorereaches the before-prompt auto-recallinstead of silently falling back to the defaults;
memory_storetag whose key is not a slug (e.g. a punctuated channel id)is rejected — an intended-scoped memory never silently falls back to the
global partition;
memory_forgetbymemoryIdis fenced to the row's scope — a scoped rowis not deleted by an unscoped or mismatched-scope call, while a matching
scope (or a global row) deletes as expected;
[SCOPE:<value>]store (no text after the tag) is rejected,and auto-capture skips it — the bare control tag is never embedded or
persisted as a memory on its own;
ltm searchis global-only by default and honors--scope <slug>— the CLInever scans across partitions unless a scope is explicitly requested, and a
non-slug
--scopekey is rejected.[SCOPE:<slug>]message whose fact fits undercaptureMaxCharsis capturedeven when the routing tag makes the raw string exceed the limit, so a long tag
can no longer flip a message's memory-worthiness; the tag is stripped before
the capture heuristics run, then the fact is embedded and stored under its
scope.
main. Thememory_storesuccess string appliesmain'sUTF-16-safe
truncateUtf16Safe(...)helper to the scope-stripped text(
truncateUtf16Safe(memoryText, 100)), so bothmain's UTF-16 fix and this PR'stag-strip hold;
pnpm check:no-conflict-markerspasses and no raw.slice(0, N)truncation remains on memory text.
main's tightened quality gates in the extensions lane: thenewly-enforced
noUncheckedIndexedAccess(the[SCOPE:<value>]capture-groupreads and one test batch access are guarded with the SDK's
expectDefined,matching
main's idiom), the oxlint rules (no-map-spread,curly, and thetype-aware
restrict-template-expressions/no-unnecessary-type-conversion,reproduced locally with the
--tsconfigshard config CI runs), and thezero-
any-cast type-suppression inventory (the added test mocks were reworked todrop every
as any).pnpm tsgo:extensions,pnpm tsgo:extensions:test, theextensions lint shard, and the type-suppression-inventory test are all green for
this plugin's files.
ltm searchCLI was the onlydb.searchcaller left without a scope filter, so a table-wide scan could exposescoped rows — it is now global-only by default with an opt-in
--scope <slug>,mirroring
memory_recall; (2) a tag-only[SCOPE:<value>]payload used to fallback to storing the raw text (embedding the control tag itself) — it is now
rejected on store and skipped on auto-capture. Both are covered by the new
regression tests (12–13 above).
auto-capture payload that is empty or whitespace-only after the tag is stripped
is rejected (never embedded as a blank memory), and auto-capture now runs its
capture heuristics on the stripped text, so the routing tag's length cannot
change a message's eligibility. Covered by regression test 14 (and the existing
tag-only test 12).
docs/plugins/memory-lancedb.md): a new Scope section (tag /slug shape, global-vs-scoped recall and forget,
memoryIdfence, global-onlyauto-recall, and the
ltm search --scopebehavior) plus a Recall selectivitytable for the three new settings, with
docs/docs_map.mdregenerated for the newheadings;
pnpm format:docs:check,docs:map:check, the MDX check, and theinternal-link check all pass.
Prepared with AI assistance.