Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 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

feat: wire SmartRetrieval (ADR-090) into production memory pipeline

rUvd66358149712
diff --git a/plugins/ruflo-rag-memory/README.md b/plugins/ruflo-rag-memory/README.md
index 2879f6680f..b69e3328ea 100644
--- a/plugins/ruflo-rag-memory/README.md
+++ b/plugins/ruflo-rag-memory/README.md
@@ -101,6 +101,26 @@ Auto-imports Claude Code's native `~/.claude/projects/*/memory/*.md` files into
Results include source attribution: `claude-code`, `auto-memory`, or `agentdb`.
+## SmartRetrieval (ADR-090)
+
+5-phase retrieval pipeline for higher-quality recall across sessions:
+
+1. **Query expansion** -- template-based variant generation (no LLM)
+2. **Multi-query fan-out + RRF** -- Reciprocal Rank Fusion across variants
+3. **Recency boost** -- exponential decay from metadata timestamps
+4. **MMR diversity** -- token-Jaccard Maximal Marginal Relevance re-ranking
+5. **Session round-robin** -- interleaved results from distinct sessions
+
+```bash
+# CLI
+npx @claude-flow/cli@latest memory search --query "auth patterns" --smart --limit 10
+
+# MCP
+mcp__claude-flow__memory_search({ query: "auth patterns", smart: true, limit: 10 })
+```
+
+Best for multi-session recall, temporal queries ("what did we decide last week?"), and diverse result sets.
+
## Unified Search
Queries across all namespaces simultaneously with MMR diversity reranking:
diff --git a/plugins/ruflo-rag-memory/skills/memory-search/SKILL.md b/plugins/ruflo-rag-memory/skills/memory-search/SKILL.md
index 71fab5b0e5..e8072901f4 100644
--- a/plugins/ruflo-rag-memory/skills/memory-search/SKILL.md
+++ b/plugins/ruflo-rag-memory/skills/memory-search/SKILL.md
@@ -37,6 +37,15 @@ Choose based on query type:
npx ruvector search "QUERY" --graph-rag --limit 10
```
+ **Smart retrieval** (when --smart or complex recall needed):
+ ```bash
+ npx @claude-flow/cli@latest memory search --query "QUERY" --smart --limit 10
+ ```
+ Or via MCP: `mcp__claude-flow__memory_search({ query: "QUERY", smart: true, limit: 10 })`
+
+ Applies 5-phase pipeline: query expansion, RRF fusion, recency boost, MMR diversity, session round-robin.
+ Best for: multi-session recall, temporal queries, diverse result sets.
+
**Unified cross-namespace**:
`mcp__claude-flow__memory_search_unified({ query: "QUERY", limit: 10 })`
diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.ts
index 724b37e341..8dff877467 100644
--- a/v3/@claude-flow/cli/src/commands/memory.ts
+++ b/v3/@claude-flow/cli/src/commands/memory.ts
@@ -279,12 +279,20 @@ const searchCommand: Command = {
description: 'Build/rebuild HNSW index before searching (enables 150x-12,500x speedup)',
type: 'boolean',
default: false
+ },
+ {
+ name: 'smart',
+ short: 's',
+ description: 'Use SmartRetrieval pipeline (query expansion, RRF, MMR, recency)',
+ type: 'boolean',
+ default: false
}
],
examples: [
{ command: 'claude-flow memory search -q "authentication patterns"', description: 'Semantic search' },
{ command: 'claude-flow memory search -q "JWT" -t keyword', description: 'Keyword search' },
- { command: 'claude-flow memory search -q "test" --build-hnsw', description: 'Build HNSW index and search' }
+ { command: 'claude-flow memory search -q "test" --build-hnsw', description: 'Build HNSW index and search' },
+ { command: 'claude-flow memory search -q "auth patterns" --smart', description: 'SmartRetrieval with RRF + MMR' }
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const query = ctx.flags.query as string || ctx.args[0];
@@ -331,33 +339,84 @@ const searchCommand: Command = {
// Use direct sql.js search with vector similarity
try {
const { searchEntries } = await import('../memory/memory-initializer.js');
+ const useSmart = (ctx.flags.smart || ctx.flags.s) as boolean;
+
+ let results: { key: string; score: number; namespace: string; preview: string }[];
+ let searchTimeMs: number;
+ let smartStats: Record<string, unknown> | undefined;
+ let backendLabel = 'HNSW + sql.js';
+
+ if (useSmart) {
+ const { smartSearch } = await import('@claude-flow/memory');
+
+ // Adapt searchEntries to the SearchFn interface
+ const rawSearch = async (req: { query: string; namespace?: string; limit?: number; threshold?: number }) => {
+ const r = await searchEntries({
+ query: req.query,
+ namespace: req.namespace || namespace,
+ limit: req.limit || limit * 3,
+ threshold: req.threshold ?? threshold,
+ });
+ return {
+ results: r.results.map(e => ({
+ id: e.id,
+ key: e.key,
+ content: e.content,
+ score: e.score,
+ namespace: e.namespace,
+ })),
+ };
+ };
- const searchResult = await searchEntries({
- query,
- namespace,
- limit,
- threshold
- });
+ const smartResult = await smartSearch(rawSearch, {
+ query,
+ namespace,
+ limit,
+ threshold,
+ });
- if (!searchResult.success) {
- output.printError(searchResult.error || 'Search failed');
- return { success: false, exitCode: 1 };
- }
+ results = smartResult.results.map(r => ({
+ key: r.key,
+ score: r.score,
+ namespace: r.namespace,
+ preview: r.content,
+ }));
+ searchTimeMs = smartResult.stats.durationMs;
+ smartStats = smartResult.stats as unknown as Record<string, unknown>;
+ backendLabel = 'SmartRetrieval (RRF + MMR + Recency)';
+ } else {
+ const searchResult = await searchEntries({
+ query,
+ namespace,
+ limit,
+ threshold
+ });
- const results = searchResult.results.map(r => ({
- key: r.key,
- score: r.score,
- namespace: r.namespace,
- preview: r.content
- }));
+ if (!searchResult.success) {
+ output.printError(searchResult.error || 'Search failed');
+ return { success: false, exitCode: 1 };
+ }
+
+ results = searchResult.results.map(r => ({
+ key: r.key,
+ score: r.score,
+ namespace: r.namespace,
+ preview: r.content
+ }));
+ searchTimeMs = searchResult.searchTime;
+ }
if (ctx.flags.format === 'json') {
- output.printJson({ query, searchType, results, searchTime: `${searchResult.searchTime}ms` });
+ output.printJson({ query, searchType, results, searchTime: `${searchTimeMs}ms`, ...(smartStats ? { stats: smartStats } : {}) });
return { success: true, data: results };
}
// Performance stats
- output.writeln(output.dim(` Search time: ${searchResult.searchTime}ms`));
+ output.writeln(output.dim(` Search time: ${searchTimeMs}ms`));
+ if (useSmart && smartStats) {
+ output.writeln(output.dim(` Backend: ${backendLabel}`));
+ output.writeln(output.dim(` Variants: ${(smartStats as any).variantCount}, Raw candidates: ${(smartStats as any).rawCandidateCount}`));
+ }
output.writeln();
if (results.length === 0) {
diff --git a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
index 48f1a2bda2..a645052781 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
@@ -337,6 +337,7 @@ export const memoryTools: MCPTool[] = [
namespace: { type: 'string', description: 'Namespace to search (default: "default")' },
limit: { type: 'number', description: 'Maximum results (default: 10)' },
threshold: { type: 'number', description: 'Minimum similarity threshold 0-1 (default: 0.3)' },
+ smart: { type: 'boolean', description: 'Enable SmartRetrieval pipeline β€” query expansion, RRF fusion, recency boost, MMR diversity (default: false)' },
},
required: ['query'],
},
@@ -354,6 +355,60 @@ export const memoryTools: MCPTool[] = [
const startTime = performance.now();
try {
+ if (input.smart) {
+ // SmartRetrieval pipeline (ADR-090)
+ const { smartSearch } = await import('@claude-flow/memory');
+
+ // Adapt searchEntries to the SearchFn interface
+ const rawSearch = async (req: { query: string; namespace?: string; limit?: number; threshold?: number }) => {
+ const r = await searchEntries({
+ query: req.query,
+ namespace: req.namespace || namespace,
+ limit: req.limit || limit * 3,
+ threshold: req.threshold ?? threshold,
+ });
+ return {
+ results: r.results.map(e => ({
+ id: e.id,
+ key: e.key,
+ content: e.content,
+ score: e.score,
+ namespace: e.namespace,
+ })),
+ };
+ };
+
+ const smartResult = await smartSearch(rawSearch, {
+ query,
+ namespace,
+ limit,
+ threshold,
+ });
+
+ const duration = performance.now() - startTime;
+
+ const results = smartResult.results.map(r => {
+ let value: unknown = r.content;
+ try { value = JSON.parse(r.content); } catch { /* keep as string */ }
+ return {
+ key: r.key,
+ namespace: r.namespace,
+ value,
+ similarity: r.score,
+ };
+ });
+
+ return {
+ query,
+ results,
+ total: results.length,
+ searchTime: `${duration.toFixed(2)}ms`,
+ backend: 'SmartRetrieval (RRF + MMR + Recency)',
+ stats: smartResult.stats,
+ };
+ }
+
+ // Original non-smart path (unchanged)
const result = await searchEntries({
query,
namespace,
diff --git a/v3/@claude-flow/memory/src/index.ts b/v3/@claude-flow/memory/src/index.ts
index 7bbdcef6de..9ca0840b3c 100644
--- a/v3/@claude-flow/memory/src/index.ts
+++ b/v3/@claude-flow/memory/src/index.ts
@@ -205,6 +205,18 @@ export { MemoryMigrator, createMigrator, migrateMultipleSources } from './migrat
export { createDatabase, getPlatformInfo, getAvailableProviders } from './database-provider.js';
export type { DatabaseProvider, DatabaseOptions } from './database-provider.js';
+// ===== Smart Retrieval (ADR-090) =====
+export { smartSearch, defaultQueryExpansions } from './smart-retrieval.js';
+export type {
+ SearchCandidate,
+ RawSearchRequest,
+ RawSearchResponse,
+ SearchFn,
+ SmartSearchOptions,
+ SmartSearchStats,
+ SmartSearchResult,
+} from './smart-retrieval.js';
+
// ===== Unified Memory Service =====
import { EventEmitter } from 'node:events';
import {
diff --git a/v3/@claude-flow/memory/src/smart-retrieval.test.ts b/v3/@claude-flow/memory/src/smart-retrieval.test.ts
new file mode 100644
index 0000000000..6f092545ad
--- /dev/null
+++ b/v3/@claude-flow/memory/src/smart-retrieval.test.ts
@@ -0,0 +1,271 @@
+import { describe, it, expect, vi } from 'vitest';
+import {
+ smartSearch,
+ defaultQueryExpansions,
+ type SearchCandidate,
+ type SearchFn,
+} from './smart-retrieval.js';
+
+function makeCandidate(partial: Partial<SearchCandidate> & { id: string; content: string }): SearchCandidate {
+ return {
+ key: partial.id,
+ namespace: 'test',
+ score: 0.5,
+ ...partial,
+ };
+}
+
+describe('defaultQueryExpansions', () => {
+ it('returns the original query plus keyword-only and context variants', () => {
+ const variants = defaultQueryExpansions('What is the capital of France?');
+ expect(variants.length).toBeGreaterThanOrEqual(2);
+ expect(variants[0]).toBe('What is the capital of France?');
+ // Keyword variant strips stopwords
+ expect(variants.some((v) => v.includes('capital') && v.includes('france'))).toBe(true);
+ });
+
+ it('drops duplicate variants', () => {
+ const variants = defaultQueryExpansions('hello');
+ expect(new Set(variants).size).toBe(variants.length);
+ });
+
+ it('handles empty input', () => {
+ expect(defaultQueryExpansions('')).toEqual([]);
+ });
+});
+
+describe('smartSearch β€” multi-query fan-out', () => {
+ it('fans out one call per variant and fuses with RRF', async () => {
+ const calls: string[] = [];
+ const search: SearchFn = async ({ query }) => {
+ calls.push(query);
+ // Each variant returns a slightly different list. Item A is top of first,
+ // bottom of second; item B is the inverse. RRF should put A and B both
+ // near the top because they each appear in two variant lists.
+ if (query.includes('tell me about')) {
+ return {
+ results: [
+ makeCandidate({ id: 'b', content: 'beta content', score: 0.9 }),
+ makeCandidate({ id: 'a', content: 'alpha content', score: 0.4 }),
+ ],
+ };
+ }
+ return {
+ results: [
+ makeCandidate({ id: 'a', content: 'alpha content', score: 0.9 }),
+ makeCandidate({ id: 'b', content: 'beta content', score: 0.4 }),
+ ],
+ };
+ };
+
+ const { results, stats } = await smartSearch(search, {
+ query: 'alpha beta',
+ limit: 5,
+ diversityMMR: false,
+ sessionDiversity: false,
+ recencyBoost: false,
+ });
+
+ expect(stats.variantCount).toBeGreaterThanOrEqual(1);
+ expect(calls.length).toBe(stats.variantCount);
+ expect(results.map((r) => r.id)).toEqual(expect.arrayContaining(['a', 'b']));
+ });
+
+ it('falls back to a single raw call when multiQuery=false', async () => {
+ const search = vi.fn<SearchFn>(async () => ({
+ results: [makeCandidate({ id: 'x', content: 'only one' })],
+ }));
+
+ await smartSearch(search, {
+ query: 'whatever',
+ multiQuery: false,
+ diversityMMR: false,
+ sessionDiversity: false,
+ recencyBoost: false,
+ });
+
+ expect(search).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('smartSearch β€” recency boost', () => {
+ it('reorders stale candidates below fresh ones at equal similarity', async () => {
+ const now = Date.parse('2026-04-11T00:00:00Z');
+ const oneDay = 24 * 60 * 60 * 1000;
+
+ const search: SearchFn = async () => ({
+ results: [
+ makeCandidate({
+ id: 'stale',
+ content: 'stale content',
+ score: 0.8,
+ updatedAt: now - 365 * oneDay, // a year old
+ }),
+ makeCandidate({
+ id: 'fresh',
+ content: 'fresh content',
+ score: 0.78,
+ updatedAt: now - oneDay, // yesterday
+ }),
+ ],
+ });
+
+ const { results } = await smartSearch(search, {
+ query: 'something',
+ limit: 2,
+ multiQuery: false,
+ diversityMMR: false,
+ sessionDiversity: false,
+ recencyHalfLifeDays: 30,
+ recencyWeight: 0.5,
+ now,
+ });
+
+ expect(results[0].id).toBe('fresh');
+ expect(results[1].id).toBe('stale');
+ });
+
+ it('is a no-op when candidates have no timestamps', async () => {
+ const search: SearchFn = async () => ({
+ results: [
+ makeCandidate({ id: 'a', content: 'alpha', score: 0.9 }),
+ makeCandidate({ id: 'b', content: 'beta', score: 0.8 }),
+ ],
+ });
+
+ const { results } = await smartSearch(search, {
+ query: 'x',
+ multiQuery: false,
+ diversityMMR: false,
+ sessionDiversity: false,
+ recencyBoost: true,
+ });
+
+ expect(results.map((r) => r.id)).toEqual(['a', 'b']);
+ });
+});
+
+describe('smartSearch β€” MMR diversity', () => {
+ it('pushes near-duplicate content down the list', async () => {
+ const search: SearchFn = async () => ({
+ results: [
+ makeCandidate({ id: '1', content: 'the cat sat on the mat quietly', score: 0.95 }),
+ makeCandidate({ id: '2', content: 'the cat sat on the mat quietly today', score: 0.94 }),
+ makeCandidate({ id: '3', content: 'quantum entanglement paradox resolved', score: 0.6 }),
+ ],
+ });
+
+ const { results } = await smartSearch(search, {
+ query: 'x',
+ limit: 3,
+ multiQuery: false,
+ recencyBoost: false,
+ sessionDiversity: false,
+ diversityMMR: true,
+ mmrLambda: 0.3, // lean heavily on diversity
+ });
+
+ // Seed is #1 (top). Between #2 (near-duplicate) and #3 (different topic),
+ // MMR with Ξ»=0.3 should pick #3 second.
+ expect(results[0].id).toBe('1');
+ expect(results[1].id).toBe('3');
+ });
+});
+
+describe('smartSearch β€” session round-robin', () => {
+ it('interleaves results across distinct sessions', async () => {
+ const search: SearchFn = async () => ({
+ results: [
+ makeCandidate({
+ id: 'a1',
+ content: 'alpha one',
+ score: 0.95,
+ metadata: { session_id: 'A' },
+ }),
+ makeCandidate({
+ id: 'a2',
+ content: 'alpha two',
+ score: 0.9,
+ metadata: { session_id: 'A' },
+ }),
+ makeCandidate({
+ id: 'b1',
+ content: 'beta one',
+ score: 0.85,
+ metadata: { session_id: 'B' },
+ }),
+ makeCandidate({
+ id: 'c1',
+ content: 'gamma one',
+ score: 0.8,
+ metadata: { session_id: 'C' },
+ }),
+ ],
+ });
+
+ const { results } = await smartSearch(search, {
+ query: 'x',
+ limit: 3,
+ multiQuery: false,
+ recencyBoost: false,
+ diversityMMR: false,
+ sessionDiversity: true,
+ });
+
+ const sessions = results.map((r) => r.metadata?.session_id);
+ // Top-3 should cover 3 distinct sessions, not just session A twice.
+ expect(new Set(sessions).size).toBe(3);
+ expect(sessions[0]).toBe('A'); // Highest-scored bucket leader first
+ });
+
+ it('passes through when all candidates share one session', async () => {
+ const search: SearchFn = async () => ({
+ results: [
+ makeCandidate({
+ id: 'a1',
+ content: 'one',
+ score: 0.9,
+ metadata: { session_id: 'S' },
+ }),
+ makeCandidate({
+ id: 'a2',
+ content: 'two',
+ score: 0.8,
+ metadata: { session_id: 'S' },
+ }),
+ ],
+ });
+
+ const { results } = await smartSearch(search, {
+ query: 'x',
+ limit: 2,
+ multiQuery: false,
+ recencyBoost: false,
+ diversityMMR: false,
+ sessionDiversity: true,
+ });
+
+ expect(results.map((r) => r.id)).toEqual(['a1', 'a2']);
+ });
+});
+
+describe('smartSearch β€” stats reporting', () => {
+ it('reports variant count, raw candidate count, and phase counts', async () => {
+ const search: SearchFn = async () => ({
+ results: [
+ makeCandidate({ id: 'a', content: 'alpha' }),
+ makeCandidate({ id: 'b', content: 'beta' }),
+ ],
+ });
+
+ const { stats } = await smartSearch(search, {
+ query: 'hello world',
+ limit: 2,
+ });
+
+ expect(stats.variantCount).toBeGreaterThanOrEqual(1);
+ expect(stats.rawCandidateCount).toBeGreaterThan(0);
+ expect(stats.variants.length).toBe(stats.variantCount);
+ expect(stats.durationMs).toBeGreaterThanOrEqual(0);
+ });
+});
diff --git a/v3/@claude-flow/memory/src/smart-retrieval.ts b/v3/@claude-flow/memory/src/smart-retrieval.ts
new file mode 100644
index 0000000000..2e9d51c3a0
--- /dev/null
+++ b/v3/@claude-flow/memory/src/smart-retrieval.ts
@@ -0,0 +1,433 @@
+/**
+ * SmartRetrieval β€” LongMemEval-derived retrieval pipeline (ADR-090)
+ *
+ * Wraps a raw HNSW `SearchFn` with the optimizations identified by the
+ * ADR-088 LongMemEval benchmark:
+ *
+ * 1. Query expansion (template-based, no LLM)
+ * 2. Multi-query fan-out + Reciprocal Rank Fusion
+ * 3. Recency boost from metadata timestamps
+ * 4. MMR diversity re-ranking (token-Jaccard proxy)
+ * 5. Session round-robin for multi-session coverage
+ *
+ * The module is pluggable: callers provide a `SearchFn` that hits whatever
+ * raw store they use (AgentDB HNSW, sql.js, a test fake, etc.). That keeps
+ * `@claude-flow/memory` free of a hard dependency on the CLI's memory-initializer
+ * and makes the pipeline easy to benchmark in isolation.
+ */
+
+// ── Types ──────────────────────────────────────────────────────
+
+export interface SearchCandidate {
+ id: string;
+ key: string;
+ content: string;
+ score: number;
+ namespace: string;
+ /** Optional metadata pulled through from the underlying store. */
+ metadata?: Record<string, unknown>;
+ /** Optional unix-ms timestamp used by the recency booster. */
+ createdAt?: number;
+ /** Optional unix-ms timestamp; preferred over createdAt when present. */
+ updatedAt?: number;
+}
+
+export interface RawSearchRequest {
+ query: string;
+ namespace?: string;
+ limit?: number;
+ threshold?: number;
+}
+
+export interface RawSearchResponse {
+ results: SearchCandidate[];
+}
+
+/** Pluggable raw search function β€” typically wraps HNSW or a test fake. */
+export type SearchFn = (req: RawSearchRequest) => Promise<RawSearchResponse>;
+
+export interface SmartSearchOptions {
+ query: string;
+ namespace?: string;
+ /** Final number of results to return (default 10). */
+ limit?: number;
+ /** Similarity floor applied to the raw store (default 0.3). */
+ threshold?: number;
+
+ // ── Phase toggles ──
+ /** Fan out 2-3 expanded query variants and fuse with RRF. Default: true. */
+ multiQuery?: boolean;
+ /** Re-score with recency boost using entry timestamps. Default: true. */
+ recencyBoost?: boolean;
+ /** Apply MMR diversity re-ranking. Default: true. */
+ diversityMMR?: boolean;
+ /** Round-robin across distinct session_ids. Default: true. */
+ sessionDiversity?: boolean;
+
+ // ── Tunables ──
+ /** How many candidates to pull from the raw store per variant (default limit Γ— 3). */
+ fanOutK?: number;
+ /** RRF constant; 60 is the standard default. */
+ rrfK?: number;
+ /** Recency half-life in days; older entries decay past this. Default 30. */
+ recencyHalfLifeDays?: number;
+ /** Max recency multiplier applied to top of the curve. Default 0.2. */
+ recencyWeight?: number;
+ /** MMR tradeoff Ξ» β€” 1.0 = pure relevance, 0.0 = pure diversity. Default 0.7. */
+ mmrLambda?: number;
+ /** Metadata key that identifies a session for round-robin. Default 'session_id'. */
+ sessionKey?: string;
+ /** "Now" for recency decay β€” pass a fixed value in tests for determinism. */
+ now?: number;
+
+ /** Override the default template-based expansions with your own set. */
+ queryExpansions?: (query: string) => string[];
+}
+
+export interface SmartSearchStats {
+ variantCount: number;
+ variants: string[];
+ rawCandidateCount: number;
+ afterRrfCount: number;
+ afterRecencyCount: number;
+ afterMmrCount: number;
+ afterSessionCount: number;
+ durationMs: number;
+}
+
+export interface SmartSearchResult {
+ results: SearchCandidate[];
+ stats: SmartSearchStats;
+}
+
+// ── Query Expansion ────────────────────────────────────────────
+
+const STOPWORDS = new Set([
+ 'a', 'an', 'and', 'are', 'as', 'at', 'be', 'but', 'by', 'did', 'do', 'does',
+ 'for', 'from', 'has', 'have', 'how', 'i', 'if', 'in', 'is', 'it', 'its', 'me',
+ 'my', 'of', 'on', 'or', 'that', 'the', 'this', 'to', 'was', 'were', 'what',
+ 'when', 'where', 'which', 'who', 'why', 'will', 'with', 'you', 'your',
+]);
+
+/**
+ * Default query expansion set. Keeps variants cheap (≀3) so we only pay
+ * ~3Γ— the HNSW cost on the hot path.
+ */
+export function defaultQueryExpansions(query: string): string[] {
+ const trimmed = query.trim();
+ if (!trimmed) return [];
+
+ const variants = new Set<string>();
+ variants.add(trimmed);
+
+ const keywords = keywordExtract(trimmed);
+ if (keywords && keywords !== trimmed.toLowerCase()) {
+ variants.add(keywords);
+ }
+
+ // Context-priming variant β€” helps when the query is short or imperative.
+ const words = trimmed.toLowerCase().replace(/[?.!]+$/, '');
+ if (words && !words.startsWith('tell me')) {
+ variants.add(`tell me about ${words}`);
+ }
+
+ return [...variants];
+}
+
+function keywordExtract(query: string): string {
+ return query
+ .toLowerCase()
+ .replace(/[^\w\s]/g, ' ')
+ .split(/\s+/)
+ .filter((w) => w.length > 2 && !STOPWORDS.has(w))
+ .join(' ');
+}
+
+// ── Reciprocal Rank Fusion ─────────────────────────────────────
+
+interface Scored {
+ candidate: SearchCandidate;
+ score: number;
+}
+
+function reciprocalRankFusion(
+ rankedLists: SearchCandidate[][],
+ k: number
+): Scored[] {
+ const fused = new Map<string, { candidate: SearchCandidate; score: number }>();
+
+ for (const list of rankedLists) {
+ for (let rank = 0; rank < list.length; rank++) {
+ const cand = list[rank];
+ const rrfContribution = 1 / (k + rank + 1);
+ const key = candidateKey(cand);
+ const existing = fused.get(key);
+ if (existing) {
+ existing.score += rrfContribution;
+ // Keep the highest raw score we've seen for display purposes.
+ if (cand.score > existing.candidate.score) {
+ existing.candidate = cand;
+ }
+ } else {
+ fused.set(key, { candidate: cand, score: rrfContribution });
+ }
+ }
+ }
+
+ return [...fused.values()].sort((a, b) => b.score - a.score);
+}
+
+function candidateKey(cand: SearchCandidate): string {
+ // Fall back through id β†’ key β†’ content hash so deduplication is robust
+ // even when the raw store omits ids.
+ return cand.id || cand.key || cand.content.slice(0, 128);
+}
+
+// ── Recency Boost ──────────────────────────────────────────────
+
+function applyRecencyBoost(
+ scored: Scored[],
+ opts: Required<Pick<SmartSearchOptions, 'recencyHalfLifeDays' | 'recencyWeight'>> & { now: number }
+): Scored[] {
+ const halfLifeMs = opts.recencyHalfLifeDays * 24 * 60 * 60 * 1000;
+ if (halfLifeMs <= 0) return scored;
+
+ return scored
+ .map(({ candidate, score }) => {
+ const ts = pickTimestamp(candidate);
+ if (!ts || !Number.isFinite(ts)) {
+ return { candidate, score };
+ }
+ const ageMs = Math.max(0, opts.now - ts);
+ // Exponential decay, normalized to [0,1].
+ const recency = Math.pow(0.5, ageMs / halfLifeMs);
+ const boosted = score * (1 + opts.recencyWeight * recency);
+ return { candidate, score: boosted };
+ })
+ .sort((a, b) => b.score - a.score);
+}
+
+function pickTimestamp(cand: SearchCandidate): number | undefined {
+ if (cand.updatedAt && Number.isFinite(cand.updatedAt)) return cand.updatedAt;
+ if (cand.createdAt && Number.isFinite(cand.createdAt)) return cand.createdAt;
+ const meta = cand.metadata;
+ if (meta) {
+ const candidates = ['timestamp', 'updatedAt', 'createdAt', 'time', 'ts'];
+ for (const k of candidates) {
+ const v = meta[k];
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
+ if (typeof v === 'string') {
+ const parsed = Date.parse(v);
+ if (Number.isFinite(parsed)) return parsed;
+ }
+ }
+ }
+ return undefined;
+}
+
+// ── MMR Diversity (token-Jaccard proxy) ────────────────────────
+
+function mmrRerank(scored: Scored[], lambda: number, limit: number): Scored[] {
+ if (scored.length <= 1) return scored.slice(0, limit);
+
+ const selected: Scored[] = [];
+ const remaining = [...scored];
+ const selectedTokens: Set<string>[] = [];
+
+ // Seed with the top-scored candidate.
+ const first = remaining.shift()!;
+ selected.push(first);
+ selectedTokens.push(tokenize(first.candidate.content));
+
+ while (selected.length < limit && remaining.length > 0) {
+ let bestIdx = -1;
+ let bestMmr = -Infinity;
+
+ for (let i = 0; i < remaining.length; i++) {
+ const cand = remaining[i];
+ const candTokens = tokenize(cand.candidate.content);
+ let maxOverlap = 0;
+ for (const selTokens of selectedTokens) {
+ const sim = jaccard(candTokens, selTokens);
+ if (sim > maxOverlap) maxOverlap = sim;
+ }
+ const mmr = lambda * cand.score - (1 - lambda) * maxOverlap;
+ if (mmr > bestMmr) {
+ bestMmr = mmr;
+ bestIdx = i;
+ }
+ }
+
+ if (bestIdx < 0) break;
+ const [chosen] = remaining.splice(bestIdx, 1);
+ selected.push(chosen);
+ selectedTokens.push(tokenize(chosen.candidate.content));
+ }
+
+ return selected;
+}
+
+function tokenize(text: string): Set<string> {
+ return new Set(
+ text
+ .toLowerCase()
+ .replace(/[^\w\s]/g, ' ')
+ .split(/\s+/)
+ .filter((t) => t.length > 2 && !STOPWORDS.has(t))
+ );
+}
+
+function jaccard(a: Set<string>, b: Set<string>): number {
+ if (a.size === 0 && b.size === 0) return 0;
+ let intersect = 0;
+ for (const t of a) if (b.has(t)) intersect++;
+ const union = a.size + b.size - intersect;
+ return union === 0 ? 0 : intersect / union;
+}
+
+// ── Session Round-Robin ────────────────────────────────────────
+
+function sessionRoundRobin(
+ scored: Scored[],
+ sessionKey: string,
+ limit: number
+): Scored[] {
+ if (scored.length === 0) return scored;
+
+ const bySession = new Map<string, Scored[]>();
+ for (const item of scored) {
+ const sid = getSessionId(item.candidate, sessionKey) ?? '__no_session__';
+ const bucket = bySession.get(sid);
+ if (bucket) bucket.push(item);
+ else bySession.set(sid, [item]);
+ }
+
+ // If every candidate falls in the same bucket we can't diversify β€” pass through.
+ if (bySession.size <= 1) return scored.slice(0, limit);
+
+ // Round-robin across session buckets, preferring each bucket's highest score.
+ const buckets = [...bySession.values()].map((b) =>
+ [...b].sort((a, b) => b.score - a.score)
+ );
+ const interleaved: Scored[] = [];
+ const seen = new Set<string>();
+
+ while (interleaved.length < limit) {
+ let progressed = false;
+ for (const bucket of buckets) {
+ while (bucket.length > 0) {
+ const next = bucket.shift()!;
+ const key = candidateKey(next.candidate);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ interleaved.push(next);
+ progressed = true;
+ break;
+ }
+ if (interleaved.length >= limit) break;
+ }
+ if (!progressed) break;
+ }
+
+ return interleaved;
+}
+
+function getSessionId(cand: SearchCandidate, key: string): string | undefined {
+ const meta = cand.metadata;
+ if (!meta) return undefined;
+ const v = meta[key];
+ return typeof v === 'string' ? v : undefined;
+}
+
+// ── Public API ─────────────────────────────────────────────────
+
+export async function smartSearch(
+ search: SearchFn,
+ opts: SmartSearchOptions
+): Promise<SmartSearchResult> {
+ const start = Date.now();
+ const limit = opts.limit ?? 10;
+ const threshold = opts.threshold ?? 0.3;
+ const fanOutK = opts.fanOutK ?? Math.max(limit * 3, 20);
+ const rrfK = opts.rrfK ?? 60;
+ const recencyHalfLifeDays = opts.recencyHalfLifeDays ?? 30;
+ const recencyWeight = opts.recencyWeight ?? 0.2;
+ const mmrLambda = opts.mmrLambda ?? 0.7;
+ const sessionKey = opts.sessionKey ?? 'session_id';
+ const now = opts.now ?? Date.now();
+
+ const multiQuery = opts.multiQuery !== false;
+ const recencyBoost = opts.recencyBoost !== false;
+ const diversityMMR = opts.diversityMMR !== false;
+ const sessionDiversity = opts.sessionDiversity !== false;
+
+ const expander = opts.queryExpansions ?? defaultQueryExpansions;
+
+ // ── Phase 1: query expansion + fan-out ──
+ const variants = multiQuery ? expander(opts.query) : [opts.query];
+ if (variants.length === 0) variants.push(opts.query);
+
+ const ranked: SearchCandidate[][] = [];
+ let totalRaw = 0;
+ for (const v of variants) {
+ const resp = await search({
+ query: v,
+ namespace: opts.namespace,
+ limit: fanOutK,
+ threshold,
+ });
+ ranked.push(resp.results);
+ totalRaw += resp.results.length;
+ }
+
+ // ── Phase 2: RRF fusion ──
+ let scored: Scored[] =
+ ranked.length === 1
+ ? ranked[0].map((c) => ({ candidate: c, score: c.score }))
+ : reciprocalRankFusion(ranked, rrfK);
+
+ const afterRrfCount = scored.length;
+
+ // ── Phase 3: recency boost ──
+ if (recencyBoost) {
+ scored = applyRecencyBoost(scored, { recencyHalfLifeDays, recencyWeight, now });
+ }
+ const afterRecencyCount = scored.length;
+
+ // Truncate before MMR so we don't re-rank thousands of items.
+ if (scored.length > fanOutK) scored = scored.slice(0, fanOutK);
+
+ // ── Phase 4: MMR diversity ──
+ if (diversityMMR) {
+ scored = mmrRerank(scored, mmrLambda, Math.min(limit * 2, scored.length));
+ } else {
+ scored = scored.slice(0, Math.min(limit * 2, scored.length));
+ }
+ const afterMmrCount = scored.length;
+
+ // ── Phase 5: session round-robin ──
+ let final: Scored[] = scored;
+ if (sessionDiversity) {
+ final = sessionRoundRobin(scored, sessionKey, limit);
+ } else {
+ final = scored.slice(0, limit);
+ }
+ const afterSessionCount = final.length;
+
+ return {
+ results: final.slice(0, limit).map(({ candidate, score }) => ({
+ ...candidate,
+ score,
+ })),
+ stats: {
+ variantCount: variants.length,
+ variants,
+ rawCandidateCount: totalRaw,
+ afterRrfCount,
+ afterRecencyCount,
+ afterMmrCount,
+ afterSessionCount,
+ durationMs: Date.now() - start,
+ },
+ };
+}