π 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(agentdb): pattern-store returns a readable id, pattern-search surfaces why tier=substring fired (#3326)
rUv0acd10642068
diff --git a/v3/@claude-flow/cli/__tests__/agentdb-pattern-bridge-fallback-3324.test.ts b/v3/@claude-flow/cli/__tests__/agentdb-pattern-bridge-fallback-3324.test.tsnew file mode 100644index 0000000000..3d94079fff--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/agentdb-pattern-bridge-fallback-3324.test.ts@@ -0,0 +1,91 @@+/**+ * Regression for #3324: `bridgeStorePattern`'s SQL-fallback branch (taken+ * when the registry exists but `reasoningBank` itself is unusable β the+ * `controller: 'bridge-fallback'` path, the common real-world state per+ * #3288) returned `result.id` as the caller's `patternId`. `result` is+ * `bridgeStoreEntry`'s own return, and `result.id` is ITS internally+ * generated row id (`generateId('entry')`) β a different value from the+ * `key` the row was actually stored under. `getEntry`/`bridgeGetEntry` look+ * up by `key`, so the handle handed back could never be read back.+ *+ * Uses the documented `__setMemoryBridgeRegistryForTests` seam (see+ * memory-store-persist-warning-2968.test.ts for the established pattern) to+ * force the `bridge-fallback` branch deterministically β `getRegistry()`+ * never resolves a real registry in this test runner (`@claude-flow/memory`+ * is intentionally externalized), so this is the only way to reach that+ * branch at all in isolation.+ */+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-3324-pattern-fallback-'));+const dbPath = join(root, 'memory.db');+let db: Database.Database | null = null;++function makeDb(): Database.Database {+ // Deliberately no CREATE TABLE here: bridgeStorePattern/bridgeGetEntry's+ // shared getDb() calls ensureBridgeSchema(db) internally (CREATE TABLE IF+ // NOT EXISTS with the real, full column set β access_count, owner_id,+ // last_accessed_at, etc.). Pre-creating a partial schema here made it a+ // no-op on that call, and bridgeGetEntry's SELECT (which reads+ // access_count) then failed against the missing column β a self-inflicted+ // false negative, not the #3324 bug. Let the bridge own its own schema.+ return new Database(dbPath);+}++afterAll(async () => {+ const { __setMemoryBridgeRegistryForTests } = await import('../src/memory/memory-bridge.js');+ __setMemoryBridgeRegistryForTests(null);+ db?.close();+ rmSync(root, { recursive: true, force: true });+});++describe('#3324 bridgeStorePattern bridge-fallback round trip', () => {+ it('the returned patternId is the actual storage key, not bridgeStoreEntry\'s internal row id', async () => {+ const { __setMemoryBridgeRegistryForTests, bridgeStorePattern, bridgeGetEntry } = await import(+ '../src/memory/memory-bridge.js'+ );++ db = makeDb();+ // registry.get('reasoningBank') β null forces bridgeStorePattern past+ // the healthy branch into its SQL-fallback ('bridge-fallback') branch.+ __setMemoryBridgeRegistryForTests({+ getAgentDB: () => ({ database: db, embedder: null }),+ get: () => null,+ });++ const marker = `bridge-fallback-roundtrip-${Date.now()}`;+ const stored = await bridgeStorePattern({+ pattern: `Use ${marker} for secure session renewal`,+ type: 'auth-pattern',+ confidence: 0.9,+ dbPath,+ });++ expect(stored).not.toBeNull();+ expect(stored!.success).toBe(true);+ expect(stored!.controller).toBe('bridge-fallback');+ // generateId('pattern') vs bridgeStoreEntry's own generateId('entry') β+ // the two id namespaces are distinguishable by prefix, which is exactly+ // the class of mixup #3324 reported (returning the entry-prefixed id+ // instead of the pattern-prefixed key).+ expect(stored!.patternId).toMatch(/^pattern[_-]/);+ expect(stored!.patternId).not.toMatch(/^entry[_-]/);++ const got = await bridgeGetEntry({ key: stored!.patternId, namespace: 'pattern', dbPath });+ expect(got).not.toBeNull();+ expect(got!.found).toBe(true);+ expect(got!.entry?.content).toContain(marker);++ // Directly confirms the row is genuinely stored under this key (not just+ // that bridgeGetEntry happens to also be broken the same way).+ const row = db.prepare('SELECT key, content FROM memory_entries WHERE key = ?').get(stored!.patternId) as+ | { key: string; content: string }+ | undefined;+ expect(row).toBeDefined();+ expect(row!.content).toContain(marker);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/bug-cluster-2219-2226.test.ts b/v3/@claude-flow/cli/__tests__/bug-cluster-2219-2226.test.tsindex 2513d8e0ee..241c31e45a 100644--- a/v3/@claude-flow/cli/__tests__/bug-cluster-2219-2226.test.ts+++ b/v3/@claude-flow/cli/__tests__/bug-cluster-2219-2226.test.ts@@ -268,3 +268,27 @@ describe('3.10.8 #bugC β boolean flags accept an explicit space-form value', (expect(parse(['--no-explore'])).toBe(false);});});++describe('#3325 β agentdb_pattern-search surfaces why tier=substring fired', () => {+ it('when tier is substring, semanticError (if present) is a diagnosable string, not silently swallowed', async () => {+ const marker = `semantic-error-3325-${process.pid}-${process.hrtime.bigint()}`;+ await agentdbPatternStore.handler({+ pattern: `Use ${marker} for secure session renewal`,+ type: 'auth-pattern',+ confidence: 0.9,+ });+ const found = await agentdbPatternSearch.handler({ query: marker, topK: 5, minConfidence: 0.1 });+ if (!found || !Array.isArray(found.results)) return; // backend unavailable in isolation β skip++ if (found.tier === 'substring' && 'semanticError' in found) {+ // The exact bug: a thrown error or {success:false} used to be+ // indistinguishable from an honest zero-match. If tier 1 did fail,+ // that reason must now be a non-empty, human-readable string.+ expect(typeof found.semanticError).toBe('string');+ expect((found.semanticError as string).length).toBeGreaterThan(0);+ }+ // tier === 'semantic', or substring with no semanticError (an honest+ // zero-match) are both fine β this test only guards against a swallowed+ // failure being indistinguishable from "nothing found".+ }, 60_000);+});diff --git a/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.tsindex 151fd37139..de015c9222 100644--- a/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts@@ -300,12 +300,23 @@ export const agentdbPatternSearch: MCPTool = {// Tier 1 β semanticlet results: Array<Record<string, unknown>> = [];let tier: 'semantic' | 'substring' = 'semantic';+ // #3325: a thrown error and a genuine zero-match were indistinguishable+ // β `catch {}` discarded the former, `semantic?.results ?? []` treated+ // `{success: false, error}` (which searchEntries returns WITHOUT+ // throwing) as the latter. Capture whichever fires so a caller that+ // lands on tier=substring can tell why, instead of source-reading.+ let semanticError: string | undefined;try {const semantic = await searchEntries({ query, namespace: 'pattern', limit: topK });+ if (semantic && semantic.success === false) {+ semanticError = semantic.error ?? 'searchEntries returned success:false';+ }results = (semantic?.results ?? []).map(parseEntry).filter((r): r is Record<string, unknown> => r !== null);- } catch { /* fall through to tier 2 */ }+ } catch (err) {+ semanticError = sanitizeError(err);+ }// Tier 2 β substring scan (catches just-written entries before HNSW indexes them).// #2226: listEntries returns metadata only (no content/value β see open #2014),@@ -351,6 +362,11 @@ export const agentdbPatternSearch: MCPTool = {reason: result ? `reasoningBank-empty:${result.controller ?? 'unknown'}` : 'reasoningBank-unavailable:registry-null',controller: 'memory-store-fallback',tier,+ // #3325: when tier=substring because tier 1 hit a real error (thrown,+ // or {success:false, error}) rather than a genuine zero-match,+ // surface why β otherwise a hard failure and an honest "not found"+ // are indistinguishable from the response alone.+ ...(tier === 'substring' && semanticError ? { semanticError } : {}),note: result? `ReasoningBank returned 0 results; tier=${tier} from pattern namespace.`: `ReasoningBank controller unavailable; tier=${tier} from pattern namespace.`,diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.tsindex 0072275cb4..3d3afb801c 100644--- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts+++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts@@ -2132,7 +2132,12 @@ export async function bridgeStorePattern(options: {} catch { /* HNSW is best-effort */ }}- return { success: true, patternId: result.id, controller: 'bridge-fallback' };+ // #3324: bridgeStoreEntry's `result.id` is its OWN internally generated+ // row id (generateId('entry')), a different value from the `key` the row+ // was actually stored under. getEntry/memory_retrieve look up by `key`,+ // so returning result.id here handed the caller a handle that can never+ // be read back β return `patternId` (the real key) instead.+ return { success: true, patternId, controller: 'bridge-fallback' };} catch {return null;}