diff --git a/v3/@claude-flow/cli/__tests__/memory-store-metadata-1426.test.ts b/v3/@claude-flow/cli/__tests__/memory-store-metadata-1426.test.ts new file mode 100644 index 0000000000..efdabdab23 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/memory-store-metadata-1426.test.ts @@ -0,0 +1,133 @@ +/** + * #1426: `memory_store` had no `metadata` input, and both write paths + * (the AgentDB bridge and the sql.js fallback) hard-coded `'{}'` into the + * metadata column. Callers could not record e.g. `{ confidence: 0.9 }`, + * which AutoMemoryBridge reads to decide sync eligibility. + * + * Covers both write paths and the input check at the MCP boundary. + */ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import Database from 'better-sqlite3'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { memoryTools } from '../src/mcp-tools/memory-tools.js'; +import { MEMORY_SCHEMA_V3 } from '../src/memory/memory-initializer.js'; + +const tool = (name: string) => memoryTools.find(t => t.name === name)!; + +async function readMetadata(dbPath: string, key: string): Promise { + const initSqlJs = (await import('sql.js')).default; + const SQL = await initSqlJs(); + const db = new SQL.Database(readFileSync(dbPath)); + try { + const stmt = db.prepare('SELECT metadata FROM memory_entries WHERE key = ?'); + stmt.bind([key]); + const row = stmt.step() ? (stmt.get()[0] as string | null) : null; + stmt.free(); + return row; + } finally { + db.close(); + } +} + +describe('memory_store persists metadata (#1426)', () => { + let dir: string; + let dbPath: string; + let prevMemory: string | undefined; + let prevBridge: string | undefined; + + beforeEach(async () => { + dir = mkdtempSync(join(tmpdir(), 'ruflo-1426-metadata-')); + dbPath = join(dir, 'memory.db'); + const initSqlJs = (await import('sql.js')).default; + const SQL = await initSqlJs(); + const db = new SQL.Database(); + db.run(MEMORY_SCHEMA_V3); + writeFileSync(dbPath, Buffer.from(db.export())); + db.close(); + + prevMemory = process.env.CLAUDE_FLOW_MEMORY_PATH; + prevBridge = process.env.CLAUDE_FLOW_DISABLE_BRIDGE; + process.env.CLAUDE_FLOW_MEMORY_PATH = dir; + process.env.CLAUDE_FLOW_DISABLE_BRIDGE = '1'; + }); + + afterEach(() => { + if (prevMemory === undefined) delete process.env.CLAUDE_FLOW_MEMORY_PATH; + else process.env.CLAUDE_FLOW_MEMORY_PATH = prevMemory; + if (prevBridge === undefined) delete process.env.CLAUDE_FLOW_DISABLE_BRIDGE; + else process.env.CLAUDE_FLOW_DISABLE_BRIDGE = prevBridge; + rmSync(dir, { recursive: true, force: true }); + }); + + it('sql.js path writes the metadata object to the metadata column', async () => { + const res = await tool('memory_store').handler({ + key: 'with-meta', + value: 'v', + namespace: 'probe-1426', + metadata: { confidence: 0.9, source: 'test' }, + dbPath, + }) as Record; + expect(res.success).toBe(true); + expect(JSON.parse((await readMetadata(dbPath, 'with-meta'))!)).toEqual({ confidence: 0.9, source: 'test' }); + }); + + it('omitting metadata still stores an empty object', async () => { + const res = await tool('memory_store').handler({ key: 'no-meta', value: 'v', dbPath }) as Record; + expect(res.success).toBe(true); + expect(await readMetadata(dbPath, 'no-meta')).toBe('{}'); + }); + + it.each([[['a']], [null], ['text'], [3]])('rejects non-object metadata %j', async (metadata) => { + const res = await tool('memory_store').handler({ key: 'bad', value: 'v', metadata, dbPath }) as Record; + expect(res.success).toBe(false); + expect(res.error).toMatch(/metadata must be a JSON object/); + expect(await readMetadata(dbPath, 'bad')).toBeNull(); + }); +}); + +describe('bridgeStoreEntry persists metadata (#1426)', () => { + it('writes the metadata object on the native bridge path', async () => { + const root = mkdtempSync(join(tmpdir(), 'ruflo-1426-bridge-')); + const bridgeDbPath = join(root, 'memory.db'); + const db = new Database(bridgeDbPath); + try { + db.exec(` + CREATE TABLE memory_entries ( + id TEXT PRIMARY KEY, key TEXT NOT NULL, namespace TEXT DEFAULT 'default', + content TEXT NOT NULL, type TEXT DEFAULT 'semantic', embedding TEXT, + embedding_dimensions INTEGER, embedding_model TEXT, tags TEXT, metadata TEXT, + provenance_type TEXT DEFAULT 'unknown', created_at INTEGER, updated_at INTEGER, + last_accessed_at INTEGER, access_count INTEGER DEFAULT 0, expires_at INTEGER, + status TEXT DEFAULT 'active', UNIQUE(namespace, key) + ); + CREATE TABLE vector_indexes (id TEXT PRIMARY KEY, name TEXT, dimensions INTEGER); + `); + const { __setMemoryBridgeRegistryForTests, bridgeStoreEntry } = await import('../src/memory/memory-bridge.js'); + const cache = new Map(); + __setMemoryBridgeRegistryForTests({ + getAgentDB: () => ({ database: db, embedder: null }), + get: (kind: string) => (kind === 'tieredCache' + ? { get: (k: string) => cache.get(k), set: (k: string, v: unknown) => { cache.set(k, v); }, delete: (k: string) => { cache.delete(k); }, size: () => cache.size } + : null), + }); + + const result = await bridgeStoreEntry({ + key: 'bridge-meta', + value: 'v', + namespace: 'probe-1426', + metadata: { confidence: 0.75 }, + generateEmbeddingFlag: false, + dbPath: bridgeDbPath, + }); + expect(result?.success).toBe(true); + const row = db.prepare('SELECT metadata FROM memory_entries WHERE key = ?').get('bridge-meta') as { metadata: string }; + expect(JSON.parse(row.metadata)).toEqual({ confidence: 0.75 }); + } finally { + db.close(); + rmSync(root, { recursive: true, force: true }); + } + }); +}); 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 24fbd6ac6d..af4319035a 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts @@ -507,6 +507,10 @@ export const memoryTools: MCPTool[] = [ items: { type: 'string' }, description: 'Optional tags for filtering', }, + metadata: { + type: 'object', + description: 'Optional JSON object stored with the entry (e.g. { confidence: 0.9 }, which AutoMemoryBridge reads for sync eligibility). Replaces any existing metadata on upsert.', + }, ttl: { type: 'number', description: 'Time-to-live in seconds (optional)' }, upsert: { type: 'boolean', description: 'Update existing key instead of failing (default: true, matching CLI `memory store`; set false for strict-insert). #2775 parity.' }, provenance_type: { @@ -539,6 +543,18 @@ export const memoryTools: MCPTool[] = [ // ADR-323: leave undefined when omitted so storeEntry's own default // ('unknown') applies uniformly across the CLI, MCP tool, and other callers. const provenanceType = input.provenance_type as string | undefined; + // #1426: metadata must be a plain JSON object; reject arrays, null and scalars. + const rawMetadata = input.metadata; + if (rawMetadata !== undefined && (typeof rawMetadata !== 'object' || rawMetadata === null || Array.isArray(rawMetadata))) { + return { + success: false, + key, + stored: false, + hasEmbedding: false, + error: 'metadata must be a JSON object', + }; + } + const metadata = rawMetadata as Record | undefined; if (!value) { return { @@ -565,6 +581,7 @@ export const memoryTools: MCPTool[] = [ namespace, generateEmbeddingFlag: true, tags, + metadata, ttl, upsert, provenanceType, diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.ts index 920c970428..2734c5d2d0 100644 --- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts +++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts @@ -1068,6 +1068,8 @@ export async function bridgeStoreEntry(options: { namespace?: string; generateEmbeddingFlag?: boolean; tags?: string[]; + /** #1426: JSON object persisted to the metadata column. */ + metadata?: Record; ttl?: number; dbPath?: string; upsert?: boolean; @@ -1242,7 +1244,7 @@ export async function bridgeStoreEntry(options: { id, key, namespace, value, embeddingJson, dimensions || null, model, tags.length > 0 ? JSON.stringify(tags) : null, - '{}', + JSON.stringify(options.metadata ?? {}), provenanceType, now, now, ttl ? now + (ttl * 1000) : null diff --git a/v3/@claude-flow/cli/src/memory/memory-initializer.ts b/v3/@claude-flow/cli/src/memory/memory-initializer.ts index e88b6cf2a7..e8af134bad 100644 --- a/v3/@claude-flow/cli/src/memory/memory-initializer.ts +++ b/v3/@claude-flow/cli/src/memory/memory-initializer.ts @@ -2980,6 +2980,8 @@ export async function storeEntry(options: { namespace?: string; generateEmbeddingFlag?: boolean; tags?: string[]; + /** #1426: JSON object persisted to the metadata column. */ + metadata?: Record; ttl?: number; dbPath?: string; upsert?: boolean; @@ -3160,7 +3162,7 @@ export async function storeEntry(options: { embeddingDimensions, embeddingModel, tags.length > 0 ? JSON.stringify(tags) : null, - '{}', + JSON.stringify(options.metadata ?? {}), persistedProvenance, now, now, diff --git a/v3/@claude-flow/memory/src/sqlite-backend-legacy-schema.test.ts b/v3/@claude-flow/memory/src/sqlite-backend-legacy-schema.test.ts new file mode 100644 index 0000000000..a6510b5dda --- /dev/null +++ b/v3/@claude-flow/memory/src/sqlite-backend-legacy-schema.test.ts @@ -0,0 +1,95 @@ +/** + * #1426 — SQLiteBackend on a memory.db created by the CLI. + * + * The CLI's memory-initializer DDL creates memory_entries without + * access_level, version and "references". SQLiteBackend's + * CREATE TABLE IF NOT EXISTS left that table as-is, so store() failed with + * "table memory_entries has no column named access_level". initialize() + * now adds the missing columns. + * + * better-sqlite3 is an optional dependency, so the suite skips without it. + */ + +import { describe, it, expect, afterAll } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { createDefaultEntry } from './types.js'; + +async function loadBetterSqlite3(): Promise { + try { + return (await import('better-sqlite3')).default; + } catch { + return null; + } +} + +// memory_entries as created by v3/@claude-flow/cli/src/memory/memory-initializer.ts +const CLI_DDL = ` + CREATE TABLE memory_entries ( + id TEXT PRIMARY KEY, + key TEXT NOT NULL, + namespace TEXT DEFAULT 'default', + content TEXT NOT NULL, + type TEXT DEFAULT 'semantic' CHECK(type IN ('semantic', 'episodic', 'procedural', 'working', 'pattern')), + embedding TEXT, + embedding_model TEXT DEFAULT 'local', + embedding_dimensions INTEGER, + tags TEXT, + metadata TEXT, + owner_id TEXT, + provenance_type TEXT DEFAULT 'unknown', + created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000), + updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000), + expires_at INTEGER, + last_accessed_at INTEGER, + access_count INTEGER DEFAULT 0, + status TEXT DEFAULT 'active' CHECK(status IN ('active', 'archived', 'deleted')), + UNIQUE(namespace, key) + ); +`; + +const root = mkdtempSync(join(tmpdir(), 'ruflo-1426-legacy-schema-')); +afterAll(() => rmSync(root, { recursive: true, force: true })); + +describe('#1426 — SQLiteBackend migrates a CLI-created memory_entries table', async () => { + const Database = await loadBetterSqlite3(); + const maybeIt = Database ? it : it.skip; + + maybeIt('adds the missing columns and keeps existing CLI rows readable', async () => { + const dbPath = join(root, 'cli-created.db'); + const seed = new Database(dbPath); + seed.exec(CLI_DDL); + seed + .prepare( + `INSERT INTO memory_entries (id, key, namespace, content, tags, metadata, created_at, updated_at) + VALUES ('cli-1', 'from-cli', 'default', 'written by the CLI', '["cli"]', '{}', 1, 1)`, + ) + .run(); + seed.close(); + + const { SQLiteBackend } = await import('./sqlite-backend.js'); + const backend = new SQLiteBackend({ databasePath: dbPath }); + await backend.initialize(); + + const entry = createDefaultEntry({ key: 'from-backend', content: 'written by SQLiteBackend' }); + await backend.store(entry); + + const stored = await backend.get(entry.id); + expect(stored?.content).toBe('written by SQLiteBackend'); + expect(stored?.accessLevel).toBe(entry.accessLevel); + + const legacy = await backend.get('cli-1'); + expect(legacy?.key).toBe('from-cli'); + expect(legacy?.accessLevel).toBe('private'); + expect(legacy?.version).toBe(1); + expect(legacy?.references).toEqual([]); + + await backend.shutdown(); + + // A second initialize() must not try to add the columns again. + const again = new SQLiteBackend({ databasePath: dbPath }); + await again.initialize(); + await again.shutdown(); + }); +}); diff --git a/v3/@claude-flow/memory/src/sqlite-backend.ts b/v3/@claude-flow/memory/src/sqlite-backend.ts index 9a67be64e3..8f413e040a 100644 --- a/v3/@claude-flow/memory/src/sqlite-backend.ts +++ b/v3/@claude-flow/memory/src/sqlite-backend.ts @@ -730,6 +730,25 @@ export class SQLiteBackend extends EventEmitter implements IMemoryBackend { ); `); + // #1426: a memory.db created by the CLI (memory-initializer DDL) has a + // memory_entries table without these columns. CREATE TABLE IF NOT EXISTS + // leaves it untouched, so every store() then failed with "no such column". + // Add whatever is missing; the defaults match createDefaultEntry(). + const migrations: Array<{ column: string; ddl: string }> = [ + { column: 'access_level', ddl: `ALTER TABLE memory_entries ADD COLUMN access_level TEXT NOT NULL DEFAULT 'private'` }, + { column: 'version', ddl: 'ALTER TABLE memory_entries ADD COLUMN version INTEGER NOT NULL DEFAULT 1' }, + { column: 'references', ddl: `ALTER TABLE memory_entries ADD COLUMN "references" TEXT NOT NULL DEFAULT '[]'` }, + { column: 'access_count', ddl: 'ALTER TABLE memory_entries ADD COLUMN access_count INTEGER NOT NULL DEFAULT 0' }, + { column: 'last_accessed_at', ddl: 'ALTER TABLE memory_entries ADD COLUMN last_accessed_at INTEGER NOT NULL DEFAULT 0' }, + ]; + const existing = new Set( + (this.db.prepare('PRAGMA table_info(memory_entries)').all() as Array<{ name: string }>) + .map((r) => r.name), + ); + for (const m of migrations) { + if (!existing.has(m.column)) this.db.exec(m.ddl); + } + // ADR-125 Phase 5 — FTS5 virtual table for keyword search. // FTS5 is built into better-sqlite3 since 11.x. Surrounding try/catch so // older SQLite builds gracefully skip FTS without taking the whole backend