Repository navigation
feat(memory-lancedb): scope memory_recall and memory_forget in a shared store - #108782
jgrandguillaume wants to merge 1 commit into
Conversation
|
Codex review: blocked before merge. Reviewed September 26, 2026, 9:46 PM ET / September 27, 2026, 01:46 UTC (Revision 24). ClawSweeper reviewWhat this changesThe branch adds caller-selected partitions to the LanceDB memory plugin’s storage, recall, forget, command-line inspection, Doctor migration, tests, and documentation. Warning SQLite table change This PR modifies persisted SQLite tables in Merge readiness⛔ Blocked before merge - 7 items remain The partitioning feature remains absent from current main and the branch has substantial, well-proven unique work. Keep this PR open, but the documented scope filter is rejected by the CLI, two smaller prior findings remain, the branch conflicts with main, and the caller-selected partition contract still needs an owner decision. Priority: P2 Review scores
Verification
How this fits togetherThe LanceDB memory plugin receives facts and recall requests from an agent, stores vectors, and returns memories to tools or prompt construction. Doctor repairs older tables before partitioned storage is enabled. flowchart LR
A[Agent facts and requests] --> B[Memory plugin]
B --> C[Validate scope]
C --> D[LanceDB rows]
D --> E[Scoped recall and forget]
E --> F[Tool and prompt results]
G[Doctor migration] --> D
Decision needed
Why: The code and docs deliberately make scope non-authorizing, while tagged memories change what automatic recall can see; accepting that user-facing contract requires product ownership. Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +531, Tests +1082, Docs +76. Total +1689 across 11 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Ship one owner-approved partition contract in which tools and CLI agree on scope filtering, legacy tables remain usable until explicit Doctor repair, and the rebased branch preserves current memory-plugin behavior. Do we have a high-confidence way to reproduce the issue? Not applicable to the feature request. The remaining CLI defect is source-reproducible: the documented scope filter cannot match the parser’s fixed five-column grammar. Is this the best way to solve the issue? No, not yet. Plugin-owned partitioning and Doctor migration fit the existing boundary, but the CLI contract must be made consistent and the organizational-scope behavior needs owner approval. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 26497820f8b9. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (23 earlier review cycles; latest 8 shown)
|
081d8d6 to
ed13a97
Compare
|
Following up on the review's maintainer options — executed the recommended split (option 2) so the two contracts can be decided independently:
On risk P1 #4 (scoped rows not participating in automatic recall): that gap is planned follow-up work — speaker/channel-aware auto-recall driven by the hook context's sender identity, opt-in and fail-safe when the speaker is unresolvable. It builds on this PR's scope column and prefilter, so it is sequenced after this design decision rather than folded in here. |
ed13a97 to
d729127
Compare
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 (openclaw#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]>
|
Addressed the review's rank-up move: the scope-column migration now goes through the plugin doctor instead of runtime self-healing, mirroring the On the remaining P1s: scoped rows staying out of automatic recall, and scope not being a trust boundary, are the documented fail-safe non-goals — speaker/channel-aware auto-recall driven by the hook context's sender identity is the planned follow-up — and both remain for the product decision routed above. @clawsweeper re-review |
d729127 to
02d1df5
Compare
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
02d1df5 to
a2464c8
Compare
|
Addressed the released-schema upgrade finding: scope detection no longer waits for the @clawsweeper re-review |
c8134ed to
db513f1
Compare
|
Rebased on current
No behavior change beyond re-composing with those two features. Full battery re-run on this head: extension suite 200/200, type-aware lint/type checks clean, and the plugin-boundary proof (real plugin module, real Doctor entries, real tools + hook, real on-disk tables, local HTTP embedding endpoint) passes all checks — the PR body is updated accordingly. @lonexreb @steipete — gentle ping on the partition-contract decision from last week (ship the caller-selected, non-authorizing scope partitions, or park the PR). Happy to adjust either way; I'll keep the branch conflict-free in the meantime. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
db513f1 to
d2a9e40
Compare
d2a9e40 to
746a2a3
Compare
|
Thanks — the 05:57 UTC review caught the branch mid-rebase: the reviewed head The current head
Full battery on this head: extension suite 202/202 (including main's new revocation and length-gate tests), type-aware lint and both type lanes clean, dead-code check clean, and the plugin-boundary proof (real plugin module, real Doctor entries, real tools + hook, on-disk tables, local HTTP embedding endpoint) passes all checks. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
The single red lane ( @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
…ed store Within one agent's LanceDB memory store the memory tools operate store-wide: memory_recall returns nearest vectors from every context the agent serves, and a query-mode memory_forget can auto-delete another context's copy of a duplicated fact. Add an optional per-row scope column applied as a native .where() prefilter in both tools, so one agent's shared store can be partitioned without splitting it. This builds on the per-agent isolation from single .where() clause (via the same quoteLanceSqlString helpers), and scope partitions WITHIN one agent's rows — it never crosses the agent boundary. Scope is an opaque partition key (project, person, channel, ...) and an organizational retrieval partition, not an authorization boundary: the key is caller-selected, so the docs state it must not be relied on to isolate untrusted callers, and the scope-blind ltm list/query/stats commands are documented as intentional operator inspection paths (ltm search mirrors the tool contract with an opt-in --scope flag). A memory is tagged by prefixing its text with [SCOPE:<slug>]; the tag is parsed into the scope column and stripped before embedding and storing, on both the store tool and the auto-capture path (capture heuristics run on the stripped text; a tag-only or whitespace-only payload is rejected). Keys must match [A-Za-z0-9_-]+; anything else is rejected rather than silently stored global. Predicates are built inside the store from the validated slug — no raw filter expression is accepted from callers. Scope acts as a partition, not a label: scoped recall returns its scope first (scope and global fetched in separate ANN passes, so strong global neighbors cannot crowd the scope out of a shared top-K) while unscoped recall, before-prompt auto-recall, and unscoped `ltm search` are global-only. memory_forget is fenced on both delete paths: query forgets filter by scope, and a memoryId forget checks the target row's scope first (agent-fenced lookup). Duplicate detection prefilters by scope, so the same fact can coexist under different scopes. Operators can see and target partitions: ltm list/query/search report each row's scope key, scope is a selectable and filterable ltm query column, and ltm stats reports the scoped/global split (on a pre-scope table the absent column is dropped from query output and a scope filter is refused with the Doctor pointer). Existing tables gain the scope column through the plugin doctor only: the migration is marked doctorOnly (the gate the legacy-envelope cleanup uses), so ordinary config preflight never collects it and never mutates an existing store — explicit `openclaw doctor --fix` previews, applies, and verifies it. Until that runs, a pre-scope table keeps working in legacy mode: every row is global, unscoped operations behave exactly as before the column existed, scoped reads match nothing, and only a scoped write is refused (storing it global would silently mis-scope it) — so upgrades never interrupt an existing store. The memory_store tool surfaces that refusal with the Doctor pointer, while auto-capture records and skips the tagged message and keeps walking its batch, so later global captures still land and the capture cursor still advances. Doctor inventories every plan before applying any, so a table from a release predating per-agent isolation gains both columns in a single doctor pass (agentId first, by migration order). Behavior-preserving until a memory is tagged: pre-existing rows stay global and unscoped behavior is unchanged, with no operator action required at upgrade. Scope-targeted auto-injection is deferred — the hook has no active-scope signal, so it fails safe to global-only. The scope policy helpers live in memory-policy.ts and the CLI flag in memory-cli.ts, following the plugin's module split. The scope filter composes with the store's newer contracts: search keeps the native query-timeout executionOptions and the deadline flows through both ANN passes of scoped recall; the receipt-backed exact-text duplicate check runs within the scope partition, so "already stored" receipts stay truthful per partition (the same fact may intentionally coexist under different scopes); the retained-tool enablement assertions stay first in every tool body; and the store's capture-length gate applies to the stored (tag-stripped) text, so the routing tag never pushes an otherwise-valid fact over the limit. Tests: 16 scope regression tests — mock-level tool/hook coverage plus real-driver store, CLI contract, and doctor coverage (legacy-mode upgrade safety incl. the auto-capture batch skip, operator scope visibility, doctor-only gating with an automatic-preflight-vs-explicit-repair split, agent-isolated upgrade, and a one-pass released-table upgrade). Extension suite 203/203. Docs: scope contract (non-authorizing, operator CLI bypass, legacy mode, doctor-only migration) documented in docs/plugins/memory-lancedb.md. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Both P2 findings are fixed on head 1. Legacy scoped-store refusal no longer stalls the capture batch. The refusal is now a named, discriminable state ( 2. Operator inspection now exposes the partition key. Suite 203/203, assertion-safety ratchet, type-aware lint, both type lanes, dead-code check, and the plugin-boundary proof all green on this head. The PR body is updated (sixteen regression tests). @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Note on the red Happy to rebase to re-run CI if a maintainer prefers, but I'm leaving the head as-is for now so the current ClawSweeper verdict (platinum hermit, no actionable findings, reviewed at exactly this sha) stays attached to the reviewed code. |
|
This pull request has been automatically marked as stale due to inactivity. |
|
Closing due to inactivity. |
Supersedes #102966 (closed: re-opened cleanly on current
main; the bot reviewstate there was stale and could not be refreshed). Following this PR's review
recommendation, the recall-threshold configurability was split into
#109283 — this PR now carries the partitioning contract only.
What Problem This Solves
#103799 isolates memories between agents. Within one agent's store, the
memory tools are still store-wide across every context that agent serves
(projects, people, channels):
memory_recallreturns the top-K nearest vectors from every context.memory_forget(query mode) runs a scope-blind search and can auto-deleteanother context's copy of a duplicated fact.
two contexts.
The only workaround is one store per context, which defeats a shared store.
What This Does
Adds an optional per-row
scopecolumn applied as a native LanceDB.where()prefilter in both tools. Every scope predicate composes withthe mandatory
agentIdfence from #103799 into a single.where()clause,built by the same
lancedb-schema.tshelpers (quoteLanceSqlString) — scopepartitions within one agent's rows and never crosses the agent boundary.
[SCOPE:<slug>]text prefix, orpass
scopeto the tools. The tag is stripped before embedding/storing (storetool and auto-capture; capture heuristics run on the stripped text, and a
tag-only payload is rejected). Non-slug keys (
[A-Za-z0-9_-]+) are rejected,never silently stored global. Predicates are built inside the store from the
validated slug — no raw filter expressions from callers.
global fetched in separate ANN passes, so strong global neighbors can't crowd
the scope out); unscoped recall, before-prompt auto-recall, and unscoped
ltm searchare global-only (--scopeis opt-in). Forget is fenced on boththe query and
memoryIdpaths. Dedup prefilters by scope, so the same factcan coexist under different scopes.
latest two rounds): the
memory-lancedb-scope-columnentry setsdoctorOnly: true— the same gate the legacy-envelope cleanup uses — soordinary config preflight never collects it and never mutates an existing
store; only explicit
openclaw doctor --fixpreviews, applies (addColumnswith a safe global default
''), and verifies it. Until that runs, apre-existing table keeps working in legacy mode: all rows are global,
unscoped recall/forget/capture and the CLI behave exactly as before this
feature, scoped reads match nothing (no partitioned rows can exist), and
only a scoped write is refused — storing it global would silently
mis-scope it. The
memory_storetool surfaces that refusal with a Doctorpointer; auto-capture records and skips the tagged message and keeps
walking its batch, so later global captures still land and the capture
cursor still advances past it. An upgrade therefore never takes an existing
store offline and requires no operator action unless partitions are wanted.
Detection is independent of the
agentIdentry (doctor inventories everyplan before applying any), so a released table missing both columns is
fully upgraded in a single doctor pass —
agentIdfirst by migration order,then
scope. Real-driver coverage runs the collector's selection rule bothways: the automatic (non-doctor-only) subset leaves the schema untouched,
then explicit repair applies and verifies.
Behavior-preserving until you tag: pre-existing rows stay global; installs
that never use scope tags see no change, and upgrading over an existing store
requires no operator action (legacy mode above).
Non-goal: scope-targeted auto-injection. The before-prompt hook has no
active-scope signal, so it fails safe to global-only; this PR is the foundation
for that follow-up.
Security model (adopting the review's recommended contract): scope is an
organizational retrieval partition, not access control. The key is
caller-selected — supplied by tool arguments or tagged text, not derived from a
trusted session identity — so the docs now open the scope section with exactly
that warning, use no tenant-flavored examples, and document the
ltm list/ltm query/ltm statscommands as intentional operatorinspection paths: they cover all partitions, and each row they return
carries its
scopekey so an operator can discover and then target apartition (
scopeis a selectable/filterableltm querycolumn;ltm statsreports the scoped/global split;
ltm searchmirrors the tool contract withopt-in
--scopeand reportsscopeper result). Today every memory isalready global to all callers, so scope only
adds isolation; binding scopes to a trusted session identity is deferred with
the same follow-up as scope-targeted auto-injection.
User Impact
never auto-recalled into an unrelated session, not deletable by an unscoped
forget.
scopeonmemory_recall/memory_forgetreads or deletes within onepartition safely; invalid keys are rejected instead of leaking to global.
duplicate.
interruption: an existing store stays fully usable;
openclaw doctor --fixis only needed to enable partitions.
searchkeeps the nativequery-timeout
executionOptions(fix(memory-lancedb): stop timed-out recall before returning results #124143) — the deadline flows through bothANN passes of scoped recall; the receipt-backed exact-text duplicate check
(fix(memory): make persistence promises receipt-backed #120989) runs within the scope partition, so "already stored" receipts
stay truthful per partition; the retained-tool enablement assertions
(fix(memory): stop retained tools after memory is disabled #125393) stay first in every tool body; and the store's capture-length gate
(fix(memory): bound LanceDB prompts and reload embedding config #125567) applies to the stored (tag-stripped) text, so the routing tag
never pushes an otherwise-valid fact over the limit.
Evidence
Real-behavior proof through the patched plugin boundary — no mocks, run on
this head: the real plugin module (imported via
tsx), the real DoctorstateMigrationsentries, the realmemory_store/memory_recall/memory_forgettools, and the realbefore_prompt_buildhook, againstreal on-disk
@lancedb/lancedbtables, with embeddings served by a localOpenAI-compatible HTTP endpoint (deterministic vectors; the scoped memory
shares the exact vector of the nearest global memory, so only the prefilter —
never distance ranking — can separate them). Three parts:
selection adds
agentIdbut notscope(thedoctorOnlygate,observed through the real entries); explicit repair then previews, applies,
and verifies the scope migration in the same doctor pass, and every
re-detect is clean.
[SCOPE:demo-shop_eu]store has itstag stripped and the scope column set (verified by reading the row back);
a non-slug key is rejected; unscoped recall hides the scoped row despite an
identical nearest vector; scoped recall returns it first; a
memoryIdforget is blocked cross-scope and allowed in-scope; the auto-recall block
contains only global memories.
global store work with no Doctor run, a scoped write is refused with the
Doctor pointer, and the table's schema is never mutated at runtime.
The only slug is the fictional
demo-shop_eu; no network beyond the localendpoint (8 real HTTP embedding requests).
Proof transcript + reproducible script (drop at repo root,
node_modules/.bin/tsx _proof-boundary.mts)Automated checks — on this head: type-aware oxlint for the extension
(clean),
tsgoprod + test lanes (no errors inmemory-lancedbfiles; thelanes' remaining errors are pre-existing in unrelated extensions on unmodified
main), the type-suppression inventory (noanycasts),oxfmtformatcheck, the docs format/MDX checks, and
pnpm test:extension memory-lancedb— 203/203, including the sixteenscope regression tests below.
The sixteen regression tests
Mock-level (tool and hook contracts,
index.test.ts):[SCOPE:<slug>]is captured verbatim (hyphens/underscores intact) andstripped from the embedded input and stored text; untagged stores stay
global.
no silent global fallback, no embedded control tag.
same-scope and global-vs-global writes still dedup.
detected even among many near-identical other-scope vectors.
global matches; unscoped recall is global-only; non-slug scope keys are
rejected.
global-only; invalid keys are rejected before any search.
memoryIdforget is fenced to the target row's scope (blocked unscopedand cross-scope, allowed in-scope).
skips invalid keys and tag-only payloads, and stores the stripped text
with its scope.
before_prompt_build) injects only global memories andsearches with the global-only predicate.
capture, still stores later global captures in the same batch (pre-scope
row shape), and advances the cursor past the tagged message.
Real-driver (
lancedb-store.test.ts):global writes behave exactly as before the feature, scoped reads match
nothing, and only a scoped write is refused with a Doctor pointer (no
runtime mutation). Operator inspection keeps working:
listreports everyrow as global,
querydrops the absentscopecolumn from output andrefuses a
scopefilter with the Doctor pointer, and the scoped countis zero.
""= global-only, slug = that partition,no argument = agent-wide),
getScopeByIdis agent-fenced, and operatorinspection exposes the partition key (
listcarriesscopeper row,queryselects and filters on it, the stats split counts scoped rows).CLI contract (
memory-cli.test.ts):ltm searchis global-only by default and passes--scopethrough to thestore's prefilter.
--scopeis rejected before any embedding is generated.Real-driver doctor (
doctor-contract-api.test.ts):doctorOnly: true; running the automatic(non-doctor-only) subset leaves the schema untouched, then explicit
repair previews, applies, and verifies — rows stay global.
agentIdandscopeis upgraded in onedoctor pass (both plans detected in the same inventory, applied in order
without re-detection).
What To Review
lancedb-store.ts(search,getScopeById) andthe
memoryScopePredicatehelper inlancedb-schema.ts: agent isolation mustnever be lost when a scope filter joins it.
extensions/memory-lancedb/index.ts: unscopedrecall / forget / auto-recall are global-only; the
memoryIdforget checksthe target row's scope before deleting. The scope policy helpers (tag/arg
parsing, scoped-priority retrieval, capture eligibility) live in
memory-policy.ts, following the plugin's module split.memory-lancedb-scope-columndoctor entry indoctor-contract-api.ts:doctorOnly: truegating (preflight never mutates), detect/migrate/verify,detection independent of the
agentIdentry so one doctor pass upgradesreleased tables — and the store's legacy mode (
lancedb-store.ts): apre-scope table stays fully usable, with only scoped writes refused.
docs/plugins/memory-lancedb.md: the scope contract (non-authorizing,operator CLI bypass, doctor-only migration) matches the behavior.
Prepared with AI assistance.