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(memory): add read-only `memory peek` command (#3508) (#3620)

rUve86134e45bde
diff --git a/v3/@claude-flow/cli/__tests__/memory-peek-3508.test.ts b/v3/@claude-flow/cli/__tests__/memory-peek-3508.test.ts
new file mode 100644
index 0000000000..5a97c95091
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/memory-peek-3508.test.ts
@@ -0,0 +1,223 @@
+/**
+ * #3508 β€” read-only memory route/peek.
+ *
+ * `memory peek` must answer "which store files does this cwd resolve to,
+ * how many rows, when was the last write, and why" without ever creating,
+ * initializing, or migrating anything β€” unlike `memory stats` (#3448),
+ * which still calls `ensureInitialized()` when no explicit path is given.
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { _resetMemoryRootCache } from '../src/memory/memory-initializer.js';
+import { memoryPeek } from '../src/memory/memory-peek.js';
+import { MAGIC } from '../src/encryption/vault.js';
+
+let testDir: string;
+let originalDbPath: string | undefined;
+let originalMemoryPath: string | undefined;
+
+beforeEach(() => {
+ testDir = mkdtempSync(join(tmpdir(), 'memory-peek-3508-'));
+ originalDbPath = process.env.CLAUDE_FLOW_DB_PATH;
+ originalMemoryPath = process.env.CLAUDE_FLOW_MEMORY_PATH;
+ delete process.env.CLAUDE_FLOW_DB_PATH;
+ delete process.env.CLAUDE_FLOW_MEMORY_PATH;
+ _resetMemoryRootCache();
+});
+
+afterEach(() => {
+ if (originalDbPath === undefined) delete process.env.CLAUDE_FLOW_DB_PATH;
+ else process.env.CLAUDE_FLOW_DB_PATH = originalDbPath;
+ if (originalMemoryPath === undefined) delete process.env.CLAUDE_FLOW_MEMORY_PATH;
+ else process.env.CLAUDE_FLOW_MEMORY_PATH = originalMemoryPath;
+ _resetMemoryRootCache();
+ rmSync(testDir, { recursive: true, force: true });
+});
+
+/** Build a real sql.js `memory.db` file on disk β€” same engine the CLI
+ * store uses β€” so the peek read path is exercised against a real file,
+ * not a mock. */
+async function writeSqlJsFixture(
+ dbPath: string,
+ rows: Array<{ id: string; key: string; namespace: string; createdAt: number; updatedAt: number; status: string }>,
+): Promise<void> {
+ mkdirSync(dirname(dbPath), { recursive: true });
+ const initSqlJs = (await import('sql.js')).default as unknown as () => Promise<any>;
+ const SQL = await initSqlJs();
+ const db = new SQL.Database();
+ db.run(`CREATE TABLE memory_entries (
+ id TEXT PRIMARY KEY, key TEXT, namespace TEXT, content TEXT,
+ created_at INTEGER, updated_at INTEGER, status TEXT
+ )`);
+ for (const r of rows) {
+ db.run(
+ 'INSERT INTO memory_entries (id, key, namespace, content, created_at, updated_at, status) VALUES (?, ?, ?, ?, ?, ?, ?)',
+ [r.id, r.key, r.namespace, 'content', r.createdAt, r.updatedAt, r.status],
+ );
+ }
+ writeFileSync(dbPath, Buffer.from(db.export()));
+ db.close();
+}
+
+/** Build a real better-sqlite3 `agentdb-memory.db` sibling, the same way
+ * the native bridge writes it. */
+async function writeNativeFixture(
+ dbPath: string,
+ rows: Array<{ id: string; key: string; namespace: string; createdAt: number; updatedAt: number; status: string }>,
+): Promise<void> {
+ mkdirSync(dirname(dbPath), { recursive: true });
+ const Database = (await import('better-sqlite3')).default as unknown as new (p: string) => any;
+ const db = new Database(dbPath);
+ db.exec(`CREATE TABLE memory_entries (
+ id TEXT PRIMARY KEY, key TEXT, namespace TEXT, content TEXT,
+ created_at INTEGER, updated_at INTEGER, status TEXT
+ )`);
+ const insert = db.prepare(
+ 'INSERT INTO memory_entries (id, key, namespace, content, created_at, updated_at, status) VALUES (?, ?, ?, ?, ?, ?, ?)',
+ );
+ for (const r of rows) insert.run(r.id, r.key, r.namespace, 'content', r.createdAt, r.updatedAt, r.status);
+ db.close();
+}
+
+function allFilesUnder(dir: string): string[] {
+ if (!existsSync(dir)) return [];
+ const out: string[] = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) out.push(...allFilesUnder(full));
+ else out.push(full);
+ }
+ return out;
+}
+
+describe('#3508 memory peek is read-only', () => {
+ it('creates nothing in a fresh project β€” the core correctness property', async () => {
+ const root = join(testDir, '.swarm');
+ process.env.CLAUDE_FLOW_MEMORY_PATH = root;
+ _resetMemoryRootCache();
+
+ const result = await memoryPeek();
+
+ expect(allFilesUnder(testDir)).toEqual([]);
+ expect(existsSync(root)).toBe(false);
+ expect(result.stores).toEqual([
+ { role: 'cli', path: join(root, 'memory.db'), exists: false, rows: null, lastWrite: null, sizeBytes: null, walBytes: null },
+ { role: 'mcp', path: join(root, 'agentdb-memory.db'), exists: false, rows: null, lastWrite: null, sizeBytes: null, walBytes: null },
+ ]);
+ expect(result.sharedKeys).toBeNull();
+ });
+
+ it('never opens a file it does not report as existing', async () => {
+ // Only the cli store exists; the mcp sibling must stay unopened/unreported as existing.
+ const root = join(testDir, '.swarm');
+ process.env.CLAUDE_FLOW_MEMORY_PATH = root;
+ _resetMemoryRootCache();
+ await writeSqlJsFixture(join(root, 'memory.db'), []);
+
+ const result = await memoryPeek();
+
+ expect(result.stores.find(s => s.role === 'cli')!.exists).toBe(true);
+ expect(result.stores.find(s => s.role === 'mcp')!.exists).toBe(false);
+ expect(existsSync(join(root, 'agentdb-memory.db'))).toBe(false);
+ });
+});
+
+describe('#3508 memory peek reports rows, last write, and route source', () => {
+ it('counts only active rows and reports the latest write for the cli store', async () => {
+ const root = join(testDir, '.swarm');
+ await writeSqlJsFixture(join(root, 'memory.db'), [
+ { id: '1', key: 'a', namespace: 'default', createdAt: 1000, updatedAt: 1000, status: 'active' },
+ { id: '2', key: 'b', namespace: 'default', createdAt: 2000, updatedAt: 5000, status: 'active' },
+ { id: '3', key: 'c', namespace: 'default', createdAt: 9999999, updatedAt: 9999999, status: 'deleted' },
+ { id: '4', key: 'd', namespace: 'default', createdAt: 3000, updatedAt: 3000, status: 'active' as unknown as string },
+ ]);
+
+ const result = await memoryPeek({ path: join(root, 'memory.db') });
+ const cli = result.stores.find(s => s.role === 'cli')!;
+
+ expect(cli.exists).toBe(true);
+ expect(cli.rows).toBe(3); // the soft-deleted row (#3) is excluded
+ expect(cli.lastWrite).toBe(new Date(5000).toISOString()); // max(updated_at) among active rows
+ expect(cli.sizeBytes).toBeGreaterThan(0);
+ expect(cli.walBytes).toBe(0); // no -wal sidecar on disk
+ expect(result.root.source).toBe('path');
+ });
+
+ it('reports rows and last write for the native mcp sibling independently', async () => {
+ const root = join(testDir, '.swarm');
+ process.env.CLAUDE_FLOW_MEMORY_PATH = root;
+ _resetMemoryRootCache();
+ await writeNativeFixture(join(root, 'agentdb-memory.db'), [
+ { id: 'n1', key: 'x', namespace: 'ns', createdAt: 1_700_000_000_000, updatedAt: 1_700_000_000_000, status: 'active' },
+ { id: 'n2', key: 'y', namespace: 'ns', createdAt: 1_700_000_001_000, updatedAt: 1_700_000_002_000, status: 'active' },
+ ]);
+
+ const result = await memoryPeek();
+ const mcp = result.stores.find(s => s.role === 'mcp')!;
+ const cli = result.stores.find(s => s.role === 'cli')!;
+
+ expect(cli.exists).toBe(false);
+ expect(mcp.exists).toBe(true);
+ expect(mcp.rows).toBe(2);
+ expect(mcp.lastWrite).toBe(new Date(1_700_000_002_000).toISOString());
+ });
+
+ it('counts sharedKeys as the intersection, never the sum of both stores', async () => {
+ const root = join(testDir, '.swarm');
+ process.env.CLAUDE_FLOW_MEMORY_PATH = root;
+ _resetMemoryRootCache();
+ await writeSqlJsFixture(join(root, 'memory.db'), [
+ { id: '1', key: 'shared-1', namespace: 'default', createdAt: 1000, updatedAt: 1000, status: 'active' },
+ { id: '2', key: 'shared-2', namespace: 'default', createdAt: 1000, updatedAt: 1000, status: 'active' },
+ { id: '3', key: 'cli-only', namespace: 'default', createdAt: 1000, updatedAt: 1000, status: 'active' },
+ ]);
+ await writeNativeFixture(join(root, 'agentdb-memory.db'), [
+ { id: 'n1', key: 'shared-1', namespace: 'default', createdAt: 1000, updatedAt: 1000, status: 'active' },
+ { id: 'n2', key: 'shared-2', namespace: 'default', createdAt: 1000, updatedAt: 1000, status: 'active' },
+ { id: 'n3', key: 'mcp-only', namespace: 'default', createdAt: 1000, updatedAt: 1000, status: 'active' },
+ ]);
+
+ const result = await memoryPeek();
+
+ // 3 + 3 = 6 is the bug #3508 calls out; the right answer is the 2-key overlap.
+ expect(result.sharedKeys).toBe(2);
+ });
+
+ it.each([
+ ['CLAUDE_FLOW_DB_PATH', 'CLAUDE_FLOW_DB_PATH' as const],
+ ['CLAUDE_FLOW_MEMORY_PATH', 'CLAUDE_FLOW_MEMORY_PATH' as const],
+ ])('labels the route source as %s when that decided it', async (envVar, expectedSource) => {
+ const root = join(testDir, '.swarm');
+ if (envVar === 'CLAUDE_FLOW_DB_PATH') process.env.CLAUDE_FLOW_DB_PATH = join(root, 'memory.db');
+ else process.env.CLAUDE_FLOW_MEMORY_PATH = root;
+ _resetMemoryRootCache();
+
+ const result = await memoryPeek();
+
+ expect(result.root.source).toBe(expectedSource);
+ });
+
+ it('defaults the route source to "default" with no override', async () => {
+ const result = await memoryPeek();
+ expect(result.root.source).toBe('default');
+ expect(result.cwd).toBe(process.cwd());
+ });
+
+ it('reports an encrypted-at-rest memory.db as rows: null, encrypted: true, with size still reported', async () => {
+ const root = join(testDir, '.swarm');
+ process.env.CLAUDE_FLOW_MEMORY_PATH = root;
+ _resetMemoryRootCache();
+ mkdirSync(root, { recursive: true });
+ const fakeEncrypted = Buffer.concat([MAGIC, Buffer.alloc(60, 7)]);
+ writeFileSync(join(root, 'memory.db'), fakeEncrypted);
+
+ const result = await memoryPeek();
+ const cli = result.stores.find(s => s.role === 'cli')!;
+
+ expect(cli.encrypted).toBe(true);
+ expect(cli.rows).toBeNull();
+ expect(cli.sizeBytes).toBe(fakeEncrypted.length);
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.ts
index d3b68b1f24..b54856b7a1 100644
--- a/v3/@claude-flow/cli/src/commands/memory.ts
+++ b/v3/@claude-flow/cli/src/commands/memory.ts
@@ -18,6 +18,7 @@ import { existsSync } from 'node:fs';
import { siblingAgentDbPath } from '../memory/memory-bridge.js';
import { validateIdentifier } from '../mcp-tools/validate-input.js';
import { memoryKeyError } from '../mcp-tools/memory-tools.js';
+import { memoryPeek } from '../memory/memory-peek.js';
/**
* #3228: a miss in one store is not a miss in the memory.
@@ -1310,6 +1311,57 @@ const statsCommand: Command = {
}
};
+// #3508: read-only route/peek β€” which store files this cwd resolves to,
+// their row counts and last write, without creating or initializing
+// anything. Unlike `stats`, this never calls into the MCP tool layer (no
+// `authorizeMcpTool` receipt, no `ensureInitialized()`): it reads both
+// files directly, in-process, read-only.
+const peekCommand: Command = {
+ name: 'peek',
+ description: 'Report which memory store files this cwd resolves to, their row counts and last write β€” read-only, creates nothing',
+ options: [DB_PATH_OPTION],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ try {
+ const result = await memoryPeek({ path: ctx.flags.path as string | undefined });
+
+ if (ctx.flags.format === 'json') {
+ output.printJson(result);
+ return { success: true, data: result };
+ }
+
+ output.writeln();
+ output.writeln(output.bold('Memory Peek'));
+ output.writeln();
+ output.writeln(`cwd: ${result.cwd}`);
+ output.writeln(`root: ${result.root.path} (source: ${result.root.source})`);
+ output.writeln();
+ output.printTable({
+ columns: [
+ { key: 'role', header: 'Role', width: 6 },
+ { key: 'path', header: 'Path', width: 40 },
+ { key: 'exists', header: 'Exists', width: 8 },
+ { key: 'rows', header: 'Rows', width: 8, align: 'right' },
+ { key: 'lastWrite', header: 'Last Write', width: 24 },
+ ],
+ data: result.stores.map((store) => ({
+ role: store.role,
+ path: store.path,
+ exists: store.exists ? 'yes' : 'no',
+ rows: store.encrypted ? 'encrypted' : (store.rows === null ? 'unknown' : String(store.rows)),
+ lastWrite: store.lastWrite ?? 'N/A',
+ })),
+ });
+ output.writeln();
+ output.writeln(`Shared keys (same namespace+key in both stores): ${result.sharedKeys === null ? 'unknown' : result.sharedKeys}`);
+
+ return { success: true, data: result };
+ } catch (error) {
+ output.printError(`Failed to peek: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ return { success: false, exitCode: 1 };
+ }
+ }
+};
+
// Configure command
const configureCommand: Command = {
name: 'configure',
@@ -2286,12 +2338,13 @@ const classifyCommand: Command = {
export 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, classifyCommand, selectOperatorCommand],
+ subcommands: [initMemoryCommand, storeCommand, retrieveCommand, searchCommand, listCommand, deleteCommand, purgeCommand, statsCommand, peekCommand, configureCommand, cleanupCommand, compressCommand, exportCommand, importCommand, distillCommand, backupCommand, classifyCommand, selectOperatorCommand],
options: [],
examples: [
{ command: 'claude-flow memory store -k "key" -v "value"', description: 'Store data' },
{ command: 'claude-flow memory search -q "auth patterns"', description: 'Search memory' },
- { command: 'claude-flow memory stats', description: 'Show statistics' }
+ { command: 'claude-flow memory stats', description: 'Show statistics' },
+ { command: 'claude-flow memory peek', description: 'Read-only: which store files this cwd resolves to, rows, last write' }
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
output.writeln();
@@ -2308,6 +2361,7 @@ export const memoryCommand: Command = {
`${output.highlight('list')} - List memory entries`,
`${output.highlight('delete')} - Delete memory entry`,
`${output.highlight('stats')} - Show statistics`,
+ `${output.highlight('peek')} - Read-only: resolved store files, rows, last write (creates nothing)`,
`${output.highlight('configure')} - Configure backend`,
`${output.highlight('cleanup')} - Clean expired entries`,
`${output.highlight('compress')} - Compress database`,
diff --git a/v3/@claude-flow/cli/src/memory/memory-peek.ts b/v3/@claude-flow/cli/src/memory/memory-peek.ts
new file mode 100644
index 0000000000..6e789a2413
--- /dev/null
+++ b/v3/@claude-flow/cli/src/memory/memory-peek.ts
@@ -0,0 +1,254 @@
+/**
+ * #3508: read-only memory route/peek.
+ *
+ * A health check needs to know which memory store files a cwd resolves to,
+ * and what is in them, without changing anything to find out. `memory stats`
+ * (even after #3463/#3448) still calls `ensureInitialized()` when no explicit
+ * path is given, and answers for one file per call. This module reports
+ * BOTH files β€” the sql.js `memory.db` the CLI writes and its native
+ * `agentdb-memory.db` sibling the MCP/bridge path writes β€” in one read-only
+ * pass, and says which resolution rule picked the root.
+ *
+ * Contract (do not relax without re-reading #3508):
+ * - never creates, initializes, or migrates anything;
+ * - never opens a file that does not exist (`existsSync` gated before any
+ * open attempt, for both engines);
+ * - every open is `readonly`/`fileMustExist` (native) or a one-shot byte
+ * buffer handed to sql.js, which is never written back to disk;
+ * - `rows: null` means "could not read" and is never a count of 0, so an
+ * empty store and an unreadable one never look the same;
+ * - an encrypted-at-rest `memory.db` reports `encrypted: true` and
+ * `rows: null`, but its size is still reported.
+ */
+import { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from 'node:fs';
+import path from 'node:path';
+import { getMemoryRoot, resolveDbPath } from './memory-initializer.js';
+import { siblingAgentDbPath } from './memory-bridge.js';
+import { isEncryptedBlob } from '../encryption/vault.js';
+
+export type MemoryRootSource =
+ | 'path'
+ | 'CLAUDE_FLOW_DB_PATH'
+ | 'CLAUDE_FLOW_MEMORY_PATH'
+ | 'config'
+ | 'default';
+
+export interface MemoryPeekStore {
+ role: 'cli' | 'mcp';
+ path: string;
+ exists: boolean;
+ rows: number | null;
+ lastWrite: string | null;
+ sizeBytes: number | null;
+ walBytes: number | null;
+ encrypted?: boolean;
+}
+
+export interface MemoryPeekResult {
+ cwd: string;
+ root: { path: string; source: MemoryRootSource };
+ stores: MemoryPeekStore[];
+ sharedKeys: number | null;
+}
+
+// Mirrors the `ACTIVE_MEMORY_ROW_SQL` convention in memory-initializer.ts:
+// legacy rows with a NULL status predate soft-delete semantics and count.
+const ACTIVE_ROW_SQL = `(status = 'active' OR status IS NULL)`;
+const ENCRYPTION_SNIFF_LEN = 64; // RFE1 magic(4)+iv(12)+tag(16); 64 gives headroom.
+
+interface StoreProbe {
+ rows: number | null;
+ lastWrite: string | null;
+ keys: Set<string> | null;
+ encrypted?: boolean;
+}
+
+function safeStatSize(filePath: string): number | null {
+ try {
+ return statSync(filePath).size;
+ } catch {
+ return null;
+ }
+}
+
+function readHeaderBytes(filePath: string, len: number): Buffer {
+ const fd = openSync(filePath, 'r');
+ try {
+ const buf = Buffer.alloc(len);
+ const bytesRead = readSync(fd, buf, 0, len, 0);
+ return buf.subarray(0, bytesRead);
+ } finally {
+ closeSync(fd);
+ }
+}
+
+function latestMillis(values: Array<number | string | null | undefined>): number {
+ let latest = -Infinity;
+ for (const raw of values) {
+ const millis = typeof raw === 'number' ? raw : Number(raw);
+ if (Number.isFinite(millis)) latest = Math.max(latest, millis);
+ }
+ return latest;
+}
+
+/** sql.js is read as a one-shot in-memory byte buffer β€” nothing is ever
+ * written back, so reading this file has no on-disk side effect. */
+async function probeSqlJsStore(dbPath: string): Promise<StoreProbe> {
+ try {
+ if (isEncryptedBlob(readHeaderBytes(dbPath, ENCRYPTION_SNIFF_LEN))) {
+ return { rows: null, lastWrite: null, keys: null, encrypted: true };
+ }
+ } catch {
+ /* header read failed (permissions/race) β€” fall through to the open attempt */
+ }
+ try {
+ const initSqlJs: any = (await import('sql.js')).default ?? (await import('sql.js'));
+ const SQL = await (typeof initSqlJs === 'function' ? initSqlJs() : initSqlJs.default());
+ const buf = readFileSync(dbPath);
+ const db = new SQL.Database(new Uint8Array(buf));
+ try {
+ const tables = db.exec(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='memory_entries'",
+ );
+ if (!tables.length) return { rows: null, lastWrite: null, keys: null };
+ const result = db.exec(
+ `SELECT namespace, key, created_at, updated_at FROM memory_entries WHERE ${ACTIVE_ROW_SQL}`,
+ );
+ const values: any[][] = result[0]?.values ?? [];
+ const keys = new Set<string>();
+ let last = -Infinity;
+ for (const [namespace, key, createdAt, updatedAt] of values) {
+ keys.add(`${String(namespace)}\u0000${String(key)}`);
+ last = Math.max(last, latestMillis([createdAt, updatedAt]));
+ }
+ return {
+ rows: values.length,
+ lastWrite: Number.isFinite(last) ? new Date(last).toISOString() : null,
+ keys,
+ };
+ } finally {
+ try { db.close(); } catch { /* best effort */ }
+ }
+ } catch {
+ return { rows: null, lastWrite: null, keys: null };
+ }
+}
+
+/** better-sqlite3 is an optional native dependency β€” absence must degrade
+ * to "could not read", never throw. Opened `readonly`/`fileMustExist`, same
+ * as `countSiblingStoreRows` in sibling-store.ts. */
+async function probeNativeStore(dbPath: string): Promise<StoreProbe> {
+ try {
+ const require = (await import('node:module')).createRequire(import.meta.url);
+ const Database = require('better-sqlite3');
+ const db = new Database(dbPath, { readonly: true, fileMustExist: true });
+ try {
+ const table = db
+ .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='memory_entries'")
+ .get();
+ if (!table) return { rows: null, lastWrite: null, keys: null };
+ const rows = db
+ .prepare(`SELECT namespace, key, created_at, updated_at FROM memory_entries WHERE ${ACTIVE_ROW_SQL}`)
+ .all() as Array<{ namespace: unknown; key: unknown; created_at: unknown; updated_at: unknown }>;
+ const keys = new Set<string>();
+ let last = -Infinity;
+ for (const row of rows) {
+ keys.add(`${String(row.namespace)}\u0000${String(row.key)}`);
+ last = Math.max(last, latestMillis([row.created_at as number, row.updated_at as number]));
+ }
+ return {
+ rows: rows.length,
+ lastWrite: Number.isFinite(last) ? new Date(last).toISOString() : null,
+ keys,
+ };
+ } finally {
+ try { db.close(); } catch { /* best effort */ }
+ }
+ } catch {
+ return { rows: null, lastWrite: null, keys: null };
+ }
+}
+
+/** Same precedence `getMemoryRoot()`/`resolveDbPath()` already own β€” this
+ * only *labels* which rule decided, it never re-derives the path itself. */
+function decideSource(cliFlag?: string): MemoryRootSource {
+ if (cliFlag && cliFlag.trim().length > 0) return 'path';
+ if (process.env.CLAUDE_FLOW_DB_PATH && process.env.CLAUDE_FLOW_DB_PATH.trim().length > 0) {
+ return 'CLAUDE_FLOW_DB_PATH';
+ }
+ if (process.env.CLAUDE_FLOW_MEMORY_PATH && process.env.CLAUDE_FLOW_MEMORY_PATH.trim().length > 0) {
+ return 'CLAUDE_FLOW_MEMORY_PATH';
+ }
+ const configCandidates = [
+ path.resolve(process.cwd(), 'claude-flow.config.json'),
+ path.resolve(process.cwd(), '.claude-flow', 'config.json'),
+ ];
+ for (const configPath of configCandidates) {
+ if (!existsSync(configPath)) continue;
+ try {
+ const raw = JSON.parse(readFileSync(configPath, 'utf-8'));
+ const fromConfig: unknown = raw?.memory?.persistPath ?? raw?.memory?.path;
+ if (typeof fromConfig === 'string' && fromConfig.trim().length > 0) return 'config';
+ } catch {
+ /* malformed config β€” getMemoryRoot() falls through to default too */
+ }
+ }
+ return 'default';
+}
+
+async function describeStore(
+ role: 'cli' | 'mcp',
+ storePath: string,
+ probe: (p: string) => Promise<StoreProbe>,
+): Promise<{ store: MemoryPeekStore; keys: Set<string> | null }> {
+ if (!existsSync(storePath)) {
+ return {
+ store: { role, path: storePath, exists: false, rows: null, lastWrite: null, sizeBytes: null, walBytes: null },
+ keys: null,
+ };
+ }
+ const result = await probe(storePath);
+ const sizeBytes = safeStatSize(storePath);
+ const walBytes = safeStatSize(`${storePath}-wal`) ?? 0;
+ return {
+ store: {
+ role,
+ path: storePath,
+ exists: true,
+ rows: result.rows,
+ lastWrite: result.lastWrite,
+ sizeBytes,
+ walBytes,
+ ...(result.encrypted ? { encrypted: true } : {}),
+ },
+ keys: result.keys,
+ };
+}
+
+/**
+ * Resolve the route and report both stores, read-only. Never creates,
+ * initializes, or migrates anything, on an empty project or any other.
+ */
+export async function memoryPeek(opts?: { path?: string }): Promise<MemoryPeekResult> {
+ const cliFlag = opts?.path;
+ const cliPath = resolveDbPath(cliFlag);
+ const mcpPath = siblingAgentDbPath(cliPath);
+ const root = { path: cliFlag ? path.dirname(cliPath) : getMemoryRoot(), source: decideSource(cliFlag) };
+
+ const cliDescribed = await describeStore('cli', cliPath, probeSqlJsStore);
+ const stores: MemoryPeekStore[] = [cliDescribed.store];
+ let mcpKeys: Set<string> | null = null;
+
+ if (mcpPath) {
+ const mcpDescribed = await describeStore('mcp', mcpPath, probeNativeStore);
+ stores.push(mcpDescribed.store);
+ mcpKeys = mcpDescribed.keys;
+ }
+
+ const cliKeys = cliDescribed.keys;
+ const sharedKeys = cliKeys && mcpKeys
+ ? [...cliKeys].filter((key) => mcpKeys!.has(key)).length
+ : null;
+
+ return { cwd: process.cwd(), root, stores, sharedKeys };
+}