Repository navigation
Conversation
Greptile SummaryThis PR introduces an opt-in Critical issues identified:
Confidence Score: 2/5
|
| let query = this.table!.vectorSearch(vector).limit(limit); | ||
| if (agentId !== undefined) { | ||
| // safe chars to prevent SQL injection | ||
| const safe = agentId.replace(/[^a-zA-Z0-9_\-.:@]/g, ""); | ||
| query = query.where(`agentId = '${safe}' OR agentId = ''`); | ||
| } |
There was a problem hiding this comment.
Post-filter starvation with agent scoping
.limit(limit) is applied before .where(), which means LanceDB performs an ANN search on the top-N nearest vectors first, then applies the agentId filter as a post-filter on that candidate set. If most of the top-N ANN candidates belong to other agents, they will be eliminated by the filter, returning 0 results even when many matching memories exist in the database for the target agent.
To get reliable results with agent scoping, consider:
- Inflating the probe limit to account for expected filtration loss (e.g., multiply by a factor like 5–10)
- Or using pre-filtering if the LanceDB version supports it
| let query = this.table!.vectorSearch(vector).limit(limit); | |
| if (agentId !== undefined) { | |
| // safe chars to prevent SQL injection | |
| const safe = agentId.replace(/[^a-zA-Z0-9_\-.:@]/g, ""); | |
| query = query.where(`agentId = '${safe}' OR agentId = ''`); | |
| } | |
| async search( | |
| vector: number[], | |
| limit = 5, | |
| minScore = 0.5, | |
| agentId?: string, | |
| ): Promise<MemorySearchResult[]> { | |
| await this.ensureInitialized(); | |
| const probeLimit = agentId !== undefined ? Math.max(limit * 5, 50) : limit; | |
| let query = this.table!.vectorSearch(vector).limit(probeLimit); | |
| if (agentId !== undefined) { | |
| // safe chars to prevent SQL injection | |
| const safe = agentId.replace(/[^a-zA-Z0-9_\-.:@]/g, ""); | |
| query = query.where(`agentId = '${safe}' OR agentId = ''`); | |
| } | |
| const results = await query.toArray(); | |
| // Truncate back to the requested limit after post-filtering | |
| const truncated = results.slice(0, limit); | |
| // LanceDB uses L2 distance by default; convert to similarity score | |
| const mapped = truncated.map((row) => { | |
| const distance = row._distance ?? 0; | |
| // Use inverse for a 0-1 range: sim = 1 / (1 + d) | |
| const score = 1 / (1 + distance); | |
| return { | |
| entry: { | |
| id: row.id as string, | |
| text: row.text as string, | |
| vector: row.vector as number[], | |
| importance: row.importance as number, | |
| category: row.category as MemoryEntry["category"], | |
| createdAt: row.createdAt as number, | |
| agentId: (row.agentId as string) ?? "", | |
| }, | |
| score, | |
| }; | |
| }); | |
| return mapped.filter((r) => r.score >= minScore); | |
| } |
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/memory-lancedb/index.ts
Line: 146-151
Comment:
**Post-filter starvation with agent scoping**
`.limit(limit)` is applied before `.where()`, which means LanceDB performs an ANN search on the top-N nearest vectors first, _then_ applies the `agentId` filter as a post-filter on that candidate set. If most of the top-N ANN candidates belong to other agents, they will be eliminated by the filter, returning 0 results even when many matching memories exist in the database for the target agent.
To get reliable results with agent scoping, consider:
- Inflating the probe limit to account for expected filtration loss (e.g., multiply by a factor like 5–10)
- Or using pre-filtering if the LanceDB version supports it
```suggestion
async search(
vector: number[],
limit = 5,
minScore = 0.5,
agentId?: string,
): Promise<MemorySearchResult[]> {
await this.ensureInitialized();
const probeLimit = agentId !== undefined ? Math.max(limit * 5, 50) : limit;
let query = this.table!.vectorSearch(vector).limit(probeLimit);
if (agentId !== undefined) {
// safe chars to prevent SQL injection
const safe = agentId.replace(/[^a-zA-Z0-9_\-.:@]/g, "");
query = query.where(`agentId = '${safe}' OR agentId = ''`);
}
const results = await query.toArray();
// Truncate back to the requested limit after post-filtering
const truncated = results.slice(0, limit);
// LanceDB uses L2 distance by default; convert to similarity score
const mapped = truncated.map((row) => {
const distance = row._distance ?? 0;
// Use inverse for a 0-1 range: sim = 1 / (1 + d)
const score = 1 / (1 + distance);
return {
entry: {
id: row.id as string,
text: row.text as string,
vector: row.vector as number[],
importance: row.importance as number,
category: row.category as MemoryEntry["category"],
createdAt: row.createdAt as number,
agentId: (row.agentId as string) ?? "",
},
score,
};
});
return mapped.filter((r) => r.score >= minScore);
}
```
How can I resolve this? If you propose a fix, please make it concise.| const agentId = cfg.agentScoping ? (ctx.agentId ?? "") : ""; | ||
|
|
There was a problem hiding this comment.
agentId stored raw but sanitized on read — causes permanent recall mismatch
When a memory is stored, the raw ctx.agentId value is written to the database (line 428). However, when searching (line 149) or deleting (line 184), the same agentId is stripped of disallowed characters:
const safe = agentId.replace(/[^a-zA-Z0-9_\-.:@]/g, "");
query = query.where(`agentId = '${safe}' OR agentId = ''`);If ctx.agentId contains any character outside the allowlist (e.g., a space, slash, or bracket), the stored value and the search filter will differ:
- Example:
ctx.agentId = "my agent"→ stored as"my agent"→ searched as"myagent"→ no match ever found - Example:
ctx.agentId = "agent/123"→ stored as"agent/123"→ searched as"agent123"→ no match
This means an agent whose ID contains any disallowed character will silently lose all its scoped memories — they are stored but never recalled.
Fix: Normalize/validate agentId at write time, before storing. Apply the same sanitization consistently at both write and read time:
| const agentId = cfg.agentScoping ? (ctx.agentId ?? "") : ""; | |
| async store(entry: Omit<MemoryEntry, "id" | "createdAt">): Promise<MemoryEntry> { | |
| await this.ensureInitialized(); | |
| // Sanitize agentId for consistency with search/delete path | |
| const sanitizedAgentId = entry.agentId.replace(/[^a-zA-Z0-9_\-.:@]/g, ""); | |
| const fullEntry: MemoryEntry = { | |
| ...entry, | |
| agentId: sanitizedAgentId, | |
| id: randomUUID(), | |
| createdAt: Date.now(), | |
| }; | |
| await this.table!.add([fullEntry]); | |
| return fullEntry; | |
| } |
Also apply the same sanitization in the agent_end hook (line 629) and in the memory_store tool (line 428) before storing.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/memory-lancedb/index.ts
Line: 428-429
Comment:
**`agentId` stored raw but sanitized on read — causes permanent recall mismatch**
When a memory is stored, the raw `ctx.agentId` value is written to the database (line 428). However, when searching (line 149) or deleting (line 184), the same `agentId` is stripped of disallowed characters:
```typescript
const safe = agentId.replace(/[^a-zA-Z0-9_\-.:@]/g, "");
query = query.where(`agentId = '${safe}' OR agentId = ''`);
```
If `ctx.agentId` contains any character outside the allowlist (e.g., a space, slash, or bracket), the stored value and the search filter will differ:
- Example: `ctx.agentId = "my agent"` → stored as `"my agent"` → searched as `"myagent"` → **no match ever found**
- Example: `ctx.agentId = "agent/123"` → stored as `"agent/123"` → searched as `"agent123"` → **no match**
This means an agent whose ID contains any disallowed character will silently lose all its scoped memories — they are stored but never recalled.
**Fix:** Normalize/validate `agentId` at write time, before storing. Apply the same sanitization consistently at both write and read time:
```suggestion
async store(entry: Omit<MemoryEntry, "id" | "createdAt">): Promise<MemoryEntry> {
await this.ensureInitialized();
// Sanitize agentId for consistency with search/delete path
const sanitizedAgentId = entry.agentId.replace(/[^a-zA-Z0-9_\-.:@]/g, "");
const fullEntry: MemoryEntry = {
...entry,
agentId: sanitizedAgentId,
id: randomUUID(),
createdAt: Date.now(),
};
await this.table!.add([fullEntry]);
return fullEntry;
}
```
Also apply the same sanitization in the `agent_end` hook (line 629) and in the `memory_store` tool (line 428) before storing.
How can I resolve this? If you propose a fix, please make it concise.| } catch { | ||
| // Best-effort: if migration fails the plugin continues to work, | ||
| // but we skip agent-scoped filtering for this table. | ||
| } |
There was a problem hiding this comment.
Silent migration failure — no observability
The PR description and inline comment indicate best-effort migration is intended ("if migration fails the plugin continues to work"), but the catch block swallows all errors without any logging. The MemoryDB class doesn't hold a reference to api.logger, so there's no way to surface the failure to the operator.
If addColumns fails on an older LanceDB version, operators enabling agentScoping: true will see all agents sharing the same memory pool with no visible indication that migration was skipped — making troubleshooting difficult.
Suggestion: Thread a logger callback through MemoryDB's constructor (or return a diagnostic flag from ensureInitialized) so that the failure can be surfaced via api.logger.warn(...) in the plugin registration path:
| } catch { | |
| // Best-effort: if migration fails the plugin continues to work, | |
| // but we skip agent-scoped filtering for this table. | |
| } | |
| class MemoryDB { | |
| private db: LanceDB.Connection | null = null; | |
| private table: LanceDB.Table | null = null; | |
| private initPromise: Promise<void> | null = null; | |
| constructor( | |
| private readonly dbPath: string, | |
| private readonly vectorDim: number, | |
| private readonly logger?: { warn(msg: string): void }, | |
| ) {} | |
| // ... in migrateAgentIdColumn: | |
| private async migrateAgentIdColumn(): Promise<void> { | |
| try { | |
| // ... existing logic ... | |
| } catch (err) { | |
| // Best-effort: if migration fails the plugin continues to work, | |
| // but we skip agent-scoped filtering for this table. | |
| if (this.logger) { | |
| this.logger.warn( | |
| `memory-lancedb: migration failed (agentId column may not be available): ${String(err)}`, | |
| ); | |
| } | |
| } | |
| } | |
| } | |
| // In plugin registration, pass logger: | |
| const db = new MemoryDB(resolvedDbPath, vectorDim, { warn: api.logger.warn }); |
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/memory-lancedb/index.ts
Line: 119-122
Comment:
**Silent migration failure — no observability**
The PR description and inline comment indicate best-effort migration is intended ("if migration fails the plugin continues to work"), but the catch block swallows all errors without any logging. The `MemoryDB` class doesn't hold a reference to `api.logger`, so there's no way to surface the failure to the operator.
If `addColumns` fails on an older LanceDB version, operators enabling `agentScoping: true` will see all agents sharing the same memory pool with no visible indication that migration was skipped — making troubleshooting difficult.
**Suggestion:** Thread a logger callback through `MemoryDB`'s constructor (or return a diagnostic flag from `ensureInitialized`) so that the failure can be surfaced via `api.logger.warn(...)` in the plugin registration path:
```suggestion
class MemoryDB {
private db: LanceDB.Connection | null = null;
private table: LanceDB.Table | null = null;
private initPromise: Promise<void> | null = null;
constructor(
private readonly dbPath: string,
private readonly vectorDim: number,
private readonly logger?: { warn(msg: string): void },
) {}
// ... in migrateAgentIdColumn:
private async migrateAgentIdColumn(): Promise<void> {
try {
// ... existing logic ...
} catch (err) {
// Best-effort: if migration fails the plugin continues to work,
// but we skip agent-scoped filtering for this table.
if (this.logger) {
this.logger.warn(
`memory-lancedb: migration failed (agentId column may not be available): ${String(err)}`,
);
}
}
}
}
// In plugin registration, pass logger:
const db = new MemoryDB(resolvedDbPath, vectorDim, { warn: api.logger.warn });
```
How can I resolve this? If you propose a fix, please make it concise.|
This pull request has been automatically marked as stale due to inactivity. |
|
Thanks for the context here. I swept through the related work, and this is now duplicate or superseded. Keep open: the PR targets a real memory-lancedb isolation gap, but the draft branch is merge-conflicting, lacks real behavior proof, and still has blocking scope-key, migration, and current-hook correctness issues. Canonical path: Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review. So I’m closing this here because the remaining work is already tracked in the canonical issue. Review detailsBest possible solution: Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review. Do we have a high-confidence way to reproduce the issue? Yes, at source level: current main constructs one shared memory-lancedb store and the tools/hooks call Is this the best way to solve the issue? No. The direction is useful, but this branch targets a legacy hook, lacks real behavior proof, and needs a canonical scope-key and migration semantics repaired against current main before it is the best merge path. Security review: Security review needs attention: The diff changes an agent memory isolation boundary and still has concrete scope-key and migration-observability issues before merge.
What I checked:
Likely related people:
Codex review notes: model gpt-5.5, reasoning high; reviewed against d7a078f1962b. |
|
ClawSweeper PR egg 🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat. Where did the egg go?
|
|
ClawSweeper applied the proposed close for this PR.
|
Summary
memory-lancedbplugin shared a single global memory pool across all agents. An agent could recall memories captured by a different agent, and explicit tool calls (memory_recall,memory_store,memory_forget) had no way to scope reads/writes to the calling agent.agentScopingconfig boolean. When enabled, memories are tagged with the originatingagentIdat capture time; recall and tool calls filter to that agent's memories plus legacy globally-shared memories (agentId = ""). A best-effort migration adds theagentIdcolumn to existing LanceDB tables. Tool registration switched from static objects to factories so each agent-run gets its own scoped context.agentScoping === false) is fully backward-compatible — the global memory pool is preserved and no existing data is altered.Change Type
Scope
Linked Issue/PR
User-visible / Behavior Changes
agentScoping(boolean, defaultfalse) in thememory-lancedbplugin settings.agentScoping === true:memory_recall,memory_store,memory_forget) only see memories belonging to the current agent plus legacy untagged (globally shared) memories.agentScoping === false(default): no behavior change.Security Impact
agentScoping === true, agents cannot read each other's scoped memories. TheagentIdvalue passed throughctx.agentIdis used in a SQL filter string. A malformedagentIdcould be used for SQL injection against the LanceDB filter.agentIdis validated against/^[a-zA-Z0-9_\-.:@]{0,128}$/before interpolation; values that do not match are rejected, not silently stripped.Repro + Verification
Environment
agentScoping === truein plugin configSteps
agentScoping === truein thememory-lancedbplugin config.agentIdvalues and store a memory from each.Expected
Actual
Evidence
Human Verification
agentScoping: falsepath exercises existing code unchanged; migration skips gracefully whenagentIdcolumn already present.agentIdcolumn get it added with''default on first open; migration failure is caught and does not crash the plugin.Review Conversations
Compatibility / Migration
agentScopingdefaults tofalse; existing behavior unchanged.agentScopingboolean in plugin config.agentIdempty string.Failure Recovery
agentScopingto false in plugin config.extensions/memory-lancedb/config.ts,extensions/memory-lancedb/index.ts.agentScoping(likely theagentIdis not being propagated throughctxin that hook context).Risks and Mitigations
agentIdinjection viactx.agentIdinto the LanceDB SQL filter string./^[a-zA-Z0-9_\-.:@]{0,128}$/) rejects unexpected values before interpolation.addColumns) fails silently on unusual LanceDB versions, leaving the table without theagentIdcolumn. Scoped filtering is then skipped.