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

fix(memory/embeddings): wire --type keyword|hybrid; ??-fix --threshold 0 (#2790)

ruvff428388d8d5
diff --git a/v3/@claude-flow/cli/__tests__/memory-search-2790.test.ts b/v3/@claude-flow/cli/__tests__/memory-search-2790.test.ts
new file mode 100644
index 0000000000..6926496317
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/memory-search-2790.test.ts
@@ -0,0 +1,81 @@
+/**
+ * Regression guard for #2790 β€” two independent defects the reporter
+ * (markt-heximal) found in memory/embeddings search:
+ *
+ * 1. --type keyword|hybrid silently ignored (only semantic ran)
+ * 2. --threshold 0 silently replaced by fallback (non-monotonic:
+ * threshold 0 returned FEWER results than threshold 0.01)
+ *
+ * Both are exercised via real execFileSync against bin/cli.js in a
+ * temp cwd β€” the wire is the actual regression surface, not the
+ * pure logic.
+ */
+
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const CLI = join(__dirname, '..', 'bin', 'cli.js');
+
+function run(args: string[], cwd: string): { stdout: string; exit: number } {
+ try {
+ const stdout = execFileSync('node', [CLI, ...args], { cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
+ return { stdout, exit: 0 };
+ } catch (err) {
+ const e = err as { status?: number; stdout?: Buffer; stderr?: Buffer };
+ return {
+ stdout: (e.stdout?.toString() ?? '') + (e.stderr?.toString() ?? ''),
+ exit: e.status ?? -1,
+ };
+ }
+}
+
+describe('#2790 memory search wiring bugs', () => {
+ let workdir: string;
+ const NAMESPACE = 'e2e-2790';
+ const KEY = 'notes';
+ const VALUE = 'Deployment notes for the storage subsystem: replication factor, shard rebalancing, snapshot retention policy, and quorum configuration for the cluster.';
+
+ beforeAll(() => {
+ workdir = mkdtempSync(join(tmpdir(), 'ruflo-2790-'));
+ run(['memory', 'init'], workdir);
+ run(['memory', 'store', '--namespace', NAMESPACE, '--key', KEY, '--value', VALUE], workdir);
+ }, 60_000);
+
+ afterAll(() => {
+ try { rmSync(workdir, { recursive: true, force: true }); } catch { /* ignore */ }
+ });
+
+ it('--type keyword returns entries whose content contains the query substring', () => {
+ // "rebalancing" is a literal substring of the stored value and is
+ // unlikely to score high under semantic β€” before #2790 this returned 0.
+ const { stdout } = run(['memory', 'search', '-q', 'rebalancing', '--namespace', NAMESPACE, '--type', 'keyword'], workdir);
+ expect(stdout).toMatch(/notes/);
+ expect(stdout).toMatch(/Found \d+ result/i);
+ }, 60_000);
+
+ it('--type keyword returns 0 hits for a genuinely absent substring', () => {
+ const { stdout } = run(['memory', 'search', '-q', 'this-string-is-not-present-anywhere', '--namespace', NAMESPACE, '--type', 'keyword'], workdir);
+ expect(stdout).toMatch(/Found 0 result/i);
+ }, 60_000);
+
+ it('--type hybrid returns at least the semantic result set', () => {
+ const semantic = run(['memory', 'search', '-q', 'storage', '--namespace', NAMESPACE, '--type', 'semantic', '--format', 'json'], workdir);
+ const hybrid = run(['memory', 'search', '-q', 'storage', '--namespace', NAMESPACE, '--type', 'hybrid', '--format', 'json'], workdir);
+ const semanticJson = JSON.parse(semantic.stdout.slice(semantic.stdout.indexOf('{')));
+ const hybridJson = JSON.parse(hybrid.stdout.slice(hybrid.stdout.indexOf('{')));
+ expect(hybridJson.results.length).toBeGreaterThanOrEqual(semanticJson.results.length);
+ }, 60_000);
+
+ it('--threshold 0 returns at least as many results as --threshold 0.01 (monotonic)', () => {
+ const zero = run(['memory', 'search', '-q', 'snapshot', '--namespace', NAMESPACE, '--threshold', '0', '--format', 'json'], workdir);
+ const nonzero = run(['memory', 'search', '-q', 'snapshot', '--namespace', NAMESPACE, '--threshold', '0.01', '--format', 'json'], workdir);
+ const zeroJson = JSON.parse(zero.stdout.slice(zero.stdout.indexOf('{')));
+ const nonzeroJson = JSON.parse(nonzero.stdout.slice(nonzero.stdout.indexOf('{')));
+ // The reporter's diagnostic invariant: lower threshold must not return
+ // FEWER results. If it does, the flag was ignored.
+ expect(zeroJson.results.length).toBeGreaterThanOrEqual(nonzeroJson.results.length);
+ }, 60_000);
+});
diff --git a/v3/@claude-flow/cli/src/commands/embeddings.ts b/v3/@claude-flow/cli/src/commands/embeddings.ts
index 1c08236853..6536423c95 100644
--- a/v3/@claude-flow/cli/src/commands/embeddings.ts
+++ b/v3/@claude-flow/cli/src/commands/embeddings.ts
@@ -125,8 +125,16 @@ const searchCommand: Command = {
action: async (ctx: CommandContext): Promise<CommandResult> => {
const query = ctx.flags.query as string;
const namespace = ctx.flags.collection as string || 'default';
- const limit = parseInt(ctx.flags.limit as string || '10', 10);
- const threshold = parseFloat(ctx.flags.threshold as string || '0.5');
+ // #2790 fix β€” `||` on a numeric-0 argument returns the fallback,
+ // so `--threshold 0` was unreachable. `??` preserves an explicit zero.
+ // The flag arrives as a string here (parser produces string for typed
+ // options passed via CLI without type coercion in some paths), so we
+ // check for undefined explicitly rather than falsy.
+ const limit = parseInt((ctx.flags.limit as string) ?? '10', 10);
+ const rawThreshold = ctx.flags.threshold;
+ const threshold = rawThreshold === undefined || rawThreshold === null
+ ? 0.5
+ : parseFloat(String(rawThreshold));
const dbPath = ctx.flags['db-path'] as string || '.swarm/memory.db';
if (!query) {
@@ -1134,7 +1142,12 @@ const neuralCommand: Command = {
action: async (ctx: CommandContext): Promise<CommandResult> => {
const feature = ctx.flags.feature as string || 'all';
const init = ctx.flags.init as boolean;
- const driftThreshold = parseFloat((ctx.flags['drift-threshold'] || ctx.flags.driftThreshold || '0.3') as string);
+ // #2790 fix β€” same `0 || fallback` bug: `--drift-threshold 0` was
+ // silently replaced by 0.3. Use nullish coalescing.
+ const rawDriftThreshold = ctx.flags['drift-threshold'] ?? ctx.flags.driftThreshold;
+ const driftThreshold = rawDriftThreshold === undefined || rawDriftThreshold === null
+ ? 0.3
+ : parseFloat(String(rawDriftThreshold));
const decayRate = parseFloat((ctx.flags['decay-rate'] || ctx.flags.decayRate || '0.01') as string);
const consolidationInterval = parseInt((ctx.flags['consolidation-interval'] || ctx.flags.consolidationInterval || '60000') as string, 10);
diff --git a/v3/@claude-flow/cli/src/commands/hooks.ts b/v3/@claude-flow/cli/src/commands/hooks.ts
index 71565dd472..45139d321a 100644
--- a/v3/@claude-flow/cli/src/commands/hooks.ts
+++ b/v3/@claude-flow/cli/src/commands/hooks.ts
@@ -1653,7 +1653,7 @@ const transferFromProjectCommand: Command = {
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const sourcePath = (ctx.flags.source as string) || ctx.args[0];
- const minConfidence = ctx.flags.minConfidence as number || 0.7;
+ const minConfidence = ctx.flags.minConfidence as number ?? 0.7;
if (!sourcePath) {
output.printError('Source project path is required. Use --source or -s flag.');
@@ -3235,7 +3235,7 @@ const coverageRouteCommand: Command = {
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const task = (ctx.flags.task as string) || ctx.args[0];
- const threshold = ctx.flags.threshold as number || 80;
+ const threshold = ctx.flags.threshold as number ?? 80;
const useRuvector = !ctx.flags['no-ruvector'];
if (!task) {
@@ -3507,7 +3507,7 @@ const coverageSuggestCommand: Command = {
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const targetPath = (ctx.flags.path as string) || ctx.args[0];
- const threshold = ctx.flags.threshold as number || 80;
+ const threshold = ctx.flags.threshold as number ?? 80;
const limit = ctx.flags.limit as number || 20;
if (!targetPath) {
@@ -3740,7 +3740,7 @@ const coverageGapsCommand: Command = {
{ command: 'claude-flow hooks coverage-gaps --threshold 90', description: 'Stricter threshold' }
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
- const threshold = ctx.flags.threshold as number || 80;
+ const threshold = ctx.flags.threshold as number ?? 80;
const groupByAgent = ctx.flags['group-by-agent'] !== false;
const criticalOnly = ctx.flags['critical-only'] as boolean || false;
diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.ts
index e17cd27151..81db6da30a 100644
--- a/v3/@claude-flow/cli/src/commands/memory.ts
+++ b/v3/@claude-flow/cli/src/commands/memory.ts
@@ -399,7 +399,13 @@ const searchCommand: Command = {
const query = ctx.flags.query as string || ctx.args[0];
let namespace = ctx.flags.namespace as string || 'all';
const limit = ctx.flags.limit as number || 10;
- const threshold = ctx.flags.threshold as number || 0.3;
+ // #2790 fix β€” `||` discards an explicit `--threshold 0` (falsy) and
+ // silently uses the fallback; that made `--threshold 0` return
+ // FEWER results than `--threshold 0.01` (non-monotonic). Nullish
+ // coalescing preserves an explicit zero. Fallback aligned with the
+ // option's declared `default: 0.7` (was `0.3` β€” the two disagreed
+ // and --help advertised a default the code did not honor).
+ const threshold = ctx.flags.threshold as number ?? 0.7;
const searchType = ctx.flags.type as string || 'semantic';
const buildHnsw = (ctx.flags['build-hnsw'] || ctx.flags.buildHnsw) as boolean;
const requestedIntent = (ctx.flags.intent as string) || 'mixed';
@@ -463,10 +469,60 @@ const searchCommand: Command = {
// Use direct sql.js search with vector similarity
try {
- const { searchEntries, resolveDbPath: _rdbSearch } = await import('../memory/memory-initializer.js');
+ const { searchEntries, listEntries, resolveDbPath: _rdbSearch } = await import('../memory/memory-initializer.js');
const dbPathSearch = _rdbSearch(ctx.flags.path as string | undefined);
const useSmart = (ctx.flags.smart || ctx.flags.s) as boolean;
+ // #2790 fix β€” keyword mode was declared, echoed, and IGNORED (every
+ // search ran semantic regardless). Wire it here: list entries in
+ // the requested namespace (or all) and substring-match against key
+ // + content. Hybrid unions the keyword hits with the semantic hits
+ // and dedups by key + namespace.
+ let keywordResults: { key: string; score: number; namespace: string; preview: string }[] = [];
+ if (searchType === 'keyword' || searchType === 'hybrid') {
+ const list = await listEntries({
+ namespace: namespace === 'all' ? undefined : namespace,
+ limit: 5000,
+ includeContent: true,
+ dbPath: dbPathSearch,
+ });
+ if (list.success) {
+ const q = (query as string).toLowerCase();
+ keywordResults = list.entries
+ .filter((e) => {
+ const c = (e as { content?: string }).content ?? '';
+ return e.key.toLowerCase().includes(q) || c.toLowerCase().includes(q);
+ })
+ .map((e) => {
+ const c = (e as { content?: string }).content ?? '';
+ const inKey = e.key.toLowerCase().includes(q);
+ // Keyword scoring: 1.0 for key hit, 0.7 for content hit
+ return {
+ key: e.key,
+ score: inKey ? 1.0 : 0.7,
+ namespace: e.namespace,
+ preview: c.slice(0, 200),
+ };
+ })
+ .sort((a, b) => b.score - a.score)
+ .slice(0, limit);
+ }
+ if (searchType === 'keyword') {
+ // Pure-keyword mode returns directly; skip the semantic path entirely.
+ if (ctx.flags.format === 'json') {
+ output.printJson({ query, searchType, results: keywordResults, searchTime: '0ms' });
+ return { success: true, data: keywordResults };
+ }
+ output.writeln();
+ output.printSuccess(`Found ${keywordResults.length} result(s) via keyword substring match`);
+ for (const r of keywordResults) {
+ output.writeln(` ${r.key} (${r.namespace}, score=${r.score.toFixed(2)}) β€” ${r.preview.slice(0, 80)}${r.preview.length > 80 ? '…' : ''}`);
+ }
+ return { success: true, data: keywordResults };
+ }
+ // Hybrid mode: keyword hits will be MERGED after semantic runs below.
+ }
+
let results: { key: string; score: number; namespace: string; preview: string }[];
let searchTimeMs: number;
let smartStats: Record<string, unknown> | undefined;
@@ -554,6 +610,23 @@ const searchCommand: Command = {
searchTimeMs = searchResult.searchTime;
}
+ // #2790 fix (hybrid mode): union keyword results with semantic
+ // results, dedup by (key, namespace), then take top `limit`.
+ if (searchType === 'hybrid' && keywordResults.length > 0) {
+ const seen = new Set(results.map((r) => `${r.namespace}::${r.key}`));
+ for (const k of keywordResults) {
+ const id = `${k.namespace}::${k.key}`;
+ if (!seen.has(id)) {
+ results.push(k);
+ seen.add(id);
+ }
+ }
+ // Rerank by score
+ results.sort((a, b) => b.score - a.score);
+ results = results.slice(0, limit);
+ backendLabel = `${backendLabel} + keyword union (#2790)`;
+ }
+
if (ctx.flags.format === 'json') {
output.printJson({ query, searchType, results, searchTime: `${searchTimeMs}ms`, ...(smartStats ? { stats: smartStats } : {}) });
return { success: true, data: results };