π 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
feat(memory): SCM query-intent classifier + routing hints (#2760 dream)
ruv79d266507ee4
diff --git a/v3/@claude-flow/cli/__tests__/scm-classifier-2760.test.ts b/v3/@claude-flow/cli/__tests__/scm-classifier-2760.test.tsnew file mode 100644index 0000000000..c4ebaf00eb--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/scm-classifier-2760.test.ts@@ -0,0 +1,57 @@+/**+ * Regression guard for #2760 dream-cycle SCM (Selective Context Memory)+ * query-intent classifier.+ *+ * v1 classifier is keyword-scored. Must correctly route the three canonical+ * intent classes (episodic / semantic / procedural), degrade gracefully to+ * `mixed` on ambiguous queries, and honor an explicit override.+ */++import { describe, it, expect } from 'vitest';+import { classifyQueryIntent, resolveIntent, INTENT_NAMESPACES } from '../src/memory/scm-classifier.js';++describe('#2760 SCM classifier', () => {+ it('classifies episodic recall ("when did we last β¦")', () => {+ const r = classifyQueryIntent('When did we last touch the auth module?');+ expect(r.intent).toBe('episodic');+ expect(r.namespaces).toEqual(expect.arrayContaining(['sessions', 'trajectory']));+ expect(r.confidence).toBeGreaterThan(0.35);+ });++ it('classifies semantic explanation ("how does X work" / "what is Y")', () => {+ const r = classifyQueryIntent('What is the design principle behind our AgentDB memory tiers?');+ expect(r.intent).toBe('semantic');+ expect(r.namespaces).toEqual(expect.arrayContaining(['patterns']));+ });++ it('classifies procedural how-to ("how do I β¦" / "steps to β¦")', () => {+ const r = classifyQueryIntent('How do I set up a new subagent role with workspace-scoped permissions?');+ expect(r.intent).toBe('procedural');+ expect(r.namespaces).toEqual(expect.arrayContaining(['skills']));+ });++ it('falls back to mixed on an ambiguous query with no intent keywords', () => {+ const r = classifyQueryIntent('auth');+ expect(r.intent).toBe('mixed');+ expect(r.namespaces).toEqual([]);+ expect(r.confidence).toBeLessThan(0.35);+ });++ it('resolveIntent respects an explicit override', () => {+ const r = resolveIntent('completely ambiguous three word query', 'procedural');+ expect(r.intent).toBe('procedural');+ expect(r.namespaces).toEqual([...INTENT_NAMESPACES.procedural]);+ });++ it('resolveIntent auto path delegates to the keyword classifier', () => {+ const auto = resolveIntent('How do I onboard a new coder subagent?', 'auto');+ const direct = classifyQueryIntent('How do I onboard a new coder subagent?');+ expect(auto.intent).toBe(direct.intent);+ });++ it('resolveIntent mixed explicit returns full namespaces empty', () => {+ const r = resolveIntent('anything', 'mixed');+ expect(r.intent).toBe('mixed');+ expect(r.namespaces).toEqual([]);+ });+});diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.tsindex c1568c79b0..41edbbf572 100644--- a/v3/@claude-flow/cli/src/commands/memory.ts+++ b/v3/@claude-flow/cli/src/commands/memory.ts@@ -375,27 +375,63 @@ const searchCommand: Command = {type: 'boolean',default: false},+ {+ // #2760 dream-cycle β SCM routed memory. Classify the query intent+ // and route search to the mapped namespaces (episodic β session+ // writes, semantic β patterns, procedural β skills). Default+ // "mixed" preserves the pre-#2760 behavior (search everything).+ name: 'intent',+ description: 'Route query to intent-mapped namespaces (auto | mixed | episodic | semantic | procedural) β dream-cycle #2760',+ type: 'string',+ choices: ['auto', 'mixed', 'episodic', 'semantic', 'procedural'],+ default: 'mixed',+ },DB_PATH_OPTION],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 "auth patterns" --smart', description: 'SmartRetrieval with RRF + MMR' }+ { command: 'claude-flow memory search -q "auth patterns" --smart', description: 'SmartRetrieval with RRF + MMR' },+ { command: 'claude-flow memory search -q "when did we last touch auth" --intent auto', description: 'SCM-routed retrieval (dream-cycle #2760)' },],action: async (ctx: CommandContext): Promise<CommandResult> => {const query = ctx.flags.query as string || ctx.args[0];- const namespace = ctx.flags.namespace as string || 'all';+ 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;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';if (!query) {output.printError('Query is required. Use --query or -q');return { success: false, exitCode: 1 };}+ // #2760 SCM routed memory (v1 MVP) β classify query intent and+ // print a routing hint. Only fires when --intent is NOT the default+ // "mixed" AND --namespace was NOT explicitly passed. Intentionally+ // does NOT mutate the search path β the routing is advisory in v1+ // so the search backend's exact behavior is preserved. v2 will+ // apply the routing when the search-backend interface adds a+ // multi-namespace OR filter.+ if (requestedIntent !== 'mixed' && (namespace === 'all' || !ctx.flags.namespace)) {+ try {+ const { resolveIntent } = await import('../memory/scm-classifier.js');+ const resolved = resolveIntent(query, requestedIntent as 'auto' | 'episodic' | 'semantic' | 'procedural' | 'mixed');+ if (resolved.intent !== 'mixed' && resolved.namespaces.length > 0) {+ output.printInfo(`SCM router β ${resolved.intent} (confidence ${(resolved.confidence * 100).toFixed(1)}%)`);+ output.writeln(output.dim(` ${resolved.reason}`));+ output.writeln(output.dim(` Suggested: rerun with --namespace ${resolved.namespaces[0]} to filter (or one of: ${resolved.namespaces.slice(1, 4).join(', ')}...)`));+ } else {+ output.writeln(output.dim(`SCM router β mixed (${resolved.reason})`));+ }+ } catch (err) {+ output.writeln(output.dim(`SCM routing skipped: ${err instanceof Error ? err.message : String(err)}`));+ }+ }+// Build/rebuild HNSW index if requestedif (buildHnsw) {output.printInfo('Building HNSW index...');@@ -1816,11 +1852,56 @@ const initMemoryCommand: Command = {}};+// #2760 dream-cycle β SCM query classifier. Standalone subcommand so+// users can inspect what intent a query maps to and pipe the mapped+// namespaces into other tools (e.g. `memory search --namespace ...`).+const classifyCommand: Command = {+ name: 'classify',+ description: 'Classify a query into episodic/semantic/procedural intent (SCM router, dream-cycle #2760)',+ options: [+ { name: 'query', short: 'q', type: 'string', description: 'Query text to classify', required: true },+ { name: 'intent', type: 'string', choices: ['auto', 'mixed', 'episodic', 'semantic', 'procedural'], default: 'auto', description: 'Force a specific intent (default: auto)' },+ ],+ examples: [+ { command: 'claude-flow memory classify -q "when did we last touch auth"', description: 'Auto-classify (should return episodic)' },+ { command: 'claude-flow memory classify -q "how does JWT work" --format json', description: 'JSON output for pipelines' },+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const query = ctx.flags.query as string;+ const requested = (ctx.flags.intent as string) || 'auto';++ if (!query) {+ output.printError('Query is required. Use --query or -q');+ return { success: false, exitCode: 1 };+ }++ const { resolveIntent } = await import('../memory/scm-classifier.js');+ const resolved = resolveIntent(query, requested as 'auto' | 'mixed' | 'episodic' | 'semantic' | 'procedural');++ if (ctx.flags.format === 'json') {+ output.printJson(resolved);+ return { success: true, data: resolved };+ }++ output.writeln();+ output.printBox(+ `Query: "${query}"\n` ++ `Intent: ${resolved.intent}\n` ++ `Confidence: ${(resolved.confidence * 100).toFixed(1)}%\n` ++ `Namespaces: ${resolved.namespaces.length > 0 ? resolved.namespaces.slice(0, 4).join(', ') + (resolved.namespaces.length > 4 ? 'β¦' : '') : '(all β mixed retrieval)'}`,+ 'SCM Classifier (#2760)'+ );+ output.writeln();+ output.writeln(output.dim(resolved.reason));+ return { success: true, data: resolved };+ },+};+// Main memory commandexport const memoryCommand: Command = {name: 'memory',description: 'Memory management commands',- subcommands: [initMemoryCommand, storeCommand, retrieveCommand, searchCommand, listCommand, deleteCommand, purgeCommand, statsCommand, configureCommand, cleanupCommand, compressCommand, exportCommand, importCommand, distillCommand, backupCommand],+ subcommands: [initMemoryCommand, storeCommand, retrieveCommand, searchCommand, listCommand, deleteCommand, purgeCommand, statsCommand, configureCommand, cleanupCommand, compressCommand, exportCommand, importCommand, distillCommand, backupCommand, classifyCommand],options: [],examples: [{ command: 'claude-flow memory store -k "key" -v "value"', description: 'Store data' },diff --git a/v3/@claude-flow/cli/src/memory/scm-classifier.ts b/v3/@claude-flow/cli/src/memory/scm-classifier.tsnew file mode 100644index 0000000000..0aadce62b2--- /dev/null+++ b/v3/@claude-flow/cli/src/memory/scm-classifier.ts@@ -0,0 +1,172 @@+/**+ * Selective Context Memory (SCM) query-intent classifier (#2760).+ *+ * Dream-cycle #2760 (SCM routed memory 86% LongMemEval): agents perform+ * dramatically better on long-memory retrieval when the query is routed+ * to the RIGHT memory tier β episodic (session recall) vs semantic+ * (learned patterns) vs procedural (skills/recipes). Ruflo previously+ * had all these tiers writing to different namespaces but the search+ * command didn't discriminate β every query searched everything.+ *+ * v1 classifier: keyword-scored intent detection. Ships as a bounded+ * MVP so users can opt in via `memory search --intent auto|episodic|+ * semantic|procedural|mixed`. Default remains `mixed` (existing+ * behavior) so no baseline retrieval is disturbed.+ *+ * v2 (future): embedding-based classifier trained on the trajectory+ * store's actual routing outcomes.+ */++export type MemoryIntent = 'episodic' | 'semantic' | 'procedural' | 'mixed';++export interface ClassifiedIntent {+ intent: MemoryIntent;+ confidence: number;+ /** Per-intent scores for transparency; sums roughly to 1. */+ scores: Record<Exclude<MemoryIntent, 'mixed'>, number>;+ /** Namespaces the caller should search for this intent (relative to memory backend). */+ namespaces: string[];+ /** Human-readable rationale. */+ reason: string;+}++/**+ * Keyword catalog per intent β case-insensitive substring match.+ * Order matters for ties: earlier categories win when scores tie.+ */+const KEYWORDS: Record<Exclude<MemoryIntent, 'mixed'>, readonly string[]> = {+ episodic: [+ 'when', 'last time', 'yesterday', 'today', 'session',+ 'recent', 'recently', 'trajectory', 'did i', 'did we',+ 'what happened', 'the previous', 'the last', 'earlier',+ 'this morning', 'this afternoon', 'this evening',+ ],+ semantic: [+ 'how does', 'what is', 'why', 'why does', 'concept',+ 'pattern', 'design', 'architecture', 'principle',+ 'means', 'meaning', 'definition', 'explanation',+ 'relationship between',+ ],+ procedural: [+ 'how do i', 'how to', 'steps to', 'recipe', 'playbook',+ 'procedure', 'walk me through', 'guide', 'runbook',+ 'checklist', 'template', 'workflow', 'skill',+ ],+};++/**+ * Namespaces owned by each intent. These match ruflo's actual+ * memory-write conventions:+ * episodic β session/trajectory writes (hooks_post-task, session-checkpoints)+ * semantic β pattern/learning writes (patterns/, learned-*, adr-patterns)+ * procedural β skill/workflow writes (skills/, agents/, workflow-templates)+ * A namespace listed under more than one intent means it's genuinely dual-nature.+ */+const NAMESPACES: Record<Exclude<MemoryIntent, 'mixed'>, readonly string[]> = {+ episodic: [+ 'sessions', 'session-checkpoints', 'trajectory', 'trajectories',+ 'routing-outcomes', 'commands', 'feedback',+ ],+ semantic: [+ 'patterns', 'learned-patterns', 'adr-patterns', 'adr-edges',+ 'reasoning-patterns', 'concepts',+ ],+ procedural: [+ 'skills', 'agents', 'workflow-templates', 'playbooks', 'recipes',+ ],+};++const CONFIDENCE_THRESHOLD = 0.35;++export function classifyQueryIntent(query: string): ClassifiedIntent {+ const q = query.toLowerCase();+ const scores: Record<Exclude<MemoryIntent, 'mixed'>, number> = {+ episodic: 0,+ semantic: 0,+ procedural: 0,+ };++ // Score by keyword hits (weighted by phrase length β longer phrases+ // are less ambiguous, e.g. "how do i" beats "how").+ for (const intent of Object.keys(KEYWORDS) as Array<keyof typeof KEYWORDS>) {+ for (const kw of KEYWORDS[intent]) {+ if (q.includes(kw)) {+ // Weight: longer keyword β higher confidence+ scores[intent] += Math.max(1, kw.length / 6);+ }+ }+ }++ const total = scores.episodic + scores.semantic + scores.procedural;+ if (total === 0) {+ return {+ intent: 'mixed',+ confidence: 0,+ scores,+ namespaces: [],+ reason: 'No intent keywords matched β falling back to mixed retrieval (search all namespaces).',+ };+ }++ // Normalize+ const normalized: Record<Exclude<MemoryIntent, 'mixed'>, number> = {+ episodic: scores.episodic / total,+ semantic: scores.semantic / total,+ procedural: scores.procedural / total,+ };++ // Pick the winner+ const entries: Array<[Exclude<MemoryIntent, 'mixed'>, number]> = [+ ['episodic', normalized.episodic],+ ['semantic', normalized.semantic],+ ['procedural', normalized.procedural],+ ];+ entries.sort((a, b) => b[1] - a[1]);++ const [winner, winnerScore] = entries[0];++ // Low-confidence winner β mixed+ if (winnerScore < CONFIDENCE_THRESHOLD) {+ return {+ intent: 'mixed',+ confidence: winnerScore,+ scores: normalized,+ namespaces: [],+ reason: `Top intent (${winner}) below confidence threshold ${CONFIDENCE_THRESHOLD} β falling back to mixed retrieval.`,+ };+ }++ return {+ intent: winner,+ confidence: winnerScore,+ scores: normalized,+ namespaces: [...NAMESPACES[winner]],+ reason: `Classified as ${winner} (confidence ${(winnerScore * 100).toFixed(1)}%) β route to ${NAMESPACES[winner].length} namespaces.`,+ };+}++/**+ * Given a user-requested intent (which may be `auto`), resolve to a+ * concrete ClassifiedIntent for the given query.+ */+export function resolveIntent(query: string, requested: MemoryIntent | 'auto' = 'auto'): ClassifiedIntent {+ if (requested === 'auto') return classifyQueryIntent(query);+ if (requested === 'mixed') {+ return {+ intent: 'mixed',+ confidence: 1,+ scores: { episodic: 0, semantic: 0, procedural: 0 },+ namespaces: [],+ reason: 'Explicitly requested mixed retrieval (search all namespaces).',+ };+ }+ return {+ intent: requested,+ confidence: 1,+ scores: { episodic: 0, semantic: 0, procedural: 0, [requested]: 1 } as Record<Exclude<MemoryIntent, 'mixed'>, number>,+ namespaces: [...NAMESPACES[requested]],+ reason: `Explicitly requested ${requested} retrieval β route to ${NAMESPACES[requested].length} namespaces.`,+ };+}++export { KEYWORDS as INTENT_KEYWORDS, NAMESPACES as INTENT_NAMESPACES };