Advanced AgentDB usage with the shipped API: several AgentDB databases side by side, distance metrics and MMR in vector-search, keyword (BM25) plus metadata-filtered search, context synthesis, causal memory, and export/import between machines. Use when combining several AgentDB stores, filtering or diversifying results, or moving data between nodes.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Agentdb Advanced?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/ruvnet-agentdb-advanced-1824763b)
---
name: agentdb-advanced
description: "Advanced AgentDB usage with the shipped API: several AgentDB databases side by side, distance metrics and MMR in vector-search, keyword (BM25) plus metadata-filtered search, context synthesis, causal memory, and export/import between machines. Use when combining several AgentDB stores, filtering or diversifying results, or moving data between nodes."
---
# AgentDB Advanced Features
## What This Skill Does
Covers the advanced pieces of the `agentdb` package that are present and runnable:
- **Several databases** - one `AgentDB` instance per file, routed by domain.
- **Distance metrics and MMR** - `agentdb vector-search -m cosine|euclidean|dot --mmr`.
- **Keyword + metadata search** - `KeywordIndex` (BM25), `MetadataFilter`, `HybridSearch`.
- **Result diversity and synthesis** - `MMRDiversityRanker`, `ContextSynthesizer`.
- **Causal memory** - `agentdb causal ...` and the `causal` controller.
- **Moving data between machines** - `agentdb export` / `agentdb import`.
There is no `createAgentDBAdapter` factory and no `enableQUICSync` option; see
"About QUIC sync" below before relying on any network sync.
## Prerequisites
- Node.js 20+
- `agentdb` 3.10+ (`npm install agentdb`; it is also a dependency of `@claude-flow/cli`)
---
## Several Databases
```typescript
import { AgentDB } from 'agentdb';
async function open(dbPath: string) {
const db = new AgentDB({ dbPath });
await db.initialize();
return db;
}
const shards = {
knowledge: await open('.agentdb/knowledge.db'),
conversations: await open('.agentdb/conversations.db'),
code: await open('.agentdb/code.db'),
};
// Route each write to the database that owns the domain
await shards.code.getController('reflexion').storeEpisode({
sessionId: 'session-1',
task: 'refactor auth middleware',
reward: 0.8,
success: true,
});
const recalled = await shards.code
.getController('reflexion')
.retrieveRelevant({ task: 'auth middleware', k: 5 });
for (const db of Object.values(shards)) await db.close();
```
Keep one `AgentDB` instance per file per process and reuse it; `close()` it on shutdown.
---
## Distance Metrics and MMR (CLI)
```bash
# Cosine (default), Euclidean or dot product
npx agentdb@latest vector-search ./vectors.db "[0.1,0.2,0.3]" -k 10 -m cosine
npx agentdb@latest vector-search ./vectors.db "[0.1,0.2,0.3]" -k 10 -m euclidean
npx agentdb@latest vector-search ./vectors.db "[0.1,0.2,0.3]" -k 10 -m dot
# Minimum similarity and table output
npx agentdb@latest vector-search ./vectors.db "[0.1,0.2,0.3]" -k 10 -t 0.75 -f table
# MMR diversity: lambda 0 = max diversity, 1 = max relevance (default 0.5)
npx agentdb@latest vector-search ./vectors.db "[0.1,0.2,0.3]" -k 10 --mmr 0.7
```
The vector must have the database's dimension (`agentdb init --dimension <n>`).
---
## Keyword and Metadata Search (API)
```typescript
import { KeywordIndex, MetadataFilter } from 'agentdb';
// BM25 keyword index
const keywords = new KeywordIndex();
keywords.add('doc-1', 'JWT refresh token rotation', { year: 2025, category: 'auth' });
keywords.add('doc-2', 'OAuth2 PKCE flow for SPAs', { year: 2023, category: 'auth' });
keywords.add('doc-3', 'Postgres connection pooling', { year: 2025, category: 'db' });
const hits = keywords.search('token rotation', 10, { category: 'auth' });
// [{ id, score, metadata }]
// MongoDB-style filters over any items with a metadata field
const items = [
{ id: 1, metadata: { year: 2025, category: 'auth', citations: 150 } },
{ id: 2, metadata: { year: 2021, category: 'auth', citations: 12 } },
];
const recent = MetadataFilter.apply(items, {
'metadata.year': { $gte: 2023 },
'metadata.citations': { $gte: 50 },
});
```
Supported operators: `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`, `$contains`,
`$exists`.
`HybridSearch` combines a vector backend with a `KeywordIndex`
(`new HybridSearch(db.vectorBackend, keywords)`) and fuses the two rankings; see its type
definitions for the query and fusion options.
The same filters are available from the CLI on stored episodes:
```bash
npx agentdb@latest reflexion retrieve "bug-fix" --k 10 --filters '{"success":true,"reward":{"$gte":0.8}}'
npx agentdb@latest query --query "authentication" --k 5 --synthesize-context
```
---
## Diversity and Context Synthesis (API)
```typescript
import { MMRDiversityRanker, ContextSynthesizer } from 'agentdb';
// candidates: [{ id, embedding: number[], similarity }]
const diverse = MMRDiversityRanker.selectDiverse(candidates, queryEmbedding, {
lambda: 0.5,
k: 10,
metric: 'cosine',
});
// memories: [{ task, reward, success, critique? }] such as retrieved episodes
const context = ContextSynthesizer.synthesize(memories, { includeRecommendations: true });
console.log(context.summary, context.successRate, context.recommendations, context.keyInsights);
```
`ContextSynthesizer` builds its summary from the stored rewards and critiques with plain text
statistics; it does not call a language model.
---
## Causal Memory (CLI)
```bash
# Add an edge: <cause> <effect> <uplift> [confidence] [sample-size]
npx agentdb@latest causal add-edge "add_tests" "code_quality" 0.25 0.95 100
# A/B experiment
npx agentdb@latest causal experiment create "test-coverage-quality" "test_coverage" "bug_rate"
npx agentdb@latest causal experiment add-observation 1 true 0.15
npx agentdb@latest causal experiment calculate 1
# Query edges and recall with a provenance certificate
npx agentdb@latest causal query
npx agentdb@latest recall with-certificate "implement authentication" 10
```
From code: `db.getController('causal')`.
---
## Moving Data Between Machines
```bash
# Export vectors and episodes (optionally gzip-compressed)
npx agentdb@latest export ./agentdb.db --output backup.json
npx agentdb@latest export ./agentdb.db --compress --output backup.json.gz
# Import on the other machine
npx agentdb@latest import ./backup.json ./agentdb.db
npx agentdb@latest import ./backup.json.gz --decompress
# Migrate a legacy v1 or claude-flow memory database
npx agentdb@latest migrate ./old.db --target ./agentdb.db --dry-run
```
Pass the output file with `--output`: in agentdb 3.10.0 a second positional argument to `export`
is not used as the output path (the file is written to `./agentdb-export.json`).
### About QUIC sync
`agentdb sync start-server`, `sync connect`, `sync push`, `sync pull` and `sync status` are
present in the CLI, and `QUICServer` / `QUICClient` / `SyncCoordinator` are exported, but the
shipped QUIC server and client are reference implementations: `start()` marks the server as
running without opening a socket, so no data crosses the network. Do not build on them for
replication; use export/import (above) or a shared database file instead.
---
## Exposing AgentDB to an MCP Client
```bash
npx agentdb@latest mcp start
```
Inside a ruflo session the equivalent operations are already registered as MCP tools, for example
`mcp__claude-flow__agentdb_hierarchical-store`, `mcp__claude-flow__agentdb_hierarchical-recall`,
`mcp__claude-flow__agentdb_causal-edge`, `mcp__claude-flow__agentdb_graph-query` and
`mcp__claude-flow__agentdb_context-synthesize`.
---
## Environment Variables
```bash
AGENTDB_PATH=./agentdb.db # database used by the CLI when --db / a path is not given
```
---
## Troubleshooting
### `AgentDB not initialized. Call initialize() first.`
Await `db.initialize()` before `getController()` or `database`.
### `Unknown controller: <name>`
`getController` accepts `'reflexion'` (alias `'memory'`), `'skills'` and `'causal'`
(alias `'causalGraph'`).
### Filtered search returns nothing
Filters match on the stored metadata path: use `'metadata.year'` for items whose year lives under
`metadata`. Relax one condition at a time.
---
## Learn More
- `npx agentdb@latest --help` - the full CLI reference for the installed version
- Type definitions under `node_modules/agentdb/dist/src/` (`search/HybridSearch.d.ts`,
`controllers/MetadataFilter.d.ts`, `controllers/MMRDiversityRanker.d.ts`)
- Source: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb
---
**Category**: Advanced / Distributed Systems
**Difficulty**: Advanced