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): report statistics for the selected database

Rudy Celekli42df589065e1
diff --git a/v3/@claude-flow/cli/__tests__/memory-stats-selected-store.test.ts b/v3/@claude-flow/cli/__tests__/memory-stats-selected-store.test.ts
new file mode 100644
index 0000000000..77ed2d2fd1
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/memory-stats-selected-store.test.ts
@@ -0,0 +1,122 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const mocks = vi.hoisted(() => ({
+ list: vi.fn(), init: vi.fn(), labels: vi.fn(), sibling: vi.fn(), json: vi.fn(), warning: vi.fn(), error: vi.fn(),
+}));
+vi.mock('../src/memory/memory-initializer.js', async importOriginal => ({
+ ...await importOriginal<typeof import('../src/memory/memory-initializer.js')>(),
+ listEntries: mocks.list,
+ initializeMemoryDatabase: mocks.init,
+ checkMemoryInitialization: mocks.labels,
+ getHNSWStatus: () => ({ algorithm: 'brute-force', available: false }),
+ loadEmbeddingModel: async () => ({ success: false, dimensions: 0 }),
+}));
+vi.mock('../src/memory/sibling-store.js', () => ({ countSiblingStoreRows: mocks.sibling }));
+vi.mock('../src/output.js', () => ({ output: {
+ printJson: mocks.json, printWarning: mocks.warning, printError: mocks.error,
+ writeln: vi.fn(), printTable: vi.fn(), printInfo: vi.fn(), bold: (s: string) => s,
+ warning: (s: string) => s, dim: (s: string) => s,
+} }));
+vi.mock('../src/prompt.js', () => ({ select: vi.fn(), input: vi.fn(), confirm: vi.fn() }));
+vi.mock('../src/mcp-client.js', () => ({ MCPClientError: class extends Error {}, callMCPTool: async (name: string, args: object) => {
+ const { memoryTools } = await import('../src/mcp-tools/memory-tools.js');
+ return memoryTools.find(tool => tool.name === name)!.handler(args);
+} }));
+const { memoryTools } = await import('../src/mcp-tools/memory-tools.js');
+const { memoryCommand } = await import('../src/commands/memory.js');
+const stats = memoryTools.find(tool => tool.name === 'memory_stats')!;
+const command = memoryCommand.subcommands!.find(command => command.name === 'stats')!;
+let dir: string;
+let selected: string;
+const entries = [
+ { namespace: 'selected', hasEmbedding: false, createdAt: '2026-03-01T00:00:00Z' },
+ { namespace: 'selected', hasEmbedding: true, createdAt: '2026-01-01T00:00:00Z' },
+];
+beforeEach(() => {
+ vi.clearAllMocks();
+ dir = mkdtempSync(join(tmpdir(), 'stats-selected-'));
+ selected = join(dir, 'selected.db');
+ writeFileSync(selected, 'store');
+ writeFileSync(selected + '-wal', 'wal');
+ vi.stubEnv('CLAUDE_FLOW_DB_PATH', '');
+ mocks.labels.mockResolvedValue({ initialized: true, version: 'selected-version' });
+ mocks.init.mockResolvedValue({ success: true });
+ mocks.sibling.mockResolvedValue(null);
+ mocks.list.mockImplementation(async ({ dbPath }) => ({ success: true, total: dbPath === selected ? 2 : 1, entries: dbPath === selected ? entries : entries.slice(0, 1) }));
+});
+afterEach(() => { vi.unstubAllEnvs(); rmSync(dir, { recursive: true, force: true }); });
+const run = (flags: Record<string, unknown> = {}) => command.action!({ cwd: dir, args: [], flags: { _: [], format: 'json', ...flags }, interactive: false });
+
+describe('stats describes the selected store', () => {
+ it('threads the optional MCP path through every page and metadata probe', async () => {
+ const result = await stats.handler({ dbPath: selected }) as any;
+ expect(result.totalEntries).toBe(2);
+ expect(mocks.list).toHaveBeenCalledWith(expect.objectContaining({ dbPath: selected }));
+ expect(mocks.labels).toHaveBeenCalledWith(selected);
+ expect(mocks.init).not.toHaveBeenCalled();
+ expect(result.location).toBe(selected);
+ expect(result.totalSize).toBe('8 B');
+ expect(result.oldestEntry).toBe('2026-01-01T00:00:00.000Z');
+ expect(result.newestEntry).toBe('2026-03-01T00:00:00.000Z');
+ });
+
+ it('honors --path over the environment and includes sibling disclosure in JSON', async () => {
+ vi.stubEnv('CLAUDE_FLOW_DB_PATH', join(dir, 'other.db'));
+ mocks.sibling.mockResolvedValue({ path: join(dir, 'agentdb-memory.db'), rows: 9 });
+ const result = await run({ path: selected }) as any;
+ expect(result.success).toBe(true);
+ expect(result.data.entries.total).toBe(2);
+ expect(result.data.storage).toEqual({ total: '8 B', location: selected });
+ expect(result.data.unreadStore.rows).toBe(9);
+ expect(mocks.sibling).toHaveBeenCalledWith(selected);
+ });
+
+ it('honors CLAUDE_FLOW_DB_PATH when --path is absent', async () => {
+ vi.stubEnv('CLAUDE_FLOW_DB_PATH', selected);
+ const result = await run() as any;
+ expect(result.data.entries.total).toBe(2);
+ expect(result.data.storage.location).toBe(selected);
+ });
+
+ it('reports unavailable stores as a failed command, including JSON mode', async () => {
+ mocks.list.mockResolvedValue({ success: false, entries: [], total: 0, error: 'read refused' });
+ const result = await run({ path: selected });
+ expect(result?.success).toBe(false);
+ expect(result?.exitCode).toBe(1);
+ expect(mocks.error).toHaveBeenCalledWith(expect.stringContaining('read refused'));
+ });
+
+ it('keeps an empty store distinct from an unavailable one', async () => {
+ mocks.list.mockResolvedValue({ success: true, entries: [], total: 0 });
+ const result = await stats.handler({ dbPath: selected }) as any;
+ expect(result.totalEntries).toBe(0);
+ expect(result.oldestEntry).toBeNull();
+ expect(result.newestEntry).toBeNull();
+ });
+ it('keeps the selected path on later pages', async () => {
+ mocks.list.mockImplementation(async ({ dbPath, offset }) => ({
+ success: true, total: 10001,
+ entries: dbPath === selected ? Array.from({ length: offset === 0 ? 10000 : 1 }, () => entries[0]) : [],
+ }));
+ const result = await stats.handler({ dbPath: selected }) as any;
+ expect(result.entriesCounted).toBe(10001);
+ expect(mocks.list).toHaveBeenCalledTimes(2);
+ expect(mocks.list.mock.calls.every(([options]) => options.dbPath === selected)).toBe(true);
+ });
+
+ it('discloses sibling rows in text output too', async () => {
+ mocks.sibling.mockResolvedValue({ path: join(dir, 'agentdb-memory.db'), rows: 9 });
+ expect((await run({ path: selected, format: 'text' }))?.success).toBe(true);
+ expect(mocks.warning).toHaveBeenCalledWith(expect.stringContaining('9 entries'));
+ });
+
+ it.each([42, ' '])('rejects invalid dbPath %j instead of inspecting another store', async dbPath => {
+ const result = await stats.handler({ dbPath }) as any;
+ expect(result.available).toBe(false);
+ expect(mocks.list).not.toHaveBeenCalled();
+ });
+
+});
diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.ts
index ca06bcaeae..fba66d5ddf 100644
--- a/v3/@claude-flow/cli/src/commands/memory.ts
+++ b/v3/@claude-flow/cli/src/commands/memory.ts
@@ -1058,10 +1058,14 @@ const statsCommand: Command = {
action: async (ctx: CommandContext): Promise<CommandResult> => {
// Call MCP memory/stats tool for real statistics
try {
- const statsResult = await callMCPTool('memory_stats', {}) as {
+ const dbPath = resolveDbPath(ctx.flags.path as string | undefined);
+ const statsResult = await callMCPTool('memory_stats', { dbPath }) as {
+ available?: boolean;
+ error?: string;
+ truncated?: boolean;
totalEntries: number;
entriesWithEmbeddings?: number;
- totalSize: string;
+ totalSize: string | null;
version: string;
backend: string;
location: string;
@@ -1069,7 +1073,14 @@ const statsCommand: Command = {
newestEntry: string | null;
};
+ if (statsResult.available === false) {
+ output.printError(`Failed to get stats: ${statsResult.error || 'Store unavailable'}`);
+ return { success: false, exitCode: 1 };
+ }
+ const unreadStore = await countSiblingStoreRows(dbPath);
const stats = {
+ ...(unreadStore ? { unreadStore } : {}),
+ ...(statsResult.truncated ? { truncated: true } : {}),
backend: statsResult.backend,
entries: {
total: statsResult.totalEntries,
@@ -1077,7 +1088,7 @@ const statsCommand: Command = {
text: statsResult.totalEntries
},
storage: {
- total: statsResult.totalSize,
+ total: statsResult.totalSize ?? 'unknown',
location: statsResult.location
},
version: statsResult.version,
@@ -1090,6 +1101,9 @@ const statsCommand: Command = {
return { success: true, data: stats };
}
+ if (unreadStore) {
+ output.printWarning(`${unreadStore.rows} entries are in ${unreadStore.path} and were not read here. Read them with --path ${unreadStore.path}.`);
+ }
output.writeln();
output.writeln(output.bold('Memory Statistics'));
output.writeln();
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 6cfee268e3..73681052dd 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
@@ -10,7 +10,7 @@
* @module v3/cli/mcp-tools/memory-tools
*/
-import { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'fs';
+import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'fs';
import { homedir } from 'os';
import { join, resolve } from 'path';
import { createHash } from 'crypto';
@@ -332,13 +332,14 @@ type ListPage<E> = {
* that reported `success: false` was read as an empty one.
*/
async function collectAllEntries<E>(
- listEntries: (options: { limit?: number; offset?: number }) => Promise<ListPage<E>>,
+ listEntries: (options: { limit?: number; offset?: number; dbPath?: string }) => Promise<ListPage<E>>,
+ dbPath?: string,
): Promise<ListPage<E>> {
const entries: E[] = [];
let total = 0;
for (let page = 0; page < MEMORY_STATS_MAX_PAGES; page++) {
- const result = await listEntries({ limit: MEMORY_STATS_PAGE, offset: entries.length });
+ const result = await listEntries({ limit: MEMORY_STATS_PAGE, offset: entries.length, dbPath });
if (!result.success) {
return { success: false, entries, total: result.total ?? total, error: result.error };
}
@@ -367,13 +368,13 @@ function memoryStatsUnavailable(error: string): {
* WAL frames, so it is allowed to fail without that meaning the store is
* missing — which is exactly the conflation #3311 reports.
*/
-async function readMemoryStatusLabels(): Promise<{
+async function readMemoryStatusLabels(dbPath?: string): Promise<{
version?: string;
features?: { vectorEmbeddings: boolean; patternLearning: boolean; temporalDecay: boolean };
}> {
try {
const { checkMemoryInitialization } = await getMemoryFunctions();
- const status = await checkMemoryInitialization();
+ const status = await checkMemoryInitialization(dbPath);
return { version: status.version, features: status.features };
} catch {
return {};
@@ -892,10 +893,17 @@ export const memoryTools: MCPTool[] = [
category: 'memory',
inputSchema: {
type: 'object',
- properties: {},
+ properties: {
+ dbPath: { type: 'string', description: 'Database file to inspect; omitted uses the MCP store default' },
+ },
},
- handler: async () => {
- await ensureInitialized();
+ handler: async (input) => {
+ if (input.dbPath !== undefined && (typeof input.dbPath !== 'string' || !input.dbPath.trim())) {
+ return memoryStatsUnavailable('dbPath must be a non-empty string');
+ }
+ const dbPath = typeof input.dbPath === 'string' ? resolve(input.dbPath) : undefined;
+ // An explicit read must not initialize or migrate the unrelated default store.
+ if (!dbPath) await ensureInitialized();
const { listEntries } = await getMemoryFunctions();
// #3311: the store's own listing decides whether memory is there.
@@ -905,9 +913,9 @@ export const memoryTools: MCPTool[] = [
// `initialized: false` from this tool alone. The probe is still read
// below, for the version and feature labels it is the only source of,
// but it no longer gets to overrule a working store.
- let listing: ListPage<{ namespace: string; hasEmbedding: boolean }>;
+ let listing: ListPage<{ namespace: string; hasEmbedding: boolean; createdAt?: string }>;
try {
- listing = await collectAllEntries(listEntries);
+ listing = await collectAllEntries(listEntries, dbPath);
} catch (error) {
return memoryStatsUnavailable(error instanceof Error ? error.message : 'Unknown error');
}
@@ -923,17 +931,37 @@ export const memoryTools: MCPTool[] = [
// from the breakdown while still being counted in the total.
const namespaces: Record<string, number> = Object.create(null) as Record<string, number>;
let withEmbeddings = 0;
+ let oldest = Infinity;
+ let newest = -Infinity;
for (const entry of listing.entries) {
namespaces[entry.namespace] = (namespaces[entry.namespace] || 0) + 1;
if (entry.hasEmbedding) withEmbeddings++;
+ const created = Date.parse(entry.createdAt ?? '');
+ if (Number.isFinite(created)) {
+ oldest = Math.min(oldest, created);
+ newest = Math.max(newest, created);
+ }
}
const counted = listing.entries.length;
- const status = await readMemoryStatusLabels();
+ const status = await readMemoryStatusLabels(dbPath);
+ let totalSize: string | null = null;
+ if (dbPath) {
+ try {
+ let bytes = statSync(dbPath).size;
+ try { bytes += statSync(dbPath + '-wal').size; } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ totalSize = `${bytes} B`;
+ } catch { /* unavailable file metadata is unknown, not zero */ }
+ }
return {
initialized: true,
totalEntries: listing.total,
+ ...(dbPath ? { location: dbPath, totalSize } : {}),
+ oldestEntry: counted >= listing.total && Number.isFinite(oldest) ? new Date(oldest).toISOString() : null,
+ newestEntry: counted >= listing.total && Number.isFinite(newest) ? new Date(newest).toISOString() : null,
entriesCounted: counted,
// The breakdown below covers `entriesCounted` rows, which is every
// row unless the listing was truncated; say so rather than letting