π 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(memory): distinguish an RFE1-encrypted store from a broken one (#2889)
Nicholas Ruest3232d0b7659f
diff --git a/v3/@claude-flow/cli/__tests__/graph-edge-writer-rfe1-guard-2889.test.ts b/v3/@claude-flow/cli/__tests__/graph-edge-writer-rfe1-guard-2889.test.tsnew file mode 100644index 0000000000..6918b06f11--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/graph-edge-writer-rfe1-guard-2889.test.ts@@ -0,0 +1,159 @@+/**+ * #2889: getBridgeDb() must distinguish a legitimately RFE1-encrypted-at-rest+ * memory.db from genuine corruption/unavailability before attempting the+ * native better-sqlite3 open. The native open throws SQLITE_NOTADB on an+ * encrypted file, which the generic catch previously swallowed identically+ * to real corruption β nothing stopped a caller from concluding the store+ * was broken and running the destructive `memory init`, which creates a+ * fresh EMPTY store instead of using the existing encrypted data.+ *+ * Modeled on __tests__/graph-writer-shared-sqlite-3693.test.ts for the+ * mock-hermeticity helper (setSharedSqliteMock) β vitest applies a queued+ * doUnmock/doMock pair in resolve-completion order, not call order, so a+ * naive afterEach(doUnmock) can leave the previous test's mock active.+ */+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { createRequire } from 'node:module';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { randomBytes } from 'node:crypto';++const req = createRequire(import.meta.url);+let RealBetterSqlite3: any;+let native = true;++beforeAll(() => {+ try {+ RealBetterSqlite3 = req('better-sqlite3');+ const probe = new RealBetterSqlite3(':memory:');+ probe.close();+ } catch {+ native = false;+ }+});++const SHARED_SQLITE = '../src/memory/shared-sqlite.js';+const GRAPH_EDGE_WRITER = '../src/memory/graph-edge-writer.js';++/** Same hermetic mock helper as the #3693 test β see that file's header+ * comment for why a plain doUnmock/doMock pair is not safe here. */+async function setSharedSqliteMock(factory?: () => unknown) {+ vi.resetModules();+ vi.doUnmock(SHARED_SQLITE);+ await import(SHARED_SQLITE);+ vi.resetModules();+ if (factory) vi.doMock(SHARED_SQLITE, factory as never);+}++/** Fresh graph-edge-writer module instance with loadBetterSqlite3 mocked to+ * a call-tracking wrapper around the real native constructor. */+async function freshGraphWriterWithSpy() {+ const loadSpy = vi.fn(async () => RealBetterSqlite3);+ await setSharedSqliteMock(() => ({ loadBetterSqlite3: loadSpy }));+ const gw = await import(GRAPH_EDGE_WRITER);+ return { gw, loadSpy };+}++let root: string;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'ruflo-2889-'));+});++afterEach(async () => {+ vi.restoreAllMocks();+ await setSharedSqliteMock(); // clear any mock, drained, so the next test starts clean+ try { rmSync(root, { recursive: true, force: true }); } catch { /* best-effort */ }+});++describe('#2889 graph-edge-writer RFE1 encryption guard', () => {+ it.skipIf(!native)('a genuinely RFE1-encrypted file returns null without attempting the native open, and warns once per process', async () => {+ const { encryptBuffer } = await import('../src/encryption/vault.js');+ const key = randomBytes(32);+ const blob = encryptBuffer(Buffer.from('irrelevant plaintext payload'), key);+ const dbPath = join(root, 'memory.db');+ writeFileSync(dbPath, blob);++ const { gw, loadSpy } = await freshGraphWriterWithSpy();+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const first = await gw.getBridgeDb(dbPath);+ const second = await gw.getBridgeDb(dbPath);++ expect(first).toBeNull();+ expect(second).toBeNull();+ // The native constructor path (loadBetterSqlite3) must never even be+ // reached for a detected-encrypted file β the guard returns before it.+ expect(loadSpy).not.toHaveBeenCalled();++ const rfe1Warnings = errSpy.mock.calls.filter((call) =>+ String(call[0]).includes('encrypted at rest') && String(call[0]).includes('memory init'),+ );+ expect(rfe1Warnings).toHaveLength(1);+ expect(rfe1Warnings[0][0]).toContain('#2889');+ expect(rfe1Warnings[0][0]).toContain('Do NOT run `memory init`'); // explicitly warns against it, never recommends it+ expect(rfe1Warnings[0][0]).toContain('NOT lost or damaged');+ });++ it.skipIf(!native)('a genuinely corrupted (non-encrypted) file returns null WITHOUT the encrypted-store warning', async () => {+ const dbPath = join(root, 'memory.db');+ writeFileSync(dbPath, Buffer.from('this is not a sqlite database and not RFE1 either, just garbage bytes'));++ const { gw, loadSpy } = await freshGraphWriterWithSpy();+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const db = await gw.getBridgeDb(dbPath);++ expect(db).toBeNull();+ // Unlike the encrypted case, a genuine corruption attempt DOES reach the+ // native constructor (and throws there, caught by the generic catch).+ expect(loadSpy).toHaveBeenCalled();+ expect(errSpy).not.toHaveBeenCalled();+ });++ it.skipIf(!native)('a normal valid plaintext memory.db is unaffected by the new header sniff', async () => {+ const dbPath = join(root, 'memory.db');+ const seed = new RealBetterSqlite3(dbPath);+ seed.pragma('journal_mode = WAL');+ seed.close();++ const { gw, loadSpy } = await freshGraphWriterWithSpy();+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const db = await gw.getBridgeDb(dbPath);++ expect(db).not.toBeNull();+ expect(loadSpy).toHaveBeenCalled();+ expect(errSpy).not.toHaveBeenCalled();+ // Regression check: graph_edges table is still created on the common path.+ const row = db.prepare(`SELECT COUNT(*) AS n FROM graph_edges`).get();+ expect(row.n).toBe(0);++ gw._resetBridgeDb();+ });++ it.skipIf(!native)('isBridgeDbEncryptedAtRest distinguishes the encrypted case from plaintext/corrupt/missing', async () => {+ const { encryptBuffer } = await import('../src/encryption/vault.js');+ const key = randomBytes(32);++ const encPath = join(root, 'enc.db');+ writeFileSync(encPath, encryptBuffer(Buffer.from('payload'), key));++ const corruptPath = join(root, 'corrupt.db');+ writeFileSync(corruptPath, Buffer.from('garbage, not a db, not rfe1'));++ const plainPath = join(root, 'plain.db');+ const seed = new RealBetterSqlite3(plainPath);+ seed.close();++ const missingPath = join(root, 'does-not-exist.db');++ const { gw } = await freshGraphWriterWithSpy();++ expect(gw.isBridgeDbEncryptedAtRest(encPath)).toBe(true);+ expect(gw.isBridgeDbEncryptedAtRest(corruptPath)).toBe(false);+ expect(gw.isBridgeDbEncryptedAtRest(plainPath)).toBe(false);+ expect(gw.isBridgeDbEncryptedAtRest(missingPath)).toBe(false);+ });+});diff --git a/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.tsindex d0fac859ad..b43e43ee30 100644--- a/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts@@ -78,6 +78,26 @@ async function getGraphEdgeWriter() {if (!graphEdgeWriterMod) graphEdgeWriterMod = await import('../memory/graph-edge-writer.js');return graphEdgeWriterMod;}++// #2889 β a null graph_edges DB handle can mean several unrelated things+// (missing native module, permissions, genuine corruption, or an RFE1+// encrypted-at-rest store). Recommending `memory init` for the encrypted+// case is actively harmful β it creates a fresh EMPTY store instead of+// using the existing encrypted data β so distinguish it before choosing+// a hint.+async function bridgeUnavailableResult(): Promise<{ error: string; hint: string }> {+ const { isBridgeDbEncryptedAtRest } = await getGraphEdgeWriter();+ if (isBridgeDbEncryptedAtRest()) {+ return {+ error: 'graph_edges DB is encrypted at rest (RFE1) β the native bridge cannot open it directly.',+ hint: 'Your existing data is intact; this is a known limitation, not corruption. Do NOT run `memory init` β see https://github.com/ruvnet/ruflo/issues/2889.',+ };+ }+ return {+ error: 'graph_edges DB unavailable (sql.js could not load)',+ hint: 'Check Node version + try `ruflo memory init` to initialize manually.',+ };+}let memInitMod: typeof import('../memory/memory-initializer.js') | null = null;async function getMemInit() {if (!memInitMod) memInitMod = await import('../memory/memory-initializer.js');@@ -1132,7 +1152,7 @@ export const agentdbGraphQuery: MCPTool = {// #2246 fix: lazy-create memory.db on first pathfinder call so// fresh environments work without a pre-existing memory init.const db = await getBridgeDb(undefined, { createIfMissing: true });- if (!db) return { success: false, error: 'graph_edges DB unavailable (sql.js could not load)', hint: 'Check Node version + try `ruflo memory init` to initialize manually.', mode, nodeId };+ if (!db) return { success: false, ...(await bridgeUnavailableResult()), mode, nodeId };// Load all rows with embedding_ref and score by cosine.// better-sqlite3 API β `db.exec(sql, params)` (sql.js) silently@@ -1176,7 +1196,7 @@ export const agentdbGraphQuery: MCPTool = {// #2246 fix: lazy-create memory.db on first pathfinder call so// fresh environments work without a pre-existing memory init.const db = await getBridgeDb(undefined, { createIfMissing: true });- if (!db) return { success: false, error: 'graph_edges DB unavailable (sql.js could not load)', hint: 'Check Node version + try `ruflo memory init` to initialize manually.', mode, nodeId };+ if (!db) return { success: false, ...(await bridgeUnavailableResult()), mode, nodeId };// better-sqlite3 API β see semantic-mode comment above.const edges = db.prepare(@@ -1379,7 +1399,7 @@ export const agentdbGraphPathfinder: MCPTool = {const { getBridgeDb } = await getGraphEdgeWriter();// #2246 fix: lazy-create memory.db on first pathfinder call.const db = await getBridgeDb(undefined, { createIfMissing: true });- if (!db) return { success: false, error: 'graph_edges DB unavailable (sql.js could not load)', hint: 'Check Node version + try `ruflo memory init` to initialize manually.', seedNodeId };+ if (!db) return { success: false, ...(await bridgeUnavailableResult()), seedNodeId };const colsSql = algorithm === 'witness-chain-divergence'? 'source_id, target_id, weight, last_reinforced, witness_id'diff --git a/v3/@claude-flow/cli/src/memory/graph-edge-writer.ts b/v3/@claude-flow/cli/src/memory/graph-edge-writer.tsindex 5193cfda17..27564710c7 100644--- a/v3/@claude-flow/cli/src/memory/graph-edge-writer.ts+++ b/v3/@claude-flow/cli/src/memory/graph-edge-writer.ts@@ -36,6 +36,86 @@ import * as crypto from 'crypto';import { getMemoryRoot } from './memory-initializer.js';import { encodeEmbedding } from './embedding-quantization.js';import { loadBetterSqlite3 } from './shared-sqlite.js';+import { isEncryptedBlob } from '../encryption/vault.js';++// ============================================================================+// #2889 β RFE1 encryption-at-rest guard+// ============================================================================+//+// When CLAUDE_FLOW_ENCRYPT_AT_REST is on, memory.db is an opaque RFE1 blob+// (see encryption/vault.ts). `new BetterSqlite3(dbPath)` has no RFE1 sniff+// and throws SQLITE_NOTADB on it, which the generic catch below swallows β+// indistinguishable from genuine corruption, a missing native module, or a+// permissions failure. That ambiguity is what let #2889 happen: nothing+// stopped a caller from concluding the store was broken and running the+// destructive `memory init`, which creates a fresh EMPTY store instead of+// using the existing encrypted data.+//+// Fix: sniff the header bytes (never buffer the whole file β memory.db can+// be multi-GB) before attempting the native open. If it's RFE1-encrypted,+// skip the native open (it would only throw) and warn once per process.++/** Read just the first `len` bytes of a file without loading the whole file+ * into memory. Mirrors the pattern in commands/doctor.ts's readHeaderBytes+ * (not imported from there β this is a memory-layer module and must not+ * depend on the command layer). */+function readHeaderBytes(filePath: string, len: number): Buffer {+ const fd = fs.openSync(filePath, 'r');+ try {+ const buf = Buffer.alloc(len);+ const bytesRead = fs.readSync(fd, buf, 0, len, 0);+ return buf.subarray(0, bytesRead);+ } finally {+ fs.closeSync(fd);+ }+}++// RFE1 wire format is magic(4) + iv(12) + ciphertext(N) + tag(16); the+// shortest possible blob is 32 bytes. 64 gives headroom.+const ENCRYPTION_SNIFF_LEN = 64;++/** True iff `filePath` is a legitimately RFE1-encrypted-at-rest file. A read+ * failure (permissions, races) is treated as "not encrypted" β the caller's+ * own open/query error handling still runs right after. */+function isRfe1EncryptedAtRest(filePath: string): boolean {+ try {+ return isEncryptedBlob(readHeaderBytes(filePath, ENCRYPTION_SNIFF_LEN));+ } catch {+ return false;+ }+}++let _warnedRfe1Encrypted = false;++function warnRfe1EncryptedOnce(dbPath: string): void {+ if (_warnedRfe1Encrypted) return;+ _warnedRfe1Encrypted = true;+ // eslint-disable-next-line no-console+ console.error(+ `[graph-edge-writer] ${dbPath} is encrypted at rest (CLAUDE_FLOW_ENCRYPT_AT_REST). ` ++ 'The native graph-edge bridge cannot open an RFE1-encrypted store directly β ' ++ 'this is a known limitation, not corruption. Your existing data is NOT lost ' ++ 'or damaged. Do NOT run `memory init` in response to this β that would create ' ++ 'a fresh, empty store instead of using your existing encrypted data. ' ++ 'See #2889 (https://github.com/ruvnet/ruflo/issues/2889) for details and recovery options.',+ );+}++/**+ * True iff the memory.db bridge at `customDbPath` (or the default location)+ * is currently RFE1-encrypted-at-rest. Callers that receive `null` from+ * getBridgeDb()/insertGraphEdge() can use this to avoid recommending the+ * destructive `memory init` command for this specific, non-corrupt case.+ */+export function isBridgeDbEncryptedAtRest(customDbPath?: string): boolean {+ const dbPath = customDbPath ?? path.join(getMemoryRoot(), 'memory.db');+ return fs.existsSync(dbPath) && isRfe1EncryptedAtRest(dbPath);+}++/** Test-only: clear the once-per-process warning flag. */+export function _resetRfe1WarningFlag(): void {+ _warnedRfe1Encrypted = false;+}// ============================================================================// Lazy-cached better-sqlite3 db handle@@ -125,6 +205,16 @@ export async function getBridgeDb(customDbPath?: string, opts?: { createIfMissinconst dbExists = fs.existsSync(dbPath);if (!dbExists && !createIfMissing) return null;+ // #2889 β detect RFE1 encryption-at-rest before even attempting the+ // native open: `new BetterSqlite3(dbPath)` on an encrypted file would+ // only throw SQLITE_NOTADB, caught by the generic catch below with no+ // way to tell it apart from genuine corruption. Skip straight to a+ // clear, actionable warning instead.+ if (dbExists && isRfe1EncryptedAtRest(dbPath)) {+ warnRfe1EncryptedOnce(dbPath);+ return null;+ }+// Ensure parent dir exists for createIfMissing case.if (!dbExists && createIfMissing) {const dir = path.dirname(dbPath);