π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(memory): unordered LIMIT truncation in search + honest sql.js persistence status (#2983)
rUvb8c37da8e91f
diff --git a/v3/@claude-flow/cli/__tests__/memory-search-truncation-2982.test.ts b/v3/@claude-flow/cli/__tests__/memory-search-truncation-2982.test.tsnew file mode 100644index 0000000000..39174014f6--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/memory-search-truncation-2982.test.ts@@ -0,0 +1,114 @@+/**+ * Regression for #2982 / #2976 (duplicate reports, same root cause):+ * `bridgeSearchEntries()`'s pre-rank SELECT truncated the corpus to+ * `LIMIT 1000` with no `ORDER BY`, so SQLite returned rows in arbitrary+ * storage order β for a freshly-inserted rowid table with no deletes,+ * that's insertion order. On any corpus over 1000 rows, the newest entries+ * never reached BM25/embedding scoring at all, no matter how well they+ * matched the query. `bridgeListEntries()` already ordered by+ * `updated_at DESC` for the same reason; this pins the search path to the+ * same guarantee.+ *+ * All SQL executes against a real better-sqlite3 fixture (mocked+ * ControllerRegistry only), matching the #2652 test's harness pattern, so+ * this exercises the production bridge query, not a stand-in.+ */+import { afterAll, describe, expect, it } from 'vitest';+import Database from 'better-sqlite3';+import { mkdtempSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++const root = mkdtempSync(join(tmpdir(), 'ruflo-2982-truncation-'));+const dbPath = join(root, 'memory.db');+const ROW_COUNT = 1005;+const NEEDLE = 'zzzneedle2982';++let db: Database.Database | null = null;++function seedRows(): void {+ db = new Database(dbPath);+ db.exec(`+ CREATE TABLE memory_entries (+ id TEXT PRIMARY KEY,+ key TEXT NOT NULL,+ namespace TEXT DEFAULT 'default',+ content TEXT NOT NULL,+ type TEXT DEFAULT 'semantic',+ embedding TEXT,+ embedding_model TEXT DEFAULT 'local',+ embedding_dimensions INTEGER,+ tags TEXT,+ metadata TEXT,+ owner_id TEXT,+ created_at INTEGER,+ updated_at INTEGER,+ expires_at INTEGER,+ last_accessed_at INTEGER,+ access_count INTEGER DEFAULT 0,+ status TEXT,+ provenance_type TEXT DEFAULT 'unknown',+ UNIQUE(namespace, key)+ );+ `);+ const insert = db.prepare(`+ INSERT INTO memory_entries (id, key, namespace, content, created_at, updated_at, status)+ VALUES (?, ?, 'fixture', ?, ?, ?, 'active')+ `);+ const insertMany = db.transaction((n: number) => {+ for (let i = 1; i <= n; i++) {+ // updated_at increases monotonically with insertion order β row n is+ // both the last-inserted (storage-order-last) AND the newest by+ // timestamp, so ORDER BY updated_at DESC is what recovers it.+ const isNeedle = i === n;+ insert.run(+ `row-${i}`,+ `key/${i}`,+ isNeedle ? `entry number ${i} contains ${NEEDLE} as a unique marker` : `filler entry number ${i}`,+ i,+ i,+ );+ }+ });+ insertMany(ROW_COUNT);+ db.close();+}++seedRows();++afterAll(() => {+ db?.close();+ rmSync(root, { recursive: true, force: true });+});++describe('#2982/#2976 search truncation', () => {+ it('recalls the newest entry even when the corpus exceeds the 1000-row pre-rank LIMIT', async () => {+ const { __setMemoryBridgeRegistryForTests, bridgeSearchEntries } = await import(+ '../src/memory/memory-bridge.js'+ );++ db = new Database(dbPath);+ __setMemoryBridgeRegistryForTests({+ getAgentDB: () => ({ database: db, embedder: null }),+ get: () => null,+ });++ const result = await bridgeSearchEntries({+ query: NEEDLE,+ namespace: 'fixture',+ limit: 10,+ threshold: 0.1,+ dbPath,+ });++ expect(result).not.toBeNull();+ expect(result!.success).toBe(true);+ const keys = result!.results.map((r) => r.key);+ // Pre-fix: an unordered `LIMIT 1000` returns rows in insertion order on+ // this fixture, i.e. rows 1..1000 β row 1005 (the needle) is excluded+ // from the pre-rank set entirely and can never be scored or returned,+ // regardless of threshold. Post-fix: ORDER BY updated_at DESC recovers+ // the newest 1000 rows (6..1005), which includes it.+ expect(keys).toContain(`key/${ROW_COUNT}`);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/memory-store-persist-warning-2968.test.ts b/v3/@claude-flow/cli/__tests__/memory-store-persist-warning-2968.test.tsnew file mode 100644index 0000000000..4adbbf8cf1--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/memory-store-persist-warning-2968.test.ts@@ -0,0 +1,117 @@+/**+ * Regression for #2968: `memory store` printed "Data stored successfully"+ * even when the underlying connection couldn't durably persist the write β+ * specifically the sql.js fallback driver (engaged when better-sqlite3's+ * native binding never got built, e.g. a skipped optionalDependency+ * postinstall), whose `.pragma()` shim rejects `wal_checkpoint(passive)`+ * with "Invalid PRAGMA command". `bridgeStoreEntry()` swallowed that error+ * unconditionally and reported unqualified success either way.+ *+ * This pins the fix: bridgeStoreEntry() now distinguishes that specific+ * failure signature from an ordinary "non-WAL / busy" pragma failure and+ * surfaces it via `persistWarning`, so callers stop claiming success blind.+ */+import { afterAll, describe, expect, it } from 'vitest';+import Database from 'better-sqlite3';+import { mkdtempSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++const root = mkdtempSync(join(tmpdir(), 'ruflo-2968-persist-warning-'));+const dbPath = join(root, 'memory.db');++let db: Database.Database | null = null;++function makeDb(): Database.Database {+ const d = new Database(dbPath);+ d.exec(`+ CREATE TABLE IF NOT EXISTS memory_entries (+ id TEXT PRIMARY KEY,+ key TEXT NOT NULL,+ namespace TEXT DEFAULT 'default',+ content TEXT NOT NULL,+ type TEXT DEFAULT 'semantic',+ embedding TEXT,+ embedding_dimensions INTEGER,+ embedding_model TEXT,+ tags TEXT,+ metadata TEXT,+ provenance_type TEXT DEFAULT 'unknown',+ created_at INTEGER,+ updated_at INTEGER,+ expires_at INTEGER,+ status TEXT DEFAULT 'active',+ UNIQUE(namespace, key)+ );+ `);+ return d;+}++afterAll(() => {+ db?.close();+ rmSync(root, { recursive: true, force: true });+});++describe('#2968 store persistence warning', () => {+ it('surfaces persistWarning when the checkpoint throws "Invalid PRAGMA" (sql.js fallback signature)', async () => {+ const { __setMemoryBridgeRegistryForTests, bridgeStoreEntry } = await import(+ '../src/memory/memory-bridge.js'+ );++ db = makeDb();+ // Simulate the sql.js shim's pragma() rejecting an unrecognized command β+ // the exact signature `agentdb`'s sql.js fallback throws in the field+ // report, without needing to stand up a real sql.js-backed registry.+ (db as unknown as { pragma: (cmd: string) => unknown }).pragma = (cmd: string) => {+ throw new Error(+ `Invalid PRAGMA command: ${cmd}. Allowed: journal_mode, synchronous, cache_size, page_size, page_count, user_version, foreign_keys, temp_store, mmap_size, wal_autocheckpoint`,+ );+ };+ __setMemoryBridgeRegistryForTests({+ getAgentDB: () => ({ database: db, embedder: null }),+ get: () => null,+ });++ const result = await bridgeStoreEntry({+ key: 'k1',+ value: 'persistence probe',+ namespace: 'fixture',+ generateEmbeddingFlag: false,+ dbPath,+ });++ expect(result).not.toBeNull();+ expect(result!.success).toBe(true);+ expect(result!.persistWarning).toBeDefined();+ expect(result!.persistWarning).toMatch(/sql\.js fallback driver/i);+ expect(result!.persistWarning).toMatch(/#2968/);+ });++ it('does NOT set persistWarning on an ordinary pragma failure unrelated to the sql.js signature', async () => {+ const { __setMemoryBridgeRegistryForTests, bridgeStoreEntry } = await import(+ '../src/memory/memory-bridge.js'+ );++ const d2 = makeDb();+ (d2 as unknown as { pragma: (cmd: string) => unknown }).pragma = () => {+ throw new Error('database is busy');+ };+ __setMemoryBridgeRegistryForTests({+ getAgentDB: () => ({ database: d2, embedder: null }),+ get: () => null,+ });++ const result = await bridgeStoreEntry({+ key: 'k2',+ value: 'unrelated pragma failure',+ namespace: 'fixture',+ generateEmbeddingFlag: false,+ dbPath,+ });++ expect(result).not.toBeNull();+ expect(result!.success).toBe(true);+ expect(result!.persistWarning).toBeUndefined();+ d2.close();+ });+});diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.tsindex 813178447d..422d0d6e1b 100644--- a/v3/@claude-flow/cli/src/commands/memory.ts+++ b/v3/@claude-flow/cli/src/commands/memory.ts@@ -232,7 +232,14 @@ const storeCommand: Command = {});output.writeln();- output.printSuccess('Data stored successfully');+ if (result.persistWarning) {+ // #2968: the write ran, but the checkpoint signal indicates it may+ // not have reached disk (sql.js fallback driver) β do not print an+ // unconditional green success for a write that might vanish.+ output.printWarning(`Data stored, but persistence is not guaranteed: ${result.persistWarning}`);+ } else {+ output.printSuccess('Data stored successfully');+ }return { success: true, data: { ...storeData, id: result.id, embedding: result.embedding, provenanceType: provenance || 'unknown' } };} catch (error) {diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.tsindex fe96cb9883..2be238f488 100644--- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts+++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts@@ -787,6 +787,13 @@ export async function bridgeStoreEntry(options: {cached?: boolean;attested?: boolean;error?: string;+ /** #2968: set when the post-write checkpoint failed in a way that+ * indicates this connection may not durably persist writes at all+ * (the sql.js fallback driver, engaged when better-sqlite3's native+ * binding is missing). The write above still ran and `success` is+ * still true β this is advisory, not a failure β but callers should+ * surface it instead of only printing an unconditional success message. */+ persistWarning?: string;} | null> {// ADR-323 β validated once in storeEntry() before this is reached on that// path, but bridgeStoreEntry() also has direct internal callers, so check@@ -962,11 +969,26 @@ export async function bridgeStoreEntry(options: {// `sqlite3` vector count) then see a stale/empty main DB file and report// "0 vectors" / empty search. A PASSIVE checkpoint flushes committed pages// into the main file without blocking writers. Best-effort, never fatal.+ let persistWarning: string | undefined;try {if (typeof ctx.db.pragma === 'function') {ctx.db.pragma('wal_checkpoint(PASSIVE)');}- } catch { /* non-WAL, busy, or unsupported β non-fatal */ }+ } catch (checkpointErr) {+ // #2968: on the sql.js fallback driver (engaged when better-sqlite3's+ // native binding never got built β e.g. a skipped optionalDependency+ // postinstall), this PRAGMA isn't implemented and throws "Invalid+ // PRAGMA command". sql.js has no WAL journal to checkpoint at all, so+ // this specific failure is the strongest signal available here that+ // the insert above may exist only in this process's in-memory image+ // and never reach disk β not the ordinary "non-WAL, busy, or+ // unsupported" case the old blanket catch assumed. Surface it rather+ // than swallow it silently; other pragma failures stay non-fatal.+ const msg = checkpointErr instanceof Error ? checkpointErr.message : String(checkpointErr);+ if (/Invalid PRAGMA/i.test(msg)) {+ persistWarning = `sql.js fallback driver in use β this write may not be durably persisted to disk (${msg}). Install better-sqlite3's native binding to restore durable writes (see issue #2968: npm rebuild better-sqlite3, or reinstall with install scripts enabled).`;+ }+ }// Phase 2: Write-through to TieredCacheconst safeNs = String(namespace).replace(/:/g, '_');@@ -985,6 +1007,7 @@ export async function bridgeStoreEntry(options: {guarded: true,cached: true,attested: true,+ ...(persistWarning ? { persistWarning } : {}),};} catch (err) {// #2775: distinguish a data-level UNIQUE constraint violation (key@@ -1089,10 +1112,17 @@ export async function bridgeSearchEntries(options: {let rows: any[];try {+ // #2982/#2976: this pre-rank SELECT truncates the corpus to 1000 rows+ // before BM25/embedding scoring runs. Without ORDER BY, SQLite returns+ // rows in arbitrary storage order (effectively oldest-inserted-first at+ // scale), so on any corpus over 1000 entries the newest β and often+ // most relevant β rows never reach scoring at all. bridgeListEntries()+ // already orders by updated_at DESC for the same reason; mirror it here.const stmt = ctx.db.prepare(`SELECT id, key, namespace, content, embedding, provenance_typeFROM memory_entriesWHERE ${ACTIVE_MEMORY_ROW_SQL} ${whereExtra}+ ORDER BY updated_at DESCLIMIT 1000`);rows = filterParams.length > 0 ? stmt.all(...filterParams) : stmt.all();@@ -1727,10 +1757,14 @@ export async function bridgeSearchHNSW(let rows: any[];try {+ // #2982/#2976: same unordered pre-rank truncation as bridgeSearchEntries+ // above β without ORDER BY, a corpus over 10000 rows silently drops+ // its newest entries before cosine scoring ever runs.const stmt = ctx.db.prepare(`SELECT id, key, namespace, content, embeddingFROM memory_entriesWHERE status = 'active' AND embedding IS NOT NULL ${nsFilter}+ ORDER BY updated_at DESCLIMIT 10000`);rows = nsFilterdiff --git a/v3/@claude-flow/cli/src/memory/memory-initializer.ts b/v3/@claude-flow/cli/src/memory/memory-initializer.tsindex 86032d37ce..b58f0cc30e 100644--- a/v3/@claude-flow/cli/src/memory/memory-initializer.ts+++ b/v3/@claude-flow/cli/src/memory/memory-initializer.ts@@ -2793,6 +2793,9 @@ export async function storeEntry(options: {id: string;embedding?: { dimensions: number; model: string };error?: string;+ /** #2968: set when the bridge's checkpoint failed in a way indicating+ * this write may not be durably persisted (sql.js fallback driver). */+ persistWarning?: string;}> {// ADR-323: validate before touching either backend so an invalid value// gets one clear error instead of a raw SQLite CHECK-constraint failure