diff --git a/v3/@claude-flow/cli/.claude/skills/agentdb-advanced/SKILL.md b/v3/@claude-flow/cli/.claude/skills/agentdb-advanced/SKILL.md index 1caa8bc88b..8296d87656 100644 --- a/v3/@claude-flow/cli/.claude/skills/agentdb-advanced/SKILL.md +++ b/v3/@claude-flow/cli/.claude/skills/agentdb-advanced/SKILL.md @@ -1,550 +1,241 @@ --- name: agentdb-advanced -description: "Master advanced AgentDB features including QUIC synchronization, multi-database management, custom distance metrics, hybrid search, and distributed systems integration. Use when building distributed AI systems, multi-agent coordination, or advanced vector search applications." +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 advanced AgentDB capabilities for distributed systems, multi-database coordination, custom distance metrics, hybrid search (vector + metadata), QUIC synchronization, and production deployment patterns. Enables building sophisticated AI systems with sub-millisecond cross-node communication and advanced search capabilities. +Covers the advanced pieces of the `agentdb` package that are present and runnable: -**Performance**: <1ms QUIC sync, hybrid search with filters, custom distance metrics. +- **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 18+ -- AgentDB v1.0.7+ (via agentic-flow) -- Understanding of distributed systems (for QUIC sync) -- Vector search fundamentals +- Node.js 20+ +- `agentdb` 3.10+ (`npm install agentdb`; it is also a dependency of `@claude-flow/cli`) --- -## QUIC Synchronization - -### What is QUIC Sync? - -QUIC (Quick UDP Internet Connections) enables sub-millisecond latency synchronization between AgentDB instances across network boundaries with automatic retry, multiplexing, and encryption. - -**Benefits**: -- <1ms latency between nodes -- Multiplexed streams (multiple operations simultaneously) -- Built-in encryption (TLS 1.3) -- Automatic retry and recovery -- Event-based broadcasting - -### Enable QUIC Sync +## Several Databases ```typescript -import { createAgentDBAdapter } from 'agentic-flow/reasoningbank'; +import { AgentDB } from 'agentdb'; -// Initialize with QUIC synchronization -const adapter = await createAgentDBAdapter({ - dbPath: '.agentdb/distributed.db', - enableQUICSync: true, - syncPort: 4433, - syncPeers: [ - '192.168.1.10:4433', - '192.168.1.11:4433', - '192.168.1.12:4433', - ], -}); - -// Patterns automatically sync across all peers -await adapter.insertPattern({ - // ... pattern data -}); - -// Available on all peers within ~1ms -``` - -### QUIC Configuration - -```typescript -const adapter = await createAgentDBAdapter({ - enableQUICSync: true, - syncPort: 4433, // QUIC server port - syncPeers: ['host1:4433'], // Peer addresses - syncInterval: 1000, // Sync interval (ms) - syncBatchSize: 100, // Patterns per batch - maxRetries: 3, // Retry failed syncs - compression: true, // Enable compression -}); -``` - -### Multi-Node Deployment - -```bash -# Node 1 (192.168.1.10) -AGENTDB_QUIC_SYNC=true \ -AGENTDB_QUIC_PORT=4433 \ -AGENTDB_QUIC_PEERS=192.168.1.11:4433,192.168.1.12:4433 \ -node server.js - -# Node 2 (192.168.1.11) -AGENTDB_QUIC_SYNC=true \ -AGENTDB_QUIC_PORT=4433 \ -AGENTDB_QUIC_PEERS=192.168.1.10:4433,192.168.1.12:4433 \ -node server.js - -# Node 3 (192.168.1.12) -AGENTDB_QUIC_SYNC=true \ -AGENTDB_QUIC_PORT=4433 \ -AGENTDB_QUIC_PEERS=192.168.1.10:4433,192.168.1.11:4433 \ -node server.js -``` - ---- - -## Distance Metrics - -### Cosine Similarity (Default) - -Best for normalized vectors, semantic similarity: - -```bash -# CLI -npx agentdb@latest query ./vectors.db "[0.1,0.2,...]" -m cosine - -# API -const result = await adapter.retrieveWithReasoning(queryEmbedding, { - metric: 'cosine', - k: 10, -}); -``` - -**Use Cases**: -- Text embeddings (BERT, GPT, etc.) -- Semantic search -- Document similarity -- Most general-purpose applications - -**Formula**: `cos(θ) = (A · B) / (||A|| × ||B||)` -**Range**: [-1, 1] (1 = identical, -1 = opposite) - -### Euclidean Distance (L2) - -Best for spatial data, geometric similarity: - -```bash -# CLI -npx agentdb@latest query ./vectors.db "[0.1,0.2,...]" -m euclidean - -# API -const result = await adapter.retrieveWithReasoning(queryEmbedding, { - metric: 'euclidean', - k: 10, -}); -``` - -**Use Cases**: -- Image embeddings -- Spatial data -- Computer vision -- When vector magnitude matters - -**Formula**: `d = √(Σ(ai - bi)²)` -**Range**: [0, ∞] (0 = identical, ∞ = very different) - -### Dot Product - -Best for pre-normalized vectors, fast computation: - -```bash -# CLI -npx agentdb@latest query ./vectors.db "[0.1,0.2,...]" -m dot - -# API -const result = await adapter.retrieveWithReasoning(queryEmbedding, { - metric: 'dot', - k: 10, -}); -``` - -**Use Cases**: -- Pre-normalized embeddings -- Fast similarity computation -- When vectors are already unit-length - -**Formula**: `dot = Σ(ai × bi)` -**Range**: [-∞, ∞] (higher = more similar) - -### Custom Distance Metrics - -```typescript -// Implement custom distance function -function customDistance(vec1: number[], vec2: number[]): number { - // Weighted Euclidean distance - const weights = [1.0, 2.0, 1.5, ...]; - let sum = 0; - for (let i = 0; i < vec1.length; i++) { - sum += weights[i] * Math.pow(vec1[i] - vec2[i], 2); - } - return Math.sqrt(sum); +async function open(dbPath: string) { + const db = new AgentDB({ dbPath }); + await db.initialize(); + return db; } -// Use in search (requires custom implementation) -``` - ---- - -## Hybrid Search (Vector + Metadata) - -### Basic Hybrid Search - -Combine vector similarity with metadata filtering: - -```typescript -// Store documents with metadata -await adapter.insertPattern({ - id: '', - type: 'document', - domain: 'research-papers', - pattern_data: JSON.stringify({ - embedding: documentEmbedding, - text: documentText, - metadata: { - author: 'Jane Smith', - year: 2025, - category: 'machine-learning', - citations: 150, - } - }), - confidence: 1.0, - usage_count: 0, - success_count: 0, - created_at: Date.now(), - last_used: Date.now(), -}); - -// Hybrid search: vector similarity + metadata filters -const result = await adapter.retrieveWithReasoning(queryEmbedding, { - domain: 'research-papers', - k: 20, - filters: { - year: { $gte: 2023 }, // Published 2023 or later - category: 'machine-learning', // ML papers only - citations: { $gte: 50 }, // Highly cited - }, -}); -``` - -### Advanced Filtering - -```typescript -// Complex metadata queries -const result = await adapter.retrieveWithReasoning(queryEmbedding, { - domain: 'products', - k: 50, - filters: { - price: { $gte: 10, $lte: 100 }, // Price range - category: { $in: ['electronics', 'gadgets'] }, // Multiple categories - rating: { $gte: 4.0 }, // High rated - inStock: true, // Available - tags: { $contains: 'wireless' }, // Has tag - }, -}); -``` - -### Weighted Hybrid Search - -Combine vector and metadata scores: - -```typescript -const result = await adapter.retrieveWithReasoning(queryEmbedding, { - domain: 'content', - k: 20, - hybridWeights: { - vectorSimilarity: 0.7, // 70% weight on semantic similarity - metadataScore: 0.3, // 30% weight on metadata match - }, - filters: { - category: 'technology', - recency: { $gte: Date.now() - 30 * 24 * 3600000 }, // Last 30 days - }, -}); -``` - ---- - -## Multi-Database Management - -### Multiple Databases - -```typescript -// Separate databases for different domains -const knowledgeDB = await createAgentDBAdapter({ - dbPath: '.agentdb/knowledge.db', -}); - -const conversationDB = await createAgentDBAdapter({ - dbPath: '.agentdb/conversations.db', -}); - -const codeDB = await createAgentDBAdapter({ - dbPath: '.agentdb/code.db', -}); - -// Use appropriate database for each task -await knowledgeDB.insertPattern({ /* knowledge */ }); -await conversationDB.insertPattern({ /* conversation */ }); -await codeDB.insertPattern({ /* code */ }); -``` - -### Database Sharding - -```typescript -// Shard by domain for horizontal scaling const shards = { - 'domain-a': await createAgentDBAdapter({ dbPath: '.agentdb/shard-a.db' }), - 'domain-b': await createAgentDBAdapter({ dbPath: '.agentdb/shard-b.db' }), - 'domain-c': await createAgentDBAdapter({ dbPath: '.agentdb/shard-c.db' }), + knowledge: await open('.agentdb/knowledge.db'), + conversations: await open('.agentdb/conversations.db'), + code: await open('.agentdb/code.db'), }; -// Route queries to appropriate shard -function getDBForDomain(domain: string) { - const shardKey = domain.split('-')[0]; // Extract shard key - return shards[shardKey] || shards['domain-a']; -} +// 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, +}); -// Insert to correct shard -const db = getDBForDomain('domain-a-task'); -await db.insertPattern({ /* ... */ }); +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. + --- -## MMR (Maximal Marginal Relevance) - -Retrieve diverse results to avoid redundancy: - -```typescript -// Without MMR: Similar results may be redundant -const standardResults = await adapter.retrieveWithReasoning(queryEmbedding, { - k: 10, - useMMR: false, -}); - -// With MMR: Diverse, non-redundant results -const diverseResults = await adapter.retrieveWithReasoning(queryEmbedding, { - k: 10, - useMMR: true, - mmrLambda: 0.5, // Balance relevance (0) vs diversity (1) -}); -``` - -**MMR Parameters**: -- `mmrLambda = 0`: Maximum relevance (may be redundant) -- `mmrLambda = 0.5`: Balanced (default) -- `mmrLambda = 1`: Maximum diversity (may be less relevant) - -**Use Cases**: -- Search result diversification -- Recommendation systems -- Avoiding echo chambers -- Exploratory search - ---- - -## Context Synthesis - -Generate rich context from multiple memories: - -```typescript -const result = await adapter.retrieveWithReasoning(queryEmbedding, { - domain: 'problem-solving', - k: 10, - synthesizeContext: true, // Enable context synthesis -}); - -// ContextSynthesizer creates coherent narrative -console.log('Synthesized Context:', result.context); -// "Based on 10 similar problem-solving attempts, the most effective -// approach involves: 1) analyzing root cause, 2) brainstorming solutions, -// 3) evaluating trade-offs, 4) implementing incrementally. Success rate: 85%" - -console.log('Patterns:', result.patterns); -// Extracted common patterns across memories -``` - ---- - -## Production Patterns - -### Connection Pooling - -```typescript -// Singleton pattern for shared adapter -class AgentDBPool { - private static instance: AgentDBAdapter; - - static async getInstance() { - if (!this.instance) { - this.instance = await createAgentDBAdapter({ - dbPath: '.agentdb/production.db', - quantizationType: 'scalar', - cacheSize: 2000, - }); - } - return this.instance; - } -} - -// Use in application -const db = await AgentDBPool.getInstance(); -const results = await db.retrieveWithReasoning(queryEmbedding, { k: 10 }); -``` - -### Error Handling - -```typescript -async function safeRetrieve(queryEmbedding: number[], options: any) { - try { - const result = await adapter.retrieveWithReasoning(queryEmbedding, options); - return result; - } catch (error) { - if (error.code === 'DIMENSION_MISMATCH') { - console.error('Query embedding dimension mismatch'); - // Handle dimension error - } else if (error.code === 'DATABASE_LOCKED') { - // Retry with exponential backoff - await new Promise(resolve => setTimeout(resolve, 100)); - return safeRetrieve(queryEmbedding, options); - } - throw error; - } -} -``` - -### Monitoring and Logging - -```typescript -// Performance monitoring -const startTime = Date.now(); -const result = await adapter.retrieveWithReasoning(queryEmbedding, { k: 10 }); -const latency = Date.now() - startTime; - -if (latency > 100) { - console.warn('Slow query detected:', latency, 'ms'); -} - -// Log statistics -const stats = await adapter.getStats(); -console.log('Database Stats:', { - totalPatterns: stats.totalPatterns, - dbSize: stats.dbSize, - cacheHitRate: stats.cacheHitRate, - avgSearchLatency: stats.avgSearchLatency, -}); -``` - ---- - -## CLI Advanced Operations - -### Database Import/Export +## Distance Metrics and MMR (CLI) ```bash -# Export with compression -npx agentdb@latest export ./vectors.db ./backup.json.gz --compress +# 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 -# Import from backup +# 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 `). + +--- + +## 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: [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 -# Merge databases -npx agentdb@latest merge ./db1.sqlite ./db2.sqlite ./merged.sqlite +# Migrate a legacy v1 or claude-flow memory database +npx agentdb@latest migrate ./old.db --target ./agentdb.db --dry-run ``` -### Database Optimization +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 -# Vacuum database (reclaim space) -sqlite3 .agentdb/vectors.db "VACUUM;" - -# Analyze for query optimization -sqlite3 .agentdb/vectors.db "ANALYZE;" - -# Rebuild indices -npx agentdb@latest reindex ./vectors.db +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 configuration -AGENTDB_PATH=.agentdb/reasoningbank.db -AGENTDB_ENABLED=true - -# Performance tuning -AGENTDB_QUANTIZATION=binary # binary|scalar|product|none -AGENTDB_CACHE_SIZE=2000 -AGENTDB_HNSW_M=16 -AGENTDB_HNSW_EF=100 - -# Learning plugins -AGENTDB_LEARNING=true - -# Reasoning agents -AGENTDB_REASONING=true - -# QUIC synchronization -AGENTDB_QUIC_SYNC=true -AGENTDB_QUIC_PORT=4433 -AGENTDB_QUIC_PEERS=host1:4433,host2:4433 +AGENTDB_PATH=./agentdb.db # database used by the CLI when --db / a path is not given ``` --- ## Troubleshooting -### Issue: QUIC sync not working +### `AgentDB not initialized. Call initialize() first.` +Await `db.initialize()` before `getController()` or `database`. -```bash -# Check firewall allows UDP port 4433 -sudo ufw allow 4433/udp +### `Unknown controller: ` +`getController` accepts `'reflexion'` (alias `'memory'`), `'skills'` and `'causal'` +(alias `'causalGraph'`). -# Verify peers are reachable -ping host1 - -# Check QUIC logs -DEBUG=agentdb:quic node server.js -``` - -### Issue: Hybrid search returns no results - -```typescript -// Relax filters -const result = await adapter.retrieveWithReasoning(queryEmbedding, { - k: 100, // Increase k - filters: { - // Remove or relax filters - }, -}); -``` - -### Issue: Memory consolidation too aggressive - -```typescript -// Disable automatic optimization -const result = await adapter.retrieveWithReasoning(queryEmbedding, { - optimizeMemory: false, // Disable auto-consolidation - k: 10, -}); -``` +### 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 -- **QUIC Protocol**: docs/quic-synchronization.pdf -- **Hybrid Search**: docs/hybrid-search-guide.md -- **GitHub**: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb -- **Website**: https://agentdb.ruv.io +- `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 -**Estimated Time**: 45-60 minutes diff --git a/v3/@claude-flow/cli/.claude/skills/agentdb-learning/SKILL.md b/v3/@claude-flow/cli/.claude/skills/agentdb-learning/SKILL.md index e21b17ff2f..2fefbec8e9 100644 --- a/v3/@claude-flow/cli/.claude/skills/agentdb-learning/SKILL.md +++ b/v3/@claude-flow/cli/.claude/skills/agentdb-learning/SKILL.md @@ -1,545 +1,218 @@ --- name: agentdb-learning -description: "Create and train AI learning plugins with AgentDB's 9 reinforcement learning algorithms. Includes Decision Transformer, Q-Learning, SARSA, Actor-Critic, and more. Use when building self-learning agents, implementing RL, or optimizing agent behavior through experience." +description: "Run reinforcement-learning sessions with AgentDB's LearningSystem (q-learning, sarsa, dqn, policy-gradient, actor-critic, ppo, decision-transformer, mcts, model-based session types), record episodes with ReflexionMemory, and drive the agentdb train/learn/reflexion CLI verbs. Use when building agents that learn from rewarded experience." --- -# AgentDB Learning Plugins +# AgentDB Learning ## What This Skill Does -Provides access to 9 reinforcement learning algorithms via AgentDB's plugin system. Create, train, and deploy learning plugins for autonomous agents that improve through experience. Includes offline RL (Decision Transformer), value-based learning (Q-Learning), policy gradients (Actor-Critic), and advanced techniques. +Shows how to make an agent learn from rewarded experience with the interfaces the `agentdb` +package actually ships: -**Performance**: Train models 10-100x faster with WASM-accelerated neural inference. +- **`LearningSystem`** - RL session lifecycle: start a session, submit feedback, predict the next + action, train the policy, end the session. +- **`ReflexionMemory`** (via `AgentDB#getController('reflexion')`) - store episodes with a reward + and a self-critique, then retrieve the relevant ones for a new task. +- **The `agentdb` CLI** - `reflexion`, `skill`, `learner`, `train`, `learn` and `store-pattern` verbs. + +There is no plugin generator: `agentdb` has no `create-plugin`, `list-templates`, `list-plugins` +or `plugin-info` command, and no `createAgentDBAdapter` factory. Use the classes and verbs below. ## Prerequisites -- Node.js 18+ -- AgentDB v1.0.7+ (via agentic-flow) -- Basic understanding of reinforcement learning (recommended) +- Node.js 20+ +- `agentdb` 3.10+ (`npm install agentdb`; it is also a dependency of `@claude-flow/cli`) --- -## Quick Start with CLI +## Quick Start with the API -### Create Learning Plugin +```typescript +import { AgentDB, EmbeddingService, LearningSystem } from 'agentdb'; -```bash -# Interactive wizard -npx agentdb@latest create-plugin +// Open (or create) a database. initialize() must be awaited before use. +const db = new AgentDB({ dbPath: '.agentdb/learning.db' }); +await db.initialize(); -# Use specific template -npx agentdb@latest create-plugin -t decision-transformer -n my-agent +const embedder = new EmbeddingService({ + model: 'Xenova/all-MiniLM-L6-v2', + dimension: 384, + provider: 'transformers', +}); +await embedder.initialize(); -# Preview without creating -npx agentdb@latest create-plugin -t q-learning --dry-run +const learning = new LearningSystem(db.database, embedder); -# Custom output directory -npx agentdb@latest create-plugin -t actor-critic -o ./plugins +// sessionType is one of the nine values listed below +const sessionId = await learning.startSession('agent-1', 'q-learning', { + learningRate: 0.1, + discountFactor: 0.99, + explorationRate: 0.1, +}); + +// Feed back what happened after taking an action in a state +await learning.submitFeedback({ + sessionId, + state: 'login-form-empty', + action: 'fill-credentials', + reward: 1, + nextState: 'logged-in', + success: true, + timestamp: Date.now(), +}); + +// Ask for the best action in a state +const prediction = await learning.predict(sessionId, 'login-form-empty'); +console.log(prediction.action, prediction.confidence, prediction.alternatives); + +// Batch-train the policy: train(sessionId, epochs, batchSize, learningRate) +const result = await learning.train(sessionId, 10, 32, 0.1); +console.log(result.epochsCompleted, result.finalLoss, result.avgReward); + +await learning.endSession(sessionId); +await db.close(); ``` -### List Available Templates - -```bash -# Show all plugin templates -npx agentdb@latest list-templates - -# Available templates: -# - decision-transformer (sequence modeling RL - recommended) -# - q-learning (value-based learning) -# - sarsa (on-policy TD learning) -# - actor-critic (policy gradient with baseline) -# - curiosity-driven (exploration-based) -``` - -### Manage Plugins - -```bash -# List installed plugins -npx agentdb@latest list-plugins - -# Get plugin information -npx agentdb@latest plugin-info my-agent - -# Shows: algorithm, configuration, training status -``` +`train()` returns `{ epochsCompleted, finalLoss, avgReward, convergenceRate, trainingTimeMs }`. --- -## Quick Start with API +## Session Types -```typescript -import { createAgentDBAdapter } from 'agentic-flow/reasoningbank'; +`LearningSystem#startSession` accepts these `sessionType` values: -// Initialize with learning enabled -const adapter = await createAgentDBAdapter({ - dbPath: '.agentdb/learning.db', - enableLearning: true, // Enable learning plugins - enableReasoning: true, - cacheSize: 1000, -}); +| sessionType | Family | +|---|---| +| `q-learning` | value-based, off-policy | +| `sarsa` | value-based, on-policy | +| `dqn` | deep Q-network | +| `policy-gradient` | policy gradient | +| `actor-critic` | policy gradient with a value baseline | +| `ppo` | proximal policy optimization | +| `decision-transformer` | offline, sequence-modelling RL | +| `mcts` | Monte Carlo tree search | +| `model-based` | model-based RL | -// Store training experience -await adapter.insertPattern({ - id: '', - type: 'experience', - domain: 'game-playing', - pattern_data: JSON.stringify({ - embedding: await computeEmbedding('state-action-reward'), - pattern: { - state: [0.1, 0.2, 0.3], - action: 2, - reward: 1.0, - next_state: [0.15, 0.25, 0.35], - done: false - } - }), - confidence: 0.9, - usage_count: 1, - success_count: 1, - created_at: Date.now(), - last_used: Date.now(), -}); - -// Train learning model -const metrics = await adapter.train({ - epochs: 50, - batchSize: 32, -}); - -console.log('Training Loss:', metrics.loss); -console.log('Duration:', metrics.duration, 'ms'); -``` +All of them share the same config (`LearningConfig`): `learningRate`, `discountFactor`, and the +optional `explorationRate`, `batchSize` and `targetUpdateFrequency`. Treat the session type as a +label for how the stored experience is scored, not as a separate neural network per type, and +measure on your own task before relying on one type over another. --- -## Available Learning Algorithms (9 Total) +## Episodic Memory with Reflexion -### 1. Decision Transformer (Recommended) - -**Type**: Offline Reinforcement Learning -**Best For**: Learning from logged experiences, imitation learning -**Strengths**: No online interaction needed, stable training - -```bash -npx agentdb@latest create-plugin -t decision-transformer -n dt-agent -``` - -**Use Cases**: -- Learn from historical data -- Imitation learning from expert demonstrations -- Safe learning without environment interaction -- Sequence modeling tasks - -**Configuration**: -```json -{ - "algorithm": "decision-transformer", - "model_size": "base", - "context_length": 20, - "embed_dim": 128, - "n_heads": 8, - "n_layers": 6 -} -``` - -### 2. Q-Learning - -**Type**: Value-Based RL (Off-Policy) -**Best For**: Discrete action spaces, sample efficiency -**Strengths**: Proven, simple, works well for small/medium problems - -```bash -npx agentdb@latest create-plugin -t q-learning -n q-agent -``` - -**Use Cases**: -- Grid worlds, board games -- Navigation tasks -- Resource allocation -- Discrete decision-making - -**Configuration**: -```json -{ - "algorithm": "q-learning", - "learning_rate": 0.001, - "gamma": 0.99, - "epsilon": 0.1, - "epsilon_decay": 0.995 -} -``` - -### 3. SARSA - -**Type**: Value-Based RL (On-Policy) -**Best For**: Safe exploration, risk-sensitive tasks -**Strengths**: More conservative than Q-Learning, better for safety - -```bash -npx agentdb@latest create-plugin -t sarsa -n sarsa-agent -``` - -**Use Cases**: -- Safety-critical applications -- Risk-sensitive decision-making -- Online learning with exploration - -**Configuration**: -```json -{ - "algorithm": "sarsa", - "learning_rate": 0.001, - "gamma": 0.99, - "epsilon": 0.1 -} -``` - -### 4. Actor-Critic - -**Type**: Policy Gradient with Value Baseline -**Best For**: Continuous actions, variance reduction -**Strengths**: Stable, works for continuous/discrete actions - -```bash -npx agentdb@latest create-plugin -t actor-critic -n ac-agent -``` - -**Use Cases**: -- Continuous control (robotics, simulations) -- Complex action spaces -- Multi-agent coordination - -**Configuration**: -```json -{ - "algorithm": "actor-critic", - "actor_lr": 0.001, - "critic_lr": 0.002, - "gamma": 0.99, - "entropy_coef": 0.01 -} -``` - -### 5. Active Learning - -**Type**: Query-Based Learning -**Best For**: Label-efficient learning, human-in-the-loop -**Strengths**: Minimizes labeling cost, focuses on uncertain samples - -**Use Cases**: -- Human feedback incorporation -- Label-efficient training -- Uncertainty sampling -- Annotation cost reduction - -### 6. Adversarial Training - -**Type**: Robustness Enhancement -**Best For**: Safety, robustness to perturbations -**Strengths**: Improves model robustness, adversarial defense - -**Use Cases**: -- Security applications -- Robust decision-making -- Adversarial defense -- Safety testing - -### 7. Curriculum Learning - -**Type**: Progressive Difficulty Training -**Best For**: Complex tasks, faster convergence -**Strengths**: Stable learning, faster convergence on hard tasks - -**Use Cases**: -- Complex multi-stage tasks -- Hard exploration problems -- Skill composition -- Transfer learning - -### 8. Federated Learning - -**Type**: Distributed Learning -**Best For**: Privacy, distributed data -**Strengths**: Privacy-preserving, scalable - -**Use Cases**: -- Multi-agent systems -- Privacy-sensitive data -- Distributed training -- Collaborative learning - -### 9. Multi-Task Learning - -**Type**: Transfer Learning -**Best For**: Related tasks, knowledge sharing -**Strengths**: Faster learning on new tasks, better generalization - -**Use Cases**: -- Task families -- Transfer learning -- Domain adaptation -- Meta-learning - ---- - -## Training Workflow - -### 1. Collect Experiences +`ReflexionMemory` stores whole task attempts with a reward and a critique, so a later attempt can +start from what worked and what failed. ```typescript -// Store experiences during agent execution -for (let i = 0; i < numEpisodes; i++) { - const episode = runEpisode(); +import { AgentDB } from 'agentdb'; - for (const step of episode.steps) { - await adapter.insertPattern({ - id: '', - type: 'experience', - domain: 'task-domain', - pattern_data: JSON.stringify({ - embedding: await computeEmbedding(JSON.stringify(step)), - pattern: { - state: step.state, - action: step.action, - reward: step.reward, - next_state: step.next_state, - done: step.done - } - }), - confidence: step.reward > 0 ? 0.9 : 0.5, - usage_count: 1, - success_count: step.reward > 0 ? 1 : 0, - created_at: Date.now(), - last_used: Date.now(), - }); - } -} -``` +const db = new AgentDB({ dbPath: '.agentdb/learning.db' }); +await db.initialize(); +const reflexion = db.getController('reflexion'); -### 2. Train Model - -```typescript -// Train on collected experiences -const trainingMetrics = await adapter.train({ - epochs: 100, - batchSize: 64, - learningRate: 0.001, - validationSplit: 0.2, +await reflexion.storeEpisode({ + sessionId: 'session-1', + task: 'fix login bug', + input: 'users are logged out after 5 minutes', + output: 'extended token refresh window', + critique: 'check token expiry before touching the session store', + reward: 0.9, + success: true, }); -console.log('Training Metrics:', trainingMetrics); -// { -// loss: 0.023, -// valLoss: 0.028, -// duration: 1523, -// epochs: 100 -// } +// Retrieve the most relevant past attempts for a new task +const episodes = await reflexion.retrieveRelevant({ task: 'login bug', k: 5 }); +for (const e of episodes) console.log(e.task, e.reward, e.critique); + +// Aggregated lessons from past attempts +console.log(await reflexion.getCritiqueSummary({ task: 'login bug' })); + +await db.close(); ``` -### 3. Evaluate Performance - -```typescript -// Retrieve similar successful experiences -const testQuery = await computeEmbedding(JSON.stringify(testState)); -const result = await adapter.retrieveWithReasoning(testQuery, { - domain: 'task-domain', - k: 10, - synthesizeContext: true, -}); - -// Evaluate action quality -const suggestedAction = result.memories[0].pattern.action; -const confidence = result.memories[0].similarity; - -console.log('Suggested Action:', suggestedAction); -console.log('Confidence:', confidence); -``` - ---- - -## Advanced Training Techniques - -### Experience Replay - -```typescript -// Store experiences in buffer -const replayBuffer = []; - -// Sample random batch for training -const batch = sampleRandomBatch(replayBuffer, batchSize: 32); - -// Train on batch -await adapter.train({ - data: batch, - epochs: 1, - batchSize: 32, -}); -``` - -### Prioritized Experience Replay - -```typescript -// Store experiences with priority (TD error) -await adapter.insertPattern({ - // ... standard fields - confidence: tdError, // Use TD error as confidence/priority - // ... -}); - -// Retrieve high-priority experiences -const highPriority = await adapter.retrieveWithReasoning(queryEmbedding, { - domain: 'task-domain', - k: 32, - minConfidence: 0.7, // Only high TD-error experiences -}); -``` - -### Multi-Agent Training - -```typescript -// Collect experiences from multiple agents -for (const agent of agents) { - const experience = await agent.step(); - - await adapter.insertPattern({ - // ... store experience with agent ID - domain: `multi-agent/${agent.id}`, - }); -} - -// Train shared model -await adapter.train({ - epochs: 50, - batchSize: 64, -}); -``` - ---- - -## Performance Optimization - -### Batch Training - -```typescript -// Collect batch of experiences -const experiences = collectBatch(size: 1000); - -// Batch insert (500x faster) -for (const exp of experiences) { - await adapter.insertPattern({ /* ... */ }); -} - -// Train on batch -await adapter.train({ - epochs: 10, - batchSize: 128, // Larger batch for efficiency -}); -``` - -### Incremental Learning - -```typescript -// Train incrementally as new data arrives -setInterval(async () => { - const newExperiences = getNewExperiences(); - - if (newExperiences.length > 100) { - await adapter.train({ - epochs: 5, - batchSize: 32, - }); - } -}, 60000); // Every minute -``` - ---- - -## Integration with Reasoning Agents - -Combine learning with reasoning for better performance: - -```typescript -// Train learning model -await adapter.train({ epochs: 50, batchSize: 32 }); - -// Use reasoning agents for inference -const result = await adapter.retrieveWithReasoning(queryEmbedding, { - domain: 'decision-making', - k: 10, - useMMR: true, // Diverse experiences - synthesizeContext: true, // Rich context - optimizeMemory: true, // Consolidate patterns -}); - -// Make decision based on learned experiences + reasoning -const decision = result.context.suggestedAction; -const confidence = result.memories[0].similarity; -``` +`getController` accepts `'reflexion'` (alias `'memory'`), `'skills'` and `'causal'` +(alias `'causalGraph'`). --- ## CLI Operations +The CLI reads the database from `AGENTDB_PATH` (default `./agentdb.db`). + ```bash -# Create plugin -npx agentdb@latest create-plugin -t decision-transformer -n my-plugin +# Create the database +npx agentdb@latest init ./agentdb.db --dimension 384 -# List plugins -npx agentdb@latest list-plugins +# Store an episode: [critique] [input] [output] +npx agentdb@latest reflexion store "session-1" "fix_login_bug" 0.9 true "check token expiry first" -# Get plugin info -npx agentdb@latest plugin-info my-plugin +# Retrieve relevant episodes +npx agentdb@latest reflexion retrieve "login bug" --k 5 --only-successes -# List templates -npx agentdb@latest list-templates +# Aggregated critique lessons for a task +npx agentdb@latest reflexion critique-summary "fix_login_bug" + +# Turn repeated successful episodes into reusable skills +npx agentdb@latest skill consolidate 3 0.7 7 +npx agentdb@latest skill search "authentication" 5 + +# Discover causal edges from episode outcomes +npx agentdb@latest learner run 3 0.6 0.7 + +# Store a learned pattern and trigger pattern learning / skill consolidation +npx agentdb@latest store-pattern --type "experience" --domain "code-edits" --pattern '{"success":true}' --confidence 0.9 +npx agentdb@latest train --domain "code-edits" --epochs 10 --batch-size 32 + +# Embedding-space training from a data file: curriculum, contrastive or hard-negatives +npx agentdb@latest learn --mode curriculum --data train.json --schedule cosine + +# Database statistics +npx agentdb@latest db stats ``` +Run `npx agentdb@latest --help` for every verb and its options. + +--- + +## Using It from Ruflo + +Inside a ruflo session the same learning loop is exposed as MCP tools, with no code to write: + +- `mcp__claude-flow__agentdb_pattern-store` / `mcp__claude-flow__agentdb_pattern-search` - store + and retrieve learned patterns. +- `mcp__claude-flow__agentdb_feedback` - record the outcome of a task. +- `mcp__claude-flow__agentdb_episode-recall` - recall past episodes. +- `mcp__claude-flow__neural_train` / `mcp__claude-flow__neural_status` - ruflo's own pattern + training and its status. + --- ## Troubleshooting -### Issue: Training not converging -```typescript -// Reduce learning rate -await adapter.train({ - epochs: 100, - batchSize: 32, - learningRate: 0.0001, // Lower learning rate -}); -``` +### `better-sqlite3 was built for a different Node.js ABI` +AgentDB falls back to sql.js (WASM) and keeps working, more slowly. Run `npm rebuild better-sqlite3`, +or clear the npx cache if you run through `npx`. -### Issue: Overfitting -```typescript -// Use validation split -await adapter.train({ - epochs: 50, - batchSize: 64, - validationSplit: 0.2, // 20% validation -}); +### `AgentDB not initialized. Call initialize() first.` +`getController()` and `database` need `await db.initialize()` first. -// Enable memory optimization -await adapter.retrieveWithReasoning(queryEmbedding, { - optimizeMemory: true, // Consolidate, reduce overfitting -}); -``` - -### Issue: Slow training -```bash -# Enable quantization for faster inference -# Use binary quantization (32x faster) -``` +### Predictions are always the same action +`predict()` only knows the actions it has seen feedback for in that session. Submit feedback for +each action you want it to choose between, with rewards that separate them. --- ## Learn More -- **Algorithm Papers**: See docs/algorithms/ for detailed papers -- **GitHub**: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb -- **MCP Integration**: `npx agentdb@latest mcp` -- **Website**: https://agentdb.ruv.io +- `npx agentdb@latest --help` - the full CLI reference for the installed version +- Type definitions: `node_modules/agentdb/dist/src/controllers/LearningSystem.d.ts` and + `ReflexionMemory.d.ts` +- Source: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb --- **Category**: Machine Learning / Reinforcement Learning -**Difficulty**: Intermediate to Advanced -**Estimated Time**: 30-60 minutes +**Difficulty**: Intermediate diff --git a/v3/@claude-flow/cli/.claude/skills/agentdb-optimization/SKILL.md b/v3/@claude-flow/cli/.claude/skills/agentdb-optimization/SKILL.md index dd8ae59826..d57a5f04c6 100644 --- a/v3/@claude-flow/cli/.claude/skills/agentdb-optimization/SKILL.md +++ b/v3/@claude-flow/cli/.claude/skills/agentdb-optimization/SKILL.md @@ -1,509 +1,208 @@ --- name: agentdb-optimization -description: "Optimize AgentDB performance with quantization (4-32x memory reduction), HNSW indexing (150x faster search), caching, and batch operations. Use when optimizing memory usage, improving search speed, or scaling to millions of vectors." +description: "Tune AgentDB storage and search with the shipped primitives: 8-bit/4-bit scalar and product quantization stores, the vector backend choice (ruvector or hnswlib), QueryCache, BatchOperations, and the agentdb stats/doctor CLI. Use when an AgentDB store uses too much memory, search is slow, or you need to measure before tuning." --- # AgentDB Performance Optimization ## What This Skill Does -Provides comprehensive performance optimization techniques for AgentDB vector databases. Achieve 150x-12,500x performance improvements through quantization, HNSW indexing, caching strategies, and batch operations. Reduce memory usage by 4-32x while maintaining accuracy. +Covers the optimization building blocks the `agentdb` package exports, and how to measure +before and after changing them: -**Performance**: <100µs vector search, <1ms pattern retrieval, 2ms batch insert for 100 vectors. +- **Quantization** - `createScalar8BitStore`, `createScalar4BitStore`, `createProductQuantizedStore` + (`QuantizedVectorStore`), plus `quantize8bit` / `quantize4bit` / `getQuantizationStats`. +- **Vector backend** - `new AgentDB({ vectorBackend: 'auto' | 'ruvector' | 'hnswlib' })`. +- **Caching** - `QueryCache` (LRU with hit-rate statistics). +- **Batching** - `BatchOperations` for bulk episode / skill / pattern inserts. +- **Measurement** - `agentdb stats`, `agentdb db stats`, `agentdb doctor`, `agentdb status`. + +No speed-up figure in this skill is a promise: the gain depends on vector count, dimension and +backend. Measure on your own data. There is no `createAgentDBAdapter` factory and no +`agentdb benchmark` command; use the classes and verbs below. ## Prerequisites -- Node.js 18+ -- AgentDB v1.0.7+ (via agentic-flow) -- Existing AgentDB database or application +- Node.js 20+ +- `agentdb` 3.10+ (`npm install agentdb`; it is also a dependency of `@claude-flow/cli`) --- -## Quick Start - -### Run Performance Benchmarks +## Quick Start: Measure First ```bash -# Comprehensive performance benchmarking -npx agentdb@latest benchmark +# Backend detection and system health +npx agentdb@latest doctor --verbose +npx agentdb@latest init ./agentdb.db --dry-run -# Results show: -# ✅ Pattern Search: 150x faster (100µs vs 15ms) -# ✅ Batch Insert: 500x faster (2ms vs 1s for 100 vectors) -# ✅ Large-scale Query: 12,500x faster (8ms vs 100s at 1M vectors) -# ✅ Memory Efficiency: 4-32x reduction with quantization +# Database statistics +npx agentdb@latest stats ./agentdb.db +npx agentdb@latest status --db ./agentdb.db --verbose ``` -### Enable Optimizations - -```typescript -import { createAgentDBAdapter } from 'agentic-flow/reasoningbank'; - -// Optimized configuration -const adapter = await createAgentDBAdapter({ - dbPath: '.agentdb/optimized.db', - quantizationType: 'binary', // 32x memory reduction - cacheSize: 1000, // In-memory cache - enableLearning: true, - enableReasoning: true, -}); -``` +`init --dry-run` shows which vector backend would be used without creating anything. --- -## Quantization Strategies - -### 1. Binary Quantization (32x Reduction) - -**Best For**: Large-scale deployments (1M+ vectors), memory-constrained environments -**Trade-off**: ~2-5% accuracy loss, 32x memory reduction, 10x faster +## Choosing the Vector Backend ```typescript -const adapter = await createAgentDBAdapter({ - quantizationType: 'binary', - // 768-dim float32 (3072 bytes) → 96 bytes binary - // 1M vectors: 3GB → 96MB -}); -``` +import { AgentDB, isHnswlibAvailable } from 'agentdb'; -**Use Cases**: -- Mobile/edge deployment -- Large-scale vector storage (millions of vectors) -- Real-time search with memory constraints +console.log('hnswlib available:', await isHnswlibAvailable()); -**Performance**: -- Memory: 32x smaller -- Search Speed: 10x faster (bit operations) -- Accuracy: 95-98% of original - -### 2. Scalar Quantization (4x Reduction) - -**Best For**: Balanced performance/accuracy, moderate datasets -**Trade-off**: ~1-2% accuracy loss, 4x memory reduction, 3x faster - -```typescript -const adapter = await createAgentDBAdapter({ - quantizationType: 'scalar', - // 768-dim float32 (3072 bytes) → 768 bytes (uint8) - // 1M vectors: 3GB → 768MB -}); -``` - -**Use Cases**: -- Production applications requiring high accuracy -- Medium-scale deployments (10K-1M vectors) -- General-purpose optimization - -**Performance**: -- Memory: 4x smaller -- Search Speed: 3x faster -- Accuracy: 98-99% of original - -### 3. Product Quantization (8-16x Reduction) - -**Best For**: High-dimensional vectors, balanced compression -**Trade-off**: ~3-7% accuracy loss, 8-16x memory reduction, 5x faster - -```typescript -const adapter = await createAgentDBAdapter({ - quantizationType: 'product', - // 768-dim float32 (3072 bytes) → 48-96 bytes - // 1M vectors: 3GB → 192MB -}); -``` - -**Use Cases**: -- High-dimensional embeddings (>512 dims) -- Image/video embeddings -- Large-scale similarity search - -**Performance**: -- Memory: 8-16x smaller -- Search Speed: 5x faster -- Accuracy: 93-97% of original - -### 4. No Quantization (Full Precision) - -**Best For**: Maximum accuracy, small datasets -**Trade-off**: No accuracy loss, full memory usage - -```typescript -const adapter = await createAgentDBAdapter({ - quantizationType: 'none', - // Full float32 precision -}); -``` - ---- - -## HNSW Indexing - -**Hierarchical Navigable Small World** - O(log n) search complexity - -### Automatic HNSW - -AgentDB automatically builds HNSW indices: - -```typescript -const adapter = await createAgentDBAdapter({ +const db = new AgentDB({ dbPath: '.agentdb/vectors.db', - // HNSW automatically enabled -}); - -// Search with HNSW (100µs vs 15ms linear scan) -const results = await adapter.retrieveWithReasoning(queryEmbedding, { - k: 10, + vectorBackend: 'auto', // 'auto' (default) | 'ruvector' | 'hnswlib' + vectorDimension: 384, }); +await db.initialize(); +console.log('backend:', db.vectorBackendName, 'sql.js fallback:', db.isWasm); +await db.close(); ``` -### HNSW Parameters +From the CLI: `npx agentdb@latest init ./agentdb.db --backend ruvector --dimension 384`. -```typescript -// Advanced HNSW configuration -const adapter = await createAgentDBAdapter({ - dbPath: '.agentdb/vectors.db', - hnswM: 16, // Connections per layer (default: 16) - hnswEfConstruction: 200, // Build quality (default: 200) - hnswEfSearch: 100, // Search quality (default: 100) -}); -``` - -**Parameter Tuning**: -- **M** (connections): Higher = better recall, more memory - - Small datasets (<10K): M = 8 - - Medium datasets (10K-100K): M = 16 - - Large datasets (>100K): M = 32 -- **efConstruction**: Higher = better index quality, slower build - - Fast build: 100 - - Balanced: 200 (default) - - High quality: 400 -- **efSearch**: Higher = better recall, slower search - - Fast search: 50 - - Balanced: 100 (default) - - High recall: 200 +`isWasm` is `true` when native `better-sqlite3` could not load and AgentDB fell back to sql.js; +`npm rebuild better-sqlite3` restores the native driver. --- -## Caching Strategies +## Quantization -### In-Memory Pattern Cache +`QuantizedVectorStore` keeps compressed vectors in memory and searches them directly. ```typescript -const adapter = await createAgentDBAdapter({ - cacheSize: 1000, // Cache 1000 most-used patterns -}); +import { + createScalar8BitStore, + createScalar4BitStore, + createProductQuantizedStore, + getQuantizationStats, +} from 'agentdb'; -// First retrieval: ~2ms (database) -// Subsequent: <1ms (cache hit) -const result = await adapter.retrieveWithReasoning(queryEmbedding, { - k: 10, -}); +const dim = 384; +const vectors: Float32Array[] = loadEmbeddings(); // your data + +// Scalar 8-bit: about 4x smaller than float32 +const sq8 = createScalar8BitStore(dim, 'cosine'); // metric: 'cosine' | 'l2' | 'ip' +vectors.forEach((v, i) => sq8.insert(`doc-${i}`, v)); +const hits = sq8.search(vectors[0], 10); // [{ id, similarity, ... }] +console.log(sq8.getStats()); // includes compressionRatio, memoryUsageBytes + +// Scalar 4-bit: smaller again, with more reconstruction error +const sq4 = createScalar4BitStore(dim, 'cosine'); + +// Product quantization: must be trained before insert/search +const pq = createProductQuantizedStore(dim, 8, 256, 'cosine'); // numSubspaces, numCentroids +await pq.train(vectors); +console.log(pq.isReady()); + +// Error / compression for one vector before committing to a scheme +console.log(getQuantizationStats(vectors[0], '8bit')); // { meanError, maxError, compressionRatio, ... } ``` -**Cache Tuning**: -- Small applications: 100-500 patterns -- Medium applications: 500-2000 patterns -- Large applications: 2000-5000 patterns +Check recall against an unquantized search on a sample of your own queries before switching. -### LRU Cache Behavior +### 1-bit (RaBitQ) quantization + +`agentdb` does not export a binary quantizer. For 1-bit compression of ruflo's memory store use the +ruflo MCP tools `mcp__claude-flow__embeddings_rabitq_build`, +`mcp__claude-flow__embeddings_rabitq_search` and `mcp__claude-flow__embeddings_rabitq_status` +(see the `vector-quantization` skill). + +--- + +## Caching ```typescript -// Cache automatically evicts least-recently-used patterns -// Most frequently accessed patterns stay in cache +import { QueryCache } from 'agentdb'; -// Monitor cache performance -const stats = await adapter.getStats(); -console.log('Cache Hit Rate:', stats.cacheHitRate); -// Aim for >80% hit rate +const cache = new QueryCache({ maxSize: 1000 }); +const key = cache.generateKey('SELECT * FROM episodes WHERE task = ?', ['login'], 'episodes'); + +// ... run the query on a miss, store the result, read it back on a hit + +console.log(cache.getStatistics()); // { hits, misses, hitRate, size, capacity, evictions, ... } +cache.invalidateCategory('episodes'); // after writes to that table ``` +`ReflexionMemory` and `SkillLibrary` already accept a `QueryCacheConfig`, and `SkillLibrary` +exposes `getCacheStats()` / `warmCache(tasks)`. + --- ## Batch Operations -### Batch Insert (500x Faster) +Insert many rows in one transaction instead of one call per row. ```typescript -// ❌ SLOW: Individual inserts -for (const doc of documents) { - await adapter.insertPattern({ /* ... */ }); // 1s for 100 docs -} +import { AgentDB, EmbeddingService, BatchOperations } from 'agentdb'; -// ✅ FAST: Batch insert -const patterns = documents.map(doc => ({ - id: '', - type: 'document', - domain: 'knowledge', - pattern_data: JSON.stringify({ - embedding: doc.embedding, - text: doc.text, - }), - confidence: 1.0, - usage_count: 0, - success_count: 0, - created_at: Date.now(), - last_used: Date.now(), -})); +const db = new AgentDB({ dbPath: '.agentdb/vectors.db' }); +await db.initialize(); +const embedder = new EmbeddingService({ + model: 'Xenova/all-MiniLM-L6-v2', dimension: 384, provider: 'transformers', +}); +await embedder.initialize(); -// Insert all at once (2ms for 100 docs) -for (const pattern of patterns) { - await adapter.insertPattern(pattern); -} +const batch = new BatchOperations(db.database, embedder); +const inserted = await batch.insertEpisodes([ + { sessionId: 's1', task: 'fix login bug', reward: 0.9, success: true }, + { sessionId: 's1', task: 'add rate limit', reward: 0.7, success: true }, +]); +console.log('inserted', inserted); + +// Compact the database after a large load +batch.optimize(); +await db.close(); ``` -### Batch Retrieval - -```typescript -// Retrieve multiple queries efficiently -const queries = [queryEmbedding1, queryEmbedding2, queryEmbedding3]; - -// Parallel retrieval -const results = await Promise.all( - queries.map(q => adapter.retrieveWithReasoning(q, { k: 5 })) -); -``` +Other bulk methods: `insertSkills`, `insertPatterns`, `batchInsertParallel`, `bulkUpdate`, +`bulkDelete`, `regenerateEmbeddings`. To remove stale rows use the CLI `prune` verbs below +(`BatchOperations#pruneData` fails in agentdb 3.10.0 with `no such column: ts`). --- -## Memory Optimization - -### Automatic Consolidation - -```typescript -// Enable automatic pattern consolidation -const result = await adapter.retrieveWithReasoning(queryEmbedding, { - domain: 'documents', - optimizeMemory: true, // Consolidate similar patterns - k: 10, -}); - -console.log('Optimizations:', result.optimizations); -// { -// consolidated: 15, // Merged 15 similar patterns -// pruned: 3, // Removed 3 low-quality patterns -// improved_quality: 0.12 // 12% quality improvement -// } -``` - -### Manual Optimization - -```typescript -// Manually trigger optimization -await adapter.optimize(); - -// Get statistics -const stats = await adapter.getStats(); -console.log('Before:', stats.totalPatterns); -console.log('After:', stats.totalPatterns); // Reduced by ~10-30% -``` - -### Pruning Strategies - -```typescript -// Prune low-confidence patterns -await adapter.prune({ - minConfidence: 0.5, // Remove confidence < 0.5 - minUsageCount: 2, // Remove usage_count < 2 - maxAge: 30 * 24 * 3600, // Remove >30 days old -}); -``` - ---- - -## Performance Monitoring - -### Database Statistics +## Memory Cleanup from the CLI ```bash -# Get comprehensive stats -npx agentdb@latest stats .agentdb/vectors.db +# Consolidate patterns and compress +npx agentdb@latest optimize-memory --compress true --consolidate-patterns true -# Output: -# Total Patterns: 125,430 -# Database Size: 47.2 MB (with binary quantization) -# Avg Confidence: 0.87 -# Domains: 15 -# Cache Hit Rate: 84% -# Index Type: HNSW -``` +# Prune low-value episodes, skills and causal edges +npx agentdb@latest reflexion prune 90 0.3 +npx agentdb@latest skill prune 3 0.4 60 +npx agentdb@latest learner prune 0.5 0.05 90 -### Runtime Metrics - -```typescript -const stats = await adapter.getStats(); - -console.log('Performance Metrics:'); -console.log('Total Patterns:', stats.totalPatterns); -console.log('Database Size:', stats.dbSize); -console.log('Avg Confidence:', stats.avgConfidence); -console.log('Cache Hit Rate:', stats.cacheHitRate); -console.log('Search Latency (avg):', stats.avgSearchLatency); -console.log('Insert Latency (avg):', stats.avgInsertLatency); -``` - ---- - -## Optimization Recipes - -### Recipe 1: Maximum Speed (Sacrifice Accuracy) - -```typescript -const adapter = await createAgentDBAdapter({ - quantizationType: 'binary', // 32x memory reduction - cacheSize: 5000, // Large cache - hnswM: 8, // Fewer connections = faster - hnswEfSearch: 50, // Low search quality = faster -}); - -// Expected: <50µs search, 90-95% accuracy -``` - -### Recipe 2: Balanced Performance - -```typescript -const adapter = await createAgentDBAdapter({ - quantizationType: 'scalar', // 4x memory reduction - cacheSize: 1000, // Standard cache - hnswM: 16, // Balanced connections - hnswEfSearch: 100, // Balanced quality -}); - -// Expected: <100µs search, 98-99% accuracy -``` - -### Recipe 3: Maximum Accuracy - -```typescript -const adapter = await createAgentDBAdapter({ - quantizationType: 'none', // No quantization - cacheSize: 2000, // Large cache - hnswM: 32, // Many connections - hnswEfSearch: 200, // High search quality -}); - -// Expected: <200µs search, 100% accuracy -``` - -### Recipe 4: Memory-Constrained (Mobile/Edge) - -```typescript -const adapter = await createAgentDBAdapter({ - quantizationType: 'binary', // 32x memory reduction - cacheSize: 100, // Small cache - hnswM: 8, // Minimal connections -}); - -// Expected: <100µs search, ~10MB for 100K vectors -``` - ---- - -## Scaling Strategies - -### Small Scale (<10K vectors) - -```typescript -const adapter = await createAgentDBAdapter({ - quantizationType: 'none', // Full precision - cacheSize: 500, - hnswM: 8, -}); -``` - -### Medium Scale (10K-100K vectors) - -```typescript -const adapter = await createAgentDBAdapter({ - quantizationType: 'scalar', // 4x reduction - cacheSize: 1000, - hnswM: 16, -}); -``` - -### Large Scale (100K-1M vectors) - -```typescript -const adapter = await createAgentDBAdapter({ - quantizationType: 'binary', // 32x reduction - cacheSize: 2000, - hnswM: 32, -}); -``` - -### Massive Scale (>1M vectors) - -```typescript -const adapter = await createAgentDBAdapter({ - quantizationType: 'product', // 8-16x reduction - cacheSize: 5000, - hnswM: 48, - hnswEfConstruction: 400, -}); +# Reclaim SQLite space +sqlite3 ./agentdb.db "VACUUM;" ``` --- ## Troubleshooting -### Issue: High memory usage +### High memory use +Move cold vectors into a `createScalar8BitStore` / `createProductQuantizedStore` store, or prune +with the commands above. Check `getStats().memoryUsageBytes` before and after. -```bash -# Check database size -npx agentdb@latest stats .agentdb/vectors.db +### Slow search +Check `db.vectorBackendName`; if it is not the backend you expected, see `agentdb doctor`. Keep +`k` as small as the task allows. -# Enable quantization -# Use 'binary' for 32x reduction -``` - -### Issue: Slow search performance - -```typescript -// Increase cache size -const adapter = await createAgentDBAdapter({ - cacheSize: 2000, // Increase from 1000 -}); - -// Reduce search quality (faster) -const result = await adapter.retrieveWithReasoning(queryEmbedding, { - k: 5, // Reduce from 10 -}); -``` - -### Issue: Low accuracy - -```typescript -// Disable or use lighter quantization -const adapter = await createAgentDBAdapter({ - quantizationType: 'scalar', // Instead of 'binary' - hnswEfSearch: 200, // Higher search quality -}); -``` - ---- - -## Performance Benchmarks - -**Test System**: AMD Ryzen 9 5950X, 64GB RAM - -| Operation | Vector Count | No Optimization | Optimized | Improvement | -|-----------|-------------|-----------------|-----------|-------------| -| Search | 10K | 15ms | 100µs | 150x | -| Search | 100K | 150ms | 120µs | 1,250x | -| Search | 1M | 100s | 8ms | 12,500x | -| Batch Insert (100) | - | 1s | 2ms | 500x | -| Memory Usage | 1M | 3GB | 96MB | 32x (binary) | +### Low recall after quantizing +Use 8-bit instead of 4-bit, or more PQ subspaces/centroids, and re-measure recall. --- ## Learn More -- **Quantization Paper**: docs/quantization-techniques.pdf -- **HNSW Algorithm**: docs/hnsw-index.pdf -- **GitHub**: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb -- **Website**: https://agentdb.ruv.io +- `npx agentdb@latest --help` - the full CLI reference for the installed version +- Type definitions: `node_modules/agentdb/dist/src/quantization/vector-quantization.d.ts`, + `core/QueryCache.d.ts`, `optimizations/BatchOperations.d.ts` +- Source: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb --- **Category**: Performance / Optimization **Difficulty**: Intermediate -**Estimated Time**: 20-30 minutes diff --git a/v3/@claude-flow/cli/__tests__/init-agentdb-skills-5161.test.ts b/v3/@claude-flow/cli/__tests__/init-agentdb-skills-5161.test.ts new file mode 100644 index 0000000000..95e1935dcb --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/init-agentdb-skills-5161.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from 'vitest'; +import { existsSync, readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { registeredToolNames, skillToolRefs } from '../../../../scripts/audit-skill-mcp-tools.mjs'; + +const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url)); +const SKILLS_ROOT = join(CLI_ROOT, '.claude', 'skills'); +const SKILLS = ['agentdb-advanced', 'agentdb-optimization', 'agentdb-learning'].map((name) => ({ + name, + file: join(SKILLS_ROOT, name, 'SKILL.md'), +})); + +// agentdb is a regular dependency of @claude-flow/cli, so it must resolve; no silent skip. +const requireFromCli = createRequire(join(CLI_ROOT, 'package.json')); +const AGENTDB_ROOT = dirname(requireFromCli.resolve('agentdb/package.json')); + +function readSkill(file: string): string { + expect(existsSync(file)).toBe(true); + const text = readFileSync(file, 'utf8'); + expect(text.length).toBeGreaterThan(0); + return text; +} + +/** Top-level verbs the shipped agentdb CLI dispatches, read from its own source. */ +function agentdbTopLevelVerbs(): Set { + const pkg = JSON.parse(readFileSync(join(AGENTDB_ROOT, 'package.json'), 'utf8')); + const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin.agentdb; + const source = readFileSync(join(AGENTDB_ROOT, bin), 'utf8'); + const start = source.indexOf("if (command === 'mcp')"); + const end = source.indexOf('Unknown command', start); + expect(start).toBeGreaterThan(-1); + expect(end).toBeGreaterThan(start); + const verbs = new Set(); + for (const m of source.slice(start, end).matchAll(/command === '([a-z][a-z-]*)'/g)) verbs.add(m[1]); + return verbs; +} + +/** Fenced code blocks only: the prose names the removed interfaces to warn against them. */ +function codeBlocks(text: string): string { + return [...text.matchAll(/^```[^\n]*\n([\s\S]*?)^```/gm)].map((m) => m[1]).join('\n'); +} + +function documentedVerbs(text: string): string[] { + return [...text.matchAll(/npx agentdb@latest ([a-z][a-z-]*)/g)].map((m) => m[1]); +} + +function importedNames(text: string): string[] { + const names: string[] = []; + for (const m of text.matchAll(/import\s*\{([^}]+)\}\s*from\s*'agentdb'/g)) { + for (const raw of m[1].split(',')) { + const name = raw.trim().split(/\s+as\s+/)[0]; + if (name) names.push(name); + } + } + return names; +} + +describe('init-installed AgentDB skills use shipped interfaces (#5161)', () => { + it('no longer teach the missing factory, plugin verbs or QUIC option in code', () => { + for (const { name, file } of SKILLS) { + const text = readSkill(file); + const code = codeBlocks(text); + expect(code.length, `${name} has no code blocks`).toBeGreaterThan(0); + for (const dead of [ + 'createAgentDBAdapter', + 'create-plugin', + 'list-templates', + 'list-plugins', + 'plugin-info', + 'enableQUICSync', + "from 'agentic-flow/reasoningbank'", + ]) { + expect(code, `${name} still uses ${dead}`).not.toContain(dead); + } + const description = /^description:\s*"([^"]*)"/m.exec(text)?.[1] ?? ''; + expect(description.length).toBeGreaterThan(0); + for (const claim of ['150x', '12,500x', '4-32x', 'QUIC']) { + expect(description, `${name} description still claims ${claim}`).not.toContain(claim); + } + } + }); + + it('only documents agentdb CLI verbs the shipped CLI dispatches', () => { + const verbs = agentdbTopLevelVerbs(); + expect(verbs.has('init')).toBe(true); + for (const { name, file } of SKILLS) { + const documented = documentedVerbs(readSkill(file)); + expect(documented.length, `${name} documents no agentdb verbs`).toBeGreaterThan(0); + expect(documented.filter((verb) => !verbs.has(verb)), name).toEqual([]); + } + }); + + it('only imports names the agentdb package exports', async () => { + const agentdb = await import(requireFromCli.resolve('agentdb')); + const exported = new Set(Object.keys(agentdb)); + let total = 0; + for (const { name, file } of SKILLS) { + const names = importedNames(readSkill(file)); + total += names.length; + expect(names.filter((n) => !exported.has(n)), name).toEqual([]); + } + expect(total).toBeGreaterThan(0); + }, 120_000); + + it('only references registered ruflo MCP tools', () => { + const registered = registeredToolNames(); + for (const { name, file } of SKILLS) { + const refs = skillToolRefs(readSkill(file)); + expect(refs.length, `${name} references no MCP tools`).toBeGreaterThan(0); + expect(refs.filter((ref) => !registered.has(ref.tool)).map((ref) => ref.tool), name).toEqual([]); + } + }); +});