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(intelligence): unified learning-stats aggregator (ADR-075, #2245 follow-up)

ruvca77f830743e
diff --git a/docs/benchmarks/runs/self-learning-2026-05-30T16-00-50-536Z.json b/docs/benchmarks/runs/self-learning-2026-05-30T16-00-50-536Z.json
new file mode 100644
index 0000000000..ec2831c203
--- /dev/null
+++ b/docs/benchmarks/runs/self-learning-2026-05-30T16-00-50-536Z.json
@@ -0,0 +1,73 @@
+{
+ "runAt": "2026-05-30T16:00:50.536Z",
+ "benchmark": "self-learning-2245",
+ "n": 10,
+ "sections": {
+ "A_recordSignalProcessed": {
+ "calls": 10,
+ "signalsProcessedDelta": 10,
+ "passed": true,
+ "elapsedMs": 0.46
+ },
+ "B_taskCompleted_trainPatterns": {
+ "calls": 10,
+ "trainedViaPipeline": 10,
+ "trajectoriesDelta": 10,
+ "patternsLearnedDelta": 11,
+ "passed": true,
+ "elapsedMs": 201.32,
+ "avgLatencyMsPerCall": 20.13
+ },
+ "C_taskCompleted_recordedOnly": {
+ "calls": 10,
+ "trajectoriesDelta": 0,
+ "passed": true,
+ "note": "negative control β€” should NOT touch trajectories",
+ "elapsedMs": 0.04
+ },
+ "D_pretrain_neuralPatterns": {
+ "attempted": 10,
+ "stored": 10,
+ "listTotal": 10,
+ "passed": true,
+ "elapsedMs": 5.07
+ },
+ "E_multiStepTrajectory": {
+ "cycles": 5,
+ "persistedCount": 5,
+ "sonaUpdateCount": 5,
+ "passed": true,
+ "note": "MCP trajectory tools feed sonaCoordinator (see hooks_intelligence_stats), not globalStats β€” observable outcomes checked here",
+ "elapsedMs": 31.15
+ },
+ "F_unifiedStats": {
+ "shape": [
+ "global",
+ "sona",
+ "memoryBridge",
+ "neuralPatterns",
+ "consistency"
+ ],
+ "observed": {
+ "global.patternsLearned": 11,
+ "global.trajectoriesRecorded": 10,
+ "global.signalsProcessed": 20,
+ "memoryBridge.totalEntries": 10,
+ "memoryBridge.reachable": true,
+ "neuralPatterns.patternCount": 10,
+ "sona.available": true,
+ "consistency.notes": 1
+ },
+ "passed": true,
+ "note": "ADR-075 β€” one aggregator across the 4 stores. Each sub-view names its source.",
+ "elapsedMs": 5.87
+ }
+ },
+ "finalState": {
+ "signalsProcessed": 10,
+ "trajectoriesRecorded": 10,
+ "patternsLearned": 11
+ },
+ "scratch": "/tmp/claude-501/learn-bench-m5Fe9p",
+ "passed": true
+}
\ No newline at end of file
diff --git a/docs/benchmarks/runs/self-learning-latest.json b/docs/benchmarks/runs/self-learning-latest.json
index 2c6abf2e50..ec2831c203 100644
--- a/docs/benchmarks/runs/self-learning-latest.json
+++ b/docs/benchmarks/runs/self-learning-latest.json
@@ -1,5 +1,5 @@
{
- "runAt": "2026-05-30T15:23:10.641Z",
+ "runAt": "2026-05-30T16:00:50.536Z",
"benchmark": "self-learning-2245",
"n": 10,
"sections": {
@@ -7,7 +7,7 @@
"calls": 10,
"signalsProcessedDelta": 10,
"passed": true,
- "elapsedMs": 0.45
+ "elapsedMs": 0.46
},
"B_taskCompleted_trainPatterns": {
"calls": 10,
@@ -15,22 +15,22 @@
"trajectoriesDelta": 10,
"patternsLearnedDelta": 11,
"passed": true,
- "elapsedMs": 160.71,
- "avgLatencyMsPerCall": 16.07
+ "elapsedMs": 201.32,
+ "avgLatencyMsPerCall": 20.13
},
"C_taskCompleted_recordedOnly": {
"calls": 10,
"trajectoriesDelta": 0,
"passed": true,
"note": "negative control β€” should NOT touch trajectories",
- "elapsedMs": 0.03
+ "elapsedMs": 0.04
},
"D_pretrain_neuralPatterns": {
"attempted": 10,
"stored": 10,
"listTotal": 10,
"passed": true,
- "elapsedMs": 4.84
+ "elapsedMs": 5.07
},
"E_multiStepTrajectory": {
"cycles": 5,
@@ -38,7 +38,29 @@
"sonaUpdateCount": 5,
"passed": true,
"note": "MCP trajectory tools feed sonaCoordinator (see hooks_intelligence_stats), not globalStats β€” observable outcomes checked here",
- "elapsedMs": 25.36
+ "elapsedMs": 31.15
+ },
+ "F_unifiedStats": {
+ "shape": [
+ "global",
+ "sona",
+ "memoryBridge",
+ "neuralPatterns",
+ "consistency"
+ ],
+ "observed": {
+ "global.patternsLearned": 11,
+ "global.trajectoriesRecorded": 10,
+ "global.signalsProcessed": 20,
+ "memoryBridge.totalEntries": 10,
+ "memoryBridge.reachable": true,
+ "neuralPatterns.patternCount": 10,
+ "sona.available": true,
+ "consistency.notes": 1
+ },
+ "passed": true,
+ "note": "ADR-075 β€” one aggregator across the 4 stores. Each sub-view names its source.",
+ "elapsedMs": 5.87
}
},
"finalState": {
@@ -46,6 +68,6 @@
"trajectoriesRecorded": 10,
"patternsLearned": 11
},
- "scratch": "/tmp/claude-501/learn-bench-S4UVqJ",
+ "scratch": "/tmp/claude-501/learn-bench-m5Fe9p",
"passed": true
}
\ No newline at end of file
diff --git a/package.json b/package.json
index 5481273c4a..9e4764ed89 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-flow",
- "version": "3.10.14",
+ "version": "3.10.15",
"description": "Ruflo - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
"main": "dist/index.js",
"type": "module",
diff --git a/ruflo/package.json b/ruflo/package.json
index 9295ff5e7c..f4de1f151f 100644
--- a/ruflo/package.json
+++ b/ruflo/package.json
@@ -1,6 +1,6 @@
{
"name": "ruflo",
- "version": "3.10.14",
+ "version": "3.10.15",
"description": "Ruflo - Enterprise AI agent orchestration platform. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
"main": "bin/ruflo.js",
"type": "module",
diff --git a/v3/@claude-flow/cli/__tests__/unified-stats-2245.test.ts b/v3/@claude-flow/cli/__tests__/unified-stats-2245.test.ts
new file mode 100644
index 0000000000..a1717294a4
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/unified-stats-2245.test.ts
@@ -0,0 +1,129 @@
+// Cross-store consistency tests for the unified learning-stats aggregator
+// (ADR-075, #2245 follow-up to ADR-074).
+//
+// Drives each learning path and asserts the corresponding counter shows up
+// where it should in the unified view. Also asserts the `consistency` block
+// either reports drift OR confirms agreement β€” no silent disagreement.
+
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const SCRATCH = mkdtempSync(join(tmpdir(), 'unified-2245-'));
+let originalCwd: string;
+
+beforeAll(async () => {
+ originalCwd = process.cwd();
+ process.chdir(SCRATCH);
+ const intel = await import('../src/memory/intelligence.js');
+ intel.clearIntelligence();
+});
+
+afterAll(() => {
+ try { process.chdir(originalCwd); } catch { /* */ }
+ try { rmSync(SCRATCH, { recursive: true, force: true }); } catch { /* */ }
+});
+
+describe('UnifiedLearningStats shape (ADR-075)', () => {
+ it('returns all four sub-views with their source paths', async () => {
+ const intel = await import('../src/memory/intelligence.js');
+ const stats = await intel.getUnifiedLearningStats();
+
+ expect(stats.global.source).toMatch(/globalStats|stats\.json/);
+ expect(stats.sona.source).toMatch(/sonaCoordinator/);
+ expect(stats.memoryBridge.source).toMatch(/memory-bridge/);
+ expect(stats.neuralPatterns.source).toMatch(/neural/);
+
+ expect(typeof stats.global.patternsLearned).toBe('number');
+ expect(typeof stats.global.trajectoriesRecorded).toBe('number');
+ expect(typeof stats.global.signalsProcessed).toBe('number');
+ expect(typeof stats.sona.trajectoriesTotal).toBe('number');
+ expect(typeof stats.memoryBridge.totalEntries).toBe('number');
+ expect(typeof stats.neuralPatterns.patternCount).toBe('number');
+
+ expect(stats.consistency).toBeDefined();
+ expect(Array.isArray(stats.consistency.notes)).toBe(true);
+ expect(typeof stats.consistency.sonaTracksGlobal).toBe('boolean');
+ expect(typeof stats.generatedAt).toBe('string');
+ });
+});
+
+describe('Driving each path moves the right counter in the unified view (#2245)', () => {
+ it('recordSignalProcessed β†’ global.signalsProcessed up', async () => {
+ const intel = await import('../src/memory/intelligence.js');
+ const before = (await intel.getUnifiedLearningStats()).global.signalsProcessed;
+ intel.recordSignalProcessed();
+ intel.recordSignalProcessed();
+ intel.flushIntelligenceStats();
+ const after = (await intel.getUnifiedLearningStats()).global.signalsProcessed;
+ expect(after).toBe(before + 2);
+ });
+
+ it('storeNeuralPatterns β†’ neuralPatterns.patternCount up', async () => {
+ const intel = await import('../src/memory/intelligence.js');
+ const neural = await import('../src/mcp-tools/neural-tools.js');
+ const before = (await intel.getUnifiedLearningStats()).neuralPatterns.patternCount;
+ await neural.storeNeuralPatterns([
+ { name: 'unified-test-1', type: 'unified-test', content: 'pattern A' },
+ { name: 'unified-test-2', type: 'unified-test', content: 'pattern B' },
+ ]);
+ const after = await intel.getUnifiedLearningStats();
+ expect(after.neuralPatterns.patternCount).toBe(before + 2);
+ expect(after.neuralPatterns.byType['unified-test']).toBeGreaterThanOrEqual(2);
+ });
+
+ it('hooks_task-completed {trainPatterns:true} β†’ global.trajectoriesRecorded up', async () => {
+ const intel = await import('../src/memory/intelligence.js');
+ const { hooksTools } = await import('../src/mcp-tools/hooks-tools.js');
+ const tool = hooksTools.find((t) => t.name === 'hooks_task-completed')!;
+ const before = (await intel.getUnifiedLearningStats()).global.trajectoriesRecorded;
+ await tool.handler({
+ taskId: 'unified-t-1', success: true, quality: 0.9, trainPatterns: true,
+ content: 'unified consistency test trajectory',
+ });
+ const after = (await intel.getUnifiedLearningStats()).global.trajectoriesRecorded;
+ expect(after).toBeGreaterThan(before);
+ }, 30_000);
+});
+
+describe('Consistency block flags drift, not silence (#2245 "contradictory sources")', () => {
+ it('reports memory-bridge unreachable explicitly when it is', async () => {
+ const intel = await import('../src/memory/intelligence.js');
+ const stats = await intel.getUnifiedLearningStats();
+ // In a fresh scratch CWD the bridge may or may not be reachable;
+ // either way, the response declares its state β€” never silently 0.
+ expect(typeof stats.memoryBridge.reachable).toBe('boolean');
+ if (!stats.memoryBridge.reachable) {
+ expect(stats.consistency.notes.some((n) => /memory-bridge/i.test(n))).toBe(true);
+ }
+ });
+
+ it('flags the "patternsLearned > 0 but neural store empty" pattern when it occurs', async () => {
+ // We already drove a task-completed earlier in this file, which moves
+ // global.patternsLearned. If neural store is still empty, the
+ // consistency note MUST mention it. If neural store has patterns,
+ // the note MUST NOT spuriously flag.
+ const intel = await import('../src/memory/intelligence.js');
+ const stats = await intel.getUnifiedLearningStats();
+ if (stats.global.patternsLearned > 0 && stats.neuralPatterns.patternCount === 0) {
+ expect(stats.consistency.notes.some((n) => /neural_patterns store is empty/i.test(n))).toBe(true);
+ } else if (stats.global.patternsLearned === 0 || stats.neuralPatterns.patternCount > 0) {
+ expect(stats.consistency.notes.every((n) => !/neural_patterns store is empty/i.test(n))).toBe(true);
+ }
+ });
+});
+
+describe('MCP tool exposes the unified view (#2245 β†’ ADR-075)', () => {
+ it('hooks_intelligence_unified-stats is registered and returns the unified shape', async () => {
+ const { hooksTools } = await import('../src/mcp-tools/hooks-tools.js');
+ const tool = hooksTools.find((t) => t.name === 'hooks_intelligence_unified-stats');
+ expect(tool).toBeDefined();
+ const r = (await tool!.handler({})) as Record<string, unknown>;
+ expect(r.global).toBeDefined();
+ expect(r.sona).toBeDefined();
+ expect(r.memoryBridge).toBeDefined();
+ expect(r.neuralPatterns).toBeDefined();
+ expect(r.consistency).toBeDefined();
+ });
+});
diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json
index fb5e6a9b65..28f36e65d2 100644
--- a/v3/@claude-flow/cli/package.json
+++ b/v3/@claude-flow/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/cli",
- "version": "3.10.14",
+ "version": "3.10.15",
"type": "module",
"description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code",
"main": "dist/src/index.js",
diff --git a/v3/@claude-flow/cli/scripts/benchmark-self-learning.mjs b/v3/@claude-flow/cli/scripts/benchmark-self-learning.mjs
index cf3de60dd3..4472feaf77 100644
--- a/v3/@claude-flow/cli/scripts/benchmark-self-learning.mjs
+++ b/v3/@claude-flow/cli/scripts/benchmark-self-learning.mjs
@@ -125,6 +125,14 @@ async function main() {
}
const dtE = performance.now() - tE;
+ // -------------------------------------------------------------------------
+ // Β§F β€” getUnifiedLearningStats (ADR-075)
+ // -------------------------------------------------------------------------
+ const tF = performance.now();
+ const unified = await intel.getUnifiedLearningStats();
+ const dtF = performance.now() - tF;
+ const unifiedOk = unified.global && unified.sona && unified.memoryBridge && unified.neuralPatterns && unified.consistency;
+
// -------------------------------------------------------------------------
// Summary
// -------------------------------------------------------------------------
@@ -170,6 +178,22 @@ async function main() {
note: 'MCP trajectory tools feed sonaCoordinator (see hooks_intelligence_stats), not globalStats β€” observable outcomes checked here',
elapsedMs: Number(dtE.toFixed(2)),
},
+ F_unifiedStats: {
+ shape: ['global', 'sona', 'memoryBridge', 'neuralPatterns', 'consistency'],
+ observed: {
+ 'global.patternsLearned': unified.global.patternsLearned,
+ 'global.trajectoriesRecorded': unified.global.trajectoriesRecorded,
+ 'global.signalsProcessed': unified.global.signalsProcessed,
+ 'memoryBridge.totalEntries': unified.memoryBridge.totalEntries,
+ 'memoryBridge.reachable': unified.memoryBridge.reachable,
+ 'neuralPatterns.patternCount': unified.neuralPatterns.patternCount,
+ 'sona.available': unified.sona.available,
+ 'consistency.notes': unified.consistency.notes.length,
+ },
+ passed: !!unifiedOk,
+ note: 'ADR-075 β€” one aggregator across the 4 stores. Each sub-view names its source.',
+ elapsedMs: Number(dtF.toFixed(2)),
+ },
},
finalState: {
signalsProcessed: A_after.signalsProcessed,
@@ -194,6 +218,8 @@ async function main() {
console.log(`| C task-completed (record-only) | ${N} | trajectories+${summary.sections.C_taskCompleted_recordedOnly.trajectoriesDelta} (expected 0) | ${summary.sections.C_taskCompleted_recordedOnly.passed ? 'βœ…' : '❌'} | ${summary.sections.C_taskCompleted_recordedOnly.elapsedMs} |`);
console.log(`| D pretrain β†’ neural_patterns | ${items.length} | stored=${summary.sections.D_pretrain_neuralPatterns.stored}, listed=${summary.sections.D_pretrain_neuralPatterns.listTotal} | ${summary.sections.D_pretrain_neuralPatterns.passed ? 'βœ…' : '❌'} | ${summary.sections.D_pretrain_neuralPatterns.elapsedMs} |`);
console.log(`| E multi-step trajectory | ${summary.sections.E_multiStepTrajectory.cycles} | persisted=${summary.sections.E_multiStepTrajectory.persistedCount}, sonaUpdate=${summary.sections.E_multiStepTrajectory.sonaUpdateCount} | ${summary.sections.E_multiStepTrajectory.passed ? 'βœ…' : '❌'} | ${summary.sections.E_multiStepTrajectory.elapsedMs} |`);
+ const f = summary.sections.F_unifiedStats;
+ console.log(`| F unified-stats | 4 stores | bridge.reachable=${f.observed['memoryBridge.reachable']}, sona.available=${f.observed['sona.available']}, neural.count=${f.observed['neuralPatterns.patternCount']}, notes=${f.observed['consistency.notes']} | ${f.passed ? 'βœ…' : '❌'} | ${f.elapsedMs} |`);
console.log('');
console.log(`Final state: signalsProcessed=${summary.finalState.signalsProcessed}, trajectoriesRecorded=${summary.finalState.trajectoriesRecorded}, patternsLearned=${summary.finalState.patternsLearned}`);
console.log(`Overall: ${allPassed ? 'βœ… ALL PASSED' : '❌ FAILED'}`);
diff --git a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
index 9948ebdd14..9ee5c4fea8 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
@@ -4450,8 +4450,31 @@ export const hooksTaskCompleted: MCPTool = {
},
};
+/**
+ * Unified learning-stats aggregator MCP tool (#2245 β†’ ADR-075).
+ *
+ * One honest call across the four historical stat sources β€” every sub-view
+ * names its store and a `consistency` block flags relationships that drift.
+ */
+export const hooksIntelligenceUnifiedStats: MCPTool = {
+ name: 'hooks_intelligence_unified-stats',
+ description: 'One honest view across the four learning stat sources: globalStats (`.claude-flow/neural/stats.json`), the in-memory SONA coordinator, memory-bridge AgentDB entries, and the neural-patterns store. Each sub-view names its source path. The `consistency` block notes cross-store drift (e.g. globalStats reports N patterns but neural_patterns is empty). Use this when one dashboard call should show "did learning happen" coherently β€” vs the four original aggregators which each return only their narrow slice. See ADR-075.',
+ category: 'hooks',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ verbose: { type: 'boolean', description: 'Include extended breakdowns', default: true },
+ },
+ },
+ handler: async (_input: Record<string, unknown>) => {
+ const intel = await import('../memory/intelligence.js');
+ return intel.getUnifiedLearningStats();
+ },
+};
+
// Export all hooks tools
export const hooksTools: MCPTool[] = [
+ hooksIntelligenceUnifiedStats,
hooksTeammateIdle,
hooksTaskCompleted,
hooksPreEdit,
diff --git a/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts
index 776f7848cf..a057dc4b58 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts
@@ -140,6 +140,32 @@ function saveNeuralStore(store: NeuralStore): void {
writeFileSync(getNeuralPath(), JSON.stringify(store, null, 2), 'utf-8');
}
+/**
+ * Public helper: read-only stats about the neural store, for the unified
+ * learning-stats aggregator. Returns total pattern count + per-type breakdown
+ * without exposing the embeddings.
+ */
+export function getNeuralStoreStats(): {
+ patternCount: number;
+ byType: Record<string, number>;
+ modelCount: number;
+ source: string;
+} {
+ const store = loadNeuralStore();
+ const patterns = Object.values(store.patterns ?? {});
+ const byType: Record<string, number> = {};
+ for (const p of patterns) {
+ const t = (p as { type?: string }).type || 'unknown';
+ byType[t] = (byType[t] ?? 0) + 1;
+ }
+ return {
+ patternCount: patterns.length,
+ byType,
+ modelCount: Object.values(store.models ?? {}).length,
+ source: '.claude-flow/neural/patterns.json (loadNeuralStore)',
+ };
+}
+
/**
* Public helper: store an array of patterns into the neural store so they
* surface via `neural_patterns list`. Used by hooks_pretrain so its extracted
diff --git a/v3/@claude-flow/cli/src/memory/intelligence.ts b/v3/@claude-flow/cli/src/memory/intelligence.ts
index 4f2cac96ee..eec8814681 100644
--- a/v3/@claude-flow/cli/src/memory/intelligence.ts
+++ b/v3/@claude-flow/cli/src/memory/intelligence.ts
@@ -829,6 +829,130 @@ export function flushIntelligenceStats(): void {
signalsSinceLastSave = 0;
}
+// ============================================================================
+// Unified learning-stats aggregator (#2245 follow-up to ADR-074)
+// ============================================================================
+
+/**
+ * The four historical stat sources (globalStats / memory_bridge_status /
+ * hooks metrics / neural_patterns count) genuinely measure different things,
+ * so we don't merge them β€” we expose ONE call that returns all four sub-views
+ * with the *source path* of each, plus a `consistency` block that spot-checks
+ * the relationships the system maintains.
+ *
+ * No new store; no migration; just one honest view across the four.
+ */
+export interface UnifiedLearningStats {
+ global: {
+ patternsLearned: number;
+ trajectoriesRecorded: number;
+ signalsProcessed: number;
+ lastAdaptation: number | null;
+ source: string;
+ };
+ sona: {
+ trajectoriesTotal: number;
+ patternsLearned: number;
+ reasoningBankSize: number;
+ avgAdaptationTimeMs: number;
+ source: string;
+ available: boolean;
+ };
+ memoryBridge: {
+ totalEntries: number;
+ perNamespace: Record<string, number>;
+ source: string;
+ reachable: boolean;
+ };
+ neuralPatterns: {
+ patternCount: number;
+ byType: Record<string, number>;
+ modelCount: number;
+ source: string;
+ };
+ consistency: {
+ sonaTracksGlobal: boolean;
+ sonaTracksGlobalDelta: number;
+ notes: string[];
+ };
+ generatedAt: string;
+}
+
+export async function getUnifiedLearningStats(): Promise<UnifiedLearningStats> {
+ const intel = getIntelligenceStats();
+ const sonaCoord = sonaCoordinator;
+ const bank = reasoningBank;
+
+ // SONA in-memory view
+ const sonaAvailable = !!sonaCoord;
+ let sonaStats = { trajectoriesTotal: 0, patternsLearned: 0, reasoningBankSize: 0, avgAdaptationTimeMs: 0 };
+ if (sonaCoord) {
+ try {
+ const s = (sonaCoord as unknown as { stats?: () => Record<string, number> }).stats?.() ?? {};
+ sonaStats = {
+ trajectoriesTotal: Number(s.trajectoriesTotal ?? s.trajectoriesProcessed ?? 0),
+ patternsLearned: Number(s.totalPatterns ?? s.patternsLearned ?? 0),
+ reasoningBankSize: (bank as unknown as { stats?: () => { patternCount?: number } })?.stats?.()?.patternCount ?? 0,
+ avgAdaptationTimeMs: (sonaCoord as unknown as { getAvgAdaptationTime?: () => number }).getAvgAdaptationTime?.() ?? 0,
+ };
+ } catch { /* SONA not yet initialised */ }
+ }
+
+ // memory-bridge
+ let bridgeStats: UnifiedLearningStats['memoryBridge'] = {
+ totalEntries: 0, perNamespace: {}, source: 'memory-bridge (skipped)', reachable: false,
+ };
+ try {
+ const mb = await import('./memory-bridge.js');
+ bridgeStats = await mb.getMemoryBridgeStats();
+ } catch { /* bridge module not loadable */ }
+
+ // neural store
+ let neuralStats: UnifiedLearningStats['neuralPatterns'] = {
+ patternCount: 0, byType: {}, modelCount: 0, source: 'neural store (skipped)',
+ };
+ try {
+ const nt = await import('../mcp-tools/neural-tools.js');
+ neuralStats = nt.getNeuralStoreStats();
+ } catch { /* neural module not loadable */ }
+
+ // Consistency notes β€” describe (don't enforce) the cross-store relationships
+ const sonaTracksGlobalDelta = sonaStats.trajectoriesTotal - intel.trajectoriesRecorded;
+ const notes: string[] = [];
+ if (sonaAvailable && Math.abs(sonaTracksGlobalDelta) > 2) {
+ notes.push(`sona.trajectoriesTotal (${sonaStats.trajectoriesTotal}) drifts from globalStats.trajectoriesRecorded (${intel.trajectoriesRecorded}) by ${sonaTracksGlobalDelta} β€” expected to track within Β±1`);
+ }
+ if (intel.patternsLearned > 0 && neuralStats.patternCount === 0) {
+ notes.push(`globalStats reports ${intel.patternsLearned} patterns learned but neural_patterns store is empty β€” pretrain has not written here, or trajectory-end isn't promoting patterns to the neural store yet`);
+ }
+ if (!bridgeStats.reachable) {
+ notes.push('memory-bridge unreachable β€” bridge-dependent counters (post-edit/-command persistence, pretrain bundle) will show 0');
+ }
+
+ return {
+ global: {
+ patternsLearned: intel.patternsLearned,
+ trajectoriesRecorded: intel.trajectoriesRecorded,
+ signalsProcessed: intel.signalsProcessed,
+ lastAdaptation: intel.lastAdaptation,
+ source: '.claude-flow/neural/stats.json (globalStats)',
+ },
+ sona: {
+ ...sonaStats,
+ source: 'sonaCoordinator (in-memory, resets per process)',
+ available: sonaAvailable,
+ },
+ memoryBridge: bridgeStats,
+ neuralPatterns: neuralStats,
+ consistency: {
+ sonaTracksGlobal: sonaAvailable ? Math.abs(sonaTracksGlobalDelta) <= 1 : true,
+ sonaTracksGlobalDelta,
+ notes,
+ },
+ generatedAt: new Date().toISOString(),
+ };
+}
+
// ============================================================================
// Public API
// ============================================================================
diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
index 1be20d14ec..ab7e03b92a 100644
--- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
@@ -2471,3 +2471,46 @@ function cosineSim(a: number[], b: number[]): number {
const mag = Math.sqrt(normA * normB);
return mag === 0 ? 0 : dot / mag;
}
+
+/**
+ * Public helper for the unified learning-stats aggregator: counts of entries
+ * per namespace + the top-level total. Best-effort β€” if the bridge isn't
+ * available it returns zeros so the aggregator can still report the other
+ * stores honestly. (#2245 follow-up.)
+ */
+export async function getMemoryBridgeStats(options: {
+ namespaces?: string[];
+ dbPath?: string;
+} = {}): Promise<{
+ totalEntries: number;
+ perNamespace: Record<string, number>;
+ source: string;
+ reachable: boolean;
+}> {
+ const namespaces = options.namespaces ?? [
+ 'default', 'patterns', 'claude-memories', 'auto-memory',
+ 'tasks', 'feedback', 'pretrain', 'trajectories',
+ ];
+ try {
+ const all = await bridgeListEntries({ dbPath: options.dbPath, limit: 1 });
+ if (!all) {
+ return { totalEntries: 0, perNamespace: {}, source: 'memory-bridge (unreachable)', reachable: false };
+ }
+ const perNamespace: Record<string, number> = {};
+ for (const ns of namespaces) {
+ try {
+ const r = await bridgeListEntries({ namespace: ns, dbPath: options.dbPath, limit: 1 });
+ const n = r?.total ?? 0;
+ if (n > 0) perNamespace[ns] = n;
+ } catch { /* skip per-namespace failure */ }
+ }
+ return {
+ totalEntries: all.total,
+ perNamespace,
+ source: 'memory-bridge AgentDB (bridgeListEntries)',
+ reachable: true,
+ };
+ } catch {
+ return { totalEntries: 0, perNamespace: {}, source: 'memory-bridge (error)', reachable: false };
+ }
+}
diff --git a/v3/docs/adr/ADR-075-unified-learning-stats.md b/v3/docs/adr/ADR-075-unified-learning-stats.md
new file mode 100644
index 0000000000..80110b3157
--- /dev/null
+++ b/v3/docs/adr/ADR-075-unified-learning-stats.md
@@ -0,0 +1,103 @@
+# ADR-075 β€” Unified Learning Stats Aggregator (#2245 follow-up)
+
+**Status**: Accepted β€” Implemented in ruflo 3.10.15
+**Date**: 2026-05-30
+**Tracking**: [#2245](https://github.com/ruvnet/ruflo/issues/2245) β€” self-learning subsystem audit
+**Supersedes**: the "future-rounds" item in ADR-074 Β§"Deliberately NOT in this round" titled *"Unify the 4 stat sources"*
+
+## Context
+
+ADR-074 (#2245 round 1) wired the three broken self-learning surfaces (`hooks_task-completed`, `signalsProcessed`, `pretrain`) and made every handler return an honest `learningPath`/`sources.stores`/`note` so callers see which path ran. It left one item to a future round:
+
+> Unify the 4 stat sources β€” designate `globalStats` as authoritative, derive `memory_bridge_status`, `hooks metrics`, and `neural_patterns count` from it. Multi-PR design work.
+
+When we tried that, we found the premise was wrong: the four sources **genuinely measure different things**. They look like duplicates of one number because they all answer "did learning happen?" β€” but each store is the authoritative record for a different layer:
+
+| Aggregator | Authoritative for |
+|---|---|
+| `globalStats` (`.claude-flow/neural/stats.json`) | "did the SONA/trajectory pipeline persist a learning event" (counter form) |
+| `sonaCoordinator` (in-memory) | "in this process, how much has SONA trained" (live, resets per process) |
+| `memory-bridge` (AgentDB) | "how many memory entries exist across all namespaces" β€” way broader than learning |
+| `neural_patterns` store | "what pattern artefacts are queryable by `neural_patterns list`" |
+
+Designating one as authoritative would either lose information or force lossy back-fill. The right move is to *aggregate the view*, not the store.
+
+## Decision
+
+Add a **read-only aggregator** that calls all four stores and returns them in one shape, with each sub-view explicitly naming its source. No new store. No migration. No data motion. One honest answer.
+
+### Public surface
+
+`getUnifiedLearningStats()` in `intelligence.ts` returns:
+
+```ts
+interface UnifiedLearningStats {
+ global: { patternsLearned, trajectoriesRecorded, signalsProcessed, lastAdaptation, source };
+ sona: { trajectoriesTotal, patternsLearned, reasoningBankSize, avgAdaptationTimeMs, source, available };
+ memoryBridge: { totalEntries, perNamespace, source, reachable };
+ neuralPatterns:{ patternCount, byType, modelCount, source };
+ consistency: { sonaTracksGlobal, sonaTracksGlobalDelta, notes };
+ generatedAt: string;
+}
+```
+
+### MCP surface
+
+`hooks_intelligence_unified-stats` exposes the aggregator to MCP clients. Description names every sub-view's store and the kind of question each answers, so an LLM agent can choose between this (one coherent dashboard) and the original narrow aggregators (one specific slice).
+
+### Helpers that fell out
+
+- `getMemoryBridgeStats({ namespaces? })` in `memory-bridge.ts` β€” read-only top-level + per-namespace entry counts. Best-effort: returns `reachable:false` instead of throwing when the bridge isn't loadable.
+- `getNeuralStoreStats()` in `neural-tools.ts` β€” top-level + per-`type` pattern count from the neural store file.
+
+Both are exported so anything wanting a coherent learning-state snapshot can build it from the same primitives.
+
+### The `consistency` block
+
+Instead of *enforcing* an invariant between stores (which would require schema-level work in the data path), we *describe* the relationships and flag drift:
+
+- `sona.trajectoriesTotal` is expected to track `globalStats.trajectoriesRecorded` within Β±1 between a process restart and the next `clearIntelligence()`. Drift outside Β±2 is a `consistency.notes` entry.
+- When `globalStats.patternsLearned > 0` but `neuralPatterns.patternCount === 0`, the consistency block reports it explicitly β€” that's the pretrain-vs-trajectory-vs-neural-store gap the reporter caught in #2245.
+- When the memory-bridge is unreachable, that's named in `consistency.notes` so bridge-dependent counters showing 0 aren't misread as "no activity."
+
+This is the same shape as the per-handler `learningPath`/`note` design from ADR-074: report what you did *and* what you couldn't do, never silently lie.
+
+## Deliberately NOT in this ADR
+
+- Schema-level unification (one store, others derived). Wrong design β€” see Context.
+- Persisting `sonaCoordinator` stats across process restarts. Out of scope; tracked under #2245's "background consolidation worker" item.
+- Wiring `post-edit` / `post-command` to feed the trajectory pipeline. Tracked as round B of the post-ADR-074 work.
+- Structured Distillation of trajectory content (arXiv:2603.13017, #2241). Tracked as round C.
+
+## Consequences
+
+- One call answers "did learning happen?" across all 4 layers, with each layer's source path named.
+- The `consistency.notes` array catches the specific drifts the reporter found (the "four contradictory sources" complaint) β€” they're now surfaced as flags on the unified call rather than as silent disagreement between separate dashboards.
+- The original aggregators stay where they are; nothing depends on them being merged. Code paths that need exactly the SONA slice still call `hooks_intelligence_stats`. Code paths that need the bridge slice still call `memory_bridge_status`. The unified call exists alongside them.
+- No data migration. No back-compat shim. New surface, new MCP tool, additive.
+
+## Verification
+
+- `__tests__/unified-stats-2245.test.ts` β€” 7 tests:
+ - Shape: all four sub-views present with `source` fields βœ…
+ - Driving each path moves the right counter:
+ - `recordSignalProcessed` β†’ `global.signalsProcessed` up βœ…
+ - `storeNeuralPatterns` β†’ `neuralPatterns.patternCount` up βœ…
+ - `hooks_task-completed {trainPatterns:true}` β†’ `global.trajectoriesRecorded` up βœ…
+ - Consistency block flags drift instead of staying silent βœ…
+ - MCP tool registered + returns the unified shape βœ…
+- `scripts/benchmark-self-learning.mjs Β§F` β€” proof artifact in `docs/benchmarks/runs/self-learning-latest.json`.
+- Build clean (`tsc -b`); full CLI suite green (modulo the 3 pre-existing flakes documented in ADR-074).
+
+## Reproduce
+
+```bash
+git clone https://github.com/ruvnet/ruflo && cd ruflo
+npm install && ( cd v3/@claude-flow/cli && npx tsc -b )
+
+# Cross-store consistency tests
+( cd v3/@claude-flow/cli && npx vitest run __tests__/unified-stats-2245.test.ts )
+
+# 6-section benchmark including Β§F unified-stats
+node v3/@claude-flow/cli/scripts/benchmark-self-learning.mjs
+```