🌊 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(intelligence): recall long memories from distinctive query terms
Rudy Celekli6786892cad6e
diff --git a/.claude/helpers/intelligence.cjs b/.claude/helpers/intelligence.cjsindex 0e51a56cae..98e3ff3cf0 100755--- a/.claude/helpers/intelligence.cjs+++ b/.claude/helpers/intelligence.cjs@@ -745,21 +745,43 @@ function getContextDetailed(prompt) {const ranked = readJSON(RANKED_PATH);if (!ranked || !ranked.entries || ranked.entries.length === 0) return null;- const promptWords = tokenize(prompt);+ const promptWords = [...new Set(tokenize(prompt))];if (promptWords.length === 0) return null;- const promptTrigrams = trigrams(promptWords);- const ALPHA = 0.6; // content match weight- const MIN_THRESHOLD = 0.05;+ // Query coverage is independent of entry length: a short diagnostic prompt+ // must still find its exact terms inside a long memory section (#4136).+ // IDF downweights generic terms shared by many entries. Terms absent from+ // every entry still count against coverage, so two incidental words cannot+ // hide the rest of an unrelated prompt.+ const candidates = ranked.entries.map(entry => ({ entry, words: new Set(entry.words || []) }));+ const weights = promptWords.map(word => {+ const frequency = candidates.reduce((count, candidate) => count + Number(candidate.words.has(word)), 0);+ return Math.log1p((candidates.length - frequency + 0.5) / (frequency + 0.5));+ });+ const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);+ if (totalWeight === 0) return null;++ const MIN_COVERAGE = 0.15;const TOP_K = 5;// Score each entryconst scored = [];- for (const entry of ranked.entries) {- const entryTrigrams = trigrams(entry.words || []);- const contentMatch = jaccardSimilarity(promptTrigrams, entryTrigrams);- const score = ALPHA * contentMatch + (1 - ALPHA) * (entry.pageRank || 0);- if (score >= MIN_THRESHOLD) {+ for (const { entry, words } of candidates) {+ let matchedWeight = 0;+ let matchedTerms = 0;+ for (let i = 0; i < promptWords.length; i++) {+ if (weights[i] > 0 && words.has(promptWords[i])) {+ matchedWeight += weights[i];+ matchedTerms++;+ }+ }+ // A single common word in a long prompt is not evidence of relevance;+ // PageRank can order relevant entries but cannot make one relevant.+ if (matchedTerms < Math.min(2, promptWords.length)) continue;+ const coverage = matchedWeight / totalWeight;+ if (coverage >= MIN_COVERAGE) {+ const pageRank = Math.max(0, Math.min(1, Number(entry.pageRank) || 0));+ const score = 0.9 * coverage + 0.1 * pageRank;scored.push({ ...entry, score });}}diff --git a/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs b/v3/@claude-flow/cli/.claude/helpers/intelligence.cjsindex 0e51a56cae..98e3ff3cf0 100755--- a/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs+++ b/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs@@ -745,21 +745,43 @@ function getContextDetailed(prompt) {const ranked = readJSON(RANKED_PATH);if (!ranked || !ranked.entries || ranked.entries.length === 0) return null;- const promptWords = tokenize(prompt);+ const promptWords = [...new Set(tokenize(prompt))];if (promptWords.length === 0) return null;- const promptTrigrams = trigrams(promptWords);- const ALPHA = 0.6; // content match weight- const MIN_THRESHOLD = 0.05;+ // Query coverage is independent of entry length: a short diagnostic prompt+ // must still find its exact terms inside a long memory section (#4136).+ // IDF downweights generic terms shared by many entries. Terms absent from+ // every entry still count against coverage, so two incidental words cannot+ // hide the rest of an unrelated prompt.+ const candidates = ranked.entries.map(entry => ({ entry, words: new Set(entry.words || []) }));+ const weights = promptWords.map(word => {+ const frequency = candidates.reduce((count, candidate) => count + Number(candidate.words.has(word)), 0);+ return Math.log1p((candidates.length - frequency + 0.5) / (frequency + 0.5));+ });+ const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);+ if (totalWeight === 0) return null;++ const MIN_COVERAGE = 0.15;const TOP_K = 5;// Score each entryconst scored = [];- for (const entry of ranked.entries) {- const entryTrigrams = trigrams(entry.words || []);- const contentMatch = jaccardSimilarity(promptTrigrams, entryTrigrams);- const score = ALPHA * contentMatch + (1 - ALPHA) * (entry.pageRank || 0);- if (score >= MIN_THRESHOLD) {+ for (const { entry, words } of candidates) {+ let matchedWeight = 0;+ let matchedTerms = 0;+ for (let i = 0; i < promptWords.length; i++) {+ if (weights[i] > 0 && words.has(promptWords[i])) {+ matchedWeight += weights[i];+ matchedTerms++;+ }+ }+ // A single common word in a long prompt is not evidence of relevance;+ // PageRank can order relevant entries but cannot make one relevant.+ if (matchedTerms < Math.min(2, promptWords.length)) continue;+ const coverage = matchedWeight / totalWeight;+ if (coverage >= MIN_COVERAGE) {+ const pageRank = Math.max(0, Math.min(1, Number(entry.pageRank) || 0));+ const score = 0.9 * coverage + 0.1 * pageRank;scored.push({ ...entry, score });}}diff --git a/v3/@claude-flow/cli/__tests__/intelligence-query-coverage-4136.test.ts b/v3/@claude-flow/cli/__tests__/intelligence-query-coverage-4136.test.tsnew file mode 100644index 0000000000..bdbd993007--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/intelligence-query-coverage-4136.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';+import { execFileSync } from 'node:child_process';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';++const helpers = [+ resolve(__dirname, '../.claude/helpers/intelligence.cjs'),+ resolve(__dirname, '../../../../.claude/helpers/intelligence.cjs'),+];++function recall(helper: string, prompt: string, entries: unknown[]): { surfaced: Array<{ id: string }> } | null {+ const root = mkdtempSync(join(tmpdir(), 'ruflo-recall-4136-'));+ const data = join(root, '.claude-flow', 'data');+ mkdirSync(data, { recursive: true });+ writeFileSync(join(data, 'ranked-context.json'), JSON.stringify({ version: 1, entries }));+ try {+ const script = `process.stdout.write(JSON.stringify(require(${JSON.stringify(helper)}).getContextDetailed(${JSON.stringify(prompt)})))`;+ return JSON.parse(execFileSync(process.execPath, ['-e', script], {+ cwd: root,+ env: { ...process.env, CLAUDE_PROJECT_DIR: root },+ encoding: 'utf8',+ }));+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+}++const filler = Array.from({ length: 220 }, (_, i) => `background${i}`);+const entries = [+ { id: 'unrelated-hub', summary: 'HTTP 500 incident index', words: ['http', '500', 'server', 'incident', ...filler], pageRank: 0.6 },+ { id: 'postgrest-rpc', summary: 'PostgREST P0002 RPC mapping', words: ['postgrest', 'http', '500', 'p0002', 'rpc', 'error', ...filler], pageRank: 0.001 },+ { id: 'wrangler-token', summary: 'Wrangler token expiry', words: ['wrangler', 'token', 'expired', 'release', ...filler], pageRank: 0.001 },+];++describe.each(helpers)('route memory recall (%s)', (helper) => {+ it('surfaces the correct long entry ahead of a high-rank generic one', () => {+ const hit = recall(helper, 'why does PostgREST return HTTP 500 for P0002 from an RPC', entries);+ expect(hit?.surfaced[0]?.id).toBe('postgrest-rpc');+ expect(hit?.surfaced.map(e => e.id)).not.toContain('unrelated-hub');+ });++ it('returns no context when only graph rank is high', () => {+ expect(recall(helper, 'firebase JWT refresh rotation', entries)).toBeNull();+ });++ it('does not let two incidental words outweigh the unmatched query', () => {+ expect(recall(helper, 'firebase JWT refresh rotation HTTP 500', entries)).toBeNull();+ });++ it('finds a different long entry on its own distinctive terms', () => {+ const hit = recall(helper, 'the wrangler token expired during release', entries);+ expect(hit?.surfaced[0]?.id).toBe('wrangler-token');+ });+});