Skip to content

feat(memory-lancedb): scope memory_recall and memory_forget + configurable thresholds - #102966

Closed
jgrandguillaume wants to merge 1 commit into
openclaw:mainfrom
jgrandguillaume:feat/memory-lancedb-scope
Closed

jgrandguillaume wants to merge 1 commit into
openclaw:mainfrom
jgrandguillaume:feat/memory-lancedb-scope

Conversation

@jgrandguillaume

@jgrandguillaume jgrandguillaume commented Jul 9, 2026 •

Copy link
Copy Markdown

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_recall selects the top-K nearest vectors globally, so a memory written
    in one context can surface as a recall result in an unrelated one.
  • memory_forget (query mode) runs an unfiltered vector search and auto-deletes a
    lone high-confidence match — so once the same fact exists in more than one
    context, it can delete the wrong context's copy.
  • The automatic before-prompt recall injects from the whole store on every
    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:

  • Duplicate detection is global. The same fact stored under two different
    contexts is rejected as a duplicate on the second write, so it can never be
    recalled within the second context.
  • Recall selectivity is hardcoded (minimum similarity score, result cap, and
    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
--filter CLI 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 a scope parameter. The tag is a routing
prefix, not part of the fact: it is parsed into the scope column and stripped
from 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 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 — and mixed with — another
partition, nor silently stored global. OpenClaw builds the .where() clause
internally 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, with
    untagged/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 stay
    hidden.
  • memory_forget — a scoped call is restricted to the exact scope
    (scope = '…'); an unscoped call is global-only. This holds for both
    delete 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 memoryId delete only removes global rows
    — so a known id from another partition cannot bypass the fence.
  • Automatic before-prompt recall — global-only. The hook has no
    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:

  • Duplicate detection is made 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 scope column to pre-existing tables
    (guarded on the driver's schema()/addColumns; a no-op for partial test
    doubles), 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 the
previously 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=alpha memories inside an alpha turn) is future work; the scope
column and .where() prefilter added here are the foundation a later change can
build on once such a signal is available at that hook.

Security model — scope is a partition primitive, not a trust boundary. The
scope value is caller-supplied (a scope argument, or a [SCOPE:<value>] tag in
the 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 scope
column and .where() prefilter added here are exactly the mechanism such a policy
would 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 it
is hidden from unscoped and other-scope operations by design. Installs that never
use scope tags see no change at all.

User Impact

  • A tagged memory is partitioned in a shared store: it is hidden from unscoped
    recall, never auto-recalled into an unrelated session, and cannot be deleted by
    an unscoped forget — real isolation without splitting into multiple stores.
  • Callers can pass scope to memory_recall to 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.
  • Callers can pass scope to memory_forget to delete safely within one
    partition
    : a scoped forget can never remove a global or other-scope copy of
    the same fact, and this fence applies to both the query and the memoryId
    delete paths (a known id from another partition cannot bypass it).
  • An invalid scope key (not a [A-Za-z0-9_-]+ slug) is rejected, not silently
    stored global — a punctuated key such as a raw channel/room id cannot leak an
    intended-scoped memory into the global partition.
  • The same fact can be stored under different scopes without the second write
    being swallowed as a duplicate.
  • Recall precision/recall is tunable via config (recallMinScore,
    recallResultCap, autoRecallOverfetch) instead of requiring a source edit.
  • No change until you use scope: with no scope tags, every row stays global —
    unscoped recall, forget, and the automatic before-prompt injection behave exactly
    as before.

Evidence

Real-behavior proof (real @lancedb/lancedb driver, 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 real
on-disk table, replaying MemoryDB's exact persistence operations — the self-heal
migration (schema() → addColumns), the scoped/unscoped .where() recall, and
the scoped delete. Deterministic vectors, no embeddings/network; the only scope
slug is the fictional demo-shop_eu and all memory text is generic.

temp store: /tmp/mldb-scope-proof-XXXXXX

PART 1 — migration on a pre-existing (legacy) table
  legacy columns: id, text, vector, importance, category, createdAt
  [PASS] legacy table has no 'scope' column
  [PASS] legacy table has no 'agent' column
  missing columns detected: ["scope","agent"]
  columns after migration: id, text, vector, importance, category, createdAt, scope, agent
  [PASS] 'scope' column added
  [PASS] 'agent' column added
  [PASS] both legacy rows preserved
  [PASS] row 'a' text preserved
  [PASS] row 'a' vector preserved (len + values)
  [PASS] migrated rows default to global scope ''

PART 2 — native .where() prefilter isolation
  scoped recall  where scope='demo-shop_eu' -> ids: [c]
  [PASS] scoped recall returns ONLY the scoped row (c)
  unscoped recall where scope=''/NULL   -> ids: [a,b]
  [PASS] unscoped recall returns ONLY global rows (a,b)
  [PASS] scoped row hidden from unscoped recall despite identical nearest vector

PART 3 — scoped delete is fenced to its scope
  rows after delete where scope='demo-shop_eu' -> ids: [a,b]
  [PASS] scoped delete removed the scoped row (c gone)
  [PASS] scoped delete preserved global rows (a,b remain)

=== RESULT: ALL CHECKS PASSED ===

The scoped row (c) is deliberately given the same nearest vector as a global
row (a), so only a real prefilter — not distance ranking — can keep it out of the
unscoped recall. The migrated scope column is non-nullable and defaults to '',
so pre-existing rows become global while their vectors are preserved (the
OR scope IS NULL branch is a defensive belt-and-suspenders for any externally
NULL rows).

Reproducible standalone script (drop at repo root, node _scope-proof.mjs)
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import * as lancedb from "@lancedb/lancedb";

const DIM = 8;
const near = Array.from({ length: DIM }, (_, i) => (i === 0 ? 1 : 0));
const far = Array.from({ length: DIM }, (_, i) => (i === DIM - 1 ? 1 : 0));
const query = near;

let failures = 0;
function check(label, cond) {
  console.log(`  [${cond ? "PASS" : "FAIL"}] ${label}`);
  if (!cond) failures++;
}
const ids = (rows) => rows.map((r) => r.id).sort().join(",");

const dir = await mkdtemp(join(tmpdir(), "mldb-scope-proof-"));
const TABLE = "memories";
console.log(`temp store: ${dir}\n`);

try {
  const db = await lancedb.connect(dir);

  console.log("PART 1 — migration on a pre-existing (legacy) table");
  await db.createTable(TABLE, [
    { id: "a", text: "prefers dark roast coffee", vector: near, importance: 1, category: "preference", createdAt: 1 },
    { id: "b", text: "team ships on fridays", vector: far, importance: 1, category: "fact", createdAt: 2 },
  ]);
  let tbl = await db.openTable(TABLE);

  const legacyCols = (await tbl.schema()).fields.map((f) => f.name);
  console.log(`  legacy columns: ${legacyCols.join(", ")}`);
  check("legacy table has no 'scope' column", !legacyCols.includes("scope"));
  check("legacy table has no 'agent' column", !legacyCols.includes("agent"));

  const existingNames = new Set((await tbl.schema()).fields.map((f) => f.name));
  const missing = ["scope", "agent"].filter((c) => !existingNames.has(c));
  console.log(`  missing columns detected: ${JSON.stringify(missing)}`);
  if (missing.length > 0) {
    await tbl.addColumns(missing.map((name) => ({ name, valueSql: "''" })));
  }

  const migratedCols = (await tbl.schema()).fields.map((f) => f.name);
  console.log(`  columns after migration: ${migratedCols.join(", ")}`);
  check("'scope' column added", migratedCols.includes("scope"));
  check("'agent' column added", migratedCols.includes("agent"));

  const migratedRows = await tbl.query().toArray();
  const rowA = migratedRows.find((r) => r.id === "a");
  const rowB = migratedRows.find((r) => r.id === "b");
  check("both legacy rows preserved", migratedRows.length === 2 && !!rowA && !!rowB);
  check("row 'a' text preserved", rowA?.text === "prefers dark roast coffee");
  check("row 'a' vector preserved (len + values)", Array.from(rowA?.vector ?? []).join(",") === near.join(","));
  check("migrated rows default to global scope ''", (rowA?.scope ?? "") === "" && (rowB?.scope ?? "") === "");

  console.log("\nPART 2 — native .where() prefilter isolation");
  // 'c' is scoped and shares the SAME (nearest) vector as global 'a', so only the
  // prefilter — not distance ranking — can keep it out of an unscoped recall.
  await tbl.add([
    { id: "c", text: "demo-shop_eu catalog prices are in EUR", vector: near, importance: 1, category: "fact", createdAt: 3, scope: "demo-shop_eu", agent: "" },
  ]);

  const scoped = await tbl.vectorSearch(query).where("scope = 'demo-shop_eu'").limit(5).toArray();
  console.log(`  scoped recall  where scope='demo-shop_eu' -> ids: [${ids(scoped)}]`);
  check("scoped recall returns ONLY the scoped row (c)", ids(scoped) === "c");

  const globalOnly = await tbl.vectorSearch(query).where("scope = '' OR scope IS NULL").limit(5).toArray();
  console.log(`  unscoped recall where scope=''/NULL   -> ids: [${ids(globalOnly)}]`);
  check("unscoped recall returns ONLY global rows (a,b)", ids(globalOnly) === "a,b");
  check("scoped row hidden from unscoped recall despite identical nearest vector", !ids(globalOnly).includes("c"));

  console.log("\nPART 3 — scoped delete is fenced to its scope");
  await tbl.delete("scope = 'demo-shop_eu'");
  const afterDelete = await tbl.query().toArray();
  console.log(`  rows after delete where scope='demo-shop_eu' -> ids: [${ids(afterDelete)}]`);
  check("scoped delete removed the scoped row (c gone)", !ids(afterDelete).includes("c"));
  check("scoped delete preserved global rows (a,b remain)", ids(afterDelete) === "a,b");

  console.log(`\n=== RESULT: ${failures === 0 ? "ALL CHECKS PASSED" : failures + " CHECK(S) FAILED"} ===`);
} finally {
  await rm(dir, { recursive: true, force: true });
}
process.exit(failures === 0 ? 0 : 1);

Automated checks

  • Type-check clean: pnpm tsgo:extensions and pnpm tsgo:extensions:test both
    exit 0 with no errors.
  • pnpm test:extension memory-lancedb — 149 tests passing, including fourteen
    regression tests:
    1. the [SCOPE:<value>] tag is captured verbatim (a value with hyphens and
      underscores 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;
    2. dedup is scope-aware — the same fact survives under different scopes, while
      same-scope and global-vs-global writes still dedup;
    3. dedup prefilters by scope before the top-K limit, so a same-scope duplicate
      is still detected even when many other scopes share a near-identical vector;
    4. scoped memory_recall prioritizes its scope — the requested scope's row is
      returned (and ranked first) even behind many strong global matches that
      would otherwise fill the candidate window;
    5. an unscoped memory_recall is global-only — a scoped row never surfaces
      in a plain recall;
    6. a scoped memory_forget deletes only within its scope — the same fact under
      a different scope survives;
    7. an unscoped memory_forget is global-only — it cannot nominate or delete
      a scoped row from another partition;
    8. auto-recall injects only global memories — a scoped row is never
      auto-recalled into an unrelated session;
    9. operator recall thresholds survive the live-config merge — a configured
      autoRecallOverfetch/recallMinScore reaches the before-prompt auto-recall
      instead of silently falling back to the defaults;
    10. a memory_store tag 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;
    11. a memory_forget by memoryId is fenced to the row's scope — a scoped row
      is not deleted by an unscoped or mismatched-scope call, while a matching
      scope (or a global row) deletes as expected;
    12. a tag-only [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;
    13. ltm search is global-only by default and honors --scope <slug> — the CLI
      never scans across partitions unless a scope is explicitly requested, and a
      non-slug --scope key is rejected.
    14. auto-capture eligibility is evaluated on the scope-stripped text — a
      [SCOPE:<slug>] message whose fact fits under captureMaxChars is captured
      even 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.
  • Rebased onto current main. The memory_store success string applies main's
    UTF-16-safe truncateUtf16Safe(...) helper to the scope-stripped text
    (truncateUtf16Safe(memoryText, 100)), so both main's UTF-16 fix and this PR's
    tag-strip hold; pnpm check:no-conflict-markers passes and no raw .slice(0, N)
    truncation remains on memory text.
  • Adapted to main's tightened quality gates in the extensions lane: the
    newly-enforced noUncheckedIndexedAccess (the [SCOPE:<value>] capture-group
    reads and one test batch access are guarded with the SDK's expectDefined,
    matching main's idiom), the oxlint rules (no-map-spread, curly, and the
    type-aware restrict-template-expressions / no-unnecessary-type-conversion,
    reproduced locally with the --tsconfig shard config CI runs), and the
    zero-any-cast type-suppression inventory (the added test mocks were reworked to
    drop every as any). pnpm tsgo:extensions, pnpm tsgo:extensions:test, the
    extensions lint shard, and the type-suppression-inventory test are all green for
    this plugin's files.
  • Closed two partition gaps found in review: (1) the ltm search CLI was the only
    db.search caller left without a scope filter, so a table-wide scan could expose
    scoped 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 fall
    back 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).
  • A follow-up review pass hardened the scoped-capture path: a scoped store or
    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 updated (docs/plugins/memory-lancedb.md): a new Scope section (tag /
    slug shape, global-vs-scoped recall and forget, memoryId fence, global-only
    auto-recall, and the ltm search --scope behavior) plus a Recall selectivity
    table for the three new settings, with docs/docs_map.md regenerated for the new
    headings; pnpm format:docs:check, docs:map:check, the MDX check, and the
    internal-link check all pass.

Prepared with AI assistance.

@clawsweeper

clawsweeper Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 15, 2026, 11:59 PM ET / July 16, 2026, 03:59 UTC.

Summary
The PR adds caller-defined scope partitioning to LanceDB memory storage, recall, forgetting, duplicate detection, CLI search, and auto-capture, plus three configurable auto-recall thresholds and documentation.

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.

  • Configuration Surfaces: 3 added, 0 changed, 0 removed. Each new threshold becomes a persisted public setting with validation, UI metadata, documentation, and live runtime behavior.
  • Persisted Columns: 2 added. scope and agent permanently change existing LanceDB table schemas and therefore require upgrade and rollback review.
  • Scope Inputs: 4 added. The two tools, CLI search flag, and [SCOPE:<slug>] text convention create multiple entry points that must share one stable contract.

Stored data model
Persistent data-model change detected: unknown-data-model-change: extensions/memory-lancedb/config.ts, unknown-data-model-change: extensions/memory-lancedb/index.test.ts, unknown-data-model-change: extensions/memory-lancedb/index.ts, vector/embedding metadata: extensions/memory-lancedb/config.ts, vector/embedding metadata: extensions/memory-lancedb/index.ts. Confirm migration or upgrade compatibility proof before merge.

Merge readiness
Overall: 🦐 gold shrimp
Proof: 🦐 gold shrimp
Patch quality: 🦐 gold shrimp
Result: blocked until stronger real behavior proof is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Resolve whether bundled scope support is product-approved instead of duplicating the existing external plugin.
  • Make the persisted schema migration safe for upgrade and rollback, with focused compatibility coverage.
  • Provide redacted real OpenClaw proof through the actual changed tools and hooks, not only direct LanceDB operations.

Proof guidance:

  • [P1] Needs stronger real behavior proof before merge: The real on-disk LanceDB transcript proves dependency primitives, but its standalone replay does not run the changed plugin tools and hooks; add a redacted live OpenClaw run covering scoped store, recall, forget, auto-capture, global-only auto-recall, and upgrade behavior, then update the PR body to trigger review or ask a maintainer for @clawsweeper re-review.

Risk before merge

  • [P1] The lazy migration creates non-null scope and agent columns; after initialization, rolling back to a released version that writes rows without those fields may stop memory writes.
  • [P1] Caller-supplied scope values are not bound to a trusted session, agent, channel, or tenant identity, so operators could mistake partitioning discipline for an authorization boundary.
  • [P1] The new tool parameters, tag syntax, CLI flag, and three configuration defaults create a permanent bundled-plugin contract that green CI cannot product-calibrate.
  • [P1] The submitted live proof does not demonstrate the actual plugin's scoped store, recall, forget, duplicate, auto-capture, global-only auto-recall, or live-config paths together.

Maintainer options:

  1. Pause For Scope Direction (recommended)
    Hold the PR until a likely owner decides whether bundled caller-defined scope should exist alongside the established external plugin.
  2. Make Migration Rollback-Safe
    If bundled scope is approved, use nullable or explicitly versioned columns and prove fresh install, upgrade, and rollback behavior before merge.
  3. Accept A Forward-Only Migration
    Maintainers may intentionally accept that opening the store with this version can make older releases unable to write it, but that operator impact should be explicit.

Next step before merge

  • [P1] A likely owner must first decide whether the bundled plugin should duplicate the external scope contract; the remaining migration and proof work becomes actionable only after that product choice.

Maintainer decision needed

  • Question: Should the bundled memory-lancedb plugin adopt a second caller-defined multi-scope contract and three new recall settings, or should advanced scope isolation remain in the existing external plugin until trusted session-derived scoping is designed?
  • Rationale: The code can implement either direction, but repository policy cannot determine whether OpenClaw should permanently duplicate the external plugin's scope semantics or expose model-supplied partition keys in a bundled memory plugin.
  • Likely owner: steipete — Recent release ownership and prior memory-lancedb review history make this the strongest available routing candidate for bundled-plugin product scope.
  • Options:
    • Keep External Scope Canonical (recommended): Direct advanced multi-scope users to memory-lancedb-pro and avoid adding a parallel bundled contract until a missing plugin API is demonstrated.
    • Sponsor Bundled Scoping: Approve bundled scope support after defining its trusted identity semantics, rollback guarantees, and complete live proof requirements.
    • Narrow To Thresholds: Split the independent recall-threshold configuration into a smaller PR while the scope model remains under product review.

Security
Cleared: Validated slug-only predicates avoid raw filter injection, and the documented caller-supplied scope does not expand existing authorization; it must remain clearly described as partitioning rather than a trust boundary.

Review findings

  • [P1] Use the existing scope plugin or justify bundled duplication — extensions/memory-lancedb/index.ts:198
  • [P1] Keep migrated columns compatible with rollback writes — extensions/memory-lancedb/index.ts:281
Review details

Best 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:

  • [P1] Use the existing scope plugin or justify bundled duplication — extensions/memory-lancedb/index.ts:198
    memory-lancedb-pro already provides multi-scope isolation through the supported plugin surface. Adding a second scope syntax and selection model to the bundled plugin creates parallel contracts and maintenance drift unless the PR first demonstrates why the existing plugin is insufficient and obtains explicit bundled-product approval.
    Confidence: 0.94
  • [P1] Keep migrated columns compatible with rollback writes — extensions/memory-lancedb/index.ts:281
    The startup migration adds scope and agent as non-null columns populated with empty strings. Once this runs, an older released plugin writes rows without those fields and can be rejected by the migrated schema; make the columns nullable or provide an explicit versioned migration and downgrade contract. The query code already treats NULL scope as global, so nullable columns fit the proposed behavior.
    Confidence: 0.89

Overall correctness: patch is incorrect
Overall confidence: 0.89

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against de3f7925c4c3.

Label changes

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp. Replaced prior rating: 🧂 unranked krab.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.

Label justifications:

  • P2: This is a meaningful optional-memory improvement with bounded plugin scope, but it is not a current core-runtime emergency or established regression.
  • merge-risk: 🚨 compatibility: The PR adds persisted configuration and automatically mutates existing LanceDB schemas in a way that may prevent downgrade writes.
  • merge-risk: 🚨 session-state: The PR changes which durable memories can be stored, deduplicated, recalled, injected, and deleted across conversation contexts.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp. Replaced prior rating: 🧂 unranked krab.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The real on-disk LanceDB transcript proves dependency primitives, but its standalone replay does not run the changed plugin tools and hooks; add a redacted live OpenClaw run covering scoped store, recall, forget, auto-capture, global-only auto-recall, and upgrade behavior, then update the PR body to trigger review or ask a maintainer for @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +374, Tests +1472, Docs +58. Total +1904 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 3 396 22 +374
Tests 1 1526 54 +1472
Docs 2 61 3 +58
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 1983 79 +1904

What I checked:

Likely related people:

  • steipete: Recent release snapshots and prior maintainer-side memory-lancedb reviews connect this owner to decisions about the bundled plugin's permanent feature scope. (role: prior reviewer and current-main area owner; confidence: medium; commits: a374c3a5bfd5; files: extensions/memory-lancedb/index.ts, extensions/memory-lancedb/config.ts, extensions/memory-lancedb/openclaw.plugin.json)
  • Vignesh Natarajan: Recent merged work hardened memory-lancedb recall and auto-capture behavior across the same runtime and configuration surface. (role: recent retrieval-path contributor; confidence: medium; commits: 61725fb37e33, 8cb0373bc1e7; files: extensions/memory-lancedb/index.ts, extensions/memory-lancedb/config.ts, extensions/memory-lancedb/openclaw.plugin.json)
  • Radek Paclt: Feature history attributes the original lifecycle-hook vector memory plugin that later became memory-lancedb to this contributor. (role: introduced behavior; confidence: medium; commits: ebfeb7a6bf53; files: extensions/memory/index.ts, extensions/memory/index.test.ts, extensions/memory-lancedb/index.ts)
  • vincentkoc: Recent memory-lancedb live-config and runtime work is directly adjacent to the PR's new live recall thresholds and hook behavior. (role: recent adjacent owner; confidence: medium; commits: ed03d91ae0c1; files: extensions/memory-lancedb/index.ts, extensions/memory-lancedb/config.ts, CHANGELOG.md)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (2 earlier review cycles)
  • reviewed 2026-07-09T15:53:16.844Z sha 663a8b3afc3076640a46c09b26bd54b204217598 :: needs real behavior proof before merge. :: [P3] Document the new memory-lancedb contract
  • reviewed 2026-07-16T03:12:20.297Z sha 2ceb44b :: needs real behavior proof before merge. :: [P1] Move the LanceDB schema upgrade out of startup | [P2] Remove the unrelated agent provenance column

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jul 9, 2026
@jgrandguillaume
jgrandguillaume force-pushed the feat/memory-lancedb-scope branch from 663a8b3 to cb5f012 Compare July 15, 2026 11:27
@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Jul 15, 2026
@jgrandguillaume
jgrandguillaume marked this pull request as ready for review July 15, 2026 13:26
@jgrandguillaume
jgrandguillaume force-pushed the feat/memory-lancedb-scope branch from cb5f012 to 6b7f973 Compare July 15, 2026 17:02
…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]>
@jgrandguillaume
jgrandguillaume force-pushed the feat/memory-lancedb-scope branch from 6b7f973 to 2ceb44b Compare July 15, 2026 17:55
@jgrandguillaume

Copy link
Copy Markdown
Author

@clawsweeper re-review

Since the last review the needs proof gap is addressed: the description now includes a real-behavior proof run against the actual @lancedb/lancedb driver on an on-disk table (schema migration preserving rows/vectors, native .where() prefilter isolation, and scoped delete — reproducible script + output inline), 149 tests pass (fourteen scope regression tests), and all CI gates are green (check-lint, check-docs, node shards, ci-gate). Rebased clean onto current main; a new "Security model" note clarifies that scope is a caller-supplied partition primitive rather than a trust boundary.

@clawsweeper

clawsweeper Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@jgrandguillaume

Copy link
Copy Markdown
Author

@clawsweeper re-run

The previous re-review run (#29444783159) completed but the verdict comment above still shows the July 9 pass, which pre-dates the real-behavior proof, so re-requesting a fresh review. The current description includes a redacted real @lancedb/lancedb run on an on-disk table (existing-table migration preserving rows/vectors, native .where() scoped/unscoped recall isolation, and scoped delete — reproducible script + output inline), the "Real behavior proof" check is green, and all CI gates pass on the current head.

@jgrandguillaume

Copy link
Copy Markdown
Author

Closing in favor of a clean re-open on current main: the review state here is stale (the verdict above pre-dates the real-behavior proof, and two re-review/re-run requests completed without refreshing it). The superseding PR carries the same single commit rebased onto today's main, with a consolidated description; all CI gates are green there. Link follows.

@jgrandguillaume

Copy link
Copy Markdown
Author

Superseding PR: #108782

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: memory-lancedb Extension: memory-lancedb merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant