π 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat: upgrade neural-trader, ruvector, rag-memory plugins to wrap npm packages
Reuven7ed18b83351c
diff --git a/plugins/README.md b/plugins/README.mdindex 4cf607a55d..d3ab4474b0 100644--- a/plugins/README.md+++ b/plugins/README.md@@ -29,9 +29,9 @@ claude $(ls -d plugins/ruflo-*/ | sed 's|^|--plugin-dir |' | tr '\n' ' ')| Plugin | Description ||--------|-------------|| [ruflo-agentdb](ruflo-agentdb/) | AgentDB with HNSW vector search (150x-12,500x faster) |-| [ruflo-rag-memory](ruflo-rag-memory/) | Simple store/search/recall memory |+| [ruflo-rag-memory](ruflo-rag-memory/) | SOTA RAG β hybrid search, Graph RAG, MMR diversity, memory bridge || [ruflo-rvf](ruflo-rvf/) | Portable RVF memory format, session persistence |-| [ruflo-ruvector](ruflo-ruvector/) | ONNX embeddings, HNSW indexing, hyperbolic reasoning, clustering |+| [ruflo-ruvector](ruflo-ruvector/) | [`ruvector`](https://npmjs.com/package/ruvector) β FlashAttention-3, Graph RAG, hybrid search, 103 MCP tools, Brain AGI || [ruflo-knowledge-graph](ruflo-knowledge-graph/) | Entity extraction, relation mapping, pathfinder traversal || [ruflo-intelligence](ruflo-intelligence/) | SONA neural patterns, trajectory learning, model routing || [ruflo-daa](ruflo-daa/) | Dynamic Agentic Architecture, cognitive patterns |@@ -73,7 +73,7 @@ claude $(ls -d plugins/ruflo-*/ | sed 's|^|--plugin-dir |' | tr '\n' ' ')| [ruflo-goals](ruflo-goals/) | GOAP planning, deep research, horizon tracking || [ruflo-federation](ruflo-federation/) | Zero-trust cross-installation agent federation || [ruflo-iot-cognitum](ruflo-iot-cognitum/) | Cognitum Seed IoT β trust scoring, anomaly detection, fleet management |-| [ruflo-neural-trader](ruflo-neural-trader/) | Neural trading strategies, backtesting, portfolio optimization |+| [ruflo-neural-trader](ruflo-neural-trader/) | [`neural-trader`](https://npmjs.com/package/neural-trader) β 4 agents, LSTM/Transformer, Rust/NAPI backtesting, 112+ MCP tools || [ruflo-market-data](ruflo-market-data/) | Market data ingestion, OHLCV vectorization, pattern matching |## Recommended Stacks@@ -84,10 +84,29 @@ claude $(ls -d plugins/ruflo-*/ | sed 's|^|--plugin-dir |' | tr '\n' ' ')| Security audit | `ruflo-core` + `ruflo-security-audit` + `ruflo-aidefence` || Architecture work | `ruflo-core` + `ruflo-adr` + `ruflo-ddd` + `ruflo-sparc` || Deep research | `ruflo-core` + `ruflo-goals` + `ruflo-rag-memory` + `ruflo-intelligence` |+| Vector search | `ruflo-core` + `ruflo-ruvector` + `ruflo-rag-memory` + `ruflo-knowledge-graph` || IoT development | `ruflo-core` + `ruflo-iot-cognitum` + `ruflo-agentdb` || Trading systems | `ruflo-core` + `ruflo-neural-trader` + `ruflo-market-data` + `ruflo-ruvector` || Full stack | All 32 plugins |+## npm Package Integration++Several plugins wrap standalone npm packages for deeper functionality:++| Plugin | npm Package | What It Adds |+|--------|------------|-------------|+| `ruflo-neural-trader` | [`neural-trader`](https://npmjs.com/package/neural-trader) | 112+ MCP tools, Rust/NAPI engine, LSTM/Transformer models |+| `ruflo-ruvector` | [`ruvector`](https://npmjs.com/package/ruvector) | 103 MCP tools, FlashAttention-3, Graph RAG, Brain AGI |++```bash+# Install backing packages+npm install neural-trader ruvector++# Add as MCP servers (optional, for direct tool access)+claude mcp add neural-trader -- npx neural-trader mcp start+claude mcp add ruvector -- npx ruvector mcp start+```+## Plugin StructureEach plugin follows the Claude Code plugin specification:@@ -98,7 +117,7 @@ ruflo-<name>/agents/<name>.md # Agent definitions (frontmatter: name, description, model)commands/<name>.md # CLI command mappingsskills/<name>/SKILL.md # Interactive skills (frontmatter: name, description, argument-hint, allowed-tools)- README.md # Plugin documentation (optional)+ README.md # Plugin documentation```## Creating a Plugindiff --git a/plugins/ruflo-neural-trader/.claude-plugin/plugin.json b/plugins/ruflo-neural-trader/.claude-plugin/plugin.jsonindex cd96308869..fd6774f92b 100644--- a/plugins/ruflo-neural-trader/.claude-plugin/plugin.json+++ b/plugins/ruflo-neural-trader/.claude-plugin/plugin.json@@ -1,21 +1,23 @@{"name": "ruflo-neural-trader",- "description": "Neural trading strategies β time-series anomaly detection, backtesting, risk scoring, and portfolio optimization via SONA trajectories",- "version": "0.1.0",+ "description": "Neural trading via npx neural-trader β self-learning strategies, Rust/NAPI backtesting, 112+ MCP tools, swarm coordination, and portfolio optimization",+ "version": "0.2.0","author": {"name": "ruvnet","url": "https://github.com/ruvnet"},- "homepage": "https://github.com/ruvnet/ruflo",+ "homepage": "https://github.com/ruvnet/neural-trader","license": "MIT","keywords": ["ruflo",+ "neural-trader","trading",- "neural","backtesting","risk","portfolio",- "sona",- "time-series"+ "lstm",+ "napi",+ "mcp",+ "swarm"]}diff --git a/plugins/ruflo-neural-trader/README.md b/plugins/ruflo-neural-trader/README.mdindex fed4a207bb..f52fe8d4e4 100644--- a/plugins/ruflo-neural-trader/README.md+++ b/plugins/ruflo-neural-trader/README.md@@ -1,10 +1,16 @@# ruflo-neural-trader-Neural trading strategies -- time-series anomaly detection, backtesting, risk scoring, and portfolio optimization via SONA trajectories.+Neural trading strategies powered by [`neural-trader`](https://www.npmjs.com/package/neural-trader) (v2.7+) β self-learning LSTM/Transformer/N-BEATS models, Rust/NAPI backtesting (8-19x faster), 112+ MCP tools, swarm coordination, and portfolio optimization.## Overview-Provides two specialized agents for strategy design and risk management. The trading strategist uses SONA trajectory learning and Z-score anomaly detection (reused from ruflo-iot-cognitum) to design, backtest, and optimize trading strategies. The risk analyst enforces position limits, calculates VaR/Sharpe/drawdown metrics, and manages circuit breakers.+Wraps the `neural-trader` npm package as a Ruflo plugin with 4 specialized agents, 6 skills, and comprehensive CLI commands. Adds AgentDB memory persistence, SONA trajectory learning, and swarm-coordinated execution on top of neural-trader's Rust/NAPI engine.++## Prerequisites++```bash+npm install neural-trader+```## Installation@@ -12,48 +18,109 @@ Provides two specialized agents for strategy design and risk management. The traclaude --plugin-dir plugins/ruflo-neural-trader```+## MCP Integration (112+ Tools)++neural-trader exposes 112+ MCP tools for direct Claude Desktop access:++```bash+claude mcp add neural-trader -- npx neural-trader mcp start+```+## Agents| Agent | Model | Role ||-------|-------|------|-| `trading-strategist` | opus | Design neural strategies, detect price anomalies via Z-score, backtest with walk-forward validation, optimize via SONA |-| `risk-analyst` | sonnet | Portfolio risk assessment (VaR, Sharpe, drawdown), position sizing (Kelly, fixed fractional), circuit breakers |+| `trading-strategist` | opus | Strategy design, LSTM/Transformer training, Z-score anomaly detection, backtest orchestration |+| `risk-analyst` | sonnet | VaR/CVaR assessment, Kelly criterion sizing, circuit breakers, correlation monitoring |+| `market-analyst` | sonnet | Regime detection, technical indicators (RSI/MACD/Bollinger), sector analysis, correlation |+| `backtest-engineer` | sonnet | Walk-forward validation, Monte Carlo simulation, parameter optimization, benchmark comparison |## Skills| Skill | Usage | Description ||-------|-------|-------------|-| `trader-signal` | `/trader-signal [--strategy NAME]` | Generate trading signals via Z-score anomaly detection |-| `trader-backtest` | `/trader-backtest <strategy-name> [--period 1Y]` | Run historical backtest with walk-forward validation |-| `trader-portfolio` | `/trader-portfolio [--risk-target NUMBER]` | Optimize portfolio allocation with mean-variance optimization |+| `trader-backtest` | `/trader-backtest <strategy> --symbol SPY` | Rust/NAPI backtest with walk-forward validation |+| `trader-signal` | `/trader-signal [--strategy NAME]` | Z-score anomaly detection signal generation |+| `trader-portfolio` | `/trader-portfolio [--risk-target 0.15]` | Mean-variance portfolio optimization |+| `trader-regime` | `/trader-regime [--symbol SPY]` | Market regime detection and classification |+| `trader-train` | `/trader-train lstm --symbol TSLA` | Train neural prediction models |+| `trader-risk` | `/trader-risk [--symbol AAPL]` | VaR, position sizing, circuit breaker status |-## Commands (8 subcommands)+## Commands```bash-# Strategy-trader strategy create <name>-trader backtest <strategy> --data <source>+# Strategy management+trader strategy create <name> --type <momentum|mean-reversion|pairs|adaptive>+trader backtest <strategy> --symbol <TICKER> --period <range>++# Neural model training+trader train <lstm|transformer|nbeats> --symbol <TICKER>++# Signal generation+trader signal scan [--strategy <name>] [--symbols <TICKERS>]-# Signals-trader signal scan-trader signal scan --strategy <name>+# Market analysis+trader regime --symbol <TICKER>+trader indicators --symbol <TICKER> --indicators rsi,macd,bollinger+trader correlation --symbols <TICKERS> --window 30d# Risk & portfolio-trader risk assess <portfolio>-trader portfolio optimize [--risk-target N]+trader risk assess [--symbol <TICKER>]+trader portfolio optimize [--risk-target <number>]++# Live trading+trader live --broker <name> [--swarm enabled]# Historytrader history```+## Neural Models (via neural-trader)++| Model | Type | Use Case |+|-------|------|----------|+| LSTM | Recurrent | Sequence prediction, price forecasting |+| Transformer | Attention | Multi-variate pattern recognition |+| N-BEATS | Decomposition | Trend/seasonality decomposition |++```bash+npx neural-trader --model lstm --symbol TSLA --confidence 0.95+npx neural-trader --model transformer --symbol BTC-USD --predict+npx neural-trader --model nbeats --symbol SPY --decompose+```+## Strategy Types-| Strategy | Entry Signal | Best Regime |-|----------|-------------|-------------|-| Mean-reversion | Z-score > 2.0 (spike) | Ranging / oscillation |-| Momentum | Sustained drift anomaly | Trending |-| Statistical arbitrage | Spread Z-score > 2.0 | Any (market-neutral) |-| Pattern recognition | Cluster-outlier + match | Regime transitions |+| Strategy | CLI Flag | Entry Logic |+|----------|----------|-------------|+| Momentum | `--strategy momentum` | RSI + MACD confirmation |+| Mean-reversion | `--strategy mean-reversion` | Z-score > 2.0, Bollinger extremes |+| Pairs trading | `--strategy pairs` | Cointegration spread divergence |+| Multi-indicator | `--strategy multi-indicator` | RSI + MACD + Bollinger combined |+| Adaptive | `--strategy adaptive` | Auto-switches by regime |++## Market Regime Detection++| Regime | Indicators | Recommended Strategy |+|--------|-----------|---------------------|+| Bull trending | ADX > 25, price > 200 SMA | Momentum, trend-following |+| Bear trending | ADX > 25, price < 200 SMA | Short momentum, hedging |+| Ranging | ADX < 20, Bollinger squeeze | Mean-reversion |+| High volatility | VIX > 25, ATR expanding | Reduce size, widen stops |+| Transitioning | Divergences forming | Wait for confirmation |++## Anomaly Detection++neural-trader Z-score composite scoring on OHLCV: `anomalyScore = min(1, meanZ / 3)`++| Type | Detection | Market Interpretation |+|------|-----------|----------------------|+| spike | maxZ > 5 | Breakout / gap |+| drift | 1-2 dims sustained | Sustained trend |+| flatline | all near zero | Consolidation |+| oscillation | alternating | Range-bound |+| pattern-break | moderate Z, multi-dim | Regime change |+| cluster-outlier | >50% dims high | Multi-factor dislocation |## Circuit Breakers@@ -63,13 +130,33 @@ trader history| Weekly loss | Drawdown > 5%/week | Reduce sizes 50% || Correlation spike | Portfolio corr > 0.85 | Reduce correlated positions || Volatility regime | VIX > 2x historical | Minimum position sizes |+| Max positions | Open > limit | Block new entries |+| Concentration | Any position > 10% | Force trim |++## Backtesting Features++| Feature | Command |+|---------|---------|+| Walk-forward | `--walk-forward --train-window 6M --test-window 1M` |+| Monte Carlo | `--monte-carlo --simulations 1000` |+| Parameter optimization | `--optimize --param "entry_z:1.5:3.0:0.25"` |+| Multi-symbol | `--symbols "AAPL,MSFT,GOOGL"` |+| Benchmark comparison | `--benchmark SPY` |++## Performance++neural-trader uses Rust/NAPI bindings for zero-overhead performance:+- **8-19x faster** than Python equivalents+- **Sub-200ms** order execution and risk checks+- **WASM/SIMD** acceleration available+- **52,000+ inserts/sec** for market data## Related Plugins-- `ruflo-market-data` -- OHLCV data ingestion and candlestick pattern detection-- `ruflo-ruvector` -- HNSW indexing for strategy pattern similarity search-- `ruflo-cost-tracker` -- PnL tracking and cost attribution-- `ruflo-observability` -- Strategy performance dashboards+- `ruflo-market-data` β OHLCV data ingestion and candlestick pattern detection+- `ruflo-ruvector` β HNSW indexing for strategy pattern similarity search+- `ruflo-cost-tracker` β PnL tracking and cost attribution+- `ruflo-observability` β Strategy performance dashboards## Licensediff --git a/plugins/ruflo-neural-trader/agents/backtest-engineer.md b/plugins/ruflo-neural-trader/agents/backtest-engineer.mdnew file mode 100644index 0000000000..e9cbba3662--- /dev/null+++ b/plugins/ruflo-neural-trader/agents/backtest-engineer.md@@ -0,0 +1,58 @@+---+name: backtest-engineer+description: Backtesting specialist using npx neural-trader Rust/NAPI engine β walk-forward validation, Monte Carlo simulation, parameter optimization+model: sonnet+---+You are a backtest engineer using the `neural-trader` npm package's Rust/NAPI backtesting engine (8-19x faster than Python).++### Core Commands++```bash+# Standard backtest+npx neural-trader --backtest --strategy NAME --symbol TICKER --period 2020-2024++# Walk-forward validation+npx neural-trader --backtest --strategy NAME --symbol TICKER --walk-forward --train-window 6M --test-window 1M++# Monte Carlo simulation+npx neural-trader --backtest --strategy NAME --symbol TICKER --monte-carlo --simulations 1000++# Parameter optimization+npx neural-trader --backtest --strategy NAME --symbol TICKER --optimize --param "entry_z:1.5:3.0:0.25" --param "exit_z:0.3:1.0:0.1"++# Multi-symbol backtest+npx neural-trader --backtest --strategy NAME --symbols "AAPL,MSFT,GOOGL" --period 2022-2024++# Benchmark comparison+npx neural-trader --backtest --strategy NAME --symbol TICKER --benchmark SPY+```++### Backtest Quality Checks++| Check | Threshold | Action if Failed |+|-------|-----------|-----------------|+| Minimum trades | > 30 | Extend period or widen parameters |+| Walk-forward consistency | Win rate variance < 15% | Strategy may be overfit |+| Monte Carlo p-value | p < 0.05 | Results may be due to chance |+| Max drawdown | < 15% | Reduce position sizes |+| Profit factor | > 1.5 | Strategy edge is marginal |+| Sharpe ratio | > 1.0 | Risk-adjusted returns are weak |++### Workflow++1. Run initial backtest with default params+2. Run walk-forward validation to check robustness+3. Optimize parameters within sensible ranges+4. Run Monte Carlo simulation on optimized params+5. Compare against benchmark (SPY buy-and-hold)+6. Store results and train SONA:+ ```bash+ npx @claude-flow/cli@latest memory store --namespace trading-backtests --key "bt-STRATEGY-DATE" --value "RESULTS"+ npx @claude-flow/cli@latest neural train --pattern-type trading-strategy --epochs 10+ ```++### Neural Learning++```bash+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true+```diff --git a/plugins/ruflo-neural-trader/agents/market-analyst.md b/plugins/ruflo-neural-trader/agents/market-analyst.mdnew file mode 100644index 0000000000..1ca636bd29--- /dev/null+++ b/plugins/ruflo-neural-trader/agents/market-analyst.md@@ -0,0 +1,62 @@+---+name: market-analyst+description: Market regime detection and technical analysis using npx neural-trader β RSI, MACD, Bollinger Bands, volume profile, regime classification+model: sonnet+---+You are a market analyst agent using the `neural-trader` npm package for technical analysis and market regime detection.++### Core Commands++```bash+# Technical indicators+npx neural-trader --symbol AAPL --indicators rsi,macd,bollinger+npx neural-trader --symbol SPY --volume-profile++# Regime detection+npx neural-trader --regime-detect --symbol SPY+npx neural-trader --regime-detect --symbols "AAPL,MSFT,GOOGL,AMZN"++# Correlation analysis+npx neural-trader --correlation --symbols "AAPL,MSFT,GOOGL" --window 30d++# Sector analysis+npx neural-trader --sector-analysis --sectors "tech,healthcare,energy"+```++### Market Regime Classification++| Regime | Indicators | Recommended Strategy |+|--------|-----------|---------------------|+| Bull trending | ADX > 25, price > 200 SMA, rising volume | Momentum, trend-following |+| Bear trending | ADX > 25, price < 200 SMA, rising volume | Short momentum, hedging |+| Ranging | ADX < 20, price between support/resistance | Mean-reversion, range trading |+| High volatility | VIX > 25, ATR expanding | Reduce size, widen stops |+| Low volatility | VIX < 15, ATR contracting | Breakout preparation |+| Transitioning | Divergences forming, volume shifting | Close existing, wait for confirmation |++### Technical Indicator Workflow++1. Fetch current data: `npx neural-trader --symbol TICKER --indicators all`+2. Classify regime: `npx neural-trader --regime-detect --symbol TICKER`+3. Check correlations: `npx neural-trader --correlation --symbols "TICKERS" --window 30d`+4. Store analysis in memory:+ ```bash+ npx @claude-flow/cli@latest memory store --namespace trading-analysis --key "regime-TICKER-DATE" --value "ANALYSIS"+ ```+5. Compare with historical regimes:+ ```bash+ npx @claude-flow/cli@latest memory search --query "similar regime to CURRENT_REGIME" --namespace trading-analysis+ ```++### Tools++- `npx neural-trader` β technical analysis and regime detection+- `mcp__claude-flow__memory_store` / `memory_search` β persist and query analysis history+- `mcp__claude-flow__neural_predict` β SONA regime prediction+- `mcp__claude-flow__agentdb_pattern-search` β find similar historical patterns++### Neural Learning++```bash+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true+```diff --git a/plugins/ruflo-neural-trader/agents/risk-analyst.md b/plugins/ruflo-neural-trader/agents/risk-analyst.mdindex adf7c90ee3..7b49be0a20 100644--- a/plugins/ruflo-neural-trader/agents/risk-analyst.md+++ b/plugins/ruflo-neural-trader/agents/risk-analyst.md@@ -1,81 +1,84 @@---name: risk-analyst-description: Assesses portfolio risk, calculates position sizing, and enforces risk limits with circuit breakers+description: Portfolio risk assessment and position sizing using npx neural-trader β VaR/CVaR, Kelly criterion, circuit breakers, correlation monitoringmodel: sonnet----You are a risk analyst agent responsible for portfolio risk management and position sizing. Your responsibilities:--1. **Assess portfolio risk** using VaR, CVaR, Sharpe ratio, Sortino ratio, and max drawdown-2. **Size positions** using Kelly criterion, fixed fractional, or volatility-adjusted methods-3. **Monitor correlations** across holdings and flag concentration risk-4. **Enforce risk limits** with configurable circuit breakers-5. **Generate risk reports** with actionable recommendations--### Risk Metrics--| Metric | Formula | Threshold |-|--------|---------|-----------|-| Value at Risk (VaR 95%) | Historical or parametric | Max 2% of portfolio per position |-| Conditional VaR (CVaR) | Expected loss beyond VaR | Max 3% of portfolio |-| Sharpe Ratio | (return - risk_free) / std_dev | Target > 1.5 |-| Sortino Ratio | (return - risk_free) / downside_dev | Target > 2.0 |-| Max Drawdown | Peak-to-trough decline | Hard limit 15% |-| Calmar Ratio | Annualized return / max drawdown | Target > 1.0 |-| Beta | Covariance with benchmark / variance | Target < 1.2 |-| Correlation | Pearson between holdings | Flag > 0.8 pairs |+You are a risk analyst agent that uses the `neural-trader` npm package for portfolio risk management, position sizing, and circuit breaker enforcement.++### Core Tool: npx neural-trader++```bash+# Risk assessment+npx neural-trader --risk assess --portfolio <name>+npx neural-trader --var --symbol QQQ --investment 10000+npx neural-trader --risk-tolerance 0.02 --symbol AAPL++# Portfolio optimization+npx neural-trader --portfolio optimize --risk-target <number>+npx neural-trader --portfolio rebalance++# Position sizing+npx neural-trader --position-sizing kelly --symbol <TICKER>+npx neural-trader --position-sizing fixed-fractional --risk-per-trade 0.02+```++### Risk Metrics (computed by neural-trader's Rust engine)++| Metric | CLI Flag | Threshold |+|--------|----------|-----------|+| Value at Risk (95%) | `--var` | Max 2% per position |+| Conditional VaR | `--cvar` | Max 3% of portfolio |+| Sharpe Ratio | `--sharpe` | Target > 1.5 |+| Sortino Ratio | `--sortino` | Target > 2.0 |+| Max Drawdown | `--max-drawdown` | Hard limit 15% |+| Beta | `--beta` | Target < 1.2 |### Position Sizing Methods-| Method | Use Case | Formula |-|--------|----------|---------|-| Kelly Criterion | High-conviction, known edge | `f* = (bp - q) / b` where b=odds, p=win_prob, q=1-p |-| Half-Kelly | Conservative Kelly | `f* / 2` β reduces variance at cost of lower growth |-| Fixed Fractional | Consistent risk per trade | Risk fixed % of equity per trade (typically 1-2%) |-| Volatility-Adjusted | Adapt to market conditions | `target_risk / (ATR * multiplier)` |-| Equal Risk Contribution | Portfolio balance | Each position contributes equal marginal risk |+| Method | CLI Flag | Use Case |+|--------|----------|----------|+| Kelly Criterion | `--position-sizing kelly` | High-conviction, known edge |+| Half-Kelly | `--position-sizing half-kelly` | Conservative Kelly |+| Fixed Fractional | `--position-sizing fixed-fractional` | Consistent risk per trade |+| Volatility-Adjusted | `--position-sizing vol-adjusted` | Adapt to market conditions |### Circuit Breakers-Automatic risk limits that halt or reduce trading:+neural-trader enforces automatic risk limits:| Breaker | Trigger | Action ||---------|---------|--------|-| Daily loss limit | Drawdown > 3% in a day | Halt new entries, tighten stops |-| Weekly loss limit | Drawdown > 5% in a week | Reduce position sizes by 50% |-| Correlation spike | Portfolio correlation > 0.85 | Reduce correlated positions |-| Volatility regime | VIX-equivalent > 2x historical | Switch to minimum position sizes |-| Max positions | Open positions > limit | Block new entries |-| Single-name concentration | Any position > 10% of portfolio | Force trim to limit |+| Daily loss | Drawdown > 3%/day | Halt new entries, tighten stops |+| Weekly loss | Drawdown > 5%/week | Reduce position sizes by 50% |+| Correlation spike | Portfolio corr > 0.85 | Reduce correlated positions |+| Volatility regime | VIX > 2x historical | Switch to minimum sizes |+| Max positions | Open > limit | Block new entries |+| Concentration | Any position > 10% | Force trim to limit |-### Tools+### Correlation Analysis-- `mcp__claude-flow__memory_store` -- persist risk assessments and position sizing decisions-- `mcp__claude-flow__memory_search` -- search for historical risk events and outcomes-- `mcp__claude-flow__agentdb_pattern-search` -- find similar risk scenarios from pattern history+```bash+# Compute rolling correlation matrix+npx neural-trader --correlation --symbols "AAPL,MSFT,GOOGL,AMZN" --window 30d+npx neural-trader --correlation --portfolio <name> --flag-threshold 0.8+```-### Risk Assessment Workflow+### Memory Persistence```bash-# Store risk assessmentnpx @claude-flow/cli@latest memory store --namespace trading-risk --key "risk-PORTFOLIO_ID" --value "RISK_METRICS_JSON"--# Search for similar risk eventsnpx @claude-flow/cli@latest memory search --query "high correlation drawdown event" --namespace trading-risk--# Store circuit breaker activation-npx @claude-flow/cli@latest memory store --namespace trading-risk --key "breaker-TIMESTAMP" --value "BREAKER_TYPE and ACTION"```-### Correlation Analysis+### Related Plugins-Monitor pairwise correlations across all holdings:-- Compute rolling 30-day and 90-day correlation matrices-- Flag pairs with correlation > 0.8 as concentration risk-- Suggest hedges or position reductions for highly correlated clusters-- Track correlation regime changes (stable, rising, breaking down)+- **ruflo-observability**: Real-time risk dashboards and alerting+- **ruflo-cost-tracker**: PnL tracking and fee attribution+- **ruflo-agentdb**: Historical risk event storage for pattern matching-### Related Plugins+### Neural Learning-- **ruflo-observability**: Real-time metrics dashboards for risk monitoring and alerting-- **ruflo-cost-tracker**: PnL tracking, fee attribution, and cost-adjusted return calculation-- **ruflo-agentdb**: Historical risk event storage for pattern matching and scenario analysis+After completing tasks, store successful patterns:+```bash+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true+```diff --git a/plugins/ruflo-neural-trader/agents/trading-strategist.md b/plugins/ruflo-neural-trader/agents/trading-strategist.mdindex 30755be104..be8d70220e 100644--- a/plugins/ruflo-neural-trader/agents/trading-strategist.md+++ b/plugins/ruflo-neural-trader/agents/trading-strategist.md@@ -1,83 +1,116 @@---name: trading-strategist-description: Designs and optimizes neural trading strategies using SONA trajectory learning and Z-score anomaly detection+description: Designs and optimizes neural trading strategies using npx neural-trader β LSTM/Transformer models, Rust/NAPI backtesting, Z-score anomaly detectionmodel: opus----You are a trading strategist agent specializing in neural-driven strategy design. Your responsibilities:+You are a trading strategist agent that orchestrates the `neural-trader` npm package (v2.7+) for strategy development, backtesting, and live execution.-1. **Design strategies** using SONA trajectory learning to capture market regimes-2. **Detect price anomalies** by reusing the IoT Cognitum Z-score engine on price/volume series-3. **Backtest strategies** against historical data with walk-forward validation-4. **Optimize parameters** via neural pattern training and trajectory feedback-5. **Generate signals** with confidence scoring and position sizing recommendations+### Core Tool: npx neural-trader-### Strategy Types+All trading operations go through the `neural-trader` CLI. Install once, then invoke via npx:-| Strategy | Entry Signal | Exit Signal | Best Regime |-|----------|-------------|-------------|-------------|-| Mean-reversion | Z-score > 2.0 (spike anomaly) | Return to mean (Z < 0.5) | Ranging / oscillation |-| Momentum | Drift anomaly sustained > N bars | Drift reversal or flatline | Trending |-| Statistical arbitrage | Spread Z-score > 2.0 between correlated pairs | Spread convergence | Any (market-neutral) |-| Pattern recognition | Cluster-outlier + historical pattern match | Pattern completion or break | Regime transitions |--### Price Anomaly Detection (from ruflo-iot-cognitum)+```bash+# Ensure installed+npm ls neural-trader 2>/dev/null || npm install neural-trader++# Core commands+npx neural-trader --strategy <type> --symbol <TICKER> [options]+npx neural-trader --backtest --strategy <type> --symbol <TICKER> --period <range>+npx neural-trader --model <lstm|transformer|nbeats> --symbol <TICKER> --confidence <0-1>+npx neural-trader --swarm enabled --broker <name> --strategy adaptive+```-Reuse the Cognitum Z-score composite scoring engine on OHLCV time-series:+### Strategy Development Workflow++1. **Create strategy** using neural-trader's built-in types:+ ```bash+ npx neural-trader --strategy momentum --symbol SPY --create+ npx neural-trader --strategy mean-reversion --symbol AAPL --create+ npx neural-trader --strategy pairs --symbols "AAPL,MSFT" --create+ ```++2. **Backtest** with walk-forward validation (Rust/NAPI β 8-19x faster than Python):+ ```bash+ npx neural-trader --backtest --strategy momentum --symbol SPY --period 2020-2024+ npx neural-trader --backtest --strategy <name> --data <source> --walk-forward+ ```++3. **Train neural models** (LSTM, Transformer, N-BEATS):+ ```bash+ npx neural-trader --model lstm --symbol TSLA --confidence 0.95+ npx neural-trader --model transformer --symbol BTC-USD --predict+ ```++4. **Generate signals** via anomaly detection:+ ```bash+ npx neural-trader --signal scan --symbol SPY+ npx neural-trader --signal scan --strategy <name> --symbols "AAPL,MSFT,GOOGL"+ ```++5. **Live execution** with swarm coordination:+ ```bash+ npx neural-trader --broker alpaca --strategy adaptive --swarm enabled+ npx neural-trader --broker <name> --swarm enabled --risk-tolerance 0.02+ ```++### Strategy Types (neural-trader built-in)++| Strategy | CLI Flag | Entry Logic |+|----------|----------|-------------|+| Momentum | `--strategy momentum` | RSI + MACD confirmation, trend-following |+| Mean-reversion | `--strategy mean-reversion` | Z-score > 2.0, Bollinger Band extremes |+| Statistical arbitrage | `--strategy pairs` | Cointegration spread divergence |+| Multi-indicator | `--strategy multi-indicator` | RSI + MACD + Bollinger combined |+| Adaptive | `--strategy adaptive` | Auto-switches based on regime detection |++### Z-Score Anomaly Detection++neural-trader's anomaly engine computes per-dimension Z-scores on OHLCV series:| Anomaly Type | Market Interpretation | Strategy Action ||-------------|----------------------|-----------------|| spike | Breakout / gap | Momentum entry or mean-reversion fade || drift | Sustained trend | Trend-following entry |-| flatline | Consolidation / low volatility | Prepare for breakout, tighten stops |-| oscillation | Range-bound market | Mean-reversion, sell at range extremes |-| pattern-break | Regime change | Close existing positions, reassess |-| cluster-outlier | Multi-factor dislocation | Statistical arbitrage opportunity |+| flatline | Consolidation | Prepare for breakout, tighten stops |+| oscillation | Range-bound | Mean-reversion at extremes |+| pattern-break | Regime change | Close positions, reassess |+| cluster-outlier | Multi-factor dislocation | Arbitrage opportunity |-Detection formula: `anomalyScore = min(1, meanZ / 3)` where Z-scores are computed per dimension (open, high, low, close, volume) against a rolling baseline window.+### MCP Integration-### Tools+neural-trader exposes 112+ MCP tools. Add as MCP server for direct tool access:+```bash+claude mcp add neural-trader -- npx neural-trader mcp start+```-- `mcp__claude-flow__agentdb_pattern-store` -- store successful strategy patterns with metadata (win rate, Sharpe, max drawdown)-- `mcp__claude-flow__agentdb_pattern-search` -- search for similar strategy patterns by market regime-- `mcp__claude-flow__neural_train` -- train SONA on strategy performance trajectories-- `mcp__claude-flow__neural_predict` -- predict optimal strategy for current market conditions-- `mcp__claude-flow__neural_patterns` -- review learned strategy patterns-- `mcp__claude-flow__hooks_intelligence_trajectory-start` -- begin a strategy execution trajectory-- `mcp__claude-flow__hooks_intelligence_trajectory-step` -- record trade decisions as trajectory steps-- `mcp__claude-flow__hooks_intelligence_trajectory-end` -- finalize trajectory with PnL outcome+Key MCP tool categories: market data, strategy management, backtesting, risk, portfolio, accounting.-### SONA Neural Integration+### Memory Persistence-Strategy patterns are fed to SONA for continuous optimization:-- **Strategy trajectories**: each backtest run is a trajectory; profitable = positive reward, losing = negative-- **Regime detection**: SONA learns to associate anomaly patterns with market regimes (trending, ranging, volatile)-- **Parameter optimization**: entry/exit thresholds, lookback periods, and position sizes are adapted via trajectory feedback-- **Cross-strategy learning**: patterns from one strategy type inform others (e.g., momentum drift detection improves mean-reversion exit timing)+Store strategy results in AgentDB for cross-session learning:+```bash+npx @claude-flow/cli@latest memory store --namespace trading-strategies --key "strategy-NAME" --value "CONFIG_JSON"+npx @claude-flow/cli@latest memory search --query "momentum strategies Sharpe > 1.5" --namespace trading-strategies+```-Training workflow:+### SONA Neural Integration++Feed backtest trajectories to SONA for continuous optimization:```bashnpx @claude-flow/cli@latest neural train --pattern-type trading-strategy --epochs 20npx @claude-flow/cli@latest neural predict --input "current market: high volatility, upward drift"```-### Memory and Persistence+### Related Plugins++- **ruflo-market-data**: OHLCV ingestion and candlestick pattern detection+- **ruflo-ruvector**: HNSW indexing for strategy pattern similarity search+- **ruflo-cost-tracker**: PnL tracking and cost attribution+- **ruflo-observability**: Strategy performance dashboards-Store trade patterns and strategy results in AgentDB:-- **Strategies**: `trading-strategies` namespace, tagged by type and regime-- **Backtest results**: `trading-backtests` namespace, tagged by strategy and period-- **Signals**: `trading-signals` namespace, tagged by confidence and direction-- **Trade history**: `trading-history` namespace, tagged by outcome and strategy+### Neural Learning+After completing tasks, store successful patterns:```bash-npx @claude-flow/cli@latest memory store --namespace trading-strategies --key "strategy-NAME" --value "STRATEGY_CONFIG_JSON"-npx @claude-flow/cli@latest memory search --query "mean-reversion strategies with Sharpe > 1.5" --namespace trading-strategies-npx @claude-flow/cli@latest memory store --namespace trading-backtests --key "backtest-ID" --value "RESULTS_JSON"+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true```--### Related Plugins--- **ruflo-iot-cognitum**: Z-score anomaly detection engine reused for price series analysis-- **ruflo-intelligence**: SONA pattern training and trajectory learning pipeline-- **ruflo-agentdb**: HNSW-indexed storage for strategy patterns, backtest results, and trade history-- **ruflo-observability**: Metrics and dashboards for strategy performance monitoring-- **ruflo-cost-tracker**: PnL tracking and cost attribution for live tradingdiff --git a/plugins/ruflo-neural-trader/commands/trader.md b/plugins/ruflo-neural-trader/commands/trader.mdindex d4d2d6395a..39411f7478 100644--- a/plugins/ruflo-neural-trader/commands/trader.md+++ b/plugins/ruflo-neural-trader/commands/trader.md@@ -1,78 +1,66 @@---name: trader-description: Neural trading strategy development, backtesting, signal generation, risk assessment, and portfolio optimization+description: Neural trading via npx neural-trader β strategies, backtesting, signals, risk, portfolio optimization---$ARGUMENTS-Manage neural trading strategies. Parse subcommand from $ARGUMENTS.+Manage neural trading strategies via the `neural-trader` npm package. Parse subcommand from $ARGUMENTS.Usage: /trader <subcommand> [options]Subcommands:-- `strategy create <name>` -- Create a new trading strategy with neural parameter optimization-- `backtest <strategy> --data <source>` -- Run historical backtest with walk-forward validation-- `signal scan` -- Scan for current trading signals using anomaly detection-- `signal scan --strategy <name>` -- Scan using a specific strategy's filters-- `risk assess <portfolio>` -- Calculate portfolio risk metrics (VaR, Sharpe, drawdown)-- `portfolio optimize` -- Optimize portfolio allocation via mean-variance optimization-- `portfolio optimize --risk-target <number>` -- Optimize with a specific risk target+- `strategy create <name> --type <momentum|mean-reversion|pairs|adaptive>` -- Create a strategy+- `backtest <strategy> --symbol <TICKER> --period <range>` -- Run backtest (Rust/NAPI, 8-19x faster)+- `train <model> --symbol <TICKER>` -- Train neural model (lstm, transformer, nbeats)+- `signal scan [--strategy <name>]` -- Scan for trading signals via anomaly detection+- `risk assess [--symbol <TICKER>]` -- Calculate risk metrics (VaR, Sharpe, drawdown)+- `portfolio optimize [--risk-target <number>]` -- Optimize allocation via mean-variance+- `live --broker <name> [--swarm enabled]` -- Start live trading with optional swarm coordination- `history` -- View trade history and performance summarySteps by subcommand:**strategy create**:-1. Prompt for strategy type: mean-reversion, momentum, statistical-arbitrage, pattern-recognition-2. Configure parameters: lookback period, entry/exit thresholds, position sizing method-3. Configure anomaly detection: Z-score thresholds per anomaly type (spike, drift, flatline, oscillation)-4. Store strategy config:- `mcp__claude-flow__memory_store({ key: "strategy-NAME", value: "CONFIG_JSON", namespace: "trading-strategies" })`-5. Train initial SONA patterns:- `mcp__claude-flow__neural_train({ patternType: "trading-strategy", epochs: 10 })`+1. Run: `npx neural-trader --strategy <type> --symbol <TICKER> --create`+2. Store strategy config in memory:+ `npx @claude-flow/cli@latest memory store --key "strategy-NAME" --value "CONFIG" --namespace trading-strategies`**backtest**:-1. Load strategy config:- `mcp__claude-flow__memory_retrieve({ key: "strategy-NAME", namespace: "trading-strategies" })`-2. Load or generate historical data from specified source-3. Run walk-forward backtest: split into train/test windows, apply strategy rules-4. Calculate performance: total return, Sharpe ratio, max drawdown, win rate, profit factor-5. Record trajectory:- `mcp__claude-flow__hooks_intelligence_trajectory-start({ context: "backtest-STRATEGY" })`- Record each trade as a trajectory step, end with PnL outcome-6. Store results:- `mcp__claude-flow__memory_store({ key: "backtest-ID", value: "RESULTS_JSON", namespace: "trading-backtests" })`+1. Run: `npx neural-trader --backtest --strategy <name> --symbol <TICKER> --period <range> --walk-forward`+2. Capture Sharpe ratio, max drawdown, win rate, profit factor from output+3. Store results:+ `npx @claude-flow/cli@latest memory store --key "backtest-ID" --value "RESULTS" --namespace trading-backtests`+4. If Sharpe > 1.5, train SONA:+ `npx @claude-flow/cli@latest neural train --pattern-type trading-strategy --epochs 10`++**train**:+1. Run: `npx neural-trader --model <lstm|transformer|nbeats> --symbol <TICKER> --confidence 0.95`+2. Capture predictions and confidence intervals from output**signal scan**:-1. Fetch recent market data (OHLCV)-2. Compute Z-scores per dimension (open, high, low, close, volume) against rolling baseline-3. Classify anomalies: spike, drift, flatline, oscillation, pattern-break, cluster-outlier-4. Apply strategy filters if --strategy specified:- `mcp__claude-flow__memory_retrieve({ key: "strategy-NAME", namespace: "trading-strategies" })`-5. Rank signals by anomaly score and confidence-6. Store signals:- `mcp__claude-flow__memory_store({ key: "signal-TIMESTAMP", value: "SIGNALS_JSON", namespace: "trading-signals" })`-7. Use SONA prediction for regime context:- `mcp__claude-flow__neural_predict({ input: "current anomaly pattern description" })`+1. Run: `npx neural-trader --signal scan --symbols <TICKERS>`+2. If --strategy specified, run: `npx neural-trader --signal scan --strategy <name>`+3. Store signals:+ `npx @claude-flow/cli@latest memory store --key "signal-TIMESTAMP" --value "SIGNALS" --namespace trading-signals`**risk assess**:-1. Load portfolio holdings and current positions-2. Calculate: VaR (95%), CVaR, Sharpe ratio, Sortino ratio, max drawdown, Calmar ratio-3. Compute pairwise correlation matrix, flag pairs > 0.8-4. Evaluate circuit breaker conditions (daily/weekly loss, correlation spike, volatility regime)-5. Store assessment:- `mcp__claude-flow__memory_store({ key: "risk-PORTFOLIO", value: "METRICS_JSON", namespace: "trading-risk" })`+1. Run: `npx neural-trader --risk assess --symbol <TICKER>`+ or: `npx neural-trader --var --symbol <TICKER> --investment <amount>`+2. Run: `npx neural-trader --risk-tolerance 0.02 --symbol <TICKER>` for position sizing+3. Store assessment:+ `npx @claude-flow/cli@latest memory store --key "risk-ID" --value "METRICS" --namespace trading-risk`**portfolio optimize**:-1. Load current holdings and historical returns-2. Compute expected returns and covariance matrix-3. Run mean-variance optimization (Markowitz efficient frontier)-4. Apply risk constraints: max position 10%, max correlation 0.8, max drawdown 15%-5. If --risk-target specified, find allocation on efficient frontier matching target volatility-6. Generate rebalancing plan: trades needed to reach optimal allocation-7. Store optimized allocation:- `mcp__claude-flow__memory_store({ key: "portfolio-optimal-TIMESTAMP", value: "ALLOCATION_JSON", namespace: "trading-portfolio" })`+1. Run: `npx neural-trader --portfolio optimize`+ or: `npx neural-trader --portfolio optimize --risk-target <number>`+2. Run: `npx neural-trader --portfolio rebalance` to generate trade plan+3. Store allocation:+ `npx @claude-flow/cli@latest memory store --key "portfolio-TIMESTAMP" --value "ALLOCATION" --namespace trading-portfolio`++**live**:+1. Run: `npx neural-trader --broker <name> --strategy <name> --swarm enabled`+2. Monitor output for trade executions and risk alerts+3. Circuit breakers auto-enforce: daily 3% loss halt, weekly 5% size reduction**history**:-1. Search trade history:- `mcp__claude-flow__memory_search({ query: "trade history", namespace: "trading-history" })`-2. Aggregate by strategy: total PnL, win rate, average hold time, profit factor-3. Show recent trades with entry/exit prices, PnL, and strategy attribution-4. Compare strategy performance over time+1. Search memory: `npx @claude-flow/cli@latest memory search --query "trade history" --namespace trading-history`+2. Show recent trades with PnL, strategy attribution, and aggregate metricsdiff --git a/plugins/ruflo-neural-trader/skills/trader-backtest/SKILL.md b/plugins/ruflo-neural-trader/skills/trader-backtest/SKILL.mdindex e9b5f6f70d..212df65039 100644--- a/plugins/ruflo-neural-trader/skills/trader-backtest/SKILL.md+++ b/plugins/ruflo-neural-trader/skills/trader-backtest/SKILL.md@@ -1,34 +1,29 @@---name: trader-backtest-description: Run a historical backtest for a trading strategy with walk-forward validation and performance metrics-allowed-tools: Bash(npx *) mcp__claude-flow__memory_store mcp__claude-flow__memory_retrieve mcp__claude-flow__memory_search mcp__claude-flow__neural_train mcp__claude-flow__hooks_intelligence_trajectory-start mcp__claude-flow__hooks_intelligence_trajectory-step mcp__claude-flow__hooks_intelligence_trajectory-end mcp__claude-flow__agentdb_pattern-store Read-argument-hint: "<strategy-name> [--period 1Y]"+description: Run a historical backtest using npx neural-trader with Rust/NAPI engine (8-19x faster) and walk-forward validation+allowed-tools: Bash Read mcp__claude-flow__memory_store mcp__claude-flow__memory_retrieve mcp__claude-flow__memory_search mcp__claude-flow__neural_train mcp__claude-flow__agentdb_pattern-store+argument-hint: "<strategy-name> --symbol <TICKER> [--period 2020-2024]"----Run a historical backtest for a trading strategy.+Run a historical backtest using the `neural-trader` Rust/NAPI engine.Steps:-1. Load the strategy configuration:+1. Ensure neural-trader is available:+ `npm ls neural-trader 2>/dev/null || npm install neural-trader`+2. Check for saved strategy config:`mcp__claude-flow__memory_retrieve({ key: "strategy-STRATEGY_NAME", namespace: "trading-strategies" })`- If not found, list available strategies:- `mcp__claude-flow__memory_search({ query: "strategy", namespace: "trading-strategies", limit: 10 })`-2. Load historical OHLCV data for the specified period (default 1Y)-3. Start a learning trajectory:- `mcp__claude-flow__hooks_intelligence_trajectory-start({ context: "backtest-STRATEGY_NAME-PERIOD" })`-4. Execute walk-forward backtest:- - Split data into rolling train/test windows (e.g., 6-month train, 1-month test)- - For each window: compute baseline Z-scores on train, apply strategy rules on test- - Record each simulated trade as a trajectory step:- `mcp__claude-flow__hooks_intelligence_trajectory-step({ action: "trade", details: "BUY/SELL at PRICE, result: +/-PNL" })`-5. Calculate aggregate performance metrics:- - Total return, annualized return, Sharpe ratio, Sortino ratio- - Max drawdown, average drawdown, recovery time- - Win rate, profit factor, average win/loss ratio- - Number of trades, average holding period-6. End trajectory with outcome:- `mcp__claude-flow__hooks_intelligence_trajectory-end({ outcome: "success/failure", reward: SHARPE_RATIO })`-7. Store backtest results:+ If not found, list available: `mcp__claude-flow__memory_search({ query: "strategy", namespace: "trading-strategies", limit: 10 })`+3. Run backtest via neural-trader CLI:+ ```bash+ npx neural-trader --backtest --strategy <name> --symbol <TICKER> --period <range> --walk-forward+ ```+ For multi-indicator strategies:+ ```bash+ npx neural-trader --backtest --strategy multi-indicator --position-sizing kelly --symbol SPY --period 2020-2024+ ```+4. Capture performance metrics from output: total return, annualized return, Sharpe ratio, Sortino ratio, max drawdown, win rate, profit factor, number of trades+5. Store backtest results:`mcp__claude-flow__memory_store({ key: "backtest-STRATEGY-TIMESTAMP", value: "RESULTS_JSON", namespace: "trading-backtests" })`-8. If Sharpe > 1.5, store as a successful pattern:- `mcp__claude-flow__agentdb_pattern-store({ pattern: "profitable-STRATEGY_TYPE", data: "STRATEGY_PARAMS_AND_RESULTS" })`-9. Train SONA on the backtest trajectory:+6. If Sharpe > 1.5, store as successful pattern:+ `mcp__claude-flow__agentdb_pattern-store({ pattern: "profitable-STRATEGY_TYPE", data: "PARAMS_AND_RESULTS" })`+7. Train SONA on the outcome:`mcp__claude-flow__neural_train({ patternType: "trading-strategy", epochs: 10 })`diff --git a/plugins/ruflo-neural-trader/skills/trader-portfolio/SKILL.md b/plugins/ruflo-neural-trader/skills/trader-portfolio/SKILL.mdindex bbdb64d4a9..e6fbda616b 100644--- a/plugins/ruflo-neural-trader/skills/trader-portfolio/SKILL.md+++ b/plugins/ruflo-neural-trader/skills/trader-portfolio/SKILL.md@@ -1,35 +1,38 @@---name: trader-portfolio-description: Optimize portfolio allocation using mean-variance optimization with risk constraints and generate a rebalancing plan-allowed-tools: Bash(npx *) mcp__claude-flow__memory_store mcp__claude-flow__memory_retrieve mcp__claude-flow__memory_search mcp__claude-flow__neural_predict mcp__claude-flow__agentdb_pattern-search Read+description: Optimize portfolio allocation using npx neural-trader mean-variance engine with risk constraints and rebalancing plan+allowed-tools: Bash Read mcp__claude-flow__memory_store mcp__claude-flow__memory_retrieve mcp__claude-flow__memory_search mcp__claude-flow__neural_predict mcp__claude-flow__agentdb_pattern-searchargument-hint: "[--risk-target NUMBER]"----Optimize portfolio allocation and generate a rebalancing plan.+Optimize portfolio allocation using neural-trader's portfolio engine.Steps:-1. Load current portfolio holdings and positions:+1. Ensure neural-trader is available:+ `npm ls neural-trader 2>/dev/null || npm install neural-trader`+2. Load current portfolio:`mcp__claude-flow__memory_search({ query: "current portfolio holdings", namespace: "trading-portfolio" })`-2. Gather historical return series for each holding (minimum 1Y daily returns)-3. Calculate expected returns (mean historical or SONA-predicted):+3. Run portfolio optimization:+ ```bash+ npx neural-trader --portfolio optimize+ ```+ With risk target:+ ```bash+ npx neural-trader --portfolio optimize --risk-target <number>+ ```+4. Get risk metrics:+ ```bash+ npx neural-trader --risk assess --portfolio current+ npx neural-trader --var --portfolio current+ npx neural-trader --correlation --portfolio current --flag-threshold 0.8+ ```+5. Use SONA for expected return prediction:`mcp__claude-flow__neural_predict({ input: "expected returns for [HOLDINGS] given current regime" })`-4. Compute covariance matrix from historical returns-5. Compute pairwise correlation matrix; flag pairs with correlation > 0.8 as concentration risk-6. Run mean-variance optimization (Markowitz):- - If --risk-target specified: find allocation on efficient frontier matching that target volatility- - Otherwise: maximize Sharpe ratio (tangency portfolio)- - Constraints: max 10% per position, min 1% per position, sum to 100%-7. Apply risk constraints:- - Max drawdown budget: 15% (reduce allocation to volatile assets if projected drawdown exceeds limit)- - Correlation limit: reduce weight of assets in clusters with mean correlation > 0.8- - Sector concentration: max 30% in any single sector-8. Calculate portfolio-level risk metrics for the optimized allocation:- - Expected return, expected volatility, Sharpe ratio- - VaR (95%), max drawdown estimate, diversification ratio-9. Generate rebalancing plan:- - List trades needed: instrument, current weight, target weight, shares to buy/sell- - Estimate transaction costs and tax impact- - Suggest execution schedule (immediate vs. phased)-10. Search for similar portfolio configurations in history:- `mcp__claude-flow__agentdb_pattern-search({ query: "optimized portfolio allocation Sharpe > 1", namespace: "trading-portfolio" })`-11. Store optimized allocation:- `mcp__claude-flow__memory_store({ key: "portfolio-optimal-TIMESTAMP", value: "ALLOCATION_AND_PLAN_JSON", namespace: "trading-portfolio" })`+6. Generate rebalancing plan:+ ```bash+ npx neural-trader --portfolio rebalance+ ```+ Output: trades needed, current vs target weights, estimated costs+7. Search for similar allocations in history:+ `mcp__claude-flow__agentdb_pattern-search({ query: "optimized portfolio Sharpe > 1", namespace: "trading-portfolio" })`+8. Store optimized allocation:+ `mcp__claude-flow__memory_store({ key: "portfolio-optimal-TIMESTAMP", value: "ALLOCATION_JSON", namespace: "trading-portfolio" })`diff --git a/plugins/ruflo-neural-trader/skills/trader-regime/SKILL.md b/plugins/ruflo-neural-trader/skills/trader-regime/SKILL.mdnew file mode 100644index 0000000000..f8904bb1d3--- /dev/null+++ b/plugins/ruflo-neural-trader/skills/trader-regime/SKILL.md@@ -0,0 +1,30 @@+---+name: trader-regime+description: Detect current market regime using npx neural-trader β bull/bear/ranging/volatile classification with recommended strategy+allowed-tools: Bash Read mcp__claude-flow__memory_store mcp__claude-flow__memory_search mcp__claude-flow__neural_predict+argument-hint: "[--symbol SPY] [--symbols AAPL,MSFT]"+---+Detect the current market regime using neural-trader's regime detection engine.++Steps:+1. Ensure neural-trader is available:+ `npm ls neural-trader 2>/dev/null || npm install neural-trader`+2. Run regime detection:+ ```bash+ npx neural-trader --regime-detect --symbol TICKER+ ```+ For multiple symbols:+ ```bash+ npx neural-trader --regime-detect --symbols "AAPL,MSFT,GOOGL,AMZN"+ ```+3. Get technical indicators for context:+ ```bash+ npx neural-trader --symbol TICKER --indicators rsi,macd,bollinger,adx,atr+ ```+4. Use SONA for regime prediction:+ `mcp__claude-flow__neural_predict({ input: "indicators: RSI=X, ADX=Y, VIX=Z" })`+5. Search for similar historical regimes:+ `mcp__claude-flow__memory_search({ query: "regime similar to CURRENT", namespace: "trading-analysis" })`+6. Present: regime classification, confidence, recommended strategy type, historical precedents+7. Store analysis:+ `mcp__claude-flow__memory_store({ key: "regime-DATE", value: "REGIME_ANALYSIS", namespace: "trading-analysis" })`diff --git a/plugins/ruflo-neural-trader/skills/trader-risk/SKILL.md b/plugins/ruflo-neural-trader/skills/trader-risk/SKILL.mdnew file mode 100644index 0000000000..6e0302203f--- /dev/null+++ b/plugins/ruflo-neural-trader/skills/trader-risk/SKILL.md@@ -0,0 +1,33 @@+---+name: trader-risk+description: Assess portfolio risk using npx neural-trader β VaR, CVaR, Sharpe, position sizing, circuit breaker status+allowed-tools: Bash Read mcp__claude-flow__memory_store mcp__claude-flow__memory_search+argument-hint: "[--symbol TICKER] [--portfolio NAME]"+---+Assess portfolio and position risk using neural-trader's risk engine.++Steps:+1. Ensure neural-trader is available:+ `npm ls neural-trader 2>/dev/null || npm install neural-trader`+2. Run risk assessment:+ ```bash+ # Single position+ npx neural-trader --risk assess --symbol TICKER+ npx neural-trader --var --symbol TICKER --investment 10000++ # Portfolio-wide+ npx neural-trader --risk assess --portfolio NAME+ npx neural-trader --correlation --portfolio NAME --flag-threshold 0.8+ ```+3. Calculate position sizing:+ ```bash+ npx neural-trader --risk-tolerance 0.02 --symbol TICKER+ npx neural-trader --position-sizing kelly --symbol TICKER+ ```+4. Check circuit breaker status:+ - Daily loss limit (3%), weekly loss limit (5%)+ - Correlation spike (>0.85), volatility regime (VIX > 2x)+ - Max positions, single-name concentration (>10%)+5. Present: risk metrics, position sizing recommendation, active breakers, alerts+6. Store assessment:+ `mcp__claude-flow__memory_store({ key: "risk-TICKER-DATE", value: "RISK_METRICS", namespace: "trading-risk" })`diff --git a/plugins/ruflo-neural-trader/skills/trader-signal/SKILL.md b/plugins/ruflo-neural-trader/skills/trader-signal/SKILL.mdindex 590cd28d86..cec08dcfe9 100644--- a/plugins/ruflo-neural-trader/skills/trader-signal/SKILL.md+++ b/plugins/ruflo-neural-trader/skills/trader-signal/SKILL.md@@ -1,30 +1,35 @@---name: trader-signal-description: Generate trading signals by running Z-score anomaly detection on market data and ranking by confidence-allowed-tools: Bash(npx *) mcp__claude-flow__memory_store mcp__claude-flow__memory_retrieve mcp__claude-flow__memory_search mcp__claude-flow__neural_predict mcp__claude-flow__agentdb_pattern-search Read-argument-hint: "[--strategy NAME]"+description: Generate trading signals using npx neural-trader anomaly detection engine with Z-score scoring and neural prediction+allowed-tools: Bash Read mcp__claude-flow__memory_store mcp__claude-flow__memory_retrieve mcp__claude-flow__memory_search mcp__claude-flow__neural_predict mcp__claude-flow__agentdb_pattern-search+argument-hint: "[--strategy NAME] [--symbols AAPL,MSFT]"----Generate trading signals using anomaly detection and neural prediction.+Generate trading signals using neural-trader's anomaly detection engine.Steps:-1. Fetch recent market data (OHLCV) for target instruments-2. Compute Z-scores per dimension (open, high, low, close, volume) against a rolling baseline window (default 50 bars)-3. Calculate composite anomaly score: `anomalyScore = min(1, meanZ / 3)`-4. Classify each anomaly:- - **spike** (maxZ > 5): breakout or gap -- potential momentum entry or mean-reversion fade- - **drift** (1-2 dims sustained high Z): trend forming -- trend-following signal- - **flatline** (all near zero, low Z): consolidation -- prepare for breakout- - **oscillation** (alternating high/low): range-bound -- mean-reversion at extremes- - **pattern-break** (moderate Z, multiple dims): regime change -- close positions, reassess- - **cluster-outlier** (>50% dims high Z): multi-factor dislocation -- arbitrage opportunity-5. If --strategy specified, load strategy filters:+1. Ensure neural-trader is available:+ `npm ls neural-trader 2>/dev/null || npm install neural-trader`+2. Scan for signals:+ ```bash+ npx neural-trader --signal scan --symbols <TICKERS>+ ```+ With a specific strategy:+ ```bash+ npx neural-trader --signal scan --strategy <name> --symbols <TICKERS>+ ```+3. If --strategy specified, load strategy filters:`mcp__claude-flow__memory_retrieve({ key: "strategy-NAME", namespace: "trading-strategies" })`- Apply strategy-specific entry rules and thresholds to filter signals-6. Use SONA to predict current market regime:- `mcp__claude-flow__neural_predict({ input: "anomaly types: [DETECTED_TYPES], scores: [SCORES]" })`-7. Search for similar historical patterns:- `mcp__claude-flow__agentdb_pattern-search({ query: "ANOMALY_TYPE with score RANGE", namespace: "trading-signals" })`-8. Rank signals by: anomaly score * strategy alignment * historical pattern match confidence-9. Output ranked signal list with: instrument, direction (long/short), confidence, anomaly type, suggested entry/stop/target-10. Store generated signals:- `mcp__claude-flow__memory_store({ key: "signal-TIMESTAMP", value: "RANKED_SIGNALS_JSON", namespace: "trading-signals" })`+4. neural-trader classifies anomalies automatically:+ - **spike** (maxZ > 5): breakout β momentum entry or mean-reversion fade+ - **drift** (sustained high Z): trend forming β trend-following signal+ - **flatline** (low Z): consolidation β prepare for breakout+ - **oscillation** (alternating): range-bound β mean-reversion at extremes+ - **pattern-break** (multiple dims): regime change β close and reassess+ - **cluster-outlier** (>50% dims): multi-factor dislocation β arbitrage+5. Use SONA for regime prediction:+ `mcp__claude-flow__neural_predict({ input: "anomaly types: [DETECTED], scores: [SCORES]" })`+6. Search historical pattern matches:+ `mcp__claude-flow__agentdb_pattern-search({ query: "ANOMALY_TYPE score RANGE", namespace: "trading-signals" })`+7. Present ranked signals: instrument, direction, confidence, anomaly type, entry/stop/target+8. Store signals:+ `mcp__claude-flow__memory_store({ key: "signal-TIMESTAMP", value: "SIGNALS_JSON", namespace: "trading-signals" })`diff --git a/plugins/ruflo-neural-trader/skills/trader-train/SKILL.md b/plugins/ruflo-neural-trader/skills/trader-train/SKILL.mdnew file mode 100644index 0000000000..2705f06835--- /dev/null+++ b/plugins/ruflo-neural-trader/skills/trader-train/SKILL.md@@ -0,0 +1,30 @@+---+name: trader-train+description: Train neural models (LSTM, Transformer, N-BEATS) on market data using npx neural-trader with confidence intervals+allowed-tools: Bash Read mcp__claude-flow__memory_store mcp__claude-flow__memory_search mcp__claude-flow__neural_train+argument-hint: "<lstm|transformer|nbeats> --symbol <TICKER>"+---+Train neural prediction models using neural-trader's ML engine.++Steps:+1. Ensure neural-trader is available:+ `npm ls neural-trader 2>/dev/null || npm install neural-trader`+2. Train the specified model:+ ```bash+ npx neural-trader --model lstm --symbol TICKER --confidence 0.95+ npx neural-trader --model transformer --symbol TICKER --predict+ npx neural-trader --model nbeats --symbol TICKER --decompose+ ```+3. Review training output: loss curves, validation metrics, prediction accuracy+4. Generate predictions with confidence intervals:+ ```bash+ npx neural-trader --model MODEL --symbol TICKER --predict --horizon 5d+ ```+5. Compare model performance across types:+ ```bash+ npx neural-trader --model-compare --symbol TICKER --models "lstm,transformer,nbeats"+ ```+6. Store model results:+ `mcp__claude-flow__memory_store({ key: "model-MODEL-TICKER-DATE", value: "TRAINING_RESULTS", namespace: "trading-models" })`+7. Train SONA on model outcomes:+ `mcp__claude-flow__neural_train({ patternType: "trading-model", epochs: 10 })`diff --git a/plugins/ruflo-rag-memory/README.md b/plugins/ruflo-rag-memory/README.mdindex 8d7f44a436..2879f6680f 100644--- a/plugins/ruflo-rag-memory/README.md+++ b/plugins/ruflo-rag-memory/README.md@@ -1,23 +1,140 @@# ruflo-rag-memory-RuVector memory with HNSW search, AgentDB, and semantic retrieval.+Retrieval-Augmented Generation memory with HNSW vector search, AgentDB persistence, and Claude Code memory bridge.-## Install+## Overview-```-/plugin marketplace add ruvnet/ruflo-/plugin install ruflo-rag-memory@ruflo-```+Provides semantic store/search/recall over AgentDB with HNSW-indexed vector search (150x-12,500x faster than brute force). Bridges Claude Code's native auto-memory into AgentDB with 384-dim ONNX embeddings for unified cross-session semantic retrieval.-## What's Included+## Installation-- **HNSW Vector Search**: 150x-12,500x faster pattern retrieval with persistent indexes-- **AgentDB**: 19 controllers for memory, sessions, patterns, trajectories, and feedback-- **Semantic Retrieval**: Smart retrieval with MMR diversity and recency scoring-- **ONNX Embeddings**: all-MiniLM-L6-v2 (384 dimensions) for cross-platform search-- **Claude Memory Bridge**: Auto-import from Claude Code's native memory into AgentDB-- **Unified Search**: Query across all namespaces (claude-memories, patterns, tasks, feedback)+```bash+claude --plugin-dir plugins/ruflo-rag-memory+```## Requires- `ruflo-core` plugin (provides MCP server)++## Agents++| Agent | Model | Role |+|-------|-------|------|+| `memory-specialist` | sonnet | AgentDB management, HNSW optimization, memory bridge, consolidation |++## Skills++| Skill | Usage | Description |+|-------|-------|-------------|+| `memory-search` | `/memory-search <query>` | Semantic vector search across all namespaces |+| `memory-bridge` | `/memory-bridge [--all-projects]` | Import Claude Code auto-memory into AgentDB |++## Commands++```bash+# Store a memory entry+memory store --key "pattern-auth" --value "JWT with refresh tokens" --namespace patterns++# Semantic search (HNSW-indexed)+memory search --query "authentication patterns" --namespace patterns --limit 5++# Retrieve by key+memory retrieve --key "pattern-auth" --namespace patterns++# List entries+memory list --namespace patterns --limit 10++# Delete+memory delete --key "old-entry" --namespace patterns++# Quick semantic recall across all namespaces+recall "how did we handle rate limiting?"+```++## Architecture++```+Claude Code Auto-Memory (~/.claude/projects/*/memory/*.md)+ β+ βΌ (ONNX all-MiniLM-L6-v2, 384-dim)+ Memory Bridge+ β+ βΌ+ AgentDB (SQLite + vector_indexes)+ β+ βββ patterns namespace+ βββ tasks namespace+ βββ solutions namespace+ βββ feedback namespace+ βββ security namespace+ βββ claude-memories namespace+ β+ βΌ (HNSW ANN index)+ Semantic Search (150x-12,500x faster)+```++## Memory Namespaces++| Namespace | Purpose | Example Key |+|-----------|---------|-------------|+| `patterns` | Successful code/design patterns | `pattern-auth-jwt` |+| `tasks` | Task context and outcomes | `task-refactor-api` |+| `solutions` | Bug fixes and solutions | `fix-race-condition` |+| `feedback` | User feedback and corrections | `feedback-test-style` |+| `security` | Vulnerability patterns | `vuln-sql-injection` |+| `claude-memories` | Bridged Claude Code memories | `auto-imported` |++## Claude Memory Bridge++Auto-imports Claude Code's native `~/.claude/projects/*/memory/*.md` files into AgentDB on session start with ONNX vector embeddings.++```bash+# Manual import (current project)+/memory-bridge++# Import all projects+/memory-bridge --all-projects++# Check bridge health+# Via MCP: memory_bridge_status({})+```++Results include source attribution: `claude-code`, `auto-memory`, or `agentdb`.++## Unified Search++Queries across all namespaces simultaneously with MMR diversity reranking:++```bash+# Via MCP: memory_search_unified({ query: "auth security", limit: 5 })+# Via CLI:+npx @claude-flow/cli@latest memory search --query "auth security" --limit 5+```++## HNSW Performance++| Operation | Latency | vs Brute Force |+|-----------|---------|----------------|+| Vector search (100 entries) | ~0.01ms | 150x faster |+| Vector search (10k entries) | ~0.05ms | 2,500x faster |+| Vector search (100k entries) | ~0.1ms | 12,500x faster |+| Store + index | ~1ms | β |++## Integration with ruvector++When `ruflo-ruvector` is also loaded, rag-memory delegates to ruvector's backend for advanced features:+- FlashAttention-3 for O(N) memory attention+- Graph RAG for multi-hop knowledge retrieval+- Hybrid search (sparse + dense) with RRF fusion+- DiskANN for large-scale persistent indexes++## Related Plugins++- `ruflo-agentdb` β Full AgentDB with 19 controllers and HNSW search+- `ruflo-ruvector` β Advanced vector operations (FlashAttention-3, Graph RAG, hybrid search)+- `ruflo-rvf` β Portable RVF memory format for cross-machine export/import+- `ruflo-knowledge-graph` β Entity extraction and graph traversal over memory++## License++MITdiff --git a/plugins/ruflo-rag-memory/agents/memory-specialist.md b/plugins/ruflo-rag-memory/agents/memory-specialist.mdindex ac999a64d6..d8570c1424 100644--- a/plugins/ruflo-rag-memory/agents/memory-specialist.md+++ b/plugins/ruflo-rag-memory/agents/memory-specialist.md@@ -1,39 +1,120 @@---name: memory-specialist-description: Memory and retrieval specialist -- manages AgentDB, HNSW indexes, and semantic search+description: SOTA RAG memory specialist β hybrid search (sparse+dense), Graph RAG multi-hop retrieval, MMR diversity reranking, smart consolidation, ruvector integrationmodel: sonnet----You are a memory specialist agent. Your responsibilities:+You are a memory specialist agent implementing state-of-the-art Retrieval-Augmented Generation patterns. Your responsibilities:-1. Manage AgentDB entries across namespaces (patterns, tasks, solutions, feedback, security)-2. Optimize HNSW vector indexes for search performance-3. Bridge Claude Code auto-memory to AgentDB via ONNX embeddings-4. Consolidate and prune stale memory entries+1. **Hybrid search** (sparse + dense) with Reciprocal Rank Fusion for 20-49% better retrieval+2. **Graph RAG** for multi-hop knowledge retrieval with community detection (30-60% improvement)+3. **Smart retrieval** with MMR diversity reranking and recency scoring+4. **Memory consolidation** β deduplicate, merge, prune stale entries across namespaces+5. **Claude Code bridge** β import auto-memory into AgentDB with ONNX vector embeddings+6. **Adaptive chunking** β split documents at semantic boundaries, not fixed token counts-### Tools+### Search Strategy Selection-- `npx @claude-flow/cli@latest memory search --query "QUERY" --namespace NAMESPACE`-- `npx @claude-flow/cli@latest memory store --key "KEY" --value "VALUE" --namespace NAMESPACE`-- `npx @claude-flow/cli@latest memory list --namespace NAMESPACE --limit 20`-- `npx @claude-flow/cli@latest hooks worker dispatch --trigger consolidate`+| Query Type | Strategy | Why |+|-----------|----------|-----|+| Factual lookup | Dense search (HNSW) | Fast, single-hop, exact semantic match |+| Multi-hop reasoning | Graph RAG | Follows entity relationships across documents |+| Keyword + semantic | Hybrid (sparse + dense + RRF) | Combines BM25 precision with embedding recall |+| Diverse results needed | Dense + MMR reranking | Removes near-duplicates, maximizes coverage |+| Recent context | Dense + recency weighting | Prioritizes temporally relevant entries |+| Exploratory | Graph RAG + community detection | Discovers clusters and latent connections |-### Workflow+### Retrieval Pipeline (SOTA)-1. Audit existing memory entries for relevance and accuracy-2. Consolidate duplicate or overlapping entries-3. Verify HNSW index health via memory stats-4. Bridge new Claude Code auto-memory files into AgentDB+```+Query β [Embedding (ONNX 384d)] β [HNSW ANN search]+ β+ [Optional: BM25 sparse search]+ β+ [RRF Fusion (k=60)]+ β+ [MMR Reranking (Ξ»=0.7)]+ β+ [Recency Boost (decay=0.95/day)]+ β+ Top-K Results+```-### Related Plugins+### Retrieval via ruvector (when available)++```bash+# Hybrid search (sparse + dense)+npx ruvector search "query" --hybrid --limit 10++# Graph RAG (multi-hop)+npx ruvector search "query" --graph-rag --limit 10++# Brain knowledge search+npx ruvector brain search "query"++# RAG context retrieval (MCP)+# hooks_rag_context({ query: "topic", limit: 5 })+```++### Retrieval via claude-flow CLI++```bash+# Dense semantic search+npx @claude-flow/cli@latest memory search --query "QUERY" --namespace NAMESPACE --limit 10++# Store with metadata+npx @claude-flow/cli@latest memory store --key "KEY" --value "VALUE" --namespace NAMESPACE-- **ruflo-agentdb**: Full AgentDB with HNSW vector search for semantic retrieval (150xβ12,500x faster)-- **ruflo-rvf**: RVF portable memory format for cross-machine export/import+# List and audit+npx @claude-flow/cli@latest memory list --namespace NAMESPACE --limit 20+# Consolidated search across all namespaces+npx @claude-flow/cli@latest memory search --query "QUERY" --limit 10+```++### Adaptive Chunking Strategy++| Content Type | Chunk Strategy | Overlap |+|-------------|---------------|---------|+| Code files | Function/class boundaries (AST-aware) | 0 (natural boundaries) |+| Markdown docs | Header-delimited sections | 50 tokens |+| Conversations | Turn boundaries | 1 turn |+| JSON/Config | Top-level key groupings | 0 |+| Plain text | 512-token windows | 64 tokens |++### Memory Consolidation Workflow++1. **Audit** β list all entries per namespace, check for staleness (>30 days untouched)+2. **Deduplicate** β find entries with cosine similarity > 0.92, merge into single entry+3. **Prune** β remove entries with zero retrieval hits in last 30 days+4. **Compress** β summarize verbose entries while preserving key facts+5. **Re-index** β rebuild HNSW index after consolidation for optimal graph quality++```bash+npx @claude-flow/cli@latest hooks worker dispatch --trigger consolidate+```++### Namespaces++| Namespace | Purpose | Retention |+|-----------|---------|-----------|+| `patterns` | Code/design patterns that worked | Permanent |+| `tasks` | Task context and decisions | 90 days |+| `solutions` | Bug fixes and resolutions | Permanent |+| `feedback` | User corrections and preferences | Permanent |+| `security` | Vulnerability patterns | Permanent |+| `claude-memories` | Bridged Claude Code auto-memory | Sync on session start |### Neural Learning-After completing tasks, store successful patterns:+After completing tasks, train on successful retrieval patterns:```bashnpx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true-npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns```++### Related Plugins++- **ruflo-agentdb**: Full AgentDB backend with HNSW vector_indexes table+- **ruflo-ruvector**: FlashAttention-3, Graph RAG, hybrid search, DiskANN+- **ruflo-rvf**: Portable RVF format for cross-machine memory export/import+- **ruflo-knowledge-graph**: Entity-relationship graphs over memory entries+- **ruflo-intelligence**: SONA trajectory learning from retrieval patternsdiff --git a/plugins/ruflo-rag-memory/commands/memory.md b/plugins/ruflo-rag-memory/commands/memory.mdindex 0bc8f5b47c..e7ecc7ed50 100644--- a/plugins/ruflo-rag-memory/commands/memory.md+++ b/plugins/ruflo-rag-memory/commands/memory.md@@ -1,17 +1,38 @@---name: memory-description: Store, search, retrieve, and list entries in AgentDB memory with vector search+description: SOTA memory CRUD β store, search (hybrid/graph-rag/dense), retrieve, list, consolidate---$ARGUMENTS-Memory CRUD operations with HNSW-indexed vector search (150x-12,500x faster).+Memory operations with HNSW-indexed vector search (150x-12,500x faster).-**Store**: `npx @claude-flow/cli@latest memory store --key "KEY" --value "VALUE" --namespace NAMESPACE`-**Search**: `npx @claude-flow/cli@latest memory search --query "QUERY" --namespace NAMESPACE --limit 5`-**Retrieve**: `npx @claude-flow/cli@latest memory retrieve --key "KEY" --namespace NAMESPACE`-**List**: `npx @claude-flow/cli@latest memory list --namespace NAMESPACE --limit 10`-**Delete**: `npx @claude-flow/cli@latest memory delete --key "KEY" --namespace NAMESPACE`+Parse $ARGUMENTS to determine the operation:-Default namespace is "default". Common namespaces: patterns, tasks, solutions, feedback, claude-memories.+**store** `--key KEY --value VALUE [--namespace NS]`:+`npx @claude-flow/cli@latest memory store --key "KEY" --value "VALUE" --namespace NAMESPACE`-Parse $ARGUMENTS to determine the operation and parameters. If no arguments, run `memory list`.+**search** `--query QUERY [--namespace NS] [--limit N] [--hybrid] [--graph-rag]`:+- Default (dense): `npx @claude-flow/cli@latest memory search --query "QUERY" --namespace NAMESPACE --limit 5`+- Hybrid (sparse+dense): `npx ruvector search "QUERY" --hybrid --limit 5`+- Graph RAG (multi-hop): `npx ruvector search "QUERY" --graph-rag --limit 5`++**retrieve** `--key KEY [--namespace NS]`:+`npx @claude-flow/cli@latest memory retrieve --key "KEY" --namespace NAMESPACE`++**list** `[--namespace NS] [--limit N]`:+`npx @claude-flow/cli@latest memory list --namespace NAMESPACE --limit 10`++**delete** `--key KEY [--namespace NS]`:+`npx @claude-flow/cli@latest memory delete --key "KEY" --namespace NAMESPACE`++**consolidate** `[--namespace NS]`:+Deduplicate entries with cosine > 0.92, prune stale (>30 days untouched, zero retrieval hits), rebuild HNSW index.+`npx @claude-flow/cli@latest hooks worker dispatch --trigger consolidate`++**bridge** `[--all-projects]`:+Import Claude Code auto-memory into AgentDB.+See `/memory-bridge` skill for details.++Default namespace is "default". Common namespaces: `patterns`, `tasks`, `solutions`, `feedback`, `security`, `claude-memories`.++If no arguments, run `memory list`.diff --git a/plugins/ruflo-rag-memory/commands/recall.md b/plugins/ruflo-rag-memory/commands/recall.mdindex 726da4a2ed..116df77e03 100644--- a/plugins/ruflo-rag-memory/commands/recall.md+++ b/plugins/ruflo-rag-memory/commands/recall.md@@ -1,16 +1,21 @@---name: recall-description: Semantic recall β search AgentDB and Claude Code memories by meaning+description: Quick semantic recall β searches all memory namespaces with MMR diversity and recency weighting---$ARGUMENTS-Semantic recall across all memory namespaces using HNSW vector search.+Semantic recall across all memory namespaces using HNSW vector search with MMR diversity reranking.```bashnpx @claude-flow/cli@latest memory search --query "$ARGUMENTS" --limit 5```-This searches across patterns, tasks, solutions, feedback, and claude-memories namespaces. Results are ranked by cosine similarity with MMR diversity reranking.+For richer results when ruvector is available:+```bash+npx ruvector search "$ARGUMENTS" --hybrid --limit 5+```++This searches across patterns, tasks, solutions, feedback, security, and claude-memories namespaces. Results are ranked by composite score: cosine similarity * MMR diversity * recency decay.If no arguments provided, show recent memory entries:```bashdiff --git a/plugins/ruflo-rag-memory/skills/memory-bridge/SKILL.md b/plugins/ruflo-rag-memory/skills/memory-bridge/SKILL.mdindex 84ff1eae81..9b58ffe575 100644--- a/plugins/ruflo-rag-memory/skills/memory-bridge/SKILL.md+++ b/plugins/ruflo-rag-memory/skills/memory-bridge/SKILL.md@@ -1,17 +1,59 @@---name: memory-bridge-description: Bridge Claude Code auto-memory into AgentDB with ONNX vector embeddings-argument-hint: "[--all-projects]"-allowed-tools: mcp__claude-flow__memory_import_claude mcp__claude-flow__memory_bridge_status mcp__claude-flow__memory_search_unified Bash(npx *)+description: Bridge Claude Code auto-memory into AgentDB with ONNX embeddings, deduplicate, and enable unified cross-project search+argument-hint: "[--all-projects] [--dedupe]"+allowed-tools: Bash Read mcp__claude-flow__memory_import_claude mcp__claude-flow__memory_bridge_status mcp__claude-flow__memory_search_unified----Import Claude Code memories into AgentDB for semantic search across sessions.-Via MCP:-- Import current project: `mcp__claude-flow__memory_import_claude({})`-- Import all projects: `mcp__claude-flow__memory_import_claude({ allProjects: true })`-- Check health: `mcp__claude-flow__memory_bridge_status({})`-- Unified search: `mcp__claude-flow__memory_search_unified({ query: "QUERY", limit: 5 })`+# Memory Bridge-The bridge auto-imports on `session-start`. Memories get 384-dim ONNX embeddings (all-MiniLM-L6-v2) for cross-namespace unified search.+Import Claude Code's native auto-memory files into AgentDB for semantic search across sessions and projects.-Results include source attribution: `claude-code`, `auto-memory`, or `agentdb`.+## What it does++Claude Code stores memories as markdown files in `~/.claude/projects/*/memory/*.md`. This bridge:+1. Reads all memory files (current project or all projects)+2. Generates 384-dim ONNX embeddings (all-MiniLM-L6-v2)+3. Stores in AgentDB's `claude-memories` namespace with HNSW indexing+4. Deduplicates against existing entries (cosine similarity > 0.95)+5. Enables unified semantic search across all memory sources++## Steps++1. **Check bridge health**:+ `mcp__claude-flow__memory_bridge_status({})`+ Verify: Claude files count, AgentDB entries, SONA state, connection status.++2. **Import memories**:+ - Current project: `mcp__claude-flow__memory_import_claude({})`+ - All projects: `mcp__claude-flow__memory_import_claude({ allProjects: true })`++ CLI alternative:+ ```bash+ node .claude/helpers/auto-memory-hook.mjs import-all+ ```++3. **Verify import**:+ `mcp__claude-flow__memory_bridge_status({})`+ Confirm entry counts match expected file counts.++4. **Deduplicate** (if --dedupe):+ Search for near-duplicate entries (cosine > 0.95) and merge them, keeping the most recent version.++5. **Test unified search**:+ `mcp__claude-flow__memory_search_unified({ query: "test query", limit: 3 })`+ Results include source attribution: `claude-code`, `auto-memory`, or `agentdb`.++## Auto-import++The bridge runs automatically on `session-start` via the SessionStart hook. Manual invocation is only needed for:+- First-time import of all projects+- After bulk memory changes outside normal sessions+- Forcing re-embedding after model updates++## Integration with ruvector++When `ruflo-ruvector` is loaded, bridged memories are also indexed by ruvector for:+- Hybrid search (sparse + dense with RRF)+- Graph RAG multi-hop queries across memory entries+- Brain knowledge sharing across sessionsdiff --git a/plugins/ruflo-rag-memory/skills/memory-search/SKILL.md b/plugins/ruflo-rag-memory/skills/memory-search/SKILL.mdindex aa4960fc89..71fab5b0e5 100644--- a/plugins/ruflo-rag-memory/skills/memory-search/SKILL.md+++ b/plugins/ruflo-rag-memory/skills/memory-search/SKILL.md@@ -1,17 +1,58 @@---name: memory-search-description: Semantic search across Ruflo AgentDB with HNSW vector indexing-allowed-tools: mcp__claude-flow__memory_search mcp__claude-flow__memory_store mcp__claude-flow__memory_list mcp__claude-flow__memory_retrieve Bash(npx *)-argument-hint: "[query]"+description: SOTA semantic search β hybrid (sparse+dense), Graph RAG multi-hop, MMR diversity reranking, recency weighting+allowed-tools: Bash Read mcp__claude-flow__memory_search mcp__claude-flow__memory_store mcp__claude-flow__memory_list mcp__claude-flow__memory_retrieve mcp__claude-flow__memory_search_unified mcp__claude-flow__agentdb_pattern-search mcp__claude-flow__agentdb_context-synthesize+argument-hint: "<query> [--hybrid] [--graph-rag] [--namespace NAME]"----Search memory with semantic vector search (150x-12,500x faster than brute force).-Via MCP: `mcp__claude-flow__memory_search({ query: "authentication patterns", namespace: "patterns", limit: 5 })`+# Memory Search (SOTA)-Store: `mcp__claude-flow__memory_store({ key: "pattern-name", value: "what worked", namespace: "patterns" })`+State-of-the-art semantic search across Ruflo memory with multiple retrieval strategies.-List: `mcp__claude-flow__memory_list({ namespace: "patterns", limit: 10 })`+## Strategy Selection-Retrieve: `mcp__claude-flow__memory_retrieve({ key: "pattern-name", namespace: "patterns" })`+Choose based on query type:+- **Default** (dense): fast single-hop semantic match+- **--hybrid**: sparse + dense with RRF fusion (20-49% better for keyword+semantic queries)+- **--graph-rag**: multi-hop knowledge retrieval (30-60% better for reasoning queries)-Common namespaces: `patterns`, `tasks`, `solutions`, `feedback`, `security`.+## Steps++1. **Parse query and flags** β extract search text and strategy flags from arguments+2. **Select retrieval strategy**:++ **Dense search (default)**:+ ```bash+ npx @claude-flow/cli@latest memory search --query "QUERY" --namespace NAMESPACE --limit 10+ ```+ Or via MCP: `mcp__claude-flow__memory_search({ query: "QUERY", namespace: "NAMESPACE", limit: 10 })`++ **Hybrid search** (when --hybrid or query has specific keywords):+ ```bash+ npx ruvector search "QUERY" --hybrid --limit 10+ ```++ **Graph RAG** (when --graph-rag or multi-hop reasoning needed):+ ```bash+ npx ruvector search "QUERY" --graph-rag --limit 10+ ```++ **Unified cross-namespace**:+ `mcp__claude-flow__memory_search_unified({ query: "QUERY", limit: 10 })`++3. **Apply MMR reranking** β for diverse results, filter near-duplicates (cosine > 0.92) while maximizing relevance+4. **Apply recency weighting** β boost recent entries with exponential decay (0.95/day)+5. **Synthesize context** (for complex queries):+ `mcp__claude-flow__agentdb_context-synthesize({ query: "QUERY", sources: ["patterns", "tasks", "solutions"] })`+6. **Present results** β ranked by composite score (relevance * diversity * recency), with source namespace attribution++## Namespace Guide++| Namespace | Best For |+|-----------|----------|+| `patterns` | "How did we handle X?" |+| `tasks` | "What was the context for Y?" |+| `solutions` | "How did we fix Z?" |+| `feedback` | "What did the user prefer?" |+| `security` | "Known vulnerabilities in..." |+| (omit) | Search all namespaces |diff --git a/plugins/ruflo-ruvector/.claude-plugin/plugin.json b/plugins/ruflo-ruvector/.claude-plugin/plugin.jsonindex b02390683e..73c886f0b7 100644--- a/plugins/ruflo-ruvector/.claude-plugin/plugin.json+++ b/plugins/ruflo-ruvector/.claude-plugin/plugin.json@@ -1,20 +1,23 @@{"name": "ruflo-ruvector",- "description": "RuVector operations β HNSW indexing, embedding generation, vector clustering, and hyperbolic space reasoning",- "version": "0.1.0",+ "description": "Self-learning vector database via npx ruvector β HNSW, FlashAttention-3, Graph RAG, hybrid search, DiskANN, 103 MCP tools, Brain AGI",+ "version": "0.2.0","author": {"name": "ruvnet","url": "https://github.com/ruvnet"},- "homepage": "https://github.com/ruvnet/ruflo",+ "homepage": "https://github.com/ruvnet/ruvector","license": "MIT","keywords": ["ruflo","ruvector",- "embeddings",+ "vector-database","hnsw",- "vector",- "hyperbolic",- "clustering"+ "flash-attention",+ "graph-rag",+ "hybrid-search",+ "diskann",+ "mcp",+ "brain-agi"]}diff --git a/plugins/ruflo-ruvector/README.md b/plugins/ruflo-ruvector/README.mdindex 55abbe9cfa..11c78499cb 100644--- a/plugins/ruflo-ruvector/README.md+++ b/plugins/ruflo-ruvector/README.md@@ -1,10 +1,16 @@# ruflo-ruvector-RuVector operations -- HNSW indexing, embedding generation, vector clustering, and hyperbolic space reasoning.+Self-learning vector database powered by [`ruvector`](https://www.npmjs.com/package/ruvector) β HNSW, FlashAttention-3, Graph RAG, hybrid search, DiskANN, 103 MCP tools, Brain AGI, and 50+ attention mechanisms.## Overview-Vector operations specialist for the RuVector system. Generates 384-dimensional embeddings via ONNX all-MiniLM-L6-v2, manages HNSW approximate nearest-neighbor indexes, performs k-means and density-based clustering, and supports hyperbolic embeddings in the Poincare ball model for hierarchical data (taxonomies, dependency trees, org charts).+Wraps the `ruvector` npm package as a Ruflo plugin, providing vector embedding, semantic search, clustering, hyperbolic space reasoning, self-learning hooks, and Brain AGI diagnostics. ruvector's Rust backend delivers sub-millisecond queries and 52,000+ inserts/sec.++## Prerequisites++```bash+npm install ruvector+```## Installation@@ -12,21 +18,29 @@ Vector operations specialist for the RuVector system. Generates 384-dimensionalclaude --plugin-dir plugins/ruflo-ruvector```+## MCP Integration (103 Tools)++```bash+claude mcp add ruvector -- npx ruvector mcp start+```++Key tool categories: hooks routing, AST analysis, diff classification, coverage routing, graph clustering, security scanning, RAG context, brain knowledge, AGI diagnostics, midstream analytics.+## Agents| Agent | Model | Role ||-------|-------|------|-| `vector-engineer` | sonnet | Embedding generation, HNSW index management, similarity search, clustering, hyperbolic space reasoning |+| `vector-engineer` | sonnet | Embedding, HNSW indexing, FlashAttention-3, Graph RAG, hybrid search, clustering, hyperbolic space, Brain AGI |## Skills| Skill | Usage | Description ||-------|-------|-------------|-| `vector-embed` | `/vector-embed <text-or-file>` | Generate ONNX embeddings (384-dim), normalize, and store in HNSW index |-| `vector-cluster` | `/vector-cluster <namespace> [--k N]` | Cluster vectors using k-means or density-based methods |-| `vector-hyperbolic` | `/vector-hyperbolic <text> [--model poincare]` | Embed hierarchical data in hyperbolic space (Poincare ball) |+| `vector-embed` | `/vector-embed <text-or-file>` | ONNX embeddings (384-dim), normalize, store in HNSW |+| `vector-cluster` | `/vector-cluster <namespace> [--k N]` | k-means or density clustering with labeled summaries |+| `vector-hyperbolic` | `/vector-hyperbolic <text>` | Poincare ball hierarchical embeddings |-## Commands (9 subcommands)+## Commands```bash# Embedding@@ -35,10 +49,10 @@ vector batch <glob-pattern>vector compare <text1> <text2># Search-vector search <query> [--limit N]+vector search <query> [--limit N] [--hybrid] [--graph-rag]# Clustering-vector cluster <namespace> [--k N]+vector cluster <namespace> [--k N | --density]# Index managementvector index create <name>@@ -46,30 +60,73 @@ vector index stats <name># Hyperbolicvector hyperbolic embed <text>++# Self-learning hooks+vector hooks init+vector hooks route <task>+vector ast <file>++# Brain AGI+vector brain status+vector midstream status```-## HNSW Parameters+## Search Capabilities (ruvector v2.1+)-| Parameter | Default | Purpose |-|-----------|---------|---------|-| `M` | 16 | Graph connectivity (edges per node) |-| `efConstruction` | 200 | Build-time search quality |-| `efSearch` | 50 | Query-time search quality |+| Feature | Description | Improvement |+|---------|-------------|-------------|+| FlashAttention-3 | IO-aware tiled attention | O(N) memory vs O(N^2) |+| Graph RAG | Knowledge graph + community detection | 30-60% better multi-hop |+| Hybrid Search | Sparse + dense with RRF fusion | 20-49% better retrieval |+| DiskANN / Vamana | SSD-friendly ANN with PQ compression | Large-scale search |+| ColBERT | Per-token late interaction | Fine-grained matching |+| Matryoshka | Adaptive-dimension with cascade | Flexible precision |+| MLA | Multi-Head Latent Attention | ~93% KV-cache compression |+| TurboQuant | 2-4 bit quantization | 6-8x memory reduction |++## Self-Learning Hooks++```bash+# Full 9-phase pretrain pipeline+npx ruvector hooks init --pretrain --build-agents quality++# Smart agent routing+npx ruvector hooks route --task "description"++# Code analysis+npx ruvector hooks ast-analyze --file src/module.ts+npx ruvector hooks diff-analyze --file src/module.ts+npx ruvector hooks coverage-route --task "description"+npx ruvector hooks security-scan --path src/+```++## Brain AGI++Access 8 AGI subsystems:++```bash+npx ruvector brain agi status # Combined diagnostics+npx ruvector brain agi sona # SONA patterns and trajectories+npx ruvector brain agi temporal # Knowledge evolution velocity+npx ruvector brain agi explore # Meta-learning curiosity & regret+npx ruvector brain search "query" # Shared brain knowledge search+```-## Normalization Options+## Performance-| Method | Use Case |-|--------|----------|-| L2 (unit sphere) | Cosine similarity -- default for semantic search |-| L1 (manhattan) | Sparse feature comparison |-| min-max | Bounded [0,1] range for visualization |-| z-score | Standardized distribution for statistical analysis |+| Operation | Latency | Notes |+|-----------|---------|-------|+| HNSW search | ~0.045ms | 8,800x vs inference |+| Memory cache | ~0.01ms | 40,000x vs inference |+| Insert | 52,000+/sec | Rust backend |+| Memory per vector | ~50 bytes | Efficient storage |## Related Plugins-- `ruflo-knowledge-graph` -- HNSW-backed semantic search across graph nodes-- `ruflo-market-data` -- Pattern vector indexing for candlestick similarity-- `ruflo-neural-trader` -- Strategy pattern similarity search+- `ruflo-agentdb` β HNSW storage backend in AgentDB+- `ruflo-intelligence` β SONA pattern learning integration+- `ruflo-knowledge-graph` β Graph RAG for multi-hop retrieval+- `ruflo-rag-memory` β Simple semantic search via ruvector## Licensediff --git a/plugins/ruflo-ruvector/agents/vector-engineer.md b/plugins/ruflo-ruvector/agents/vector-engineer.mdindex a5810297c7..16006cfba6 100644--- a/plugins/ruflo-ruvector/agents/vector-engineer.md+++ b/plugins/ruflo-ruvector/agents/vector-engineer.md@@ -1,88 +1,144 @@---name: vector-engineer-description: Vector operations specialist β embedding generation, HNSW index management, similarity search, clustering, and hyperbolic space reasoning+description: Vector operations specialist using npx ruvector β HNSW indexing, FlashAttention-3, Graph RAG, hybrid search, DiskANN, Brain AGI, 103 MCP toolsmodel: sonnet----You are a vector engineer for the RuVector system. Your responsibilities:+You are a vector engineer that orchestrates the `ruvector` npm package for embedding, indexing, search, clustering, and self-learning intelligence.-1. **Generate embeddings** using ONNX all-MiniLM-L6-v2 (384-dimensional) for text, code, diffs, and documents-2. **Manage HNSW indexes** β create, populate, query, and monitor graph-based approximate nearest-neighbor indexes-3. **Similarity search** β find semantically related content using cosine, L1, or custom distance metrics-4. **Cluster vectors** β group related vectors using k-means or density-based (DBSCAN-style) clustering-5. **Hyperbolic embeddings** β embed hierarchical data (taxonomies, org charts, dependency trees) in the Poincare ball model+### Core Tool: npx ruvector++All vector operations go through the `ruvector` CLI. Install once, then invoke via npx:++```bash+# Ensure installed+npm ls ruvector 2>/dev/null || npm install ruvector++# MCP server (103 tools)+npx ruvector mcp start++# Hooks system (self-learning)+npx ruvector hooks init --pretrain --build-agents quality+npx ruvector hooks route --task "description"+npx ruvector hooks ast-analyze --file src/module.ts+npx ruvector hooks diff-analyze --file src/module.ts+npx ruvector hooks coverage-route --task "description"++# Brain AGI+npx ruvector brain agi status+npx ruvector brain agi sona+npx ruvector brain agi temporal+npx ruvector brain agi explore++# Midstream+npx ruvector midstream status+npx ruvector midstream benchmark+```++### MCP Integration++ruvector exposes 103 MCP tools. Add as MCP server for direct tool access:+```bash+claude mcp add ruvector -- npx ruvector mcp start+```++Key tool categories:+- `hooks_route`, `hooks_route_enhanced` β smart agent routing+- `hooks_ast_analyze`, `hooks_ast_complexity` β code structure analysis+- `hooks_diff_analyze`, `hooks_diff_classify` β change classification+- `hooks_coverage_route`, `hooks_coverage_suggest` β test-aware routing+- `hooks_graph_mincut`, `hooks_graph_cluster` β code boundaries+- `hooks_security_scan` β vulnerability detection+- `hooks_rag_context` β semantic context retrieval+- `brain_search`, `brain_share`, `brain_status` β shared brain knowledge+- `brain_agi_status`, `brain_sona_stats` β AGI diagnostics++### Search Capabilities (ruvector v2.1+)++| Feature | Description | Improvement |+|---------|-------------|-------------|+| FlashAttention-3 | IO-aware tiled attention, O(N) memory | Replaces O(N^2) |+| Graph RAG | Knowledge graph + community detection | 30-60% better multi-hop |+| Hybrid Search | Sparse + dense with RRF fusion | 20-49% better retrieval |+| DiskANN / Vamana | SSD-friendly ANN with PQ compression | Large-scale search |+| ColBERT | Per-token late interaction (MaxSim) | Fine-grained matching |+| Matryoshka | Adaptive-dimension with cascade | Flexible precision |+| MLA | Multi-Head Latent Attention | ~93% KV-cache compression |+| TurboQuant | 2-4 bit KV-cache quantization | 6-8x memory reduction |### HNSW Parameters Guide| Parameter | Default | Purpose | Tuning ||-----------|---------|---------|--------|-| `M` | 16 | Graph connectivity (edges per node) | Higher = better recall, more memory. 12-48 typical range. |-| `efConstruction` | 200 | Build-time search quality | Higher = better index quality, slower build. 100-500 typical. |-| `efSearch` | 50 | Query-time search quality | Higher = better recall, slower queries. 10-200 typical. |--For most workloads, defaults are optimal. Increase `M` and `efConstruction` for large indexes (>100k vectors). Increase `efSearch` when recall matters more than latency.+| `M` | 16 | Graph connectivity | Higher = better recall, more memory |+| `efConstruction` | 200 | Build-time quality | Higher = better index, slower build |+| `efSearch` | 50 | Query-time quality | Higher = better recall, slower queries |-### Embedding Operations+### Self-Learning Hooks-- **Single text**: Embed a string, return 384-dim float32 vector-- **Batch documents**: Embed multiple files or text chunks in a single pass-- **Code chunks**: Embed source code with language-aware chunking (function/class boundaries)-- **Diff embeddings**: Embed git diffs to find semantically similar changes+ruvector's 9-phase pretrain pipeline:+```bash+npx ruvector hooks init --pretrain --build-agents quality+```+Phases: AST analysis, diff embeddings, coverage routing, neural training, graph analysis, security scanning, co-edit pattern learning, agent building, RAG context indexing.-### Clustering+### Embedding Operations-- **k-means**: Partition vectors into k groups by centroid proximity. Good for known cluster counts.-- **DBSCAN-style density clustering**: Find clusters of arbitrary shape based on density. Good for unknown cluster counts, detects outliers.+```bash+# Single text embedding (ONNX all-MiniLM-L6-v2, 384-dim)+npx ruvector embed "your text here"-### Hyperbolic Embeddings (Poincare Ball)+# Batch embedding+npx ruvector embed --batch --glob "src/**/*.ts"-Embed hierarchical data in hyperbolic space where distances grow exponentially toward the boundary. This naturally captures tree-like structures with far fewer dimensions than Euclidean space.+# Similarity search+npx ruvector search "query text" --limit 10-- Taxonomy/ontology embeddings-- Dependency tree similarity-- Org chart proximity-- Module hierarchy analysis+# Compare two texts+npx ruvector compare "text1" "text2"+```-### Normalization Options+### Performance (ruvector benchmarks)-| Method | Use Case |-|--------|----------|-| L2 (unit sphere) | Cosine similarity β default for semantic search |-| L1 (manhattan) | Sparse feature comparison |-| min-max | Bounded [0,1] range for visualization |-| z-score | Standardized distribution for statistical analysis |+| Operation | Latency | Throughput |+|-----------|---------|------------|+| ONNX inference | ~400ms | baseline |+| HNSW search | ~0.045ms | 8,800x faster |+| Memory cache | ~0.01ms | 40,000x faster |+| Insert | - | 52,000+ vectors/sec |+| Memory per vector | ~50 bytes | - |-### MCP Tools+### Clustering-- `mcp__claude-flow__embeddings_generate` β generate embedding for text-- `mcp__claude-flow__embeddings_search` β similarity search in HNSW index-- `mcp__claude-flow__embeddings_compare` β cosine similarity between two texts-- `mcp__claude-flow__embeddings_init` β initialize embedding engine and HNSW index-- `mcp__claude-flow__embeddings_status` β check embedding engine and index health-- `mcp__claude-flow__embeddings_hyperbolic` β Poincare ball embedding for hierarchical data-- `mcp__claude-flow__embeddings_neural` β neural substrate embeddings via RuVector-- `mcp__claude-flow__ruvllm_hnsw_create` β create a new HNSW index with custom parameters-- `mcp__claude-flow__ruvllm_hnsw_add` β add vectors to an existing HNSW index-- `mcp__claude-flow__ruvllm_hnsw_route` β route a query to the best matching vectors+- **k-means**: `npx ruvector cluster --namespace patterns --k 5`+- **Density (DBSCAN)**: `npx ruvector cluster --namespace patterns --density`-### Neural Learning+### Hyperbolic Embeddings (Poincare Ball)-Record embedding and search outcomes to improve retrieval quality over time:+For hierarchical data (dependency trees, taxonomies, module structures):```bash-npx @claude-flow/cli@latest hooks post-task --task-id "vector-TASK_ID" --success true --train-neural true-npx @claude-flow/cli@latest neural train --pattern-type coordination --epochs 5+npx ruvector embed --model poincare "hierarchical concept"+npx ruvector search --model poincare "query" --limit 10```-### Memory+### Memory Persistence-Store successful vector configurations and search patterns for reuse:+Store vector configurations and search patterns in AgentDB:```bash-npx @claude-flow/cli@latest memory store --namespace vector-patterns --key "hnsw-config-DOMAIN" --value "M=16,efC=200,efS=50,recall=0.97"-npx @claude-flow/cli@latest memory search --query "HNSW configuration for DOMAIN" --namespace vector-patterns+npx @claude-flow/cli@latest memory store --namespace vector-patterns --key "hnsw-config-DOMAIN" --value "M=16,efC=200,efS=50"+npx @claude-flow/cli@latest memory search --query "HNSW configuration" --namespace vector-patterns```### Related Plugins-- **ruflo-agentdb**: HNSW storage backend β persists indexes in AgentDB's vector_indexes table-- **ruflo-intelligence**: Neural embeddings and SONA pattern learning that feed into vector operations-- **ruflo-rag-memory**: Simple semantic search β delegates to RuVector for HNSW-backed retrieval+- **ruflo-agentdb**: HNSW storage backend β persists indexes in AgentDB+- **ruflo-intelligence**: Neural embeddings and SONA pattern learning+- **ruflo-rag-memory**: Simple semantic search delegating to ruvector+- **ruflo-knowledge-graph**: Graph RAG integration for multi-hop retrieval++### Neural Learning++After completing tasks, store successful patterns:+```bash+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true+```diff --git a/plugins/ruflo-ruvector/commands/vector.md b/plugins/ruflo-ruvector/commands/vector.mdindex b318d11175..8c78a7c55d 100644--- a/plugins/ruflo-ruvector/commands/vector.md+++ b/plugins/ruflo-ruvector/commands/vector.md@@ -1,24 +1,67 @@---name: vector-description: RuVector embedding, HNSW index, clustering, and hyperbolic space commands+description: RuVector operations via npx ruvector β embedding, search, clustering, indexing, hyperbolic, hooks, brain AGI----Vector operations commands:+$ARGUMENTS+Vector operations via the `ruvector` npm package. Parse subcommand from $ARGUMENTS.-1. Parse the user's subcommand (embed, batch, search, compare, cluster, index, hyperbolic)+Usage: /vector <subcommand> [options]-2. For **embed `<text>`**: call `mcp__claude-flow__embeddings_generate` with the text. Return the 384-dim vector and confirm it was stored in the active HNSW index.+Subcommands:-3. For **batch `<glob-pattern>`**: expand the glob to matching files, read each file, call `mcp__claude-flow__embeddings_generate` for each chunk, and call `mcp__claude-flow__ruvllm_hnsw_add` to insert all vectors. Report count and index size.+1. For **embed `<text>`**:+ Run: `npx ruvector embed "TEXT"`+ For files: `npx ruvector embed --file src/module.ts`+ Return the 384-dim vector and confirm storage.-4. For **search `<query>` [--limit N]**: call `mcp__claude-flow__embeddings_search` with the query text and limit (default 10). Present results ranked by similarity score.+2. For **batch `<glob-pattern>`**:+ Run: `npx ruvector embed --batch --glob "PATTERN"`+ Report count of vectors inserted and index size.-5. For **compare `<text1>` `<text2>`**: call `mcp__claude-flow__embeddings_compare` with both texts. Report cosine similarity as a decimal and a percentage.+3. For **search `<query>` [--limit N]**:+ Run: `npx ruvector search "QUERY" --limit N`+ Present results ranked by similarity score.+ For hybrid search: `npx ruvector search "QUERY" --hybrid`+ For Graph RAG: `npx ruvector search "QUERY" --graph-rag`-6. For **cluster `<namespace>` [--k N]**: fetch all vectors from the namespace, compute pairwise distances, run k-means (if --k given) or density clustering (if --k omitted), label each vector with its cluster ID, and present cluster summaries with member counts and centroid descriptions.+4. For **compare `<text1>` `<text2>`**:+ Run: `npx ruvector compare "TEXT1" "TEXT2"`+ Report cosine similarity as decimal and percentage.-7. For **index create `<name>`**: call `mcp__claude-flow__ruvllm_hnsw_create` with the index name and default parameters (M=16, efConstruction=200). Confirm creation.+5. For **cluster `<namespace>` [--k N]**:+ Run: `npx ruvector cluster --namespace NAMESPACE --k N`+ Without --k, uses density clustering: `npx ruvector cluster --namespace NAMESPACE --density`+ Present cluster summaries with labels, counts, and cohesion.-8. For **index stats `<name>`**: call `mcp__claude-flow__embeddings_status` for the named index. Report vector count, dimension, M, efConstruction, efSearch, and memory usage.+6. For **index create `<name>`**:+ Run: `npx ruvector index create NAME --M 16 --efConstruction 200`+ Confirm creation with parameters.-9. For **hyperbolic embed `<text>`**: call `mcp__claude-flow__embeddings_hyperbolic` with the text and model=poincare. Return the Poincare ball coordinates and curvature.+7. For **index stats `<name>`**:+ Run: `npx ruvector index stats NAME`+ Report vector count, dimension, M, efConstruction, memory usage.++8. For **hyperbolic embed `<text>`**:+ Run: `npx ruvector embed --model poincare "TEXT"`+ Return Poincare ball coordinates.++9. For **hooks init**:+ Run: `npx ruvector hooks init --pretrain --build-agents quality`+ Initialize self-learning with 9-phase pretrain pipeline.++10. For **hooks route `<task>`**:+ Run: `npx ruvector hooks route --task "DESCRIPTION"`+ Return smart agent routing recommendation.++11. For **ast `<file>`**:+ Run: `npx ruvector hooks ast-analyze --file FILE`+ Return AST analysis with symbols, complexity, imports.++12. For **brain status**:+ Run: `npx ruvector brain agi status`+ Show AGI subsystem diagnostics.++13. For **midstream status**:+ Run: `npx ruvector midstream status`+ Show streaming analysis platform overview.diff --git a/plugins/ruflo-ruvector/skills/vector-cluster/SKILL.md b/plugins/ruflo-ruvector/skills/vector-cluster/SKILL.mdindex 88e2af6273..40a1138813 100644--- a/plugins/ruflo-ruvector/skills/vector-cluster/SKILL.md+++ b/plugins/ruflo-ruvector/skills/vector-cluster/SKILL.md@@ -1,39 +1,42 @@---name: vector-cluster-description: Cluster vectors by similarity using k-means or density-based methods, then label and summarize groups+description: Cluster vectors by similarity using npx ruvector k-means or density-based methods with labeled group summariesargument-hint: "<namespace> [--k N]"-allowed-tools: mcp__claude-flow__embeddings_search mcp__claude-flow__embeddings_generate mcp__claude-flow__embeddings_compare mcp__claude-flow__embeddings_status mcp__claude-flow__ruvllm_hnsw_route mcp__claude-flow__memory_search mcp__claude-flow__memory_store mcp__claude-flow__memory_list Read Bash+allowed-tools: Bash Read mcp__claude-flow__memory_search mcp__claude-flow__memory_store mcp__claude-flow__memory_list---# Vector Cluster-Cluster vectors in a namespace by semantic similarity, producing labeled groups with summaries.+Cluster vectors in a namespace by semantic similarity using `ruvector`.## When to use-Use this skill when you have a collection of embeddings (e.g., all files in a project, all memory entries in a namespace) and want to discover natural groupings. Clustering reveals themes, identifies outliers, and helps organize large vector collections.+Use this skill when you have a collection of embeddings and want to discover natural groupings. Clustering reveals themes, identifies outliers, and helps organize large vector collections.## Steps-1. **Fetch all vectors** -- call `mcp__claude-flow__memory_list` with the target namespace to enumerate entries, then call `mcp__claude-flow__memory_search` with a broad query to retrieve vectors. For HNSW-backed namespaces, use `mcp__claude-flow__embeddings_status` to check the vector count.-2. **Compute pairwise distances** -- for each pair of vectors, compute cosine distance (1 - cosine_similarity). Build a distance matrix.-3. **Select clustering method**:- - If `--k N` is provided, use **k-means**: initialize k centroids via k-means++, assign vectors to nearest centroid, recompute centroids, repeat until convergence (max 100 iterations).- - If `--k` is omitted, use **density clustering**: find core points (vectors with >= minPts neighbors within epsilon distance), expand clusters from core points, mark remaining vectors as outliers.-4. **Label clusters** -- for each cluster, examine the source texts of member vectors and generate a descriptive label summarizing the cluster theme.-5. **Visualize** -- present a summary table with cluster ID, label, member count, and cohesion score (average intra-cluster similarity). List outliers separately if density clustering was used.-6. **Store results** -- call `mcp__claude-flow__memory_store` to persist cluster assignments in the `vector-clusters` namespace for future reference.--## CLI alternative--```bash-npx @claude-flow/cli@latest embeddings search --query "*" --namespace patterns --limit 1000-npx @claude-flow/cli@latest memory list --namespace patterns-```+1. **Ensure ruvector is available**:+ ```bash+ npm ls ruvector 2>/dev/null || npm install ruvector+ ```+2. **Run clustering**:+ - With known cluster count: `npx ruvector cluster --namespace NAMESPACE --k N`+ - With auto-detection: `npx ruvector cluster --namespace NAMESPACE --density`+3. **Review output** -- ruvector reports: cluster ID, label, member count, cohesion score, and outliers (for density mode)+4. **Store results**:+ `mcp__claude-flow__memory_store({ key: "clusters-NAMESPACE-TIMESTAMP", value: "CLUSTER_ASSIGNMENTS", namespace: "vector-clusters" })`## Interpreting results-- **High cohesion** (>0.85): tight, well-defined cluster with closely related content+- **High cohesion** (>0.85): tight, well-defined cluster- **Medium cohesion** (0.6-0.85): related but diverse content-- **Low cohesion** (<0.6): loose grouping, may benefit from splitting with higher k-- **Outliers**: content that does not fit any cluster -- often novel or anomalous entries worth investigating+- **Low cohesion** (<0.6): loose grouping, try higher k+- **Outliers**: novel or anomalous entries worth investigating++## Graph-based clustering (ruvector v2.1+)++ruvector supports Louvain community detection and spectral clustering for graph-structured data:+```bash+npx ruvector hooks graph-cluster --namespace NAMESPACE+npx ruvector hooks graph-mincut --namespace NAMESPACE+```diff --git a/plugins/ruflo-ruvector/skills/vector-embed/SKILL.md b/plugins/ruflo-ruvector/skills/vector-embed/SKILL.mdindex 74165edfa9..bfefded3df 100644--- a/plugins/ruflo-ruvector/skills/vector-embed/SKILL.md+++ b/plugins/ruflo-ruvector/skills/vector-embed/SKILL.md@@ -1,36 +1,43 @@---name: vector-embed-description: Generate ONNX embeddings (all-MiniLM-L6-v2, 384-dim), normalize, and store in an HNSW index+description: Generate embeddings via npx ruvector (ONNX all-MiniLM-L6-v2, 384-dim), normalize, and store in HNSW indexargument-hint: "<text-or-file>"-allowed-tools: mcp__claude-flow__embeddings_generate mcp__claude-flow__embeddings_init mcp__claude-flow__embeddings_status mcp__claude-flow__embeddings_compare mcp__claude-flow__ruvllm_hnsw_create mcp__claude-flow__ruvllm_hnsw_add mcp__claude-flow__ruvllm_hnsw_route mcp__claude-flow__memory_store mcp__claude-flow__memory_search Read Bash+allowed-tools: Bash Read mcp__claude-flow__memory_store mcp__claude-flow__memory_search---# Vector Embed-Generate and store vector embeddings for text or file contents.+Generate and store vector embeddings using the `ruvector` npm package.## When to use-Use this skill to embed text, code, or documents into 384-dimensional vectors for semantic search, similarity comparison, or clustering. Embeddings are generated via ONNX all-MiniLM-L6-v2 and stored in an HNSW index for fast approximate nearest-neighbor retrieval.+Use this skill to embed text, code, or documents into 384-dimensional vectors for semantic search, similarity comparison, or clustering. ruvector uses ONNX all-MiniLM-L6-v2 with HNSW indexing (52,000+ inserts/sec, ~0.045ms search).## Steps-1. **Ensure the embedding engine is ready** -- call `mcp__claude-flow__embeddings_status` to check engine health. If not initialized, call `mcp__claude-flow__embeddings_init`.-2. **Read the input** -- if the argument is a file path, read the file contents. If it is raw text, use it directly. For large files, chunk into segments of ~512 tokens with 50-token overlap.-3. **Generate the embedding** -- call `mcp__claude-flow__embeddings_generate` with the text. The engine returns a 384-dim float32 vector.-4. **Normalize** -- the embedding is L2-normalized by default (unit sphere) for cosine similarity. Specify `--norm l1`, `--norm minmax`, or `--norm zscore` for alternatives.-5. **Store in HNSW index** -- call `mcp__claude-flow__ruvllm_hnsw_add` to insert the vector with metadata (source text hash, timestamp, file path if applicable).-6. **Confirm** -- report the vector ID, dimension (384), norm, and index the vector was stored in.+1. **Ensure ruvector is available**:+ ```bash+ npm ls ruvector 2>/dev/null || npm install ruvector+ ```+2. **Embed the input**:+ - For text: `npx ruvector embed "your text here"`+ - For a file: `npx ruvector embed --file src/module.ts`+ - For batch: `npx ruvector embed --batch --glob "src/**/*.ts"`+3. **Normalization** -- ruvector L2-normalizes by default (unit sphere, cosine similarity). Alternatives: `--norm l1`, `--norm minmax`, `--norm zscore`+4. **Confirm** -- report vector ID, dimension (384), norm, and index stored in+5. **Store metadata** in AgentDB if needed:+ `mcp__claude-flow__memory_store({ key: "embed-SOURCE", value: "VECTOR_METADATA", namespace: "vector-patterns" })`++## MCP alternative++If ruvector MCP server is connected (`claude mcp add ruvector -- npx ruvector mcp start`):+- `hooks_rag_context` β semantic context retrieval+- `brain_search` β shared brain knowledge search-## CLI alternative+## Batch embedding```bash-npx @claude-flow/cli@latest embeddings embed --text "your text here"-npx @claude-flow/cli@latest embeddings batch --glob "src/**/*.ts"-npx @claude-flow/cli@latest embeddings init --force-npx @claude-flow/cli@latest embeddings status+npx ruvector embed --batch --glob "src/**/*.ts"```-## Batch embedding--For multiple files, iterate over each file, chunk contents, and embed each chunk. Use `mcp__claude-flow__ruvllm_hnsw_add` with batch mode for efficient insertion. Report total vectors inserted and index growth.+Reports total vectors inserted and index growth.diff --git a/plugins/ruflo-ruvector/skills/vector-hyperbolic/SKILL.md b/plugins/ruflo-ruvector/skills/vector-hyperbolic/SKILL.mdindex 8547ec9c9b..999114febd 100644--- a/plugins/ruflo-ruvector/skills/vector-hyperbolic/SKILL.md+++ b/plugins/ruflo-ruvector/skills/vector-hyperbolic/SKILL.md@@ -1,36 +1,37 @@---name: vector-hyperbolic-description: Embed hierarchical data in hyperbolic space (Poincare ball model), compute geodesic distances, and find hierarchical neighbors+description: Embed hierarchical data in hyperbolic space via npx ruvector Poincare ball model, compute geodesic distancesargument-hint: "<text> [--model poincare]"-allowed-tools: mcp__claude-flow__embeddings_hyperbolic mcp__claude-flow__embeddings_generate mcp__claude-flow__embeddings_compare mcp__claude-flow__embeddings_status mcp__claude-flow__ruvllm_hnsw_create mcp__claude-flow__ruvllm_hnsw_add mcp__claude-flow__ruvllm_hnsw_route mcp__claude-flow__memory_store mcp__claude-flow__memory_search Read Bash+allowed-tools: Bash Read mcp__claude-flow__memory_store mcp__claude-flow__memory_search---# Vector Hyperbolic-Embed hierarchical data in the Poincare ball model for operations that respect tree-like structure.+Embed hierarchical data in the Poincare ball model using `ruvector`.## When to use-Use this skill when your data has inherent hierarchy -- dependency trees, module structures, taxonomies, org charts, ontologies, or any parent-child relationship graph. Hyperbolic space naturally captures hierarchical distances: nodes near the center are generic/root-level, nodes near the boundary are specific/leaf-level. This requires far fewer dimensions than Euclidean embeddings to represent the same hierarchical fidelity.+Use this skill when your data has inherent hierarchy β dependency trees, module structures, taxonomies, org charts, ontologies. Hyperbolic space captures hierarchical distances with far fewer dimensions than Euclidean embeddings.## Steps-1. **Identify hierarchical structure** -- determine what hierarchy the data represents (dependency tree, taxonomy, module graph, etc.). If needed, read source files to extract parent-child relationships.-2. **Embed in Poincare ball** -- call `mcp__claude-flow__embeddings_hyperbolic` with the text and `model=poincare`. The engine returns coordinates inside the unit ball where:- - Coordinates near the origin represent generic/root concepts- - Coordinates near the boundary represent specific/leaf concepts- - Geodesic distance between points reflects hierarchical distance-3. **Compute geodesic distances** -- for two hyperbolic embeddings, compute the Poincare distance: `d(u, v) = arcosh(1 + 2 * ||u - v||^2 / ((1 - ||u||^2)(1 - ||v||^2)))`. This distance grows logarithmically with tree depth, preserving hierarchy.-4. **Find hierarchical neighbors** -- call `mcp__claude-flow__ruvllm_hnsw_route` with the hyperbolic embedding to find nearest neighbors in the hyperbolic HNSW index. Neighbors are semantically and hierarchically related.-5. **Analyze hierarchy** -- report the embedding's position (center vs. boundary), its nearest hierarchical neighbors, and the geodesic distances. Identify parent-like (closer to center) and child-like (closer to boundary) neighbors.-6. **Store results** -- call `mcp__claude-flow__memory_store` to persist the hyperbolic embedding and hierarchy analysis in the `hyperbolic-embeddings` namespace.--## CLI alternative--```bash-npx @claude-flow/cli@latest embeddings embed --text "your text" --model poincare-npx @claude-flow/cli@latest embeddings search --query "your query" --model poincare-```+1. **Ensure ruvector is available**:+ ```bash+ npm ls ruvector 2>/dev/null || npm install ruvector+ ```+2. **Embed in Poincare ball**:+ ```bash+ npx ruvector embed --model poincare "hierarchical concept"+ ```+ Coordinates near origin = generic/root; near boundary = specific/leaf.+3. **Search in hyperbolic space**:+ ```bash+ npx ruvector search --model poincare "query" --limit 10+ ```+4. **Geodesic distance**: `d(u, v) = arcosh(1 + 2 * ||u-v||^2 / ((1-||u||^2)(1-||v||^2)))`+ Distance grows logarithmically with tree depth, preserving hierarchy.+5. **Store results**:+ `mcp__claude-flow__memory_store({ key: "hyperbolic-CONCEPT", value: "COORDINATES_AND_NEIGHBORS", namespace: "hyperbolic-embeddings" })`## Poincare ball properties@@ -38,12 +39,12 @@ npx @claude-flow/cli@latest embeddings search --query "your query" --model poinc|----------|---------|| Norm close to 0 | Generic, root-level concept || Norm close to 1 | Specific, leaf-level concept |-| Small geodesic distance | Closely related in the hierarchy |-| Large geodesic distance | Distantly related or in different subtrees |+| Small geodesic distance | Closely related in hierarchy |+| Large geodesic distance | Distant or different subtrees |## Use cases- **Dependency analysis**: embed module imports to find tightly coupled subtrees- **Code architecture**: map class hierarchies to discover structural patterns- **Knowledge organization**: embed concepts to reveal taxonomic relationships-- **Codebase navigation**: find the most specific or most general modules relative to a query+- **Codebase navigation**: find most specific/general modules relative to a query