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,ollama): tag filter for memory list, export v1.1, local Ollama default model (#3526) (#3526)

Mathew Beanef67d3b201fce
diff --git a/v3/@claude-flow/cli/__tests__/memory-list-tag-filter.test.ts b/v3/@claude-flow/cli/__tests__/memory-list-tag-filter.test.ts
new file mode 100644
index 0000000000..c655dd37a9
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/memory-list-tag-filter.test.ts
@@ -0,0 +1,249 @@
+/**
+ * Coverage for `bridgeListEntries({ tags })` (split out of #3512).
+ *
+ * The tag filter is pushed into the SQL query as
+ * `EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?)` per required tag
+ * (AND semantics) instead of pulling every row into the process to filter
+ * in JS β€” a prior version fetched up to 100k rows per call whenever a tag
+ * filter was set. An earlier revision of this filter used SQL `LIKE`
+ * against the raw JSON-array TEXT, which was both ASCII case-insensitive
+ * and matched raw JSON bytes rather than parsed array elements (#3526
+ * review); `json_each` compares real, decoded array values instead. This
+ * suite checks the filtering semantics (AND, exact-tag matching,
+ * pagination/total), that a tag must not match a longer tag that merely
+ * contains it as a substring, case-sensitivity, and JSON-injection-shaped
+ * tag values.
+ */
+
+import { describe, it, expect, afterAll } from 'vitest';
+import Database from 'better-sqlite3';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+
+const roots: string[] = [];
+
+/** Fresh temp dir + db file per test so seeded ids/rows never collide. */
+function freshDbPath(): string {
+ const root = mkdtempSync(join(tmpdir(), 'ruflo-tag-filter-'));
+ roots.push(root);
+ return join(root, 'memory.db');
+}
+
+function makeDb(dbPath: string): Database.Database {
+ const d = new Database(dbPath);
+ d.exec(`
+ CREATE TABLE IF NOT EXISTS 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)
+ );
+ `);
+ return d;
+}
+
+function seed(
+ d: Database.Database,
+ rows: Array<{ id: string; key: string; tags: string[] | null }>,
+): void {
+ const stmt = d.prepare(`
+ INSERT INTO memory_entries (id, key, namespace, content, tags, created_at, updated_at)
+ VALUES (?, ?, 'probe-tags', 'v', ?, ?, ?)
+ `);
+ let t = 1_700_000_000_000;
+ for (const row of rows) {
+ stmt.run(row.id, row.key, row.tags ? JSON.stringify(row.tags) : null, t, t);
+ t += 1_000; // strictly increasing updated_at so ORDER BY DESC is deterministic
+ }
+}
+
+/** Minimal cache wrapper matching what cacheGet/cacheSet/cacheInvalidate expect. */
+function makeTieredCache() {
+ const store = new Map<string, unknown>();
+ return {
+ get: (k: string) => store.get(k),
+ set: (k: string, v: unknown) => { store.set(k, v); },
+ delete: (k: string) => { store.delete(k); },
+ size: () => store.size,
+ };
+}
+
+let db: Database.Database | null = null;
+
+afterAll(() => {
+ db?.close();
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+});
+
+describe('bridgeListEntries({ tags }) β€” SQL-pushed tag filter', () => {
+ it('AND-matches required tags, excludes entries missing any of them or with no tags', async () => {
+ const { __setMemoryBridgeRegistryForTests, bridgeListEntries } = await import('../src/memory/memory-bridge.js');
+
+ const dbPath = freshDbPath();
+ db = makeDb(dbPath);
+ seed(db, [
+ { id: '1', key: 'both', tags: ['alpha', 'beta'] },
+ { id: '2', key: 'alpha-only', tags: ['alpha'] },
+ { id: '3', key: 'beta-only', tags: ['beta'] },
+ { id: '4', key: 'untagged', tags: null },
+ { id: '5', key: 'other', tags: ['gamma'] },
+ ]);
+ __setMemoryBridgeRegistryForTests({
+ getAgentDB: () => ({ database: db, embedder: null }),
+ get: (kind: string) => (kind === 'tieredCache' ? makeTieredCache() : null),
+ });
+
+ const result = await bridgeListEntries({ namespace: 'probe-tags', tags: ['alpha', 'beta'], dbPath });
+
+ expect(result).not.toBeNull();
+ expect(result!.success).toBe(true);
+ expect(result!.total).toBe(1);
+ expect(result!.entries.map(e => e.key)).toEqual(['both']);
+ expect(result!.entries[0].tags).toEqual(['alpha', 'beta']);
+ });
+
+ it('does not false-match a tag that is only a substring of a longer tag', async () => {
+ const { __setMemoryBridgeRegistryForTests, bridgeListEntries } = await import('../src/memory/memory-bridge.js');
+
+ const dbPath = freshDbPath();
+ db = makeDb(dbPath);
+ seed(db, [
+ { id: '1', key: 'short-tag', tags: ['a'] },
+ { id: '2', key: 'long-tag', tags: ['ab'] },
+ ]);
+ __setMemoryBridgeRegistryForTests({
+ getAgentDB: () => ({ database: db, embedder: null }),
+ get: (kind: string) => (kind === 'tieredCache' ? makeTieredCache() : null),
+ });
+
+ const result = await bridgeListEntries({ namespace: 'probe-tags', tags: ['a'], dbPath });
+
+ expect(result).not.toBeNull();
+ expect(result!.success).toBe(true);
+ expect(result!.entries.map(e => e.key)).toEqual(['short-tag']);
+ });
+
+ it('handles tag values containing LIKE metacharacters and quotes literally', async () => {
+ const { __setMemoryBridgeRegistryForTests, bridgeListEntries } = await import('../src/memory/memory-bridge.js');
+
+ const dbPath = freshDbPath();
+ db = makeDb(dbPath);
+ seed(db, [
+ { id: '1', key: 'percent-tag', tags: ['50%_done'] },
+ { id: '2', key: 'quote-tag', tags: ['say "hi"'] },
+ { id: '3', key: 'plain-tag', tags: ['plain'] },
+ ]);
+ __setMemoryBridgeRegistryForTests({
+ getAgentDB: () => ({ database: db, embedder: null }),
+ get: (kind: string) => (kind === 'tieredCache' ? makeTieredCache() : null),
+ });
+
+ const percentResult = await bridgeListEntries({ namespace: 'probe-tags', tags: ['50%_done'], dbPath });
+ expect(percentResult!.entries.map(e => e.key)).toEqual(['percent-tag']);
+
+ const quoteResult = await bridgeListEntries({ namespace: 'probe-tags', tags: ['say "hi"'], dbPath });
+ expect(quoteResult!.entries.map(e => e.key)).toEqual(['quote-tag']);
+ });
+
+ it('respects limit/offset and reports the filtered total, not the pre-filter count', async () => {
+ const { __setMemoryBridgeRegistryForTests, bridgeListEntries } = await import('../src/memory/memory-bridge.js');
+
+ const dbPath = freshDbPath();
+ db = makeDb(dbPath);
+ seed(db, [
+ { id: '1', key: 'tagged-1', tags: ['keep'] },
+ { id: '2', key: 'tagged-2', tags: ['keep'] },
+ { id: '3', key: 'tagged-3', tags: ['keep'] },
+ { id: '4', key: 'untagged-1', tags: null },
+ { id: '5', key: 'untagged-2', tags: ['drop'] },
+ ]);
+ __setMemoryBridgeRegistryForTests({
+ getAgentDB: () => ({ database: db, embedder: null }),
+ get: (kind: string) => (kind === 'tieredCache' ? makeTieredCache() : null),
+ });
+
+ const page1 = await bridgeListEntries({ namespace: 'probe-tags', tags: ['keep'], limit: 2, offset: 0, dbPath });
+ expect(page1!.total).toBe(3);
+ expect(page1!.entries).toHaveLength(2);
+
+ const page2 = await bridgeListEntries({ namespace: 'probe-tags', tags: ['keep'], limit: 2, offset: 2, dbPath });
+ expect(page2!.total).toBe(3);
+ expect(page2!.entries).toHaveLength(1);
+ });
+
+ // #3526 review β€” exact match via json_each, not a case-insensitive LIKE
+ // substring match against raw JSON text.
+ it('a tag filter of "prod" does not match an entry tagged "PROD" (case-sensitive exact match)', async () => {
+ const { __setMemoryBridgeRegistryForTests, bridgeListEntries } = await import('../src/memory/memory-bridge.js');
+
+ const dbPath = freshDbPath();
+ db = makeDb(dbPath);
+ seed(db, [
+ { id: '1', key: 'upper', tags: ['PROD'] },
+ { id: '2', key: 'lower', tags: ['prod'] },
+ ]);
+ __setMemoryBridgeRegistryForTests({
+ getAgentDB: () => ({ database: db, embedder: null }),
+ get: (kind: string) => (kind === 'tieredCache' ? makeTieredCache() : null),
+ });
+
+ const result = await bridgeListEntries({ namespace: 'probe-tags', tags: ['prod'], dbPath });
+ expect(result!.entries.map(e => e.key)).toEqual(['lower']);
+ });
+
+ it('a tag filter does not false-match a JSON-injection-shaped tag value', async () => {
+ const { __setMemoryBridgeRegistryForTests, bridgeListEntries } = await import('../src/memory/memory-bridge.js');
+
+ const dbPath = freshDbPath();
+ db = makeDb(dbPath);
+ seed(db, [
+ { id: '1', key: 'injected', tags: ['x","prod'] },
+ { id: '2', key: 'real', tags: ['prod'] },
+ ]);
+ __setMemoryBridgeRegistryForTests({
+ getAgentDB: () => ({ database: db, embedder: null }),
+ get: (kind: string) => (kind === 'tieredCache' ? makeTieredCache() : null),
+ });
+
+ const result = await bridgeListEntries({ namespace: 'probe-tags', tags: ['prod'], dbPath });
+ expect(result!.entries.map(e => e.key)).toEqual(['real']);
+ });
+
+ // #3526 review β€” an explicit limit: 0 must return zero rows, not fall
+ // back to the default limit (`parseInt(...) || 20` treated 0 as falsy).
+ it('limit: 0 returns zero entries, not the default', async () => {
+ const { __setMemoryBridgeRegistryForTests, bridgeListEntries } = await import('../src/memory/memory-bridge.js');
+
+ const dbPath = freshDbPath();
+ db = makeDb(dbPath);
+ seed(db, [
+ { id: '1', key: 'a', tags: null },
+ { id: '2', key: 'b', tags: null },
+ { id: '3', key: 'c', tags: null },
+ ]);
+ __setMemoryBridgeRegistryForTests({
+ getAgentDB: () => ({ database: db, embedder: null }),
+ get: (kind: string) => (kind === 'tieredCache' ? makeTieredCache() : null),
+ });
+
+ const result = await bridgeListEntries({ namespace: 'probe-tags', limit: 0, dbPath });
+ expect(result!.success).toBe(true);
+ expect(result!.entries).toHaveLength(0);
+ expect(result!.total).toBe(3);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/memory-list-tags-cli-wiring-3526.test.ts b/v3/@claude-flow/cli/__tests__/memory-list-tags-cli-wiring-3526.test.ts
new file mode 100644
index 0000000000..1dacb261ef
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/memory-list-tags-cli-wiring-3526.test.ts
@@ -0,0 +1,82 @@
+/**
+ * Regression guard for a PR #3526 review finding: the CLI's `memory list
+ * --tags` flag was parsed (declared as an option, described in --help) but
+ * never read from `ctx.flags.tags` or threaded through to `listEntries()`
+ * β€” so it silently returned every row in the namespace regardless of the
+ * `--tags` value given. Only `memory_list` (the MCP tool) actually filtered
+ * by tags. This drives the real built CLI exactly like a user would (the
+ * bug is in wiring at the command-action layer, not in `listEntries`
+ * itself, so a unit-level call to `listEntries` wouldn't have caught it).
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, rmSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { dirname } from 'node:path';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const CLI = join(HERE, '..', 'bin', 'cli.js');
+const CLI_BUILT = existsSync(CLI);
+
+function run(args: string[], cwd: string): { stdout: string; exit: number | null } {
+ try {
+ const stdout = execFileSync('node', [CLI, ...args], {
+ cwd,
+ encoding: 'utf-8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ timeout: 60_000,
+ });
+ return { stdout, exit: 0 };
+ } catch (err) {
+ const e = err as { status?: number | null; stdout?: Buffer; stderr?: Buffer };
+ return {
+ stdout: (e.stdout?.toString() ?? '') + (e.stderr?.toString() ?? ''),
+ exit: e.status ?? null,
+ };
+ }
+}
+
+function listJson(cwd: string, extraArgs: string[] = []): Array<{ key: string }> {
+ const { stdout } = run(['memory', 'list', '-n', 'tagwire3526', '--format', 'json', ...extraArgs], cwd);
+ const start = stdout.indexOf('[');
+ expect(start).toBeGreaterThanOrEqual(0);
+ return JSON.parse(stdout.slice(start)) as Array<{ key: string }>;
+}
+
+describe.skipIf(!CLI_BUILT)('memory list --tags CLI wiring (#3526 review)', () => {
+ let workdir: string;
+
+ beforeAll(() => {
+ workdir = mkdtempSync(join(tmpdir(), 'ruflo-tagwire3526-'));
+ run(['memory', 'init'], workdir);
+ run(['memory', 'store', '-k', 'a', '-n', 'tagwire3526', '--value', 'has prod tag', '--tags', 'prod'], workdir);
+ run(['memory', 'store', '-k', 'b', '-n', 'tagwire3526', '--value', 'has staging tag', '--tags', 'staging'], workdir);
+ run(['memory', 'store', '-k', 'c', '-n', 'tagwire3526', '--value', 'no tags at all'], workdir);
+ }, 60_000);
+
+ afterAll(() => {
+ try { rmSync(workdir, { recursive: true, force: true }); } catch { /* ignore */ }
+ });
+
+ it('memory list with no --tags returns every entry in the namespace', () => {
+ const entries = listJson(workdir);
+ expect(entries.map(e => e.key).sort()).toEqual(['a', 'b', 'c']);
+ });
+
+ it('memory list --tags prod filters down to only the matching entry, not every row', () => {
+ const entries = listJson(workdir, ['--tags', 'prod']);
+ expect(entries.map(e => e.key)).toEqual(['a']);
+ });
+
+ it('memory list --tags staging filters to the other matching entry', () => {
+ const entries = listJson(workdir, ['--tags', 'staging']);
+ expect(entries.map(e => e.key)).toEqual(['b']);
+ });
+
+ it('memory list --tags nonexistent returns zero entries, not every row', () => {
+ const entries = listJson(workdir, ['--tags', 'nonexistent']);
+ expect(entries).toEqual([]);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/memory-listentries-non-bridge-provenance-tags-3526.test.ts b/v3/@claude-flow/cli/__tests__/memory-listentries-non-bridge-provenance-tags-3526.test.ts
new file mode 100644
index 0000000000..919f4fad53
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/memory-listentries-non-bridge-provenance-tags-3526.test.ts
@@ -0,0 +1,161 @@
+/**
+ * Regression guard for PR #3526 review findings on the non-bridge
+ * (sql.js fallback) `listEntries()` path in memory-initializer.ts:
+ *
+ * BLOCKING β€” the tags-filter `WHERE` clause added alongside ADR-323's
+ * provenance filter REPLACED the existing `provenance_type IN (...)`
+ * clause instead of being ANDed with it. The non-bridge path is the
+ * default on Windows, is used whenever CLAUDE_FLOW_DISABLE_BRIDGE=1 is
+ * set, and is used whenever the bridge fails to load for any reason β€” and
+ * it is what serves `memory search --provenance-filter` in keyword/hybrid
+ * mode. Dropping the clause let unverified `user_claim` rows leak into
+ * results that are supposed to be `tool_result`-only (ADR-323
+ * fact-checking relies on this filter).
+ *
+ * The existing ADR-323 provenance coverage (adr-323-memory-provenance.test.ts)
+ * only drives the real CLI, which uses the native bridge in this
+ * environment and therefore never exercised the sql.js fallback branch β€”
+ * this suite explicitly force-disables the bridge (CLAUDE_FLOW_DISABLE_BRIDGE=1,
+ * the package's own documented switch) so the bug is actually reachable,
+ * and also runs the same assertions with the bridge left enabled for
+ * comparison.
+ *
+ * MINOR β€” the tags filter used SQL `LIKE` against the raw JSON-array TEXT,
+ * which is (a) ASCII case-insensitive (a filter of "prod" matched an entry
+ * tagged "PROD") and (b) matched raw JSON bytes rather than parsed array
+ * elements (a tag literally containing `"prod` could false-match). Fixed
+ * via `EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?)` β€” exact,
+ * case-sensitive match against real JSON array elements.
+ *
+ * MINOR β€” `limit: 0` returned the default limit (100) instead of zero
+ * rows, because `parseInt(String(limit), 10) || 100` treats an explicit 0
+ * as falsy.
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+let dir: string;
+let dbPath: string;
+const ORIGINAL_DISABLE_BRIDGE = process.env.CLAUDE_FLOW_DISABLE_BRIDGE;
+
+beforeEach(() => {
+ dir = mkdtempSync(path.join(tmpdir(), 'ruflo-3526-listentries-'));
+ dbPath = path.join(dir, 'memory.db');
+});
+
+afterEach(() => {
+ if (ORIGINAL_DISABLE_BRIDGE === undefined) delete process.env.CLAUDE_FLOW_DISABLE_BRIDGE;
+ else process.env.CLAUDE_FLOW_DISABLE_BRIDGE = ORIGINAL_DISABLE_BRIDGE;
+ rmSync(dir, { recursive: true, force: true });
+});
+
+async function seedProvenanceRows(storeEntry: typeof import('../src/memory/memory-initializer.js').storeEntry) {
+ // 9 rows total (matches the reviewer's repro shape): 1 tool_result, 8
+ // of other provenance types, so a correct filter must return exactly 1.
+ await storeEntry({ key: 'tool/1', value: 'a tool result', dbPath, provenanceType: 'tool_result', generateEmbeddingFlag: false });
+ for (let i = 0; i < 8; i++) {
+ await storeEntry({
+ key: `claim/${i}`,
+ value: `unverified claim ${i}`,
+ dbPath,
+ provenanceType: 'user_claim',
+ generateEmbeddingFlag: false,
+ });
+ }
+}
+
+describe('listEntries provenance filter β€” non-bridge (sql.js) path must AND with the tags clause, not replace it (#3526)', () => {
+ it('with the native bridge explicitly disabled, provenanceFilter still excludes non-matching rows', async () => {
+ process.env.CLAUDE_FLOW_DISABLE_BRIDGE = '1';
+ const { initializeMemoryDatabase, storeEntry, listEntries } = await import('../src/memory/memory-initializer.js');
+ const init = await initializeMemoryDatabase({ dbPath, verbose: false });
+ expect(init.success).toBe(true);
+ await seedProvenanceRows(storeEntry);
+
+ const all = await listEntries({ dbPath, provenanceFilter: undefined });
+ expect(all.total).toBe(9);
+
+ const filtered = await listEntries({ dbPath, provenanceFilter: ['tool_result'] });
+ expect(filtered.success).toBe(true);
+ expect(filtered.total).toBe(1);
+ expect(filtered.entries.map(e => e.key)).toEqual(['tool/1']);
+ });
+
+ it('with the native bridge available (default), provenanceFilter excludes non-matching rows the same way', async () => {
+ delete process.env.CLAUDE_FLOW_DISABLE_BRIDGE;
+ const { initializeMemoryDatabase, storeEntry, listEntries } = await import('../src/memory/memory-initializer.js');
+ const init = await initializeMemoryDatabase({ dbPath, verbose: false });
+ expect(init.success).toBe(true);
+ await seedProvenanceRows(storeEntry);
+
+ const filtered = await listEntries({ dbPath, provenanceFilter: ['tool_result'] });
+ expect(filtered.success).toBe(true);
+ expect(filtered.total).toBe(1);
+ expect(filtered.entries.map(e => e.key)).toEqual(['tool/1']);
+ });
+
+ it('provenanceFilter and tags are ANDed together, not one replacing the other', async () => {
+ process.env.CLAUDE_FLOW_DISABLE_BRIDGE = '1';
+ const { initializeMemoryDatabase, storeEntry, listEntries } = await import('../src/memory/memory-initializer.js');
+ const init = await initializeMemoryDatabase({ dbPath, verbose: false });
+ expect(init.success).toBe(true);
+
+ await storeEntry({ key: 'a', value: 'v', dbPath, provenanceType: 'tool_result', tags: ['prod'], generateEmbeddingFlag: false });
+ await storeEntry({ key: 'b', value: 'v', dbPath, provenanceType: 'user_claim', tags: ['prod'], generateEmbeddingFlag: false });
+ await storeEntry({ key: 'c', value: 'v', dbPath, provenanceType: 'tool_result', tags: ['staging'], generateEmbeddingFlag: false });
+
+ const result = await listEntries({ dbPath, provenanceFilter: ['tool_result'], tags: ['prod'] });
+ expect(result.success).toBe(true);
+ expect(result.entries.map(e => e.key)).toEqual(['a']);
+ });
+});
+
+describe('listEntries tags filter β€” exact match, not case-insensitive substring (#3526 minor)', () => {
+ it('a tag filter of "prod" does not match an entry tagged "PROD" (LIKE is ASCII case-insensitive)', async () => {
+ process.env.CLAUDE_FLOW_DISABLE_BRIDGE = '1';
+ const { initializeMemoryDatabase, storeEntry, listEntries } = await import('../src/memory/memory-initializer.js');
+ const init = await initializeMemoryDatabase({ dbPath, verbose: false });
+ expect(init.success).toBe(true);
+
+ await storeEntry({ key: 'upper', value: 'v', dbPath, tags: ['PROD'], generateEmbeddingFlag: false });
+ await storeEntry({ key: 'lower', value: 'v', dbPath, tags: ['prod'], generateEmbeddingFlag: false });
+
+ const result = await listEntries({ dbPath, tags: ['prod'] });
+ expect(result.entries.map(e => e.key)).toEqual(['lower']);
+ });
+
+ it('a tag filter does not false-match a JSON-injection-shaped tag value', async () => {
+ process.env.CLAUDE_FLOW_DISABLE_BRIDGE = '1';
+ const { initializeMemoryDatabase, storeEntry, listEntries } = await import('../src/memory/memory-initializer.js');
+ const init = await initializeMemoryDatabase({ dbPath, verbose: false });
+ expect(init.success).toBe(true);
+
+ // Tag array containing a literal string that would sit inside the raw
+ // JSON text next to a real "prod" element if matched via LIKE-on-JSON.
+ await storeEntry({ key: 'injected', value: 'v', dbPath, tags: ['x","prod'], generateEmbeddingFlag: false });
+ await storeEntry({ key: 'real', value: 'v', dbPath, tags: ['prod'], generateEmbeddingFlag: false });
+
+ const result = await listEntries({ dbPath, tags: ['prod'] });
+ expect(result.entries.map(e => e.key)).toEqual(['real']);
+ });
+});
+
+describe('listEntries limit β€” explicit 0 means zero results, not the default (#3526 minor, non-bridge path)', () => {
+ it('limit: 0 returns zero entries', async () => {
+ process.env.CLAUDE_FLOW_DISABLE_BRIDGE = '1';
+ const { initializeMemoryDatabase, storeEntry, listEntries } = await import('../src/memory/memory-initializer.js');
+ const init = await initializeMemoryDatabase({ dbPath, verbose: false });
+ expect(init.success).toBe(true);
+ for (let i = 0; i < 5; i++) {
+ await storeEntry({ key: `k${i}`, value: 'v', dbPath, generateEmbeddingFlag: false });
+ }
+
+ const result = await listEntries({ dbPath, limit: 0 });
+ expect(result.success).toBe(true);
+ expect(result.entries).toHaveLength(0);
+ // total still reports the true row count β€” only the page is empty.
+ expect(result.total).toBe(5);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/ollama-local-default-model.test.ts b/v3/@claude-flow/cli/__tests__/ollama-local-default-model.test.ts
new file mode 100644
index 0000000000..276cdddf52
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/ollama-local-default-model.test.ts
@@ -0,0 +1,207 @@
+/**
+ * Self-hosted Ollama (or any OpenAI-compatible local server) as the ruflo
+ * execution provider β€” two gaps found while pointing ruflo at a local
+ * endpoint from Claude Code and Grok Build hosts:
+ *
+ * 1. Precedence: `RUFLO_PROVIDER=ollama` was silently overridden by a stray
+ * `OPENROUTER_API_KEY` whenever `ANTHROPIC_API_KEY` was absent, because
+ * the OpenRouter key-presence branch ran before the explicit choice was
+ * honoured. Key-presence inference must only apply when no provider was
+ * chosen explicitly.
+ *
+ * 2. Model: a tier-routed agent (`haiku` / `sonnet` / `opus`) reaches the
+ * Ollama branch with the MODEL_MAP output (`claude-haiku-4-5-20251001`,
+ * …), a name no Ollama store has. The model saved by
+ * `providers configure -p ollama -m <tag>` (or `OLLAMA_DEFAULT_MODEL`)
+ * is now the default for tier aliases and Anthropic ids; explicit local
+ * names (`ollama:<tag>` or a bare tag) still pass through untouched.
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { callAnthropicMessages } from '../src/mcp-tools/agent-execute-core.js';
+import { configManager } from '../src/services/config-file-manager.js';
+
+const ENV_KEYS = [
+ 'ANTHROPIC_API_KEY',
+ 'OPENROUTER_API_KEY',
+ 'OPENROUTER_BASE_URL',
+ 'OLLAMA_API_KEY',
+ 'OLLAMA_BASE_URL',
+ 'OLLAMA_DEFAULT_MODEL',
+ 'RUFLO_PROVIDER',
+] as const;
+
+const OLLAMA = 'http://127.0.0.1:11434';
+
+describe('self-hosted Ollama: explicit provider precedence + local default model', () => {
+ let dir: string;
+ let prevCwd: string | undefined;
+ let prevEnv: Record<string, string | undefined>;
+ let fetchSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'ruflo-ollama-local-'));
+ prevCwd = process.env.CLAUDE_FLOW_CWD;
+ process.env.CLAUDE_FLOW_CWD = dir;
+ prevEnv = {};
+ for (const key of ENV_KEYS) {
+ prevEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+ (configManager as unknown as { config: unknown }).config = null;
+ (configManager as unknown as { configPath: unknown }).configPath = null;
+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ id: 'chatcmpl-test',
+ model: 'qwen3-coder:30b',
+ choices: [{ message: { role: 'assistant', content: 'PONG' }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
+ }),
+ } as unknown as Response);
+ });
+
+ afterEach(() => {
+ if (prevCwd === undefined) delete process.env.CLAUDE_FLOW_CWD;
+ else process.env.CLAUDE_FLOW_CWD = prevCwd;
+ for (const key of ENV_KEYS) {
+ if (prevEnv[key] === undefined) delete process.env[key];
+ else process.env[key] = prevEnv[key];
+ }
+ (configManager as unknown as { config: unknown }).config = null;
+ (configManager as unknown as { configPath: unknown }).configPath = null;
+ rmSync(dir, { recursive: true, force: true });
+ fetchSpy.mockRestore();
+ });
+
+ function lastRequest(): { url: string; body: Record<string, unknown>; headers: Record<string, string> } {
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ return { url, body: JSON.parse(init.body as string), headers: init.headers as Record<string, string> };
+ }
+
+ it('RUFLO_PROVIDER=ollama is honoured even when OPENROUTER_API_KEY is set and ANTHROPIC_API_KEY is not', async () => {
+ process.env.RUFLO_PROVIDER = 'ollama';
+ process.env.OLLAMA_BASE_URL = OLLAMA;
+ process.env.OPENROUTER_API_KEY = 'sk-or-stray';
+
+ const result = await callAnthropicMessages({ prompt: 'ping', model: 'qwen3-coder:30b' });
+
+ expect(result.success).toBe(true);
+ const { url, headers } = lastRequest();
+ expect(url).toBe(`${OLLAMA}/v1/chat/completions`);
+ expect(headers.Authorization).toBeUndefined();
+ });
+
+ it('a per-agent explicit provider outranks OpenRouter key-presence inference too', async () => {
+ process.env.OLLAMA_BASE_URL = OLLAMA;
+ process.env.OPENROUTER_API_KEY = 'sk-or-stray';
+
+ await callAnthropicMessages({ prompt: 'ping', model: 'qwen3-coder:30b', provider: 'ollama' });
+
+ expect(lastRequest().url).toBe(`${OLLAMA}/v1/chat/completions`);
+ });
+
+ it('with no explicit provider, OpenRouter key-presence inference is unchanged', async () => {
+ process.env.OPENROUTER_API_KEY = 'sk-or-real';
+
+ await callAnthropicMessages({ prompt: 'ping', model: 'sonnet' });
+
+ expect(lastRequest().url).toBe('https://openrouter.ai/api/v1/chat/completions');
+ });
+
+ it('OLLAMA_DEFAULT_MODEL replaces tier aliases and Anthropic model ids, and only those', async () => {
+ process.env.RUFLO_PROVIDER = 'ollama';
+ process.env.OLLAMA_BASE_URL = OLLAMA;
+ process.env.OLLAMA_DEFAULT_MODEL = 'qwen3-coder:30b';
+
+ const cases: Array<[string | undefined, string]> = [
+ ['claude-haiku-4-5-20251001', 'qwen3-coder:30b'], // MODEL_MAP output for a tier-routed agent
+ ['claude-sonnet-5', 'qwen3-coder:30b'],
+ ['sonnet', 'qwen3-coder:30b'],
+ [undefined, 'qwen3-coder:30b'],
+ ['ollama:gemma4:12b', 'gemma4:12b'], // explicit prefix strips
+ ['devstral:latest', 'devstral:latest'], // bare local tag passes through
+ ];
+ for (const [model, expected] of cases) {
+ fetchSpy.mockClear();
+ await callAnthropicMessages({ prompt: 'ping', model });
+ expect(lastRequest().body.model, `model=${model}`).toBe(expected);
+ }
+ });
+
+ it('the model saved by `providers configure -p ollama -m` is the default when no env override is set', async () => {
+ writeFileSync(
+ join(dir, 'claude-flow.config.json'),
+ JSON.stringify({ agents: { providers: [{ name: 'ollama', enabled: true, baseUrl: OLLAMA, model: 'gemma4:12b' }] } }),
+ );
+ process.env.RUFLO_PROVIDER = 'ollama';
+
+ await callAnthropicMessages({ prompt: 'ping', model: 'claude-sonnet-5' });
+
+ const { url, body } = lastRequest();
+ expect(url).toBe(`${OLLAMA}/v1/chat/completions`);
+ expect(body.model).toBe('gemma4:12b');
+ });
+
+ it('env OLLAMA_DEFAULT_MODEL wins over the persisted model', async () => {
+ writeFileSync(
+ join(dir, 'claude-flow.config.json'),
+ JSON.stringify({ agents: { providers: [{ name: 'ollama', enabled: true, baseUrl: OLLAMA, model: 'gemma4:12b' }] } }),
+ );
+ process.env.RUFLO_PROVIDER = 'ollama';
+ process.env.OLLAMA_DEFAULT_MODEL = 'qwen3-coder:30b';
+
+ await callAnthropicMessages({ prompt: 'ping', model: 'haiku' });
+
+ expect(lastRequest().body.model).toBe('qwen3-coder:30b');
+ });
+
+ // Regression: a signed-in local Ollama daemon forwards any
+ // `-cloud`-suffixed model name straight to Ollama's real cloud service.
+ // Silently rewriting a tier-routed/self-hosted request to
+ // 'gpt-oss:120b-cloud' when the endpoint is NOT actually Ollama Cloud
+ // (here, a local 127.0.0.1 base URL) would leak the prompt off-machine
+ // without the user ever asking for that. This must fail loudly instead β€”
+ // no request should even be sent.
+ it('without OLLAMA_DEFAULT_MODEL, a self-hosted/local base URL fails loudly instead of synthesizing a -cloud model name', async () => {
+ process.env.RUFLO_PROVIDER = 'ollama';
+ process.env.OLLAMA_BASE_URL = OLLAMA;
+
+ const result = await callAnthropicMessages({ prompt: 'ping', model: 'claude-sonnet-5' });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatch(/OLLAMA_DEFAULT_MODEL/);
+ expect(result.error).not.toBeUndefined();
+ // No -cloud model name was ever synthesized or sent anywhere.
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it('without OLLAMA_DEFAULT_MODEL, a tier alias against a self-hosted/local base URL also fails loudly (no silent cloud default)', async () => {
+ process.env.RUFLO_PROVIDER = 'ollama';
+ process.env.OLLAMA_BASE_URL = OLLAMA;
+
+ const result = await callAnthropicMessages({ prompt: 'ping', model: 'sonnet' });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatch(/OLLAMA_DEFAULT_MODEL/);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ // A base URL that IS genuinely Ollama's cloud endpoint (the default when
+ // no OLLAMA_BASE_URL override is given at all) may still fall back to the
+ // cloud-suffixed default β€” that's the one case where sending a
+ // `-cloud`-suffixed name is not a surprise cloud egress.
+ it('with no OLLAMA_BASE_URL override at all (real Ollama Cloud endpoint), the -cloud fallback default still applies', async () => {
+ process.env.RUFLO_PROVIDER = 'ollama';
+ process.env.OLLAMA_API_KEY = 'sk-ollama-cloud-test';
+
+ const result = await callAnthropicMessages({ prompt: 'ping', model: 'claude-sonnet-5' });
+
+ expect(result.success).toBe(true);
+ expect(lastRequest().url).toBe('https://ollama.com/v1/chat/completions');
+ expect(lastRequest().body.model).toBe('gpt-oss:120b-cloud');
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.ts
index b54856b7a1..1e02c488a9 100644
--- a/v3/@claude-flow/cli/src/commands/memory.ts
+++ b/v3/@claude-flow/cli/src/commands/memory.ts
@@ -864,12 +864,17 @@ const listCommand: Command = {
const namespace = ctx.flags.namespace as string;
const limit = ctx.flags.limit as number;
const includeEmbedding = ctx.flags.embeddings === true && ctx.flags.format === 'json';
+ // Mirrors memory_list's MCP tool handling: comma-separated flag β†’
+ // non-empty string array, require entries to carry every tag (AND).
+ const tags = ctx.flags.tags
+ ? (ctx.flags.tags as string).split(',').map(t => t.trim()).filter((t): t is string => t.length > 0)
+ : undefined;
// Use sql.js directly for consistent data access
try {
const { listEntries, resolveDbPath: _rdbList } = await import('../memory/memory-initializer.js');
const dbPathList = _rdbList(ctx.flags.path as string | undefined);
- const listResult = await listEntries({ namespace, limit, offset: 0, dbPath: dbPathList, ...(includeEmbedding && { includeEmbedding: true }) });
+ const listResult = await listEntries({ namespace, limit, offset: 0, dbPath: dbPathList, tags, ...(includeEmbedding && { includeEmbedding: true }) });
if (!listResult.success) {
output.printError(`Failed to list: ${listResult.error}`);
diff --git a/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts b/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts
index 794a5857eb..a4e78583fd 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts
@@ -232,7 +232,11 @@ export async function callAnthropicMessages(input: AnthropicCallInput): Promise<
...input,
apiKey: ollamaKey || persistedOllama?.apiKey || 'local',
baseUrl: resolvedBaseUrl,
- model: input.model || persistedOllama?.model,
+ model: input.model,
+ // Local default for tier aliases / Anthropic ids (see
+ // resolveOllamaModel): OLLAMA_DEFAULT_MODEL, then the model saved by
+ // `providers configure -p ollama -m <tag>`.
+ defaultModel: process.env.OLLAMA_DEFAULT_MODEL || persistedOllama?.model,
});
}
return { success: false, error: 'Ollama was selected but no API key or self-hosted endpoint is configured.' };
@@ -328,15 +332,17 @@ export async function callAnthropicMessages(input: AnthropicCallInput): Promise<
*
* Translates the Anthropic-flavored input shape onto OpenAI chat-completions
* and translates the response back so callers never see provider-specific
- * fields. Logical model names are mapped to Ollama Cloud defaults:
- * - 'haiku' / 'sonnet' β†’ 'gpt-oss:120b-cloud' (sensible single default)
- * - 'opus' β†’ 'gpt-oss:120b-cloud' (no opus tier on Ollama)
- * - explicit 'ollama:<model>' or bare provider-native name β†’ passed through
+ * fields. Logical model names ('haiku' / 'sonnet' / 'opus' / a tier-routed
+ * `claude-*` id) resolve to the configured OLLAMA_DEFAULT_MODEL / persisted
+ * default; only when the endpoint is genuinely Ollama's cloud service AND no
+ * default is configured does this fall back to 'gpt-oss:120b-cloud' β€” a
+ * self-hosted/local endpoint with no default configured fails loudly instead
+ * (see resolveOllamaModel). An explicit 'ollama:<model>' or bare
+ * provider-native name always passes through unchanged.
*/
async function callOllamaCompat(
- input: AnthropicCallInput & { apiKey: string; baseUrl?: string },
+ input: AnthropicCallInput & { apiKey: string; baseUrl?: string; defaultModel?: string },
): Promise<AnthropicCallResult> {
- const model = resolveOllamaModel(input.model);
const startedAt = Date.now();
// #2962 β€” input.baseUrl (resolved by the caller from persisted
// `providers configure` config, then OLLAMA_BASE_URL) takes precedence
@@ -345,6 +351,19 @@ async function callOllamaCompat(
// Cloud. Falls back to the original OLLAMA_BASE_URL-or-cloud behavior
// for any direct caller that doesn't pass baseUrl.
const base = (input.baseUrl || process.env.OLLAMA_BASE_URL || 'https://ollama.com').replace(/\/+$/, '');
+ // Only a base URL actually pointed at Ollama's real cloud endpoint may
+ // fall back to a `-cloud`-suffixed default model β€” see resolveOllamaModel.
+ const isCloudEndpoint = /^https:\/\/ollama\.com\/?$/i.test(base);
+ let model: string;
+ try {
+ model = resolveOllamaModel(input.model, input.defaultModel, isCloudEndpoint);
+ } catch (err) {
+ return {
+ success: false,
+ error: err instanceof Error ? err.message : String(err),
+ durationMs: Date.now() - startedAt,
+ };
+ }
const url = `${base}/v1/chat/completions`;
// Self-hosted endpoints typically don't need an Authorization header
// (the daemon binds to 11434 with no auth by default), but Ollama Cloud
@@ -509,16 +528,42 @@ function resolveOpenAICompatModel(input: string | undefined, fallback: string):
return input;
}
-function resolveOllamaModel(input: string | undefined): string {
- const DEFAULT = 'gpt-oss:120b-cloud';
- if (!input) return DEFAULT;
- // Logical β†’ cloud default
+/**
+ * Resolve the model name to send to an Ollama-compatible endpoint.
+ *
+ * Self-hosted setups name their default via OLLAMA_DEFAULT_MODEL or
+ * `providers configure -p ollama -m <tag>` (`defaultModel`, resolved by the
+ * caller). When no default is configured AND the endpoint is not actually
+ * Ollama's real cloud service, this must NOT silently rewrite a tier-routed
+ * `claude-*` id (or a bare tier alias) to a `-cloud`-suffixed model name: a
+ * signed-in local Ollama daemon forwards any `-cloud`-suffixed model to
+ * Ollama's actual cloud service, so a silent rewrite would leak a prompt
+ * that was supposed to stay local. Fail loudly instead and tell the caller
+ * how to fix it β€” a loud, local failure beats silent cloud egress.
+ */
+function resolveOllamaModel(input: string | undefined, defaultModel?: string, isCloudEndpoint = false): string {
+ const cloudDefault = 'gpt-oss:120b-cloud';
+ const resolveDefault = (): string => {
+ if (defaultModel) return defaultModel;
+ if (isCloudEndpoint) return cloudDefault;
+ throw new Error(
+ 'No Ollama model configured for this self-hosted/local endpoint β€” refusing to fall back to '
+ + `a cloud-suffixed default ("${cloudDefault}") a local Ollama daemon would forward to Ollama `
+ + 'Cloud. Set OLLAMA_DEFAULT_MODEL, or run `providers configure -p ollama -m <tag>`, to pin a '
+ + 'real local model.',
+ );
+ };
+ if (!input) return resolveDefault();
+ // Logical tier alias β†’ default
if (input === 'haiku' || input === 'sonnet' || input === 'opus' || input === 'inherit') {
- return DEFAULT;
+ return resolveDefault();
}
// Explicit provider prefix
if (input.startsWith('ollama:')) return input.slice('ollama:'.length);
- // Bare name with cloud suffix (e.g. 'llama3:70b-cloud') passes through
+ // Anthropic model ids (what executeAgentTask sends for a tier-routed agent
+ // via MODEL_MAP) never exist on an Ollama endpoint β†’ default.
+ if (/^claude-/i.test(input)) return resolveDefault();
+ // Bare name (e.g. 'qwen3-coder:30b', 'llama3:70b-cloud') passes through
return input;
}
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 5e419a7f0c..a599bb3c56 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
@@ -917,6 +917,11 @@ export const memoryTools: MCPTool[] = [
type: 'object',
properties: {
namespace: { type: 'string', description: 'Filter by namespace' },
+ tags: {
+ type: 'array',
+ items: { type: 'string' },
+ description: 'Require entries to include all of these tags (AND). Matches the description claim "optionally filtered by namespace/tags".',
+ },
limit: { type: 'number', description: 'Maximum results (default: 50)' },
offset: { type: 'number', description: 'Offset for pagination (default: 0)' },
},
@@ -926,6 +931,9 @@ export const memoryTools: MCPTool[] = [
const { listEntries } = await getMemoryFunctions();
const namespace = input.namespace as string | undefined;
+ const tags = Array.isArray(input.tags)
+ ? (input.tags as unknown[]).filter((t): t is string => typeof t === 'string' && t.length > 0)
+ : undefined;
const limit = (input.limit as number) || 50;
const offset = (input.offset as number) || 0;
@@ -934,6 +942,7 @@ export const memoryTools: MCPTool[] = [
try {
const result = await listEntries({
namespace,
+ tags,
limit,
offset,
});
@@ -941,6 +950,7 @@ export const memoryTools: MCPTool[] = [
const entries = result.entries.map(e => ({
key: e.key,
namespace: e.namespace,
+ tags: e.tags ?? [],
storedAt: e.createdAt,
updatedAt: e.updatedAt,
accessCount: e.accessCount,
@@ -1707,7 +1717,9 @@ export const memoryTools: MCPTool[] = [
}
const all = { entries: [...merged.values()] };
const payload = {
- schema: 'ruflo-memory-export/v1',
+ // ruflo-memory-export/v1.1: tags round-trip with export/import.
+ // v1 importers ignore unknown fields; v1.1 importers restore tags.
+ schema: 'ruflo-memory-export/v1.1',
exportedAt: new Date().toISOString(),
namespace: namespace ?? null,
count: all.entries.length,
@@ -1718,6 +1730,8 @@ export const memoryTools: MCPTool[] = [
// never-populated alias. Fall back to null only if content is
// missing for backward-compat with the schema.
value: typeof e.content === 'string' ? e.content : ((e as { value?: unknown }).value ?? null),
+ // Preserve tags so memory_import is lossless for tag sets.
+ tags: Array.isArray(e.tags) ? e.tags : [],
createdAt: e.createdAt, updatedAt: e.updatedAt, accessCount: e.accessCount, hasEmbedding: e.hasEmbedding, size: e.size,
})),
};
@@ -1738,8 +1752,9 @@ export const memoryTools: MCPTool[] = [
{
// #1916: `ruflo memory import <file>` referenced an unregistered tool.
// Reads a ruflo-memory-export JSON and re-stores each entry.
+ // Honour `tags` on each entry (export v1.1+; ignored if absent).
name: 'memory_import',
- description: 'Import memory entries from a JSON export file (produced by memory_export) into .swarm/memory.db, re-embedding values. Use when native Read is wrong because the data must be re-stored as memory rows (with new embeddings), not just read. For importing Claude Code\'s own memory files use memory_import_claude. Pair with memory_export on the source.',
+ description: 'Import memory entries from a JSON export file (produced by memory_export) into .swarm/memory.db, re-embedding values. Preserves tags when present in the export (ruflo-memory-export/v1.1+). Use when native Read is wrong because the data must be re-stored as memory rows (with new embeddings), not just read. For importing Claude Code\'s own memory files use memory_import_claude. Pair with memory_export on the source.',
category: 'memory',
inputSchema: {
type: 'object',
@@ -1763,7 +1778,7 @@ export const memoryTools: MCPTool[] = [
let vectors = 0;
const inputPath = String(input.inputPath ?? '');
if (!inputPath || !existsSync(inputPath)) return { error: `File not found: ${inputPath || '(empty)'}` };
- let doc: { entries?: Array<{ key: string; namespace?: string; value?: unknown }> };
+ let doc: { entries?: Array<{ key: string; namespace?: string; value?: unknown; tags?: string[] | string }> };
try { doc = JSON.parse(readFileSync(inputPath, 'utf-8')); }
catch (e) { return { error: `Invalid export JSON: ${(e as Error).message}` }; }
const entries = Array.isArray(doc.entries) ? doc.entries : [];
@@ -1785,15 +1800,33 @@ export const memoryTools: MCPTool[] = [
if (keyError) throw new Error(`${keyError}: ${JSON.stringify(e.key)}`);
}
}
- let imported = 0; let skipped = 0; let failed = 0;
+ let imported = 0; let skipped = 0; let failed = 0; let withTags = 0;
const errors: string[] = [];
for (const e of entries) {
if (!e || typeof e.key !== 'string') { skipped++; continue; }
const value = typeof e.value === 'string' ? e.value : JSON.stringify(e.value ?? null);
+ // Restore tags from export. Accept array or JSON/comma string
+ // for robustness with hand-edited fidelity manifests.
+ let tags: string[] = [];
+ if (Array.isArray(e.tags)) {
+ tags = e.tags.filter((t): t is string => typeof t === 'string' && t.length > 0);
+ } else if (typeof e.tags === 'string' && e.tags.trim()) {
+ try {
+ const parsed = JSON.parse(e.tags);
+ if (Array.isArray(parsed)) {
+ tags = parsed.filter((t): t is string => typeof t === 'string' && t.length > 0);
+ } else {
+ tags = e.tags.split(',').map(s => s.trim()).filter(Boolean);
+ }
+ } catch {
+ tags = e.tags.split(',').map(s => s.trim()).filter(Boolean);
+ }
+ }
try {
- const result = await storeEntry({ key: e.key, value, namespace: nsOverride ?? e.namespace ?? 'default', upsert: input.merge !== false, dbPath });
+ const result = await storeEntry({ key: e.key, value, namespace: nsOverride ?? e.namespace ?? 'default', tags, upsert: input.merge !== false, dbPath });
if (!result.success) throw new Error(result.error || 'Memory write was rejected');
imported++;
+ if (tags.length > 0) withTags++;
if (result.embedding) vectors++;
} catch (error) {
failed++;
@@ -1805,7 +1838,7 @@ export const memoryTools: MCPTool[] = [
error: failed > 0 ? `${failed} memory write(s) failed: ${errors.join('; ')}` : undefined,
failed,
inputPath,
- imported: { entries: imported, vectors, patterns: 0 },
+ imported: { entries: imported, vectors, patterns: 0, withTags },
skipped,
duration: Date.now() - t0,
};
diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
index f30e18e4a9..de68248cd7 100644
--- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
@@ -1551,6 +1551,8 @@ export async function bridgeListEntries(options: {
includeEmbedding?: boolean;
/** #4056: also return rows whose TTL has passed (with `expiresAt`). For cleanup only. */
includeExpired?: boolean;
+ /** Require entries to include all of these tags (AND). */
+ tags?: string[];
}): Promise<{
success: boolean;
entries: {
@@ -1568,6 +1570,8 @@ export async function bridgeListEntries(options: {
content?: string;
provenanceType?: string;
embeddingQ8?: { dims: number; scale: number; b64: string };
+ /** Tag set stored with the entry (empty array when none). */
+ tags?: string[];
}[];
total: number;
error?: string;
@@ -1580,7 +1584,7 @@ export async function bridgeListEntries(options: {
if (!ctx) return null;
try {
- const { namespace, limit = 20, offset = 0, provenanceFilter } = options;
+ const { namespace, limit = 20, offset = 0, provenanceFilter, tags: requiredTags } = options;
if (provenanceFilter?.some(p => !isValidProvenanceType(p))) return null;
const filters: string[] = [];
@@ -1593,6 +1597,20 @@ export async function bridgeListEntries(options: {
filters.push(`provenance_type IN (${provenanceFilter.map(() => '?').join(',')})`);
filterParams.push(...provenanceFilter);
}
+ // Tags are stored as JSON-array TEXT (e.g. `["a","b"]`). Match each
+ // required tag as an exact element via SQLite's json_each so the filter
+ // runs in SQL instead of pulling the whole table into memory to filter
+ // there. A LIKE-based substring match is ASCII case-insensitive (so
+ // `prod` would match `PROD`) and matches raw JSON bytes rather than
+ // parsed array elements (so a tag literally containing `"prod` could
+ // false-match) β€” json_each compares real, decoded array values.
+ const tagFilter = Array.isArray(requiredTags)
+ ? requiredTags.filter((t): t is string => typeof t === 'string' && t.length > 0)
+ : [];
+ for (const tag of tagFilter) {
+ filters.push(`EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?)`);
+ filterParams.push(tag);
+ }
const extraFilter = filters.length > 0 ? `AND ${filters.join(' AND ')}` : '';
// #2120 β€” `status IS NULL` accepted alongside `'active'`. Old
@@ -1605,6 +1623,14 @@ export async function bridgeListEntries(options: {
// status column.
const statusFilter = liveMemoryRowSql({ includeExpired: options.includeExpired });
+ // `|| 20` would treat an explicit `limit: 0` as falsy and silently
+ // substitute the default (returning 20 rows instead of the requested
+ // zero) β€” only fall back to the default when parsing genuinely failed.
+ const parsedLimit = parseInt(String(limit), 10);
+ const safeLimit = Number.isNaN(parsedLimit) ? 20 : parsedLimit;
+ const parsedOffset = parseInt(String(offset), 10);
+ const safeOffset = Number.isNaN(parsedOffset) ? 0 : parsedOffset;
+
// Count
let total = 0;
try {
@@ -1620,15 +1646,25 @@ export async function bridgeListEntries(options: {
// List
const entries: any[] = [];
try {
+ // Include tags so export/list can round-trip them.
const stmt = ctx.db.prepare(`
- SELECT id, key, namespace, content, embedding, access_count, created_at, updated_at, provenance_type, expires_at
+ SELECT id, key, namespace, content, embedding, access_count, created_at, updated_at, provenance_type, expires_at, tags
FROM memory_entries
WHERE ${statusFilter} ${extraFilter}
ORDER BY updated_at DESC
LIMIT ? OFFSET ?
`);
- const rows = stmt.all(...filterParams, options.includeEmbedding ? Math.min(limit, MAX_LIST_EMBEDDINGS) : limit, offset);
+ const rows = stmt.all(...filterParams, options.includeEmbedding ? Math.min(safeLimit, MAX_LIST_EMBEDDINGS) : safeLimit, safeOffset);
for (const row of rows) {
+ let tags: string[] = [];
+ if (row.tags) {
+ try {
+ const parsed = typeof row.tags === 'string' ? JSON.parse(row.tags) : row.tags;
+ if (Array.isArray(parsed)) {
+ tags = parsed.filter((t: unknown): t is string => typeof t === 'string');
+ }
+ } catch { /* invalid tags JSON */ }
+ }
const entry: Record<string, unknown> = {
// #2073: don't truncate id when content is requested β€” callers
// (notably memory_export) need the full id to round-trip via import.
@@ -1642,6 +1678,7 @@ export async function bridgeListEntries(options: {
expiresAt: row.expires_at ?? null,
hasEmbedding: !!(row.embedding && String(row.embedding).length > 10),
provenanceType: row.provenance_type || 'unknown',
+ tags,
};
if (options.includeContent) {
entry.content = row.content || '';
diff --git a/v3/@claude-flow/cli/src/memory/memory-initializer.ts b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
index 85b2fffb2d..04c9870a99 100644
--- a/v3/@claude-flow/cli/src/memory/memory-initializer.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
@@ -3519,6 +3519,8 @@ export async function listEntries(options: {
includeEmbedding?: boolean;
/** #4056: also return rows whose TTL has passed (with `expiresAt`). For cleanup only; normal reads hide them. */
includeExpired?: boolean;
+ /** Require entries to include all of these tags (AND). */
+ tags?: string[];
}): Promise<{
success: boolean;
entries: {
@@ -3537,6 +3539,8 @@ export async function listEntries(options: {
provenanceType?: string;
/** ADR-472: present when `includeEmbedding: true` and the row has a valid stored vector. */
embeddingQ8?: EmbeddingQ8;
+ /** Tag set stored with the entry (empty array when none). */
+ tags?: string[];
}[];
total: number;
error?: string;
@@ -3566,7 +3570,8 @@ export async function listEntries(options: {
limit = 20,
offset = 0,
dbPath: customPath,
- provenanceFilter
+ provenanceFilter,
+ tags: requiredTags,
} = options;
const swarmDir = getMemoryRoot();
@@ -3596,18 +3601,43 @@ export async function listEntries(options: {
// #2120 β€” accept `status IS NULL` alongside `'active'`. Old DBs
// that predate the status column may have NULL after migration.
// See memory-bridge.ts:bridgeListEntries for full context.
- // Get total count
const whereClauses = [liveMemoryRowSql({ includeExpired: options.includeExpired })];
const whereParams: string[] = [];
if (namespace) {
whereClauses.push('namespace = ?');
whereParams.push(namespace);
}
+ // ADR-323: restrict to the requested provenance types. This must be
+ // ANDed alongside any tags filter below, never replaced by it β€” dropping
+ // this clause lets unverified user_claim rows leak into results that
+ // are supposed to be tool_result-only.
if (provenanceFilter?.length) {
whereClauses.push(`provenance_type IN (${provenanceFilter.map(() => '?').join(',')})`);
whereParams.push(...provenanceFilter);
}
+ // Tags are stored as JSON-array TEXT (e.g. `["a","b"]`). Match each
+ // required tag as an exact element via SQLite's json_each so a tag of
+ // `prod` can't be satisfied by a substring like `"prod` or by a
+ // differently-cased value like `PROD` (LIKE is ASCII case-insensitive
+ // and matches raw JSON-array bytes, not parsed array elements).
+ const tagFilter = Array.isArray(requiredTags)
+ ? requiredTags.filter((t): t is string => typeof t === 'string' && t.length > 0)
+ : [];
+ for (const tag of tagFilter) {
+ whereClauses.push(`EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?)`);
+ whereParams.push(tag);
+ }
const whereSql = whereClauses.join(' AND ');
+
+ // `|| 100` would treat an explicit `limit: 0` as falsy and silently
+ // substitute the default (returning rows instead of the requested
+ // zero) β€” only fall back to the default when parsing genuinely failed.
+ const parsedLimit = parseInt(String(limit), 10);
+ const safeLimit = Number.isNaN(parsedLimit) ? 100 : parsedLimit;
+ const parsedOffset = parseInt(String(offset), 10);
+ const safeOffset = Number.isNaN(parsedOffset) ? 0 : parsedOffset;
+
+ // Get total count
const countStmt = db.prepare(`SELECT COUNT(*) as cnt FROM memory_entries WHERE ${whereSql}`);
if (whereParams.length > 0) countStmt.bind(whereParams);
const countRows: unknown[][] = [];
@@ -3615,25 +3645,23 @@ export async function listEntries(options: {
countRows.push(countStmt.get());
}
countStmt.free();
- const countResult = countRows.length > 0 ? [{ values: countRows }] : [];
- const total = countResult[0]?.values?.[0]?.[0] as number || 0;
+ const total = (countRows[0]?.[0] as number) || 0;
- // Get entries
- const safeLimit = Math.min(parseInt(String(limit), 10) || 100, options.includeEmbedding ? MAX_LIST_EMBEDDINGS : Number.MAX_SAFE_INTEGER);
- const safeOffset = parseInt(String(offset), 10) || 0;
- // #2120 β€” same NULL-as-active acceptance as the count above.
+ // Get entries. ADR-472: embedding rows are capped at MAX_LIST_EMBEDDINGS.
+ const listLimit = options.includeEmbedding ? Math.min(safeLimit, MAX_LIST_EMBEDDINGS) : safeLimit;
+ // Include tags so export/list can round-trip them.
const listStmt = db.prepare(
- `SELECT id, key, namespace, content, embedding, access_count, created_at, updated_at, provenance_type, expires_at
+ `SELECT id, key, namespace, content, embedding, access_count, created_at, updated_at, provenance_type, expires_at, tags
FROM memory_entries WHERE ${whereSql}
ORDER BY updated_at DESC LIMIT ? OFFSET ?`
);
- listStmt.bind([...whereParams, safeLimit, safeOffset]);
+ listStmt.bind([...whereParams, listLimit, safeOffset]);
const listRows: unknown[][] = [];
while (listStmt.step()) {
listRows.push(listStmt.get());
}
listStmt.free();
- const result = listRows.length > 0 ? [{ values: listRows }] : [];
+
const entries: {
id: string;
key: string;
@@ -3647,49 +3675,59 @@ export async function listEntries(options: {
content?: string;
provenanceType?: string;
embeddingQ8?: EmbeddingQ8;
+ tags?: string[];
}[] = [];
- if (result[0]?.values) {
- for (const row of result[0].values) {
- const [id, key, ns, content, embedding, accessCount, createdAt, updatedAt, provenanceTypeVal, expiresAtVal] = row as [
- string, string, string, string, string | null, number, string, string, string | null, number | null
- ];
- const entry: {
- id: string;
- key: string;
- namespace: string;
- size: number;
- accessCount: number;
- createdAt: string;
- updatedAt: string;
- expiresAt?: number | null;
- hasEmbedding: boolean;
- content?: string;
- provenanceType?: string;
- embeddingQ8?: EmbeddingQ8;
- } = {
- // #2073: don't truncate id when content is requested β€” callers
- // (notably memory_export) need the full id to round-trip via import.
- id: options.includeContent ? String(id) : String(id).substring(0, 20),
- key: key || String(id).substring(0, 15),
- namespace: ns || 'default',
- size: (content || '').length,
- accessCount: accessCount || 0,
- createdAt: createdAt || new Date().toISOString(),
- updatedAt: updatedAt || new Date().toISOString(),
- expiresAt: expiresAtVal ?? null,
- hasEmbedding: !!embedding && embedding.length > 10,
- provenanceType: provenanceTypeVal || 'unknown'
- };
- if (options.includeContent) {
- entry.content = content || '';
- }
- if (options.includeEmbedding) {
- const q8 = encodeEmbeddingQ8(embedding);
- if (q8) entry.embeddingQ8 = q8;
- }
- entries.push(entry);
+ for (const row of listRows) {
+ const [id, key, ns, content, embedding, accessCount, createdAt, updatedAt, provenanceTypeVal, expiresAtVal, tagsJson] = row as [
+ string, string, string, string, string | null, number, string, string, string | null, number | null, string | null
+ ];
+ let tags: string[] = [];
+ if (tagsJson) {
+ try {
+ const parsed = JSON.parse(tagsJson);
+ if (Array.isArray(parsed)) {
+ tags = parsed.filter((t): t is string => typeof t === 'string');
+ }
+ } catch { /* invalid tags JSON */ }
+ }
+ const entry: {
+ id: string;
+ key: string;
+ namespace: string;
+ size: number;
+ accessCount: number;
+ createdAt: string;
+ updatedAt: string;
+ expiresAt?: number | null;
+ hasEmbedding: boolean;
+ content?: string;
+ provenanceType?: string;
+ embeddingQ8?: EmbeddingQ8;
+ tags?: string[];
+ } = {
+ // #2073: don't truncate id when content is requested β€” callers
+ // (notably memory_export) need the full id to round-trip via import.
+ id: options.includeContent ? String(id) : String(id).substring(0, 20),
+ key: key || String(id).substring(0, 15),
+ namespace: ns || 'default',
+ size: (content || '').length,
+ accessCount: accessCount || 0,
+ createdAt: createdAt || new Date().toISOString(),
+ updatedAt: updatedAt || new Date().toISOString(),
+ expiresAt: expiresAtVal ?? null,
+ hasEmbedding: !!embedding && embedding.length > 10,
+ provenanceType: provenanceTypeVal || 'unknown',
+ tags,
+ };
+ if (options.includeContent) {
+ entry.content = content || '';
+ }
+ if (options.includeEmbedding) {
+ const q8 = encodeEmbeddingQ8(embedding);
+ if (q8) entry.embeddingQ8 = q8;
}
+ entries.push(entry);
}
db.close();