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): scrub deleted payload from tombstones (#4351)

ordinary being947204c0827b
diff --git a/v3/@claude-flow/cli/__tests__/memory-delete-scrubs-payload-3785.test.ts b/v3/@claude-flow/cli/__tests__/memory-delete-scrubs-payload-3785.test.ts
new file mode 100644
index 0000000000..e1c152dc92
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/memory-delete-scrubs-payload-3785.test.ts
@@ -0,0 +1,174 @@
+/**
+ * #3785 residual: `memory delete` is a soft delete, but the tombstone used to
+ * keep the deleted payload on disk. Both the native bridge and the sql.js
+ * fallback hid the row via `status='deleted'` while leaving `content` (and the
+ * native path left `embedding`) intact, so a deleted value remained readable
+ * by anyone opening the SQLite file directly.
+ *
+ * The tombstone keeps its identity/status for upsert resurrection and audit,
+ * but must scrub the payload columns.
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { deleteEntry, MEMORY_SCHEMA_V3, purgeNamespace } from '../src/memory/memory-initializer.js';
+
+const SECRET = 'deleted-value-must-not-survive';
+const EMBEDDING = JSON.stringify([0.1, 0.2, 0.3]);
+const TAGS = JSON.stringify(['secret-tag']);
+const METADATA = JSON.stringify({ secret: true });
+
+let Database: any = null;
+try {
+ Database = (await import('better-sqlite3')).default;
+ const probe = new Database(':memory:');
+ probe.close();
+} catch {
+ Database = null; // native binding unavailable locally; CI runs this case
+}
+
+const nativeIt = Database ? it : it.skip;
+
+const scrubExpected = {
+ status: 'deleted',
+ content: '',
+ embedding: null,
+ embedding_model: null,
+ embedding_dimensions: null,
+ tags: null,
+ metadata: null,
+};
+
+async function seedSqlJs(dbPath: string): Promise<void> {
+ const initSqlJs = (await import('sql.js')).default;
+ const SQL = await initSqlJs();
+ const db = new SQL.Database();
+ try {
+ db.run(MEMORY_SCHEMA_V3);
+ db.run(
+ `INSERT INTO memory_entries
+ (id, key, namespace, content, embedding, embedding_model,
+ embedding_dimensions, tags, metadata, created_at, updated_at, status)
+ VALUES ('secret-id', 'secret-key', 'scrub', ?, ?, 'test-model',
+ 3, ?, ?, 1, 1, 'active')`,
+ [SECRET, EMBEDDING, TAGS, METADATA],
+ );
+ writeFileSync(dbPath, Buffer.from(db.export()));
+ } finally {
+ db.close();
+ }
+}
+
+function expectNoRawPayload(dbPath: string): void {
+ const raw = readFileSync(dbPath);
+ for (const marker of [SECRET, EMBEDDING, TAGS, METADATA]) {
+ expect(raw.includes(Buffer.from(marker))).toBe(false);
+ }
+}
+
+async function readSqlJsRow(dbPath: string): Promise<Record<string, unknown>> {
+ const initSqlJs = (await import('sql.js')).default;
+ const SQL = await initSqlJs();
+ const db = new SQL.Database(readFileSync(dbPath));
+ try {
+ const result = db.exec(
+ `SELECT status, content, embedding, embedding_model,
+ embedding_dimensions, tags, metadata
+ FROM memory_entries WHERE key = 'secret-key'`,
+ );
+ const columns = result[0]?.columns ?? [];
+ const values = result[0]?.values?.[0] ?? [];
+ return Object.fromEntries(columns.map((column, i) => [column, values[i]]));
+ } finally {
+ db.close();
+ }
+}
+
+describe('memory delete scrubs the tombstoned payload (#3785)', () => {
+ let dir = '';
+ let prevDisableBridge: string | undefined;
+
+ beforeEach(() => {
+ prevDisableBridge = process.env.CLAUDE_FLOW_DISABLE_BRIDGE;
+ });
+
+ afterEach(() => {
+ if (prevDisableBridge === undefined) delete process.env.CLAUDE_FLOW_DISABLE_BRIDGE;
+ else process.env.CLAUDE_FLOW_DISABLE_BRIDGE = prevDisableBridge;
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ });
+
+ it('scrubs content and vectors on the sql.js fallback', async () => {
+ dir = mkdtempSync(join(tmpdir(), 'ruflo-delete-scrub-sqljs-'));
+ const dbPath = join(dir, 'memory.db');
+ await seedSqlJs(dbPath);
+
+ process.env.CLAUDE_FLOW_DISABLE_BRIDGE = '1';
+
+ const result = await deleteEntry({ key: 'secret-key', namespace: 'scrub', dbPath });
+ expect(result).toMatchObject({ success: true, deleted: true });
+
+ expect(await readSqlJsRow(dbPath)).toEqual(scrubExpected);
+ expectNoRawPayload(dbPath);
+ });
+
+ it('zeroes the payload when purging a namespace', async () => {
+ dir = mkdtempSync(join(tmpdir(), 'ruflo-purge-scrub-sqljs-'));
+ const dbPath = join(dir, 'memory.db');
+ await seedSqlJs(dbPath);
+ process.env.CLAUDE_FLOW_DISABLE_BRIDGE = '1';
+
+ const result = await purgeNamespace({ namespace: 'scrub', dbPath });
+ expect(result).toMatchObject({ success: true, deletedCount: 1, remainingEntries: 0 });
+
+ expectNoRawPayload(dbPath);
+ });
+
+ nativeIt('scrubs content and vectors on the native bridge', async () => {
+ dir = mkdtempSync(join(tmpdir(), 'ruflo-delete-scrub-native-'));
+ const dbPath = join(dir, 'memory.db');
+ const db = new Database(dbPath);
+ let closed = false;
+ try {
+ db.exec(MEMORY_SCHEMA_V3);
+ db.prepare(
+ `INSERT INTO memory_entries
+ (id, key, namespace, content, embedding, embedding_model,
+ embedding_dimensions, tags, metadata, created_at, updated_at, status)
+ VALUES ('secret-id', 'secret-key', 'scrub', ?, ?, 'test-model',
+ 3, ?, ?, 1, 1, 'active')`,
+ ).run(SECRET, EMBEDDING, TAGS, METADATA);
+
+ const { __setMemoryBridgeRegistryForTests, bridgeDeleteEntry } = await import(
+ '../src/memory/memory-bridge.js'
+ );
+ __setMemoryBridgeRegistryForTests({
+ getAgentDB: () => ({ database: db, embedder: null }),
+ get: () => null,
+ });
+
+ const result = await bridgeDeleteEntry({ key: 'secret-key', namespace: 'scrub', dbPath });
+ expect(result).toMatchObject({ success: true, deleted: true });
+
+ const row = db.prepare(
+ `SELECT status, content, embedding, embedding_model,
+ embedding_dimensions, tags, metadata
+ FROM memory_entries WHERE key = 'secret-key'`,
+ ).get();
+ expect(row).toEqual(scrubExpected);
+
+ // Flush and truncate WAL so the check reads the durable main image, not
+ // an older frame that still contains the pre-delete payload.
+ db.pragma('wal_checkpoint(TRUNCATE)');
+ db.close();
+ closed = true;
+ expectNoRawPayload(dbPath);
+ } finally {
+ const { __setMemoryBridgeRegistryForTests } = await import('../src/memory/memory-bridge.js');
+ __setMemoryBridgeRegistryForTests(null);
+ if (!closed) db.close();
+ }
+ });
+});
diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
index 3c01f27420..f2ac49c0de 100644
--- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
@@ -1845,12 +1845,29 @@ export async function bridgeDeleteEntry(options: {
return { success: false, deleted: false, key, namespace, remainingEntries: 0, error: `MutationGuard rejected: ${guardResult.reason}` };
}
- // Soft delete using parameterized query
+ // #3785: secure_delete zeroes the old cells while the payload columns are
+ // scrubbed; otherwise SQLite can leave the deleted text in free pages.
+ try {
+ ctx.db.pragma('secure_delete = ON');
+ } catch { /* non-fatal: the logical scrub below still hides the row */ }
+
+ // Soft delete using parameterized query. The tombstone must keep only
+ // what later upserts/audits need: the payload columns are scrubbed here,
+ // not merely hidden by the status filter. `content` is NOT NULL in the
+ // schema, so "scrubbed" is the empty string rather than SQL NULL; that
+ // still removes the deleted value from disk and from any raw SQLite read.
let changes = 0;
try {
const result = ctx.db.prepare(`
UPDATE memory_entries
- SET status = 'deleted', updated_at = ?
+ SET status = 'deleted',
+ content = '',
+ embedding = NULL,
+ embedding_model = NULL,
+ embedding_dimensions = NULL,
+ tags = NULL,
+ metadata = NULL,
+ updated_at = ?
WHERE key = ? AND namespace = ? AND ${ACTIVE_MEMORY_ROW_SQL}
`).run(Date.now(), key, namespace);
changes = result?.changes ?? 0;
@@ -1935,6 +1952,11 @@ export async function bridgePurgeNamespace(options: {
let deletedCount = 0;
try {
+ // #3785: a hard DELETE without secure_delete leaves the purged payload
+ // in free pages; purge claims to be irreversible.
+ try {
+ ctx.db.pragma('secure_delete = ON');
+ } catch { /* non-fatal: the rows are still removed below */ }
const result = ctx.db.prepare(`DELETE FROM memory_entries WHERE namespace = ?`).run(namespace);
deletedCount = result?.changes ?? 0;
} catch (e) {
diff --git a/v3/@claude-flow/cli/src/memory/memory-initializer.ts b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
index ba016a2895..1fb36cf2ac 100644
--- a/v3/@claude-flow/cli/src/memory/memory-initializer.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
@@ -3973,6 +3973,11 @@ export async function deleteEntry(options: {
const fileBuffer = readFileMaybeEncrypted(dbPath, null);
const db = new SQL.Database(fileBuffer);
+ // #3785: zero the old cells as well as the live row. Without
+ // secure_delete, UPDATE leaves the previous text in SQLite free pages,
+ // so the "deleted" value is still recoverable from the file image.
+ db.run('PRAGMA secure_delete = ON');
+
// Check if entry exists first
const checkStmt = db.prepare(`
SELECT id FROM memory_entries
@@ -4004,12 +4009,19 @@ export async function deleteEntry(options: {
};
}
- // Delete the entry (soft delete by setting status to 'deleted')
- // Also null out the embedding to clean up vector data from SQLite
+ // Soft delete by setting status to 'deleted'. Scrub the payload, not
+ // only the vector: a tombstone that keeps `content` on disk still
+ // exposes deleted data to anyone who opens the SQLite file. `content`
+ // is NOT NULL, so use the empty string rather than SQL NULL.
db.run(`
UPDATE memory_entries
SET status = 'deleted',
+ content = '',
embedding = NULL,
+ embedding_model = NULL,
+ embedding_dimensions = NULL,
+ tags = NULL,
+ metadata = NULL,
updated_at = strftime('%s', 'now') * 1000
WHERE key = ?
AND namespace = ?
@@ -4206,6 +4218,9 @@ export async function purgeNamespace(options: {
const fileBuffer = readFileMaybeEncrypted(dbPath, null);
const db = new SQL.Database(fileBuffer);
+ // #3785: purge is advertised as irreversible; zero free pages too.
+ db.run('PRAGMA secure_delete = ON');
+
const beforeResult = db.exec(`SELECT COUNT(*) FROM memory_entries WHERE namespace = ?`, [namespace]);
const deletedCount = (beforeResult[0]?.values?.[0]?.[0] as number) || 0;