Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(memory): long messages no longer fail memory search ("Expression tree is too large")

Frank Arena88c23f7c1c06
diff --git a/src/memory/second-brain-db.ts b/src/memory/second-brain-db.ts
index 44a248f6..2752b368 100644
--- a/src/memory/second-brain-db.ts
+++ b/src/memory/second-brain-db.ts
@@ -68,6 +68,27 @@ export interface PersonConnectionRow {
strength: number;
}
+/** Most distinct terms a memory search uses; keeps queries far below SQLite's
+ * expression-depth limit (1000), which a long pasted message used to blow
+ * through in both the FTS query and its LIKE fallback, failing the turn. */
+const MAX_SEARCH_TERMS = 32;
+
+/**
+ * Search terms for a free-text query: distinct lowercase words of 2+ letters
+ * or digits (punctuation and FTS operators can't leak in), first occurrence
+ * order, capped at MAX_SEARCH_TERMS.
+ */
+export function ftsSearchTerms(query: string): string[] {
+ const seen = new Set<string>();
+ for (const match of query.toLowerCase().matchAll(/[\p{L}\p{N}_]+/gu)) {
+ const term = match[0];
+ if (term.length < 2 || seen.has(term)) continue;
+ seen.add(term);
+ if (seen.size >= MAX_SEARCH_TERMS) break;
+ }
+ return [...seen];
+}
+
export class SecondBrainDB {
private db: SqliteDatabase;
@@ -372,12 +393,13 @@ export class SecondBrainDB {
}
searchRelevant(userKey: string, query: string, limit: number = 10): MemoryRow[] {
- const tokens = query.split(/\s+/).filter(t => t.length > 0).map(t => t.replace(/"/g, '""'));
+ const tokens = ftsSearchTerms(query);
if (tokens.length === 0) {
const stmt = this.db.prepare(`SELECT * FROM memories WHERE user_key = ? AND dismissed = 0 AND scope IN ('active', 'durable') ORDER BY updated_at DESC LIMIT ?`);
return stmt.all(userKey, limit) as MemoryRow[];
}
- const ftsQuery = tokens.join(' OR ');
+ // Quoted: punctuation in a term can't break FTS5 query syntax.
+ const ftsQuery = tokens.map((term) => `"${term}"`).join(' OR ');
const ftsStmt = this.db.prepare(`
SELECT m.* FROM memories m
JOIN memories_fts fts ON m.rowid = fts.rowid
@@ -396,12 +418,13 @@ export class SecondBrainDB {
}
searchSubconscious(userKey: string, query: string, limit: number = 10): MemoryRow[] {
- const tokens = query.split(/\s+/).filter(t => t.length > 0).map(t => t.replace(/"/g, '""'));
+ const tokens = ftsSearchTerms(query);
if (tokens.length === 0) {
const stmt = this.db.prepare(`SELECT * FROM memories WHERE user_key = ? AND dismissed = 0 AND scope = 'subconscious' ORDER BY updated_at DESC LIMIT ?`);
return stmt.all(userKey, limit) as MemoryRow[];
}
- const ftsQuery = tokens.join(' OR ');
+ // Quoted: punctuation in a term can't break FTS5 query syntax.
+ const ftsQuery = tokens.map((term) => `"${term}"`).join(' OR ');
const ftsStmt = this.db.prepare(`
SELECT m.* FROM memories m
JOIN memories_fts fts ON m.rowid = fts.rowid
diff --git a/src/memory/second-brain-search.test.ts b/src/memory/second-brain-search.test.ts
new file mode 100644
index 00000000..59f391bf
--- /dev/null
+++ b/src/memory/second-brain-search.test.ts
@@ -0,0 +1,71 @@
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+import { getDefaultConfig } from '../utils/config.js';
+import { UserMemoryStore } from './user-memory.js';
+import { ftsSearchTerms, isBetterSqlite3Available } from './second-brain-db.js';
+
+const tempDirs: string[] = [];
+const sqliteAvailable = isBetterSqlite3Available();
+
+function createStore(): UserMemoryStore {
+ const dir = mkdtempSync(join(tmpdir(), 'mercury-sb-search-'));
+ tempDirs.push(dir);
+ const config = getDefaultConfig();
+ config.memory.secondBrain = { enabled: true };
+ return new UserMemoryStore(config, 'user:owner', join(dir, 'second-brain', 'second-brain.db'));
+}
+
+afterEach(() => {
+ while (tempDirs.length > 0) {
+ try { rmSync(tempDirs.pop()!, { recursive: true, force: true }); } catch {}
+ }
+});
+
+/** A long pasted message: thousands of distinct tokens, paths, punctuation, FTS operators. */
+function hugePaste(): string {
+ const lines: string[] = ['I am running YuE2 in ComfyUI. My favorite test color is teal. Here is the log:'];
+ for (let i = 0; i < 1200; i++) {
+ lines.push(`[${i}] loading F:\\ComfyUI\\models\\yue2\\shard_${i}.safetensors (AND NOT "x" OR y*) step=${i * 7} tok${i}`);
+ }
+ return lines.join('\n');
+}
+
+describe('ftsSearchTerms', () => {
+ it('keeps distinct words of 2+ characters, lowercased, in order', () => {
+ expect(ftsSearchTerms('Teal is my favorite TEAL color, a b!')).toEqual(['teal', 'is', 'my', 'favorite', 'color']);
+ });
+
+ it('drops punctuation and FTS operators characters so they cannot break the query', () => {
+ expect(ftsSearchTerms('"quoted" C:\\path\\file.md (x OR y*) NEAR/2')).toEqual(['quoted', 'path', 'file', 'md', 'or', 'near']);
+ });
+
+ it('caps a huge message at 32 terms', () => {
+ expect(ftsSearchTerms(hugePaste())).toHaveLength(32);
+ });
+
+ it('handles non-Latin text', () => {
+ expect(ftsSearchTerms('café naïve 東京')).toEqual(['café', 'naïve', '東京']);
+ });
+});
+
+describe('memory search with a long pasted message', () => {
+ it.skipIf(!sqliteAvailable)('does not throw "Expression tree is too large" and still finds relevant memories', () => {
+ const store = createStore();
+ store.remember([
+ { type: 'preference', summary: 'Favorite test color is teal.', confidence: 0.9, importance: 0.8, durability: 0.9 },
+ ]);
+ expect(() => store.search(hugePaste())).not.toThrow();
+ expect(() => store.searchAll(hugePaste())).not.toThrow();
+ expect(store.search(hugePaste()).map((m) => m.summary)).toContain('Favorite test color is teal.');
+ });
+
+ it.skipIf(!sqliteAvailable)('still matches ordinary short queries', () => {
+ const store = createStore();
+ store.remember([
+ { type: 'preference', summary: 'Favorite test color is teal.', confidence: 0.9, importance: 0.8, durability: 0.9 },
+ ]);
+ expect(store.search('what is my favorite color?').map((m) => m.summary)).toContain('Favorite test color is teal.');
+ });
+});